@visa/cli 3.3.0 → 3.3.1-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Ky=Object.create;var Mo=Object.defineProperty;var Gy=Object.getOwnPropertyDescriptor;var Wy=Object.getOwnPropertyNames;var Yy=Object.getPrototypeOf,zy=Object.prototype.hasOwnProperty;var Nt=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Ju=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},No=(e,t)=>{for(var n in t)Mo(e,n,{get:t[n],enumerable:!0})},Xu=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Wy(t))!zy.call(e,s)&&s!==n&&Mo(e,s,{get:()=>t[s],enumerable:!(r=Gy(t,s))||r.enumerable});return e};var R=(e,t,n)=>(n=e!=null?Ky(Yy(e)):{},Xu(t||!e||!e.__esModule?Mo(n,"default",{value:e,enumerable:!0}):n,e)),Jy=e=>Xu(Mo({},"__esModule",{value:!0}),e);var As=Ju((tA,l_)=>{l_.exports={name:"@visa/cli",version:"3.3.0",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{"sync:server-json":"node scripts/sync-server-json.mjs","check:server-json":"node scripts/sync-server-json.mjs --check",prebuild:"node scripts/sync-server-json.mjs && pnpm --filter @visa/money build && pnpm --filter @visa/crypto build && pnpm --filter subway-sdk build && pnpm --filter @visa-cli/tools build",build:"tsc --noEmit && node esbuild.config.js",prepack:"node scripts/sync-server-json.mjs --check",dev:"tsc --watch",pretest:"pnpm build",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0",commander:"^12.1.0",zod:"^3.23.0"},devDependencies:{"@visa/crypto":"workspace:*","subway-sdk":"workspace:*","@visa/money":"workspace:*","@visa/observability":"workspace:*","@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.31.0","@types/jest":"^30.0.0","@types/node":"^25.9.3","@typescript-eslint/eslint-plugin":"^8.62.0","@typescript-eslint/parser":"^8.62.0","@types/express":"^5.0.0",esbuild:"^0.28.1",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.4","ts-jest":"^29.4.11",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","native/visa-keychain-win.cpp","native/build-win.bat","native/bin/win32-x64/visa-keychain-win.exe","server.json","README.md","LICENSE"]}});function Pb(){je.existsSync(Tc)||je.mkdirSync(Tc,{recursive:!0,mode:448})}function Ob(){if(!xc){if(Pb(),je.existsSync(qs)&&je.statSync(qs).size>$b){let t=qs+".1";je.existsSync(t)&&je.unlinkSync(t),je.renameSync(qs,t)}xc=je.createWriteStream(qs,{flags:"a"})}return xc}function Mb(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function li(e,...t){let n=new Date().toISOString(),r=t.map(o=>typeof o=="string"?o:JSON.stringify(o,null,2)).join(" "),s=`[${n}] [${e}] ${r}
1
+ "use strict";var Ky=Object.create;var Mo=Object.defineProperty;var Gy=Object.getOwnPropertyDescriptor;var Wy=Object.getOwnPropertyNames;var Yy=Object.getPrototypeOf,zy=Object.prototype.hasOwnProperty;var Nt=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Ju=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},No=(e,t)=>{for(var n in t)Mo(e,n,{get:t[n],enumerable:!0})},Xu=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Wy(t))!zy.call(e,s)&&s!==n&&Mo(e,s,{get:()=>t[s],enumerable:!(r=Gy(t,s))||r.enumerable});return e};var R=(e,t,n)=>(n=e!=null?Ky(Yy(e)):{},Xu(t||!e||!e.__esModule?Mo(n,"default",{value:e,enumerable:!0}):n,e)),Jy=e=>Xu(Mo({},"__esModule",{value:!0}),e);var As=Ju((tA,l_)=>{l_.exports={name:"@visa/cli",version:"3.3.1-rc.0",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{"sync:server-json":"node scripts/sync-server-json.mjs","check:server-json":"node scripts/sync-server-json.mjs --check",prebuild:"node scripts/sync-server-json.mjs && pnpm --filter @visa/money build && pnpm --filter @visa/crypto build && pnpm --filter subway-sdk build && pnpm --filter @visa-cli/tools build",build:"tsc --noEmit && node esbuild.config.js",prepack:"node scripts/sync-server-json.mjs --check",dev:"tsc --watch",pretest:"pnpm build",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0",commander:"^12.1.0",zod:"^3.23.0"},devDependencies:{"@visa/crypto":"workspace:*","subway-sdk":"workspace:*","@visa/money":"workspace:*","@visa/observability":"workspace:*","@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.31.0","@types/jest":"^30.0.0","@types/node":"^25.9.3","@typescript-eslint/eslint-plugin":"^8.62.0","@typescript-eslint/parser":"^8.62.0","@types/express":"^5.0.0",esbuild:"^0.28.1",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.4","ts-jest":"^29.4.11",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","native/visa-keychain-win.cpp","native/build-win.bat","native/bin/win32-x64/visa-keychain-win.exe","server.json","README.md","LICENSE"]}});function Pb(){je.existsSync(Tc)||je.mkdirSync(Tc,{recursive:!0,mode:448})}function Ob(){if(!xc){if(Pb(),je.existsSync(qs)&&je.statSync(qs).size>$b){let t=qs+".1";je.existsSync(t)&&je.unlinkSync(t),je.renameSync(qs,t)}xc=je.createWriteStream(qs,{flags:"a"})}return xc}function Mb(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function li(e,...t){let n=new Date().toISOString(),r=t.map(o=>typeof o=="string"?o:JSON.stringify(o,null,2)).join(" "),s=`[${n}] [${e}] ${r}
2
2
  `;Mb(e)&&process.stderr.write(s),Ob().write(s)}var je,Cc,Af,Tc,qs,$b,xc,g,_t=Nt(()=>{"use strict";je=R(require("fs")),Cc=R(require("path")),Af=R(require("os")),Tc=Cc.join(Af.homedir(),".visa-mcp"),qs=Cc.join(Tc,"mcp-server.log"),$b=5*1024*1024,xc=null;g={debug:(...e)=>li("DEBUG",...e),info:(...e)=>li("INFO",...e),warn:(...e)=>li("WARN",...e),error:(...e)=>li("ERROR",...e)}});var ui,Pf,Of,kc,Ks,Mf=Nt(()=>{"use strict";ui=R(require("fs")),Pf=R(require("path")),Of=R(require("os")),kc=Pf.join(Of.homedir(),".visa-mcp"),Ks=class{static ensureConfigDir(){ui.existsSync(kc)||ui.mkdirSync(kc,{recursive:!0,mode:448})}static getConfigDir(){return kc}static TOOL_STATES={login:!0,get_status:!0,get_cards:!0,add_card:!0,pay:!1,transaction_history:!0,update_spending_controls:!0,enroll_device:!1,verify_otp:!1,reset:!0,batch:!0,generate_x402_image:!1,browser_launch:!1,browser_navigate:!1,browser_snapshot:!1,browser_click:!1,browser_type:!1,browser_scroll:!1,generate_music_card:!1,generate_image_card:!1,query_onchain_prices_card:!1,generate_music_tempo_card:!1,check_music_status_tempo_card:!1,generate_image_fast_card:!1,generate_video_tempo_card:!1};static loadToolStates(){return{...this.TOOL_STATES}}static getDisabledTools(){let t=new Set;for(let[n,r]of Object.entries(this.TOOL_STATES))r||t.add(n);return t}static isToolDisabled(t){return this.TOOL_STATES[t]===!1}}});function Nf(e){let t=Lf.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function Gs(){return Uf.join(Ks.getConfigDir(),Ub)}function Df(e){if((0,Rc.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function jb(e){let t=e.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!t)return!1;let n=Number.parseInt(t[1],16),r=Number.parseInt(t[2],16);if(!Number.isFinite(n)||!Number.isFinite(r))return!1;let s=[n>>8&255,n&255,r>>8&255,r&255].join(".");return Df(s)}function Bb(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,Rc.isIP)(t);return n===4?Df(t):n===6?t==="::1"||jb(t):!1}function Ec(e,t="auth.serverUrl"){let n;try{n=new URL(e)}catch{throw new Error(`${t} must be a valid URL (got: ${JSON.stringify(e)})`)}if(n.username||n.password)throw new Error(`${t} must not include username or password credentials`);if(n.protocol!=="https:"&&!(n.protocol==="http:"&&Bb(n.hostname)))throw new Error(`${t} ${Db}`)}function Jn(){let e=Gs();if(!hn.existsSync(e))return{};try{let t=hn.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?(g.warn("settings:corrupt",{path:Nf(e),reason:"not_object"}),{}):n}catch(t){return g.warn("settings:corrupt",{path:Nf(e),error:t?.message||String(t)}),{}}}function Ac(e){Ks.ensureConfigDir();let t=Gs(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
3
3
  `;hn.writeFileSync(n,r,{mode:384}),hn.renameSync(n,t)}function $c(e){let t=Jn()[e];return typeof t=="string"?t:void 0}function fi(e){let t=Jn()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function Pc(e){let t=Jn()[e];if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim().length>0){let n=Number(t);if(Number.isFinite(n))return n}}function pi(e,t){if(jf.some(o=>e.startsWith(o)))throw new Ft(e);if(e in di)throw new gn(e);let n=Xn[e];if(!n)throw new nt(e);let r;if(n.type==="boolean")if(typeof t=="boolean")r=t;else if(typeof t=="string"){let o=t.toLowerCase();if(o==="true")r=!0;else if(o==="false")r=!1;else throw new Error(`${e} expects true or false (got: ${JSON.stringify(t)})`)}else throw new Error(`${e} expects a boolean (got: ${typeof t})`);else if(n.type==="number")if(typeof t=="number")r=t;else if(typeof t=="string"&&t.trim().length>0){let o=Number(t);if(!Number.isFinite(o))throw new Error(`${e} expects a number (got: ${JSON.stringify(t)})`);r=o}else throw new Error(`${e} expects a number (got: ${typeof t})`);else{if(typeof t!="string"||t.length===0)throw new Error(`${e} expects a non-empty string`);r=t}n.validate&&n.validate(r);let s=Jn();return s[e]=r,Ac(s),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:Gs()}}function mi(e){if(jf.some(o=>e.startsWith(o)))throw new Ft(e);let t=Xn[e];if(e in di){let o=Jn(),i=e in o;return i&&(delete o[e],Ac(o)),{key:e,removed:i,requiresRestart:!1,path:Gs()}}if(!t)throw new nt(e);let r=Jn(),s=e in r;return s&&(delete r[e],Ac(r)),{key:e,removed:s,requiresRestart:s&&!!t.requiresRestart,path:Gs()}}function Bf(){let e=Jn();return Object.entries(di).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}function Vb(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function qb(){try{let e=As();return Vb(e.version)}catch{return!1}}function Kb(e){return e.envVar!==void 0&&e.envVar!==""?(Ec(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(Ec(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?Hb:Fb}function Ue(){return Kb({envVar:process.env.VISA_AUTH_URL,settingValue:$c("auth.serverUrl"),isPrerelease:qb()})}function Ff(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":fi("ui.suppressBrowser")??!1}function Hf(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":fi("ui.suppressFeed")??!1}function Vf(){let e=process.env.VISA_CREDIT_SESSION_CAP_CENTS;if(e!==void 0){let n=Number(e);if(Number.isFinite(n)&&n>=10&&n<=1e4)return Math.floor(n)}let t=Pc("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):Ic}var hn,Rc,Lf,Uf,Ub,Db,Xn,Ic,di,nt,Ft,gn,jf,Fb,Hb,Ht=Nt(()=>{"use strict";hn=R(require("fs")),Rc=require("node:net"),Lf=R(require("os")),Uf=R(require("path"));Mf();_t();Ub="settings.json",Db="must use https unless it points at localhost/loopback for local development";Xn={"auth.serverUrl":{type:"string",description:"Auth server base URL. Override for staging / self-hosted backends.",requiresRestart:!0,validate:e=>{if(typeof e!="string")throw new Error("auth.serverUrl must be a string");Ec(e)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."},"ui.suppressFeed":{type:"boolean",description:"When true, generated images/music are not auto-submitted to the public Made-with-Visa feed."},"tools.meta":{type:"boolean",description:"Show category meta-tools (generate_image, generate_video, generate_music, run_llm, ...). Restart required.",requiresRestart:!0},"tools.discover":{type:"boolean",description:"Show the dynamic-catalog tools (discover_tools, execute_tool). Restart required.",requiresRestart:!0},"merchants.discover":{type:"string",description:'Platform-merchant JIT tool discovery: "all" = every live merchant, "off" = none, comma-separated slugs = exactly those. Equivalent to VISA_MERCHANT_DISCOVER / VISA_MERCHANT_SLUGS env. Restart required.',requiresRestart:!0,validate:e=>{if(typeof e!="string")throw new Error("merchants.discover must be a string");let t=e.trim().toLowerCase();if(t===""||t==="all"||t==="off"||t==="*")return;let n=/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/,r=e.split(",").map(s=>s.trim()).filter(Boolean);for(let s of r)if(!n.test(s))throw new Error(`merchants.discover: "${s}" is not a valid merchant slug`)}},"credit.sessionCapCents":{type:"number",description:"Default cap (in cents) for start_session and pay-as-you-go one-shot approvals. Server clamps to [10, 10000] = $0.10\u2013$100. Default 500 ($5).",validate:e=>{if(typeof e!="number"||!Number.isFinite(e))throw new Error("credit.sessionCapCents must be a number");if(!Number.isInteger(e))throw new Error("credit.sessionCapCents must be a whole number of cents (no fractional cents)");if(e<10||e>1e4)throw new Error("credit.sessionCapCents must be between 10 ($0.10) and 10000 ($100)")}}},Ic=500,di={"tools.specific":"Legacy direct _card MCP tools are retired. Use category meta-tools or discover_tools/execute_tool.","credit.sessionMode":"The session-mode toggle is retired. Use start_session, close_session, and get_session_status."};nt=class extends Error{constructor(t){let n=Object.keys(Xn).sort().join(", ");super(`Unknown setting "${t}". Settable keys: ${n}. For server-controlled values (biometric.*, spending.*) use the dedicated tools (biometric_on/off, update_spending_controls).`),this.name="UnknownSettingKeyError"}},Ft=class extends Error{constructor(t){let n="";t.startsWith("biometric.")?n="biometric_on / biometric_off":t.startsWith("spending.")?n="update_spending_controls":t.startsWith("cards.")?n="add_card / remove_card / set_default_card":t.startsWith("account.")&&(n="login / reset"),super(`"${t}" is a server-controlled value and cannot be set via config set. `+(n?`Use ${n} instead.`:"No client-side override is supported.")),this.name="ServerOnlySettingError"}},gn=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+di[t]),this.name="RetiredSettingKeyError"}},jf=["biometric.","spending.","account.","cards.","biometric"];Fb="https://auth.visacli.sh",Hb="https://auth-visa-code-preview.up.railway.app"});var es=Ju(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.micros=qv;be.fromCents=Kv;be.fromUsdc=Gv;be.fromUsd=Wv;be.toCents=Yv;be.toCentsForAcquirer=zv;be.toUsdc=Jv;be.toWire=Xv;be.fromWire=Zv;be.toDisplay=Qv;be.toUsdRounded2dp=ew;be.add=tw;be.sub=nw;be.clampNonNegative=rw;be.isNonNegative=sw;be.max=ow;be.min=iw;var Wt=10000n,Ip=1000000n;function qv(e){return e}function Kv(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*Wt}function Gv(e){return e}function Wv(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function Yv(e){if(e>=0n)return Number(e/Wt);let t=e/Wt,n=e%Wt;return Number(n===0n?t:t-1n)}function zv(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/Wt)}function Jv(e){return e}function Xv(e){return e.toString()}function Zv(e){if(typeof e!="string"||e.length===0)throw new TypeError(`fromWire: expected non-empty string, got ${typeof e} ${JSON.stringify(e)}`);if(!/^-?\d+$/.test(e))throw new TypeError(`fromWire: not a valid micros integer: ${JSON.stringify(e)}`);return BigInt(e)}function Qv(e,t={}){let n=t.decimals??2,r=t.symbol??"$",s=e<0n,o=s?-e:e,i=o/Ip,a=o%Ip,c=s?"-":"";if(n===0)return`${c}${r}${i.toString()}`;let l=a.toString().padStart(6,"0").slice(0,n);return`${c}${r}${i.toString()}.${l}`}function ew(e){let t=e<0n,n=t?-e:e,r=n/Wt,o=n%Wt*2n,i;o<Wt?i=r:o>Wt?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function tw(e,t){return e+t}function nw(e,t){return e-t}function rw(e){return e<0n?0n:e}function sw(e){return e>=0n}function ow(e,t){return e>t?e:t}function iw(e,t){return e<t?e:t}});function dl(e,t){switch(e){case"name_not_found":return new xm(t);case"delivery_failed":return new Tm(t);case"timeout":return new ao(t);case"not_registered":return new Cm;case"register_failed":return new ji(t);case"invalid_message":return new km(t);case"rate_limited":return new Em(t);default:return new Ct(e,t)}}var Sm,Ct,xm,Tm,ao,Cm,Pe,km,ji,Em,fl=Nt(()=>{"use strict";Sm=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Ct=class extends Error{code;constructor(e,t){super(t),this.name="SubwayError",this.code=e}},xm=class extends Ct{constructor(e){super("name_not_found",`Agent not registered: ${e}`),this.name="NameNotFoundError"}},Tm=class extends Ct{constructor(e){super("delivery_failed",e),this.name="DeliveryFailedError"}},ao=class extends Ct{constructor(e="RPC call timed out"){super("timeout",e),this.name="TimeoutError"}},Cm=class extends Ct{constructor(){super("not_registered","Client has not registered with the bridge"),this.name="NotRegisteredError"}},Pe=class extends Ct{constructor(e){super("connection_failed",e),this.name="ConnectionError"}},km=class extends Ct{constructor(e){super("invalid_message",e),this.name="InvalidMessageError"}},ji=class extends Ct{constructor(e){super("register_failed",e),this.name="RegisterFailedError"}},Em=class extends Ct{constructor(e="Rate limited"){super("rate_limited",e),this.name="RateLimitedError"}}});function Sr(e){return e.includes(".")?e:`${e}.relay`}function pl(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function jw(){if(typeof WebSocket<"u")return WebSocket;try{let e=Sm("ws");return e.default??e}catch{return}}function Bw(e,t,n){return Math.min(Math.max(e,t),n)}function dS(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function fg(e,t,n=""){let r=dS(e),s=e?.length;if(!r||t!==void 0){let i=n&&`"${n}" `,a="",c=r?`length=${s}`:`type=${typeof e}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):new TypeError(l)}return e}function Nm(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function fS(e,t){fg(e,void 0,"digestInto() output");let n=t.outputLen;if(e.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function co(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function yl(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Et(e,t){return e<<32-t|e>>>t}function pg(e,t={}){let n=(s,o)=>e(o).update(s).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=s=>e(s),Object.assign(n,t),Object.freeze(n)}function pS(e,t,n){return e&t^~e&n}function mS(e,t,n){return e&t^e&n^t&n}function gS(e,t=!1){return t?{h:Number(e&Bi),l:Number(e>>Lm&Bi)}:{h:Number(e>>Lm&Bi)|0,l:Number(e&Bi)|0}}function hS(e,t=!1){let n=e.length,r=new Uint32Array(n),s=new Uint32Array(n);for(let o=0;o<n;o++){let{h:i,l:a}=gS(e[o],t);[r[o],s[o]]=[i,a]}return[r,s]}function Xt(e,t,n,r){let s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}function PS(e){return sS(e)}function OS(e,t){return aS(t,e)}function NS(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function DS(e){let t=MS(IS(e.payload)),n=`${e.messageId}
4
4
  ${e.senderPeerId}
@@ -6,7 +6,7 @@ ${e.senderName}
6
6
  ${e.timestampMs}
7
7
  ${e.messageType}
8
8
  ${t}
9
- ${e.nonce}`;return LS.encode(n)}function jS(e,t,n,r,s,o,i){return DS({messageId:e,senderPeerId:t,senderName:n,timestampMs:r,messageType:s,payload:o,nonce:i})}function BS(e){let t=0;for(;t<e.length;){let n=e[t],r=n>>3,s=n&7;if(t++,s===0){for(;t<e.length&&e[t]&128;)t++;t++}else if(s===2){let o=0,i=0;for(;t<e.length&&e[t]&128;)o|=(e[t]&127)<<i,i+=7,t++;if(o|=(e[t]&127)<<i,t++,r===2&&o>=64)return e.slice(t,t+32);t+=o}else return null}return null}function lx(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Ig(e,t,n=""){let r=lx(e),s=e?.length;if(!r||t!==void 0){let i=n&&`"${n}" `,a="",c=r?`length=${s}`:`type=${typeof e}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):new TypeError(l)}return e}function Wm(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function ux(e,t){Ig(e,void 0,"digestInto() output");let n=t.outputLen;if(e.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function El(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function wl(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function dx(e,t={}){let n=(s,o)=>e(o).update(s).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=s=>e(s),Object.assign(n,t),Object.freeze(n)}function mx(e,t=!1){return t?{h:Number(e&Vi),l:Number(e>>Ym&Vi)}:{h:Number(e>>Ym&Vi)|0,l:Number(e&Vi)|0}}function gx(e,t=!1){let n=e.length,r=new Uint32Array(n),s=new Uint32Array(n);for(let o=0;o<n;o++){let{h:i,l:a}=mx(e[o],t);[r[o],s[o]]=[i,a]}return[r,s]}function Qt(e,t,n,r){let s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}function Ex(){return ox.randomSecretKey()}function Pg(e){return rx(e)}function Ax(){let e=Ex();return{secretKey:e,publicKey:Pg(e)}}function Rx(e){if((0,Ln.existsSync)(e)){let n=(0,Ln.readFileSync)(e),r=new Uint8Array(n.buffer.slice(n.byteOffset,n.byteOffset+32));return{secretKey:r,publicKey:Pg(r)}}let t=Ax();return(0,Ln.mkdirSync)((0,Qm.dirname)(e),{recursive:!0}),(0,Ln.writeFileSync)(e,new Uint8Array(t.secretKey)),t}function Ix(e){let{secretKey:t,publicKey:n}=Rx(e);return{privateKey:t,publicKey:n}}async function $x(e,t,n,r,s,o,i,a){let c=jS(t,n,r,s,o,i,a);return{signature:await OS(e,c),signatureInput:US.subwayAgentMsgV1}}function Zm(e){return NS(e)}var Ln,Qm,Fw,Hw,Vw,qw,Kw,eg,Yi,Gi,Am,Rm,ml,gl,Gw,ea,Ww,Ce,Yw,zw,Jw,en,ta,Al,tg,Rl,Jt,Im,Il,ng,Xw,is,Zw,zi,_r,se,$m,$,rg,sg,og,ig,hl,Sl,lo,Cr,xr,ag,cg,kt,Qw,Pm,eS,xl,$l,tS,lg,nS,rS,sS,oS,iS,aS,Pl,ug,Ji,cS,dg,Tl,lS,Om,Mm,uS,mg,gg,In,Oe,Bi,Lm,Um,Dm,ns,rs,Fi,Hi,yS,_S,bS,vS,wS,SS,xS,$n,TS,CS,hg,kS,ES,Pn,On,AS,RS,IS,$S,jm,MS,yg,LS,US,_g,Xi,Wi,Bm,Fm,_l,bl,FS,as,HS,ke,VS,qS,KS,Un,na,Ol,bg,vg,Zt,Hm,wg,Sg,GS,Ml,WS,Zi,vr,ie,Vm,P,YS,zS,xg,Tg,vl,Cl,uo,cs,Tr,JS,Cg,At,XS,qm,ZS,QS,ex,tx,kg,nx,Eg,rx,Ag,sx,ox,Qi,ix,Rg,kl,ax,Km,Gm,cx,fx,px,Me,Vi,Ym,zm,Jm,ss,os,qi,Ki,hx,yx,_x,bx,vx,wx,$g,Sx,xx,Mn,Nn,Tx,Cx,kx,Xm,Px,Ox,Og,Nl=Nt(()=>{"use strict";fl();fl();Ln=require("fs"),Qm=require("path");Fw=1e3,Hw=10,Vw=3e4,qw=3e4,Kw=class{url;ws=null;_status="disconnected";messageHandlers=new Set;statusHandlers=new Set;reconnectAttempt=0;reconnectTimer=null;pingTimer=null;stopped=!1;autoReconnect;reconnectInterval;maxReconnectAttempts;pingInterval;constructor(e){this.url=e.url,this.autoReconnect=e.autoReconnect??!0,this.reconnectInterval=e.reconnectInterval??Fw,this.maxReconnectAttempts=e.maxReconnectAttempts??Hw,this.pingInterval=e.pingInterval??Vw}get status(){return this._status}onMessage(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}onStatusChange(e){return this.statusHandlers.add(e),()=>this.statusHandlers.delete(e)}connect(){return this.stopped=!1,new Promise((e,t)=>{let n=jw();if(!n){t(new Pe('No WebSocket implementation available. Install the "ws" package for Node.js.'));return}this.setStatus("connecting");try{this.ws=new n(this.url)}catch(s){t(new Pe(`Failed to create WebSocket: ${s}`));return}let r=!1;this.ws.onopen=()=>{this.reconnectAttempt=0,this.setStatus("connected"),this.startPing(),r||(r=!0,e())},this.ws.onmessage=s=>{let o;try{o=JSON.parse(typeof s.data=="string"?s.data:s.data.toString())}catch{return}for(let i of this.messageHandlers)i(o)},this.ws.onclose=()=>{this.ws=null,this.stopPing(),!this.stopped&&this.autoReconnect?this.scheduleReconnect():this.setStatus("disconnected"),r||(r=!0,t(new Pe("WebSocket closed before connection established")))},this.ws.onerror=()=>{r||(r=!0,t(new Pe(`WebSocket connection failed: ${this.url}`)))}})}disconnect(){this.stopped=!0,this.clearReconnectTimer(),this.stopPing(),this.ws&&(this.ws.onclose=null,this.ws.onerror=null,this.ws.onmessage=null,this.ws.close(),this.ws=null),this.setStatus("disconnected")}send(e){if(!this.ws||this.ws.readyState!==1)throw new Pe("WebSocket is not connected");this.ws.send(JSON.stringify(e))}startPing(){this.stopPing(),this.pingInterval>0&&(this.pingTimer=setInterval(()=>{try{this.send({type:"ping"})}catch{}},this.pingInterval))}stopPing(){this.pingTimer!==null&&(clearInterval(this.pingTimer),this.pingTimer=null)}scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts){this.setStatus("disconnected");return}this.setStatus("reconnecting");let e=Bw(this.reconnectInterval*Math.pow(2,this.reconnectAttempt),this.reconnectInterval,qw);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(!this.stopped)try{await this.connect()}catch{}},e)}clearReconnectTimer(){this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}setStatus(e){if(this._status!==e){this._status=e;for(let t of this.statusHandlers)t(e)}}},eg=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:Yi,n:Gi,Gx:Am,Gy:Rm,a:ml,d:gl,h:Gw}=eg,ea=32,Ww=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},Ce=(e="")=>{let t=new Error(e);throw Ww(t,Ce),t},Yw=e=>typeof e=="bigint",zw=e=>typeof e=="string",Jw=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,en=(e,t,n="")=>{let r=Jw(e),s=e?.length,o=t!==void 0;if(!r||o&&s!==t){let i=n&&`"${n}" `,a=o?` of length ${t}`:"",c=r?`length=${s}`:`type=${typeof e}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):new TypeError(l)}return e},ta=e=>new Uint8Array(e),Al=e=>Uint8Array.from(e),tg=(e,t)=>e.toString(16).padStart(t,"0"),Rl=e=>Array.from(en(e)).map(t=>tg(t,2)).join(""),Jt={_0:48,_9:57,A:65,F:70,a:97,f:102},Im=e=>{if(e>=Jt._0&&e<=Jt._9)return e-Jt._0;if(e>=Jt.A&&e<=Jt.F)return e-(Jt.A-10);if(e>=Jt.a&&e<=Jt.f)return e-(Jt.a-10)},Il=e=>{let t="hex invalid";if(!zw(e))return Ce(t);let n=e.length,r=n/2;if(n%2)return Ce(t);let s=ta(r);for(let o=0,i=0;o<r;o++,i+=2){let a=Im(e.charCodeAt(i)),c=Im(e.charCodeAt(i+1));if(a===void 0||c===void 0)return Ce(t);s[o]=a*16+c}return s},ng=()=>globalThis?.crypto,Xw=()=>ng()?.subtle??Ce("crypto.subtle must be defined, consider polyfill"),is=(...e)=>{let t=0;for(let s of e)t+=en(s).length;let n=ta(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},Zw=(e=ea)=>ng().getRandomValues(ta(e)),zi=BigInt,_r=(e,t,n,r="bad number: out of range")=>{if(!Yw(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},se=(e,t=Yi)=>{let n=e%t;return n>=0n?n:t+n},$m=(1n<<255n)-1n,$=e=>{e<0n&&Ce("negative coordinate");let t=(e>>255n)*19n+(e&$m);return t=(t>>255n)*19n+(t&$m),t%Yi},rg=e=>se(e,Gi),sg=(e,t)=>{(e===0n||t<=0n)&&Ce("no inverse n="+e+" mod="+t);let n=se(e,t),r=t,s=0n,o=1n;for(;n!==0n;){let i=r/n,a=r%n,c=s-o*i;r=n,n=a,s=o,o=c}return r===1n?se(s,t):Ce("no inverse")},og=e=>{let t=ug[e];return typeof t!="function"&&Ce("hashes."+e+" not set"),t},ig=e=>en(e,64,"digest"),hl=e=>e instanceof lo?e:Ce("Point expected"),Sl=2n**256n,lo=class br{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=Sl;this.X=_r(t,0n,o),this.Y=_r(n,0n,o),this.Z=_r(r,1n,o),this.T=_r(s,0n,o),Object.freeze(this)}static CURVE(){return eg}static fromAffine(t){return new br(t.x,t.y,1n,$(t.x*t.y))}static fromBytes(t,n=!1){let r=gl,s=Al(en(t,ea)),o=t[31];s[31]=o&-129;let i=cg(s);_r(i,0n,n?Sl:Yi);let c=$(i*i),l=se(c-1n),u=$(r*c+1n),{isValid:d,value:p}=eS(l,u);d||Ce("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!n&&p===0n&&m&&Ce("bad point: x==0, isLastByteOdd"),m!==f&&(p=se(-p)),new br(p,i,1n,$(p*i))}static fromHex(t,n){return br.fromBytes(Il(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=ml,n=gl,r=this;if(r.is0())return Ce("bad point: ZERO");let{X:s,Y:o,Z:i,T:a}=r,c=$(s*s),l=$(o*o),u=$(i*i),d=$(u*u),p=$(c*t),f=$(u*(p+l)),m=se(d+$(n*$(c*l)));if(f!==m)return Ce("bad point: equation left != right (1)");let h=$(s*o),w=$(i*a);return h!==w?Ce("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=hl(t),c=$(n*a),l=$(o*s),u=$(r*a),d=$(i*s);return c===l&&u===d}is0(){return this.equals(xr)}negate(){return new br(se(-this.X),this.Y,this.Z,se(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=ml,o=$(t*t),i=$(n*n),a=$(2n*r*r),c=$(s*o),l=se(t+n),u=se($(l*l)-o-i),d=se(c+i),p=se(d-a),f=se(c-i),m=$(u*p),h=$(d*f),w=$(u*f),C=$(p*d);return new br(m,h,C,w)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=hl(t),u=ml,d=gl,p=$(n*i),f=$(r*a),m=$($(o*d)*l),h=$(s*c),w=se($(se(n+r)*se(i+a))-p-f),C=se(h-m),b=se(h+m),v=se(f-$(u*p)),S=$(w*C),A=$(b*v),I=$(w*v),y=$(C*b);return new br(S,A,y,I)}subtract(t){return this.add(hl(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(_r(t,1n,Gi),!n&&this.is0()))return xr;if(t===1n)return this;if(this.equals(Cr))return uS(t).p;let r=xr,s=Cr;for(let o=this;t>0n;o=o.double(),t>>=1n)t&1n?r=r.add(o):n&&(s=s.add(o));return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(this.equals(xr))return{x:0n,y:1n};let s=sg(r,Yi);$(r*s)!==1n&&Ce("invalid inverse");let o=$(t*s),i=$(n*s);return{x:o,y:i}}toBytes(){let{x:t,y:n}=this.toAffine(),r=ag(n);return r[31]|=t&1n?128:0,r}toHex(){return Rl(this.toBytes())}clearCofactor(){return this.multiply(zi(Gw),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Gi/2n,!1).double();return Gi%2n&&(t=t.add(this)),t.is0()}},Cr=new lo(Am,Rm,1n,se(Am*Rm)),xr=new lo(0n,1n,1n,0n);lo.BASE=Cr;lo.ZERO=xr;ag=e=>Il(tg(_r(e,0n,Sl),64)).reverse(),cg=e=>zi("0x"+Rl(Al(en(e)).reverse())),kt=(e,t)=>{let n=e;for(;t-- >0n;)n=$(n*n);return n},Qw=e=>{let t=$(e*e),n=$(t*e),r=$(kt(n,2n)*n),s=$(kt(r,1n)*e),o=$(kt(s,5n)*s),i=$(kt(o,10n)*o),a=$(kt(i,20n)*i),c=$(kt(a,40n)*a),l=$(kt(c,80n)*c),u=$(kt(l,80n)*c),d=$(kt(u,10n)*o);return{pow_p_5_8:$(kt(d,2n)*e),b2:n}},Pm=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,eS=(e,t)=>{let n=$(t*$(t*t)),r=$($(n*n)*t),s=Qw($(e*r)).pow_p_5_8,o=$(e*$(n*s)),i=$(t*$(o*o)),a=o,c=$(o*Pm),l=i===e,u=i===se(-e),d=i===se(-e*Pm);return l&&(o=a),(u||d)&&(o=c),(se(o)&1n)===1n&&(o=se(-o)),{isValid:l||u,value:o}},xl=e=>rg(cg(e)),$l=(...e)=>Promise.resolve(og("sha512Async")(is(...e))).then(ig),tS=(...e)=>ig(og("sha512")(is(...e))),lg=e=>{let t=Al(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=xl(n),o=Cr.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},nS=e=>$l(en(e,ea)).then(lg),rS=e=>lg(tS(en(e,ea))),sS=e=>rS(e).pointBytes,oS=e=>$l(e.hashable).then(e.finish),iS=(e,t,n)=>{let{pointBytes:r,scalar:s}=e,o=xl(t),i=Cr.multiply(o).toBytes();return{hashable:is(i,r,n),finish:l=>{let u=rg(o+xl(l)*s);return en(is(i,ag(u)),64)}}},aS=async(e,t)=>{let n=en(e),r=await nS(t),s=await $l(r.prefix,n);return oS(iS(r,s,n))},Pl=Object.freeze({bytesToHex:Rl,hexToBytes:Il,concatBytes:is,mod:se,invert:sg,randomBytes:Zw}),ug={sha512Async:async e=>{let t=Xw(),n=is(e);return ta(await t.digest("SHA-512",n.buffer))},sha512:void 0},Ji=8,cS=256,dg=Math.ceil(cS/Ji)+1,Tl=2**(Ji-1),lS=()=>{let e=[],t=Cr,n=t;for(let r=0;r<dg;r++){n=t,e.push(n);for(let s=1;s<Tl;s++)n=n.add(t),e.push(n);t=n.double()}return e},Om=void 0,Mm=(e,t)=>{let n=t.negate();return e?n:t},uS=e=>{let t=Om||(Om=lS()),n=xr,r=Cr,s=2**Ji,o=s,i=zi(s-1),a=zi(Ji);for(let c=0;c<dg;c++){let l=Number(e&i);e>>=a,l>Tl&&(l-=o,e+=1n);let u=c*Tl,d=u,p=u+Math.abs(l)-1,f=c%2!==0,m=l<0;l===0?r=r.add(Mm(f,t[d])):n=n.add(Mm(m,t[p]))}return e!==0n&&Ce("invalid wnaf"),{p:n,f:r}};mg=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});gg=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=yl(this.buffer)}update(e){Nm(this),fg(e);let{view:t,buffer:n,blockLen:r}=this,s=e.length;for(let o=0;o<s;){let i=Math.min(r-this.pos,s-o);if(i===r){let a=yl(e);for(;r<=s-o;o+=r)this.process(a,o);continue}n.set(e.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Nm(this),fS(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,co(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let u=o;u<r;u++)t[u]=0;n.setBigUint64(r-8,BigInt(this.length*8),s),this.process(n,0);let i=yl(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<c;u++)i.setUint32(4*u,l[u],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:s,destroyed:o,pos:i}=this;return e.destroyed=o,e.finished=s,e.length=r,e.pos=i,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},In=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Oe=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Bi=BigInt(2**32-1),Lm=BigInt(32);Um=(e,t,n)=>e>>>n,Dm=(e,t,n)=>e<<32-n|t>>>n,ns=(e,t,n)=>e>>>n|t<<32-n,rs=(e,t,n)=>e<<32-n|t>>>n,Fi=(e,t,n)=>e<<64-n|t>>>n-32,Hi=(e,t,n)=>e>>>n-32|t<<64-n;yS=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),_S=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,bS=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),vS=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,wS=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),SS=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,xS=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]),$n=new Uint32Array(64),TS=class extends gg{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:r,E:s,F:o,G:i,H:a}=this;return[e,t,n,r,s,o,i,a]}set(e,t,n,r,s,o,i,a){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=s|0,this.F=o|0,this.G=i|0,this.H=a|0}process(e,t){for(let u=0;u<16;u++,t+=4)$n[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let d=$n[u-15],p=$n[u-2],f=Et(d,7)^Et(d,18)^d>>>3,m=Et(p,17)^Et(p,19)^p>>>10;$n[u]=m+$n[u-7]+f+$n[u-16]|0}let{A:n,B:r,C:s,D:o,E:i,F:a,G:c,H:l}=this;for(let u=0;u<64;u++){let d=Et(i,6)^Et(i,11)^Et(i,25),p=l+d+pS(i,a,c)+xS[u]+$n[u]|0,m=(Et(n,2)^Et(n,13)^Et(n,22))+mS(n,r,s)|0;l=c,c=a,a=i,i=o+p|0,o=s,s=r,r=n,n=p+m|0}n=n+this.A|0,r=r+this.B|0,s=s+this.C|0,o=o+this.D|0,i=i+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,s,o,i,a,c,l)}roundClean(){co($n)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),co(this.buffer)}},CS=class extends TS{A=In[0]|0;B=In[1]|0;C=In[2]|0;D=In[3]|0;E=In[4]|0;F=In[5]|0;G=In[6]|0;H=In[7]|0;constructor(){super(32)}},hg=hS(["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(e=>BigInt(e))),kS=hg[0],ES=hg[1],Pn=new Uint32Array(80),On=new Uint32Array(80),AS=class extends gg{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:s,Cl:o,Dh:i,Dl:a,Eh:c,El:l,Fh:u,Fl:d,Gh:p,Gl:f,Hh:m,Hl:h}=this;return[e,t,n,r,s,o,i,a,c,l,u,d,p,f,m,h]}set(e,t,n,r,s,o,i,a,c,l,u,d,p,f,m,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=s|0,this.Cl=o|0,this.Dh=i|0,this.Dl=a|0,this.Eh=c|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=p|0,this.Gl=f|0,this.Hh=m|0,this.Hl=h|0}process(e,t){for(let b=0;b<16;b++,t+=4)Pn[b]=e.getUint32(t),On[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let v=Pn[b-15]|0,S=On[b-15]|0,A=ns(v,S,1)^ns(v,S,8)^Um(v,S,7),I=rs(v,S,1)^rs(v,S,8)^Dm(v,S,7),y=Pn[b-2]|0,T=On[b-2]|0,Y=ns(y,T,19)^Fi(y,T,61)^Um(y,T,6),X=rs(y,T,19)^Hi(y,T,61)^Dm(y,T,6),H=bS(I,X,On[b-7],On[b-16]),_e=vS(H,A,Y,Pn[b-7],Pn[b-16]);Pn[b]=_e|0,On[b]=H|0}let{Ah:n,Al:r,Bh:s,Bl:o,Ch:i,Cl:a,Dh:c,Dl:l,Eh:u,El:d,Fh:p,Fl:f,Gh:m,Gl:h,Hh:w,Hl:C}=this;for(let b=0;b<80;b++){let v=ns(u,d,14)^ns(u,d,18)^Fi(u,d,41),S=rs(u,d,14)^rs(u,d,18)^Hi(u,d,41),A=u&p^~u&m,I=d&f^~d&h,y=wS(C,S,I,ES[b],On[b]),T=SS(y,w,v,A,kS[b],Pn[b]),Y=y|0,X=ns(n,r,28)^Fi(n,r,34)^Fi(n,r,39),H=rs(n,r,28)^Hi(n,r,34)^Hi(n,r,39),_e=n&s^n&i^s&i,re=r&o^r&a^o&a;w=m|0,C=h|0,m=p|0,h=f|0,p=u|0,f=d|0,{h:u,l:d}=Xt(c|0,l|0,T|0,Y|0),c=i|0,l=a|0,i=s|0,a=o|0,s=n|0,o=r|0;let J=yS(Y,H,re);n=_S(J,T,X,_e),r=J|0}({h:n,l:r}=Xt(this.Ah|0,this.Al|0,n|0,r|0)),{h:s,l:o}=Xt(this.Bh|0,this.Bl|0,s|0,o|0),{h:i,l:a}=Xt(this.Ch|0,this.Cl|0,i|0,a|0),{h:c,l}=Xt(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=Xt(this.Eh|0,this.El|0,u|0,d|0),{h:p,l:f}=Xt(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=Xt(this.Gh|0,this.Gl|0,m|0,h|0),{h:w,l:C}=Xt(this.Hh|0,this.Hl|0,w|0,C|0),this.set(n,r,s,o,i,a,c,l,u,d,p,f,m,h,w,C)}roundClean(){co(Pn,On)}destroy(){this.destroyed=!0,co(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},RS=class extends AS{Ah=Oe[0]|0;Al=Oe[1]|0;Bh=Oe[2]|0;Bl=Oe[3]|0;Ch=Oe[4]|0;Cl=Oe[5]|0;Dh=Oe[6]|0;Dl=Oe[7]|0;Eh=Oe[8]|0;El=Oe[9]|0;Fh=Oe[10]|0;Fl=Oe[11]|0;Gh=Oe[12]|0;Gl=Oe[13]|0;Hh=Oe[14]|0;Hl=Oe[15]|0;constructor(){super(64)}},IS=pg(()=>new CS,mg(1)),$S=pg(()=>new RS,mg(3)),jm=ug;jm.sha512||(jm.sha512=e=>$S(e));MS=Pl.bytesToHex,yg=Pl.hexToBytes;Pl.concatBytes;LS=new TextEncoder,US={subwayAgentMsgV1:"message_id;sender_peer_id;sender_name;timestamp_ms;message_type;payload_hash;nonce"};yg("302e020100300506032b657004220420");yg("302a300506032b6570032100");_g=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:Xi,n:Wi,Gx:Bm,Gy:Fm,a:_l,d:bl,h:FS}=_g,as=32,HS=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},ke=(e="")=>{let t=new Error(e);throw HS(t,ke),t},VS=e=>typeof e=="bigint",qS=e=>typeof e=="string",KS=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,Un=(e,t,n="")=>{let r=KS(e),s=e?.length,o=t!==void 0;if(!r||o&&s!==t){let i=n&&`"${n}" `,a=o?` of length ${t}`:"",c=r?`length=${s}`:`type=${typeof e}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):new TypeError(l)}return e},na=e=>new Uint8Array(e),Ol=e=>Uint8Array.from(e),bg=(e,t)=>e.toString(16).padStart(t,"0"),vg=e=>Array.from(Un(e)).map(t=>bg(t,2)).join(""),Zt={_0:48,_9:57,A:65,F:70,a:97,f:102},Hm=e=>{if(e>=Zt._0&&e<=Zt._9)return e-Zt._0;if(e>=Zt.A&&e<=Zt.F)return e-(Zt.A-10);if(e>=Zt.a&&e<=Zt.f)return e-(Zt.a-10)},wg=e=>{let t="hex invalid";if(!qS(e))return ke(t);let n=e.length,r=n/2;if(n%2)return ke(t);let s=na(r);for(let o=0,i=0;o<r;o++,i+=2){let a=Hm(e.charCodeAt(i)),c=Hm(e.charCodeAt(i+1));if(a===void 0||c===void 0)return ke(t);s[o]=a*16+c}return s},Sg=()=>globalThis?.crypto,GS=()=>Sg()?.subtle??ke("crypto.subtle must be defined, consider polyfill"),Ml=(...e)=>{let t=0;for(let s of e)t+=Un(s).length;let n=na(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},WS=(e=as)=>Sg().getRandomValues(na(e)),Zi=BigInt,vr=(e,t,n,r="bad number: out of range")=>{if(!VS(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},ie=(e,t=Xi)=>{let n=e%t;return n>=0n?n:t+n},Vm=(1n<<255n)-1n,P=e=>{e<0n&&ke("negative coordinate");let t=(e>>255n)*19n+(e&Vm);return t=(t>>255n)*19n+(t&Vm),t%Xi},YS=e=>ie(e,Wi),zS=(e,t)=>{(e===0n||t<=0n)&&ke("no inverse n="+e+" mod="+t);let n=ie(e,t),r=t,s=0n,o=1n;for(;n!==0n;){let i=r/n,a=r%n,c=s-o*i;r=n,n=a,s=o,o=c}return r===1n?ie(s,t):ke("no inverse")},xg=e=>{let t=Ag[e];return typeof t!="function"&&ke("hashes."+e+" not set"),t},Tg=e=>Un(e,64,"digest"),vl=e=>e instanceof uo?e:ke("Point expected"),Cl=2n**256n,uo=class wr{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=Cl;this.X=vr(t,0n,o),this.Y=vr(n,0n,o),this.Z=vr(r,1n,o),this.T=vr(s,0n,o),Object.freeze(this)}static CURVE(){return _g}static fromAffine(t){return new wr(t.x,t.y,1n,P(t.x*t.y))}static fromBytes(t,n=!1){let r=bl,s=Ol(Un(t,as)),o=t[31];s[31]=o&-129;let i=Cg(s);vr(i,0n,n?Cl:Xi);let c=P(i*i),l=ie(c-1n),u=P(r*c+1n),{isValid:d,value:p}=ZS(l,u);d||ke("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!n&&p===0n&&m&&ke("bad point: x==0, isLastByteOdd"),m!==f&&(p=ie(-p)),new wr(p,i,1n,P(p*i))}static fromHex(t,n){return wr.fromBytes(wg(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=_l,n=bl,r=this;if(r.is0())return ke("bad point: ZERO");let{X:s,Y:o,Z:i,T:a}=r,c=P(s*s),l=P(o*o),u=P(i*i),d=P(u*u),p=P(c*t),f=P(u*(p+l)),m=ie(d+P(n*P(c*l)));if(f!==m)return ke("bad point: equation left != right (1)");let h=P(s*o),w=P(i*a);return h!==w?ke("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=vl(t),c=P(n*a),l=P(o*s),u=P(r*a),d=P(i*s);return c===l&&u===d}is0(){return this.equals(Tr)}negate(){return new wr(ie(-this.X),this.Y,this.Z,ie(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=_l,o=P(t*t),i=P(n*n),a=P(2n*r*r),c=P(s*o),l=ie(t+n),u=ie(P(l*l)-o-i),d=ie(c+i),p=ie(d-a),f=ie(c-i),m=P(u*p),h=P(d*f),w=P(u*f),C=P(p*d);return new wr(m,h,C,w)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=vl(t),u=_l,d=bl,p=P(n*i),f=P(r*a),m=P(P(o*d)*l),h=P(s*c),w=ie(P(ie(n+r)*ie(i+a))-p-f),C=ie(h-m),b=ie(h+m),v=ie(f-P(u*p)),S=P(w*C),A=P(b*v),I=P(w*v),y=P(C*b);return new wr(S,A,y,I)}subtract(t){return this.add(vl(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(vr(t,1n,Wi),!n&&this.is0()))return Tr;if(t===1n)return this;if(this.equals(cs))return cx(t).p;let r=Tr,s=cs;for(let o=this;t>0n;o=o.double(),t>>=1n)t&1n?r=r.add(o):n&&(s=s.add(o));return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(this.equals(Tr))return{x:0n,y:1n};let s=zS(r,Xi);P(r*s)!==1n&&ke("invalid inverse");let o=P(t*s),i=P(n*s);return{x:o,y:i}}toBytes(){let{x:t,y:n}=this.toAffine(),r=JS(n);return r[31]|=t&1n?128:0,r}toHex(){return vg(this.toBytes())}clearCofactor(){return this.multiply(Zi(FS),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Wi/2n,!1).double();return Wi%2n&&(t=t.add(this)),t.is0()}},cs=new uo(Bm,Fm,1n,ie(Bm*Fm)),Tr=new uo(0n,1n,1n,0n);uo.BASE=cs;uo.ZERO=Tr;JS=e=>wg(bg(vr(e,0n,Cl),64)).reverse(),Cg=e=>Zi("0x"+vg(Ol(Un(e)).reverse())),At=(e,t)=>{let n=e;for(;t-- >0n;)n=P(n*n);return n},XS=e=>{let t=P(e*e),n=P(t*e),r=P(At(n,2n)*n),s=P(At(r,1n)*e),o=P(At(s,5n)*s),i=P(At(o,10n)*o),a=P(At(i,20n)*i),c=P(At(a,40n)*a),l=P(At(c,80n)*c),u=P(At(l,80n)*c),d=P(At(u,10n)*o);return{pow_p_5_8:P(At(d,2n)*e),b2:n}},qm=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,ZS=(e,t)=>{let n=P(t*P(t*t)),r=P(P(n*n)*t),s=XS(P(e*r)).pow_p_5_8,o=P(e*P(n*s)),i=P(t*P(o*o)),a=o,c=P(o*qm),l=i===e,u=i===ie(-e),d=i===ie(-e*qm);return l&&(o=a),(u||d)&&(o=c),(ie(o)&1n)===1n&&(o=ie(-o)),{isValid:l||u,value:o}},QS=e=>YS(Cg(e)),ex=(...e)=>Promise.resolve(xg("sha512Async")(Ml(...e))).then(Tg),tx=(...e)=>Tg(xg("sha512")(Ml(...e))),kg=e=>{let t=Ol(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=QS(n),o=cs.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},nx=e=>ex(Un(e,as)).then(kg),Eg=e=>kg(tx(Un(e,as))),rx=e=>Eg(e).pointBytes,Ag={sha512Async:async e=>{let t=GS(),n=Ml(e);return na(await t.digest("SHA-512",n.buffer))},sha512:void 0},sx=e=>(e=e===void 0?WS(as):e,Un(e,as)),ox=Object.freeze({getExtendedPublicKeyAsync:nx,getExtendedPublicKey:Eg,randomSecretKey:sx}),Qi=8,ix=256,Rg=Math.ceil(ix/Qi)+1,kl=2**(Qi-1),ax=()=>{let e=[],t=cs,n=t;for(let r=0;r<Rg;r++){n=t,e.push(n);for(let s=1;s<kl;s++)n=n.add(t),e.push(n);t=n.double()}return e},Km=void 0,Gm=(e,t)=>{let n=t.negate();return e?n:t},cx=e=>{let t=Km||(Km=ax()),n=Tr,r=cs,s=2**Qi,o=s,i=Zi(s-1),a=Zi(Qi);for(let c=0;c<Rg;c++){let l=Number(e&i);e>>=a,l>kl&&(l-=o,e+=1n);let u=c*kl,d=u,p=u+Math.abs(l)-1,f=c%2!==0,m=l<0;l===0?r=r.add(Gm(f,t[d])):n=n.add(Gm(m,t[p]))}return e!==0n&&ke("invalid wnaf"),{p:n,f:r}};fx=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),px=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=wl(this.buffer)}update(e){Wm(this),Ig(e);let{view:t,buffer:n,blockLen:r}=this,s=e.length;for(let o=0;o<s;){let i=Math.min(r-this.pos,s-o);if(i===r){let a=wl(e);for(;r<=s-o;o+=r)this.process(a,o);continue}n.set(e.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Wm(this),ux(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,El(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let u=o;u<r;u++)t[u]=0;n.setBigUint64(r-8,BigInt(this.length*8),s),this.process(n,0);let i=wl(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<c;u++)i.setUint32(4*u,l[u],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:s,destroyed:o,pos:i}=this;return e.destroyed=o,e.finished=s,e.length=r,e.pos=i,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Me=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Vi=BigInt(2**32-1),Ym=BigInt(32);zm=(e,t,n)=>e>>>n,Jm=(e,t,n)=>e<<32-n|t>>>n,ss=(e,t,n)=>e>>>n|t<<32-n,os=(e,t,n)=>e<<32-n|t>>>n,qi=(e,t,n)=>e<<64-n|t>>>n-32,Ki=(e,t,n)=>e>>>n-32|t<<64-n;hx=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),yx=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,_x=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),bx=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,vx=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),wx=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,$g=gx(["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(e=>BigInt(e))),Sx=$g[0],xx=$g[1],Mn=new Uint32Array(80),Nn=new Uint32Array(80),Tx=class extends px{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:s,Cl:o,Dh:i,Dl:a,Eh:c,El:l,Fh:u,Fl:d,Gh:p,Gl:f,Hh:m,Hl:h}=this;return[e,t,n,r,s,o,i,a,c,l,u,d,p,f,m,h]}set(e,t,n,r,s,o,i,a,c,l,u,d,p,f,m,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=s|0,this.Cl=o|0,this.Dh=i|0,this.Dl=a|0,this.Eh=c|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=p|0,this.Gl=f|0,this.Hh=m|0,this.Hl=h|0}process(e,t){for(let b=0;b<16;b++,t+=4)Mn[b]=e.getUint32(t),Nn[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let v=Mn[b-15]|0,S=Nn[b-15]|0,A=ss(v,S,1)^ss(v,S,8)^zm(v,S,7),I=os(v,S,1)^os(v,S,8)^Jm(v,S,7),y=Mn[b-2]|0,T=Nn[b-2]|0,Y=ss(y,T,19)^qi(y,T,61)^zm(y,T,6),X=os(y,T,19)^Ki(y,T,61)^Jm(y,T,6),H=_x(I,X,Nn[b-7],Nn[b-16]),_e=bx(H,A,Y,Mn[b-7],Mn[b-16]);Mn[b]=_e|0,Nn[b]=H|0}let{Ah:n,Al:r,Bh:s,Bl:o,Ch:i,Cl:a,Dh:c,Dl:l,Eh:u,El:d,Fh:p,Fl:f,Gh:m,Gl:h,Hh:w,Hl:C}=this;for(let b=0;b<80;b++){let v=ss(u,d,14)^ss(u,d,18)^qi(u,d,41),S=os(u,d,14)^os(u,d,18)^Ki(u,d,41),A=u&p^~u&m,I=d&f^~d&h,y=vx(C,S,I,xx[b],Nn[b]),T=wx(y,w,v,A,Sx[b],Mn[b]),Y=y|0,X=ss(n,r,28)^qi(n,r,34)^qi(n,r,39),H=os(n,r,28)^Ki(n,r,34)^Ki(n,r,39),_e=n&s^n&i^s&i,re=r&o^r&a^o&a;w=m|0,C=h|0,m=p|0,h=f|0,p=u|0,f=d|0,{h:u,l:d}=Qt(c|0,l|0,T|0,Y|0),c=i|0,l=a|0,i=s|0,a=o|0,s=n|0,o=r|0;let J=hx(Y,H,re);n=yx(J,T,X,_e),r=J|0}({h:n,l:r}=Qt(this.Ah|0,this.Al|0,n|0,r|0)),{h:s,l:o}=Qt(this.Bh|0,this.Bl|0,s|0,o|0),{h:i,l:a}=Qt(this.Ch|0,this.Cl|0,i|0,a|0),{h:c,l}=Qt(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=Qt(this.Eh|0,this.El|0,u|0,d|0),{h:p,l:f}=Qt(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=Qt(this.Gh|0,this.Gl|0,m|0,h|0),{h:w,l:C}=Qt(this.Hh|0,this.Hl|0,w|0,C|0),this.set(n,r,s,o,i,a,c,l,u,d,p,f,m,h,w,C)}roundClean(){El(Mn,Nn)}destroy(){this.destroyed=!0,El(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Cx=class extends Tx{Ah=Me[0]|0;Al=Me[1]|0;Bh=Me[2]|0;Bl=Me[3]|0;Ch=Me[4]|0;Cl=Me[5]|0;Dh=Me[6]|0;Dl=Me[7]|0;Eh=Me[8]|0;El=Me[9]|0;Fh=Me[10]|0;Fl=Me[11]|0;Gh=Me[12]|0;Gl=Me[13]|0;Hh=Me[14]|0;Hl=Me[15]|0;constructor(){super(64)}},kx=dx(()=>new Cx,fx(3)),Xm=Ag;Xm.sha512||(Xm.sha512=e=>kx(e));Px="ws://localhost:9001/ws",Ox=3e4,Og=class{transport;options;_peerId=null;_name;_keypair=null;messageHandlers=new Set;topicHandlers=new Map;rpcHandlers=new Map;defaultRpcHandler=null;pendingCalls=new Map;pendingSend=new Map;pendingResolve=new Map;eventListeners=new Map;registerPromise=null;hasConnectedOnce=!1;constructor(e){if(this._name=Sr(e.name),e.keyPath)try{this._keypair=Ix(e.keyPath)}catch{}this.options={name:this._name,url:e.url??Px,relay:e.relay??"",autoReconnect:e.autoReconnect??!0,reconnectInterval:e.reconnectInterval??1e3,maxReconnectAttempts:e.maxReconnectAttempts??10,rpcTimeout:e.rpcTimeout??Ox,pingInterval:e.pingInterval??3e4},this.transport=new Kw({url:this.options.url,autoReconnect:this.options.autoReconnect,reconnectInterval:this.options.reconnectInterval,maxReconnectAttempts:this.options.maxReconnectAttempts,pingInterval:this.options.pingInterval}),this.transport.onMessage(t=>this.handleBridgeMessage(t)),this.transport.onStatusChange(t=>this.handleStatusChange(t))}initKeypairFromSecret(e){try{let t=Buffer.from(e,"base64"),n=BS(new Uint8Array(t));n&&(this._keypair={privateKey:n,publicKey:PS(n)})}catch{}}get name(){return this._name}get peerId(){return this._peerId}get status(){return this.transport.status}async connect(){return await this.transport.connect(),new Promise((e,t)=>{this.registerPromise={resolve:e,reject:t};let n={type:"register",name:this._name};this.options.relay&&(n.relay=this.options.relay),this._keypair&&(n.public_key=Zm(this._keypair.publicKey));try{this.transport.send(n)}catch(r){this.registerPromise=null,t(r instanceof Error?r:new Pe(String(r)))}})}disconnect(){for(let[,e]of this.pendingCalls)clearTimeout(e.timer),e.reject(new Pe("Client disconnected"));this.pendingCalls.clear();for(let[,e]of this.pendingSend)e.reject(new Pe("Client disconnected"));this.pendingSend.clear();for(let[,e]of this.pendingResolve)e.reject(new Pe("Client disconnected"));this.pendingResolve.clear(),this.registerPromise&&(this.registerPromise.reject(new Pe("Client disconnected")),this.registerPromise=null),this.transport.disconnect(),this._peerId=null,this.hasConnectedOnce=!1}async send(e,t,n,r){let s=Sr(e),o=pl();return new Promise((i,a)=>{this.pendingSend.set(s,{resolve:i,reject:a});try{this.transport.send({type:"send",to:s,message_type:t,payload:n,metadata:r})}catch(c){this.pendingSend.delete(s),a(c instanceof Error?c:new Pe(String(c)))}setTimeout(()=>{this.pendingSend.has(s)&&(this.pendingSend.delete(s),i({messageId:o,to:s}))},5e3)})}async sendSigned(e,t,n,r){if(!this._keypair||!this._peerId)return this.send(e,t,n,r);let s=Sr(e),o=pl(),i=Date.now(),a=Math.floor(Math.random()*2**32),c=new TextEncoder().encode(n),{signature:l,signatureInput:u}=await $x(this._keypair.privateKey,o,this._peerId,this._name,i,t,c,a);return new Promise((d,p)=>{this.pendingSend.set(s,{resolve:d,reject:p});try{this.transport.send({type:"send_signed",to:s,message_id:o,sender_peer_id:this._peerId,sender_name:this._name,timestamp_ms:i,message_type:t,payload:n,metadata:r,signature:Buffer.from(l).toString("base64"),signature_input:u,nonce:a})}catch(f){this.pendingSend.delete(s),p(f instanceof Error?f:new Pe(String(f)))}setTimeout(()=>{this.pendingSend.has(s)&&(this.pendingSend.delete(s),d({messageId:o,to:s}))},5e3)})}async call(e,t,n,r){let s=Sr(e),o=r?.correlationId??pl(),i=r?.timeout??this.options.rpcTimeout;return new Promise((a,c)=>{let l=setTimeout(()=>{this.pendingCalls.delete(o),c(new ao(`RPC call to ${s}.${t} timed out after ${i}ms`))},i);this.pendingCalls.set(o,{resolve:a,reject:c,timer:l});try{this.transport.send({type:"call",to:s,method:t,payload:n??"",correlation_id:o})}catch(u){clearTimeout(l),this.pendingCalls.delete(o),c(u instanceof Error?u:new Pe(String(u)))}})}async broadcast(e,t,n){this.transport.send({type:"broadcast",topic:e,message_type:t,payload:n})}subscribe(e,t){let n=this.topicHandlers.get(e);if(!n){n=new Set,this.topicHandlers.set(e,n);try{this.transport.send({type:"subscribe",topic:e})}catch{}}return n.add(t),()=>{n.delete(t),n.size===0&&this.topicHandlers.delete(e)}}onMessage(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}onCall(e,t){return this.rpcHandlers.set(e,t),()=>this.rpcHandlers.delete(e)}onAnyCall(e){return this.defaultRpcHandler=e,()=>{this.defaultRpcHandler=null}}async resolve(e){let t=Sr(e);return new Promise((n,r)=>{this.pendingResolve.set(t,{resolve:n,reject:r});try{this.transport.send({type:"resolve",name:t})}catch(s){this.pendingResolve.delete(t),r(s instanceof Error?s:new Pe(String(s)))}setTimeout(()=>{this.pendingResolve.has(t)&&(this.pendingResolve.delete(t),r(new ao(`Resolve ${t} timed out`)))},1e4)})}on(e,t){let n=this.eventListeners.get(e);return n||(n=new Set,this.eventListeners.set(e,n)),n.add(t),()=>n.delete(t)}off(e,t){let n=this.eventListeners.get(e);n&&n.delete(t)}emit(e,...t){let n=this.eventListeners.get(e);if(n)for(let r of n)try{r(...t)}catch{}}handleBridgeMessage(e){switch(e.type){case"registered":this._peerId=e.peer_id,this._name=e.name,e.secret_key&&!this._keypair&&this.initKeypairFromSecret(e.secret_key),this.hasConnectedOnce=!0,this.registerPromise&&(this.registerPromise.resolve(),this.registerPromise=null),this.emit("connected",{name:e.name,peerId:e.peer_id}),this.resubscribeTopics();break;case"sent":{let t=this.pendingSend.get(e.to);t&&(this.pendingSend.delete(e.to),t.resolve({messageId:e.message_id,to:e.to}));break}case"call_result":{let t=this.pendingCalls.get(e.correlation_id);t&&(clearTimeout(t.timer),this.pendingCalls.delete(e.correlation_id),t.resolve({correlationId:e.correlation_id,success:e.success,payload:e.payload,error:e.error}));break}case"message":{let t={fromName:e.from_name,fromPeerId:e.from_peer_id,messageId:e.message_id,messageType:e.message_type,payload:e.payload,metadata:e.metadata??{},timestampMs:e.timestamp_ms,verified:e.verified,provenance:e.provenance?.map(n=>({signerName:n.signer_name,verified:n.verified})),attestation:e.attestation?{relayName:e.attestation.relay_name,verified:e.attestation.verified}:void 0,delegation:e.delegation?{parentName:e.delegation.parent_name,scope:e.delegation.scope,valid:e.delegation.valid,expired:e.delegation.expired}:void 0};for(let n of this.messageHandlers)try{n(t)}catch{}this.emit("message",t);break}case"inbound_call":this.handleInboundCall(e);break;case"broadcast_message":{let t={topic:e.topic,fromName:e.from_name,fromPeerId:e.from_peer_id,messageId:e.message_id,messageType:e.message_type,payload:e.payload,metadata:e.metadata??{},timestampMs:e.timestamp_ms,verified:e.verified,provenance:e.provenance?.map(r=>({signerName:r.signer_name,verified:r.verified})),attestation:e.attestation?{relayName:e.attestation.relay_name,verified:e.attestation.verified}:void 0,delegation:e.delegation?{parentName:e.delegation.parent_name,scope:e.delegation.scope,valid:e.delegation.valid,expired:e.delegation.expired}:void 0},n=this.topicHandlers.get(e.topic);if(n)for(let r of n)try{r(t)}catch{}this.emit("broadcast",t);break}case"resolved":{let t=this.pendingResolve.get(e.name);t&&(this.pendingResolve.delete(e.name),t.resolve({name:e.name,peerId:e.peer_id}));break}case"error":{let t=dl(e.code,e.message);this.registerPromise&&e.code==="register_failed"&&(this.registerPromise.reject(new ji(e.message)),this.registerPromise=null),this.emit("error",t);break}}}async handleInboundCall(e){let t={correlationId:e.correlation_id,fromName:e.from_name,fromPeerId:e.from_peer_id,method:e.method,payload:e.payload,verified:e.verified},n=this.rpcHandlers.get(e.method)??this.defaultRpcHandler,r;if(!n)r={success:!1,error:`No handler for method: ${e.method}`};else try{r=await n(t)}catch(s){r={success:!1,error:s instanceof Error?s.message:String(s)}}try{this.transport.send({type:"call_response",correlation_id:e.correlation_id,success:r.success,payload:r.payload??"",error:r.error??""})}catch{}}handleStatusChange(e){switch(e){case"disconnected":this._peerId=null,this.emit("disconnected");break;case"reconnecting":this.emit("reconnecting",this.transport.reconnectAttempt??0);break;case"connected":if(this.hasConnectedOnce){let t={type:"register",name:this.options.name};this.options.relay&&(t.relay=this.options.relay),this._keypair&&(t.public_key=Zm(this._keypair.publicKey));try{this.transport.send(t)}catch{}}break}}resubscribeTopics(){for(let e of this.topicHandlers.keys())try{this.transport.send({type:"subscribe",topic:e})}catch{}}};});function Qx(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function oh(e,t,n=""){let r=Qx(e),s=e?.length,o=t!==void 0;if(!r||o&&s!==t){let i=n&&`"${n}" `,a=o?` of length ${t}`:"",c=r?`length=${s}`:`type=${typeof e}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):new TypeError(l)}return e}function Fg(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function eT(e,t){oh(e,void 0,"digestInto() output");let n=t.outputLen;if(e.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function Vl(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function jl(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function tT(e,t={}){let n=(s,o)=>e(o).update(s).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=s=>e(s),Object.assign(n,t),Object.freeze(n)}function sT(e,t=!1){return t?{h:Number(e&ra),l:Number(e>>Hg&ra)}:{h:Number(e>>Hg&ra)|0,l:Number(e&ra)|0}}function oT(e,t=!1){let n=e.length,r=new Uint32Array(n),s=new Uint32Array(n);for(let o=0;o<n;o++){let{h:i,l:a}=sT(e[o],t);[r[o],s[o]]=[i,a]}return[r,s]}function nn(e,t,n,r){let s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}function yT(){return zx.randomSecretKey()}function da(e){return qx(e)}function ah(){let e=yT();return{secretKey:e,publicKey:da(e)}}function po(e,t){return Wx(t,e)}function _T(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function bT(e){let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function ps(e){return _T(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function vT(e){let t=e.length%4===0?0:4-e.length%4,n=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return bT(n)}function wT(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function lh(e){let t=da(e);return{kty:"OKP",crv:"Ed25519",x:ps(t),d:ps(e)}}function uh(e){return{kty:"OKP",crv:"Ed25519",x:ps(e)}}function mo(e){if(wT(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return vT(e.d)}var Gg,aa,ia,Mg,Ng,Ll,Ul,Mx,ds,Nx,Ee,Lx,Ux,Dx,It,ua,ql,Wg,Kl,tn,Lg,Gl,Yg,jx,fs,zg,ca,kr,oe,Ug,O,Jg,Xg,Zg,Qg,Dl,Bl,fo,Rr,Ar,eh,th,Rt,Bx,Dg,Fx,Fl,Hx,Wl,nh,Vx,Yl,qx,Kx,Gx,Wx,zl,rh,Yx,zx,la,Jx,sh,Hl,Xx,jg,Bg,Zx,nT,rT,Ne,ra,Hg,Vg,qg,ls,us,sa,oa,iT,aT,cT,lT,uT,dT,ih,fT,pT,Dn,jn,mT,gT,hT,Kg,MI,ch,NI,LI,UI,DI,fa=Nt(()=>{"use strict";Gg=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:aa,n:ia,Gx:Mg,Gy:Ng,a:Ll,d:Ul,h:Mx}=Gg,ds=32,Nx=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},Ee=(e="")=>{let t=new Error(e);throw Nx(t,Ee),t},Lx=e=>typeof e=="bigint",Ux=e=>typeof e=="string",Dx=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,It=(e,t,n="")=>{let r=Dx(e),s=e?.length,o=t!==void 0;if(!r||o&&s!==t){let i=n&&`"${n}" `,a=o?` of length ${t}`:"",c=r?`length=${s}`:`type=${typeof e}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):new TypeError(l)}return e},ua=e=>new Uint8Array(e),ql=e=>Uint8Array.from(e),Wg=(e,t)=>e.toString(16).padStart(t,"0"),Kl=e=>Array.from(It(e)).map(t=>Wg(t,2)).join(""),tn={_0:48,_9:57,A:65,F:70,a:97,f:102},Lg=e=>{if(e>=tn._0&&e<=tn._9)return e-tn._0;if(e>=tn.A&&e<=tn.F)return e-(tn.A-10);if(e>=tn.a&&e<=tn.f)return e-(tn.a-10)},Gl=e=>{let t="hex invalid";if(!Ux(e))return Ee(t);let n=e.length,r=n/2;if(n%2)return Ee(t);let s=ua(r);for(let o=0,i=0;o<r;o++,i+=2){let a=Lg(e.charCodeAt(i)),c=Lg(e.charCodeAt(i+1));if(a===void 0||c===void 0)return Ee(t);s[o]=a*16+c}return s},Yg=()=>globalThis?.crypto,jx=()=>Yg()?.subtle??Ee("crypto.subtle must be defined, consider polyfill"),fs=(...e)=>{let t=0;for(let s of e)t+=It(s).length;let n=ua(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},zg=(e=ds)=>Yg().getRandomValues(ua(e)),ca=BigInt,kr=(e,t,n,r="bad number: out of range")=>{if(!Lx(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},oe=(e,t=aa)=>{let n=e%t;return n>=0n?n:t+n},Ug=(1n<<255n)-1n,O=e=>{e<0n&&Ee("negative coordinate");let t=(e>>255n)*19n+(e&Ug);return t=(t>>255n)*19n+(t&Ug),t%aa},Jg=e=>oe(e,ia),Xg=(e,t)=>{(e===0n||t<=0n)&&Ee("no inverse n="+e+" mod="+t);let n=oe(e,t),r=t,s=0n,o=1n,i=1n,a=0n;for(;n!==0n;){let c=r/n,l=r%n,u=s-i*c,d=o-a*c;r=n,n=l,s=i,o=a,i=u,a=d}return r===1n?oe(s,t):Ee("no inverse")},Zg=e=>{let t=rh[e];return typeof t!="function"&&Ee("hashes."+e+" not set"),t},Qg=e=>It(e,64,"digest"),Dl=e=>e instanceof fo?e:Ee("Point expected"),Bl=2n**256n,fo=class Er{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=Bl;this.X=kr(t,0n,o),this.Y=kr(n,0n,o),this.Z=kr(r,1n,o),this.T=kr(s,0n,o),Object.freeze(this)}static CURVE(){return Gg}static fromAffine(t){return new Er(t.x,t.y,1n,O(t.x*t.y))}static fromBytes(t,n=!1){let r=Ul,s=ql(It(t,ds)),o=t[31];s[31]=o&-129;let i=th(s);kr(i,0n,n?Bl:aa);let c=O(i*i),l=oe(c-1n),u=O(r*c+1n),{isValid:d,value:p}=Fx(l,u);d||Ee("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!n&&p===0n&&m&&Ee("bad point: x==0, isLastByteOdd"),m!==f&&(p=oe(-p)),new Er(p,i,1n,O(p*i))}static fromHex(t,n){return Er.fromBytes(Gl(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Ll,n=Ul,r=this;if(r.is0())return Ee("bad point: ZERO");let{X:s,Y:o,Z:i,T:a}=r,c=O(s*s),l=O(o*o),u=O(i*i),d=O(u*u),p=O(c*t),f=O(u*(p+l)),m=oe(d+O(n*O(c*l)));if(f!==m)return Ee("bad point: equation left != right (1)");let h=O(s*o),w=O(i*a);return h!==w?Ee("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=Dl(t),c=O(n*a),l=O(o*s),u=O(r*a),d=O(i*s);return c===l&&u===d}is0(){return this.equals(Ar)}negate(){return new Er(oe(-this.X),this.Y,this.Z,oe(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=Ll,o=O(t*t),i=O(n*n),a=O(2n*r*r),c=O(s*o),l=oe(t+n),u=oe(O(l*l)-o-i),d=oe(c+i),p=oe(d-a),f=oe(c-i),m=O(u*p),h=O(d*f),w=O(u*f),C=O(p*d);return new Er(m,h,C,w)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=Dl(t),u=Ll,d=Ul,p=O(n*i),f=O(r*a),m=O(O(o*d)*l),h=O(s*c),w=oe(O(oe(n+r)*oe(i+a))-p-f),C=oe(h-m),b=oe(h+m),v=oe(f-O(u*p)),S=O(w*C),A=O(b*v),I=O(w*v),y=O(C*b);return new Er(S,A,y,I)}subtract(t){return this.add(Dl(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(kr(t,1n,ia),!n&&this.is0()))return Ar;if(t===1n)return this;if(this.equals(Rr))return Zx(t).p;let r=Ar,s=Rr;for(let o=this;t>0n;o=o.double(),t>>=1n)t&1n?r=r.add(o):n&&(s=s.add(o));return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(this.equals(Ar))return{x:0n,y:1n};let s=Xg(r,aa);O(r*s)!==1n&&Ee("invalid inverse");let o=O(t*s),i=O(n*s);return{x:o,y:i}}toBytes(){let{x:t,y:n}=this.toAffine(),r=eh(n);return r[31]|=t&1n?128:0,r}toHex(){return Kl(this.toBytes())}clearCofactor(){return this.multiply(ca(Mx),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(ia/2n,!1).double();return ia%2n&&(t=t.add(this)),t.is0()}},Rr=new fo(Mg,Ng,1n,oe(Mg*Ng)),Ar=new fo(0n,1n,1n,0n);fo.BASE=Rr;fo.ZERO=Ar;eh=e=>Gl(Wg(kr(e,0n,Bl),64)).reverse(),th=e=>ca("0x"+Kl(ql(It(e)).reverse())),Rt=(e,t)=>{let n=e;for(;t-- >0n;)n=O(n*n);return n},Bx=e=>{let t=O(e*e),n=O(t*e),r=O(Rt(n,2n)*n),s=O(Rt(r,1n)*e),o=O(Rt(s,5n)*s),i=O(Rt(o,10n)*o),a=O(Rt(i,20n)*i),c=O(Rt(a,40n)*a),l=O(Rt(c,80n)*c),u=O(Rt(l,80n)*c),d=O(Rt(u,10n)*o);return{pow_p_5_8:O(Rt(d,2n)*e),b2:n}},Dg=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,Fx=(e,t)=>{let n=O(t*O(t*t)),r=O(O(n*n)*t),s=Bx(O(e*r)).pow_p_5_8,o=O(e*O(n*s)),i=O(t*O(o*o)),a=o,c=O(o*Dg),l=i===e,u=i===oe(-e),d=i===oe(-e*Dg);return l&&(o=a),(u||d)&&(o=c),(oe(o)&1n)===1n&&(o=oe(-o)),{isValid:l||u,value:o}},Fl=e=>Jg(th(e)),Hx=(...e)=>Promise.resolve(Zg("sha512Async")(fs(...e))).then(Qg),Wl=(...e)=>Qg(Zg("sha512")(fs(...e))),nh=e=>{let t=ql(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=Fl(n),o=Rr.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},Vx=e=>Hx(It(e,ds)).then(nh),Yl=e=>nh(Wl(It(e,ds))),qx=e=>Yl(e).pointBytes,Kx=e=>e.finish(Wl(e.hashable)),Gx=(e,t,n)=>{let{pointBytes:r,scalar:s}=e,o=Fl(t),i=Rr.multiply(o).toBytes();return{hashable:fs(i,r,n),finish:l=>{let u=Jg(o+Fl(l)*s);return It(fs(i,eh(u)),64)}}},Wx=(e,t)=>{let n=It(e),r=Yl(t),s=Wl(r.prefix,n);return Kx(Gx(r,s,n))},zl=Object.freeze({bytesToHex:Kl,hexToBytes:Gl,concatBytes:fs,mod:oe,invert:Xg,randomBytes:zg}),rh={sha512Async:async e=>{let t=jx(),n=fs(e);return ua(await t.digest("SHA-512",n.buffer))},sha512:void 0},Yx=e=>(e=e===void 0?zg(ds):e,It(e,ds)),zx=Object.freeze({getExtendedPublicKeyAsync:Vx,getExtendedPublicKey:Yl,randomSecretKey:Yx}),la=8,Jx=256,sh=Math.ceil(Jx/la)+1,Hl=2**(la-1),Xx=()=>{let e=[],t=Rr,n=t;for(let r=0;r<sh;r++){n=t,e.push(n);for(let s=1;s<Hl;s++)n=n.add(t),e.push(n);t=n.double()}return e},jg=void 0,Bg=(e,t)=>{let n=t.negate();return e?n:t},Zx=e=>{let t=jg||(jg=Xx()),n=Ar,r=Rr,s=2**la,o=s,i=ca(s-1),a=ca(la);for(let c=0;c<sh;c++){let l=Number(e&i);e>>=a,l>Hl&&(l-=o,e+=1n);let u=c*Hl,d=u,p=u+Math.abs(l)-1,f=c%2!==0,m=l<0;l===0?r=r.add(Bg(f,t[d])):n=n.add(Bg(m,t[p]))}return e!==0n&&Ee("invalid wnaf"),{p:n,f:r}};nT=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),rT=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=jl(this.buffer)}update(e){Fg(this),oh(e);let{view:t,buffer:n,blockLen:r}=this,s=e.length;for(let o=0;o<s;){let i=Math.min(r-this.pos,s-o);if(i===r){let a=jl(e);for(;r<=s-o;o+=r)this.process(a,o);continue}n.set(e.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Fg(this),eT(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,Vl(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let u=o;u<r;u++)t[u]=0;n.setBigUint64(r-8,BigInt(this.length*8),s),this.process(n,0);let i=jl(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<c;u++)i.setUint32(4*u,l[u],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:s,destroyed:o,pos:i}=this;return e.destroyed=o,e.finished=s,e.length=r,e.pos=i,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Ne=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),ra=BigInt(2**32-1),Hg=BigInt(32);Vg=(e,t,n)=>e>>>n,qg=(e,t,n)=>e<<32-n|t>>>n,ls=(e,t,n)=>e>>>n|t<<32-n,us=(e,t,n)=>e<<32-n|t>>>n,sa=(e,t,n)=>e<<64-n|t>>>n-32,oa=(e,t,n)=>e>>>n-32|t<<64-n;iT=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),aT=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,cT=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),lT=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,uT=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),dT=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,ih=oT(["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(e=>BigInt(e))),fT=ih[0],pT=ih[1],Dn=new Uint32Array(80),jn=new Uint32Array(80),mT=class extends rT{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:s,Cl:o,Dh:i,Dl:a,Eh:c,El:l,Fh:u,Fl:d,Gh:p,Gl:f,Hh:m,Hl:h}=this;return[e,t,n,r,s,o,i,a,c,l,u,d,p,f,m,h]}set(e,t,n,r,s,o,i,a,c,l,u,d,p,f,m,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=s|0,this.Cl=o|0,this.Dh=i|0,this.Dl=a|0,this.Eh=c|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=p|0,this.Gl=f|0,this.Hh=m|0,this.Hl=h|0}process(e,t){for(let b=0;b<16;b++,t+=4)Dn[b]=e.getUint32(t),jn[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let v=Dn[b-15]|0,S=jn[b-15]|0,A=ls(v,S,1)^ls(v,S,8)^Vg(v,S,7),I=us(v,S,1)^us(v,S,8)^qg(v,S,7),y=Dn[b-2]|0,T=jn[b-2]|0,Y=ls(y,T,19)^sa(y,T,61)^Vg(y,T,6),X=us(y,T,19)^oa(y,T,61)^qg(y,T,6),H=cT(I,X,jn[b-7],jn[b-16]),_e=lT(H,A,Y,Dn[b-7],Dn[b-16]);Dn[b]=_e|0,jn[b]=H|0}let{Ah:n,Al:r,Bh:s,Bl:o,Ch:i,Cl:a,Dh:c,Dl:l,Eh:u,El:d,Fh:p,Fl:f,Gh:m,Gl:h,Hh:w,Hl:C}=this;for(let b=0;b<80;b++){let v=ls(u,d,14)^ls(u,d,18)^sa(u,d,41),S=us(u,d,14)^us(u,d,18)^oa(u,d,41),A=u&p^~u&m,I=d&f^~d&h,y=uT(C,S,I,pT[b],jn[b]),T=dT(y,w,v,A,fT[b],Dn[b]),Y=y|0,X=ls(n,r,28)^sa(n,r,34)^sa(n,r,39),H=us(n,r,28)^oa(n,r,34)^oa(n,r,39),_e=n&s^n&i^s&i,re=r&o^r&a^o&a;w=m|0,C=h|0,m=p|0,h=f|0,p=u|0,f=d|0,{h:u,l:d}=nn(c|0,l|0,T|0,Y|0),c=i|0,l=a|0,i=s|0,a=o|0,s=n|0,o=r|0;let J=iT(Y,H,re);n=aT(J,T,X,_e),r=J|0}({h:n,l:r}=nn(this.Ah|0,this.Al|0,n|0,r|0)),{h:s,l:o}=nn(this.Bh|0,this.Bl|0,s|0,o|0),{h:i,l:a}=nn(this.Ch|0,this.Cl|0,i|0,a|0),{h:c,l}=nn(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=nn(this.Eh|0,this.El|0,u|0,d|0),{h:p,l:f}=nn(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=nn(this.Gh|0,this.Gl|0,m|0,h|0),{h:w,l:C}=nn(this.Hh|0,this.Hl|0,w|0,C|0),this.set(n,r,s,o,i,a,c,l,u,d,p,f,m,h,w,C)}roundClean(){Vl(Dn,jn)}destroy(){this.destroyed=!0,Vl(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},gT=class extends mT{Ah=Ne[0]|0;Al=Ne[1]|0;Bh=Ne[2]|0;Bl=Ne[3]|0;Ch=Ne[4]|0;Cl=Ne[5]|0;Dh=Ne[6]|0;Dl=Ne[7]|0;Eh=Ne[8]|0;El=Ne[9]|0;Fh=Ne[10]|0;Fl=Ne[11]|0;Gh=Ne[12]|0;Gl=Ne[13]|0;Hh=Ne[14]|0;Hl=Ne[15]|0;constructor(){super(64)}},hT=tT(()=>new gT,nT(3)),Kg=rh;Kg.sha512||(Kg.sha512=e=>hT(e));MI=zl.bytesToHex,ch=zl.hexToBytes,NI=zl.concatBytes;LI=new TextEncoder;UI=ch("302e020100300506032b657004220420"),DI=ch("302a300506032b6570032100");});function ST(e){let t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return dh.createHash("sha256").update(t,"utf8").digest("base64url")}function xT(e,t,n){return`visa-agent-binding:v1:${e}:${t}:${n}`}function TT(e,t,n="visa",r=Math.floor(Date.now()/1e3)){let s=uh(da(e)),o=Buffer.from(xT(t,ST(s),r),"utf8"),i=Buffer.from(po(e,o)).toString("base64url");return{name:t,mesh:n,agent_pubkey:s,proof:{ts:r,sig:i}}}async function ph(e){let t=TT(e.seed,e.name,e.mesh??"visa",e.nowSec),n=e.fetchImpl??fetch,r=`${e.authUrl.replace(/\/+$/,"")}/v2/harness/agents`,s=await n(r,{method:"POST",headers:{"content-type":"application/json","x-api-key":e.apiKey},body:JSON.stringify(t)});if(!s.ok){let o="";try{o=(await s.json())?.error??""}catch{}throw new Error(`Visa binding issuance failed (${s.status})${o?`: ${o}`:""}`)}return await s.json()}function mh(e){return new Uint8Array(fh.readFileSync(e))}var dh,fh,gh=Nt(()=>{"use strict";dh=R(require("crypto")),fh=R(require("fs"));fa()});var ha={};No(ha,{MESH:()=>at,RELAY_URL:()=>yo,connectOrThrow:()=>hs,ensureMailbox:()=>ru,isSubwayEnabled:()=>Zl,listRegistered:()=>nu,loadRegistry:()=>go,makeClient:()=>gs,maybeMintVisaBinding:()=>vh,meshName:()=>$t,readInbox:()=>ET,registerName:()=>eu,resolveActingName:()=>ga,seedSubwayKeyFromTapAgent:()=>bh,sendMessage:()=>tu,sendVia:()=>AT,subwayKeyPath:()=>ma});function $t(e){return e.includes(".")?e:`${e}.${at}`}function Zl(e){if(process.env.VISA_DEV==="1")return!0;let t=e??"0.0.0";return t==="0.0.0"||t.startsWith("0.0.")?!0:/-rc\.|-beta\./.test(t)}function _h(){Ae.mkdirSync(Ql,{recursive:!0,mode:448})}function CT(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function ma(e){return ms.join(Ql,`${CT(e)}.key`)}function go(){if(!Ae.existsSync(Xl))return{};try{return JSON.parse(Ae.readFileSync(Xl,"utf8"))}catch{return{}}}function hh(e){_h(),Ae.writeFileSync(Xl,JSON.stringify(e,null,2),{mode:384})}function yh(){try{return ho.userInfo().username}catch{return"local"}}function bh(e){if(Ae.existsSync(e)||!Ae.existsSync(Jl))return null;let t=Ae.readdirSync(Jl).filter(r=>r.endsWith(".json"));if(t.length===0)return null;let n=t.map(r=>ms.join(Jl,r)).sort((r,s)=>Ae.statSync(s).mtimeMs-Ae.statSync(r).mtimeMs)[0];try{let r=JSON.parse(Ae.readFileSync(n,"utf8"));if(!r.private_key_jwk)return null;let s=mo(r.private_key_jwk);return _h(),Ae.writeFileSync(e,Buffer.from(s),{mode:384}),r.agent_id??null}catch{return null}}function gs(e,t={}){return new Og({name:$t(e),url:yo,keyPath:ma(e),autoReconnect:t.autoReconnect??!1})}async function hs(e,t=15e3){await Promise.race([e.connect(),new Promise((n,r)=>setTimeout(()=>r(new Error(`Subway relay connect timed out after ${t}ms (${yo})`)),t))])}function ga(e){if(e)return e;let t=Object.keys(go());if(t.length===1)return t[0];throw t.length===0?new Error("No Subway names registered yet. Run `visa register <name>` first."):new Error(`Multiple names registered (${t.join(", ")}). Pass --as <name>.`)}async function vh(e){if(at!=="visa")return null;let t=process.env.VISA_CLI_API_KEY?.trim();if(!t)return console.warn("[subway] .visa mesh needs a Visa Key (VISA_CLI_API_KEY) with a card on file to mint a binding; registering without one."),null;try{return await ph({authUrl:Ue(),apiKey:t,seed:mh(ma(e)),name:$t(e)})}catch(n){return console.warn(`[subway] Visa binding not minted: ${n instanceof Error?n.message:String(n)}`),null}}async function eu(e){let t=ma(e),n=bh(t),r=$t(e),s=await vh(e),o=s?{binding:s.binding,bindingExpiresAt:new Date(Date.now()+s.expires_in*1e3).toISOString()}:{};if(at==="visa"&&!process.env.SUBWAY_RELAY){let a=go();return a[e]={relayName:r,mesh:at,peerId:null,owner:yh(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},hh(a),{relayName:r,mesh:at,peerId:null,tapAgentId:n,...s?{binding:s.binding}:{},note:s?"Visa binding minted; relay admission pending a .visa relay (set SUBWAY_RELAY).":"No Visa binding minted; set VISA_CLI_API_KEY (card on file) and SUBWAY_RELAY for a .visa relay."}}let i=gs(e,{autoReconnect:!1});try{await hs(i);let a=go();return a[e]={relayName:r,mesh:at,peerId:i.peerId,owner:yh(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},hh(a),{relayName:r,mesh:at,peerId:i.peerId,tapAgentId:n,...s?{binding:s.binding}:{}}}finally{i.disconnect()}}async function tu(e,t,n){let r=gs(e,{autoReconnect:!1});try{await hs(r);let s=$t(t);return await r.sendSigned(s,"chat",n),{to:s,as:$t(e)}}finally{r.disconnect()}}function nu(){let e=go();return Object.entries(e).map(([t,n])=>({name:t,...n}))}async function ru(e){let t=pa.get(e);if(t)return{relayName:$t(e),peerId:t.client.peerId};let n=gs(e,{autoReconnect:!0}),r=[];return n.onMessage(s=>{r.push({from:s.fromName,text:s.payload,ts:s.timestampMs,verified:!!s.verified}),r.length>kT&&r.shift()}),pa.set(e,{client:n,buffer:r}),await hs(n),{relayName:$t(e),peerId:n.peerId}}async function ET(e,t=20,n=!1){await ru(e);let r=pa.get(e);if(!r)return[];let s=r.buffer.slice(-t);return n&&(r.buffer.length=0),s}async function AT(e,t,n){await ru(e);let r=pa.get(e);if(!r)throw new Error(`mailbox for ${e} unavailable`);let s=$t(t);return await r.client.sendSigned(s,"chat",n),{to:s,as:$t(e)}}var Ae,ho,ms,at,yo,Ql,Xl,Jl,pa,kT,_o=Nt(()=>{"use strict";Nl();fa();Ae=R(require("fs")),ho=R(require("os")),ms=R(require("path"));Ht();gh();at=process.env.SUBWAY_MESH??"relay",yo=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";Ql=ms.join(ho.homedir(),".visa-cli","subway"),Xl=ms.join(Ql,"registry.json"),Jl=ms.join(ho.homedir(),".visa-cli","agents");pa=new Map,kT=200});var Ia={};No(Ia,{initSentry:()=>sE,isSentryConfigured:()=>rE,reportFatal:()=>oE});function rE(){return!1}async function sE(){return null}async function oE(e,t){process.exit(t?.exitCode??1)}var $a=Nt(()=>{});var YE={};No(YE,{printGroupHelpAndExit:()=>pt});module.exports=Jy(YE);var Cy=require("commander"),Na=R(require("crypto")),ae=R(require("fs")),ne=R(require("os")),Qe=R(require("path")),ky=require("child_process"),Du=require("node:readline/promises"),Ey=require("util");var Do=require("child_process"),ad=require("util"),cn=R(require("fs")),jo=R(require("os")),Ya=R(require("path"));var td=R(require("crypto"));var Lt="e9501a252b778bce5a3d77710667afdd9198a750d1d989d95fb32d80e485bf15";var nd="VISA_ALLOW_INSECURE_MOCKS",Zu,Qu,ed;function Va(e){return`${e}-${td.randomBytes(24).toString("base64url")}`}function rd(e=process.env){return e.NODE_ENV==="test"||e[nd]==="true"}function on(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&rd(e)}function Nr(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&rd(e)}function qa(){return`Set ${nd}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function sd(){return Zu??=Va("mock-session"),Zu}function od(e=process.env){return e.NODE_ENV==="test"?Lt:(Qu??=Va("mock-rc"),Qu)}function id(){return ed??=Va("mock-signature"),ed}var mt=(0,ad.promisify)(Do.execFile),za=Ya.join(jo.homedir(),".visa-mcp"),Es=Ya.join(za,"session-token"),We="visa-cli",an="session-token",Lo="rc-access",Xy=5e3,Uo=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function Zy(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
9
+ ${e.nonce}`;return LS.encode(n)}function jS(e,t,n,r,s,o,i){return DS({messageId:e,senderPeerId:t,senderName:n,timestampMs:r,messageType:s,payload:o,nonce:i})}function BS(e){let t=0;for(;t<e.length;){let n=e[t],r=n>>3,s=n&7;if(t++,s===0){for(;t<e.length&&e[t]&128;)t++;t++}else if(s===2){let o=0,i=0;for(;t<e.length&&e[t]&128;)o|=(e[t]&127)<<i,i+=7,t++;if(o|=(e[t]&127)<<i,t++,r===2&&o>=64)return e.slice(t,t+32);t+=o}else return null}return null}function lx(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Ig(e,t,n=""){let r=lx(e),s=e?.length;if(!r||t!==void 0){let i=n&&`"${n}" `,a="",c=r?`length=${s}`:`type=${typeof e}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):new TypeError(l)}return e}function Wm(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function ux(e,t){Ig(e,void 0,"digestInto() output");let n=t.outputLen;if(e.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function El(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function wl(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function dx(e,t={}){let n=(s,o)=>e(o).update(s).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=s=>e(s),Object.assign(n,t),Object.freeze(n)}function mx(e,t=!1){return t?{h:Number(e&Vi),l:Number(e>>Ym&Vi)}:{h:Number(e>>Ym&Vi)|0,l:Number(e&Vi)|0}}function gx(e,t=!1){let n=e.length,r=new Uint32Array(n),s=new Uint32Array(n);for(let o=0;o<n;o++){let{h:i,l:a}=mx(e[o],t);[r[o],s[o]]=[i,a]}return[r,s]}function Qt(e,t,n,r){let s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}function Ex(){return ox.randomSecretKey()}function Pg(e){return rx(e)}function Ax(){let e=Ex();return{secretKey:e,publicKey:Pg(e)}}function Rx(e){if((0,Ln.existsSync)(e)){let n=(0,Ln.readFileSync)(e),r=new Uint8Array(n.buffer.slice(n.byteOffset,n.byteOffset+32));return{secretKey:r,publicKey:Pg(r)}}let t=Ax();return(0,Ln.mkdirSync)((0,Qm.dirname)(e),{recursive:!0}),(0,Ln.writeFileSync)(e,new Uint8Array(t.secretKey)),t}function Ix(e){let{secretKey:t,publicKey:n}=Rx(e);return{privateKey:t,publicKey:n}}async function $x(e,t,n,r,s,o,i,a){let c=jS(t,n,r,s,o,i,a);return{signature:await OS(e,c),signatureInput:US.subwayAgentMsgV1}}function Zm(e){return NS(e)}var Ln,Qm,Fw,Hw,Vw,qw,Kw,eg,Yi,Gi,Am,Rm,ml,gl,Gw,ea,Ww,Ce,Yw,zw,Jw,en,ta,Al,tg,Rl,Jt,Im,Il,ng,Xw,is,Zw,zi,_r,se,$m,$,rg,sg,og,ig,hl,Sl,lo,Cr,xr,ag,cg,kt,Qw,Pm,eS,xl,$l,tS,lg,nS,rS,sS,oS,iS,aS,Pl,ug,Ji,cS,dg,Tl,lS,Om,Mm,uS,mg,gg,In,Oe,Bi,Lm,Um,Dm,ns,rs,Fi,Hi,yS,_S,bS,vS,wS,SS,xS,$n,TS,CS,hg,kS,ES,Pn,On,AS,RS,IS,$S,jm,MS,yg,LS,US,_g,Xi,Wi,Bm,Fm,_l,bl,FS,as,HS,ke,VS,qS,KS,Un,na,Ol,bg,vg,Zt,Hm,wg,Sg,GS,Ml,WS,Zi,vr,ie,Vm,P,YS,zS,xg,Tg,vl,Cl,uo,cs,Tr,JS,Cg,At,XS,qm,ZS,QS,ex,tx,kg,nx,Eg,rx,Ag,sx,ox,Qi,ix,Rg,kl,ax,Km,Gm,cx,fx,px,Me,Vi,Ym,zm,Jm,ss,os,qi,Ki,hx,yx,_x,bx,vx,wx,$g,Sx,xx,Mn,Nn,Tx,Cx,kx,Xm,Px,Ox,Og,Nl=Nt(()=>{"use strict";fl();fl();Ln=require("fs"),Qm=require("path");Fw=1e3,Hw=10,Vw=3e4,qw=3e4,Kw=class{url;ws=null;_status="disconnected";messageHandlers=new Set;statusHandlers=new Set;reconnectAttempt=0;reconnectTimer=null;pingTimer=null;stopped=!1;autoReconnect;reconnectInterval;maxReconnectAttempts;pingInterval;constructor(e){this.url=e.url,this.autoReconnect=e.autoReconnect??!0,this.reconnectInterval=e.reconnectInterval??Fw,this.maxReconnectAttempts=e.maxReconnectAttempts??Hw,this.pingInterval=e.pingInterval??Vw}get status(){return this._status}onMessage(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}onStatusChange(e){return this.statusHandlers.add(e),()=>this.statusHandlers.delete(e)}connect(){return this.stopped=!1,new Promise((e,t)=>{let n=jw();if(!n){t(new Pe('No WebSocket implementation available. Install the "ws" package for Node.js.'));return}this.setStatus("connecting");try{this.ws=new n(this.url)}catch(s){t(new Pe(`Failed to create WebSocket: ${s}`));return}let r=!1;this.ws.onopen=()=>{this.reconnectAttempt=0,this.setStatus("connected"),this.startPing(),r||(r=!0,e())},this.ws.onmessage=s=>{let o;try{o=JSON.parse(typeof s.data=="string"?s.data:s.data.toString())}catch{return}for(let i of this.messageHandlers)i(o)},this.ws.onclose=()=>{this.ws=null,this.stopPing(),!this.stopped&&this.autoReconnect?this.scheduleReconnect():this.setStatus("disconnected"),r||(r=!0,t(new Pe("WebSocket closed before connection established")))},this.ws.onerror=()=>{r||(r=!0,t(new Pe(`WebSocket connection failed: ${this.url}`)))}})}disconnect(){this.stopped=!0,this.clearReconnectTimer(),this.stopPing(),this.ws&&(this.ws.onclose=null,this.ws.onerror=null,this.ws.onmessage=null,this.ws.close(),this.ws=null),this.setStatus("disconnected")}send(e){if(!this.ws||this.ws.readyState!==1)throw new Pe("WebSocket is not connected");this.ws.send(JSON.stringify(e))}startPing(){this.stopPing(),this.pingInterval>0&&(this.pingTimer=setInterval(()=>{try{this.send({type:"ping"})}catch{}},this.pingInterval))}stopPing(){this.pingTimer!==null&&(clearInterval(this.pingTimer),this.pingTimer=null)}scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts){this.setStatus("disconnected");return}this.setStatus("reconnecting");let e=Bw(this.reconnectInterval*Math.pow(2,this.reconnectAttempt),this.reconnectInterval,qw);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(!this.stopped)try{await this.connect()}catch{}},e)}clearReconnectTimer(){this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}setStatus(e){if(this._status!==e){this._status=e;for(let t of this.statusHandlers)t(e)}}},eg=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:Yi,n:Gi,Gx:Am,Gy:Rm,a:ml,d:gl,h:Gw}=eg,ea=32,Ww=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},Ce=(e="")=>{let t=new Error(e);throw Ww(t,Ce),t},Yw=e=>typeof e=="bigint",zw=e=>typeof e=="string",Jw=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,en=(e,t,n="")=>{let r=Jw(e),s=e?.length,o=t!==void 0;if(!r||o&&s!==t){let i=n&&`"${n}" `,a=o?` of length ${t}`:"",c=r?`length=${s}`:`type=${typeof e}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):new TypeError(l)}return e},ta=e=>new Uint8Array(e),Al=e=>Uint8Array.from(e),tg=(e,t)=>e.toString(16).padStart(t,"0"),Rl=e=>Array.from(en(e)).map(t=>tg(t,2)).join(""),Jt={_0:48,_9:57,A:65,F:70,a:97,f:102},Im=e=>{if(e>=Jt._0&&e<=Jt._9)return e-Jt._0;if(e>=Jt.A&&e<=Jt.F)return e-(Jt.A-10);if(e>=Jt.a&&e<=Jt.f)return e-(Jt.a-10)},Il=e=>{let t="hex invalid";if(!zw(e))return Ce(t);let n=e.length,r=n/2;if(n%2)return Ce(t);let s=ta(r);for(let o=0,i=0;o<r;o++,i+=2){let a=Im(e.charCodeAt(i)),c=Im(e.charCodeAt(i+1));if(a===void 0||c===void 0)return Ce(t);s[o]=a*16+c}return s},ng=()=>globalThis?.crypto,Xw=()=>ng()?.subtle??Ce("crypto.subtle must be defined, consider polyfill"),is=(...e)=>{let t=0;for(let s of e)t+=en(s).length;let n=ta(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},Zw=(e=ea)=>ng().getRandomValues(ta(e)),zi=BigInt,_r=(e,t,n,r="bad number: out of range")=>{if(!Yw(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},se=(e,t=Yi)=>{let n=e%t;return n>=0n?n:t+n},$m=(1n<<255n)-1n,$=e=>{e<0n&&Ce("negative coordinate");let t=(e>>255n)*19n+(e&$m);return t=(t>>255n)*19n+(t&$m),t%Yi},rg=e=>se(e,Gi),sg=(e,t)=>{(e===0n||t<=0n)&&Ce("no inverse n="+e+" mod="+t);let n=se(e,t),r=t,s=0n,o=1n;for(;n!==0n;){let i=r/n,a=r%n,c=s-o*i;r=n,n=a,s=o,o=c}return r===1n?se(s,t):Ce("no inverse")},og=e=>{let t=ug[e];return typeof t!="function"&&Ce("hashes."+e+" not set"),t},ig=e=>en(e,64,"digest"),hl=e=>e instanceof lo?e:Ce("Point expected"),Sl=2n**256n,lo=class br{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=Sl;this.X=_r(t,0n,o),this.Y=_r(n,0n,o),this.Z=_r(r,1n,o),this.T=_r(s,0n,o),Object.freeze(this)}static CURVE(){return eg}static fromAffine(t){return new br(t.x,t.y,1n,$(t.x*t.y))}static fromBytes(t,n=!1){let r=gl,s=Al(en(t,ea)),o=t[31];s[31]=o&-129;let i=cg(s);_r(i,0n,n?Sl:Yi);let c=$(i*i),l=se(c-1n),u=$(r*c+1n),{isValid:d,value:p}=eS(l,u);d||Ce("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!n&&p===0n&&m&&Ce("bad point: x==0, isLastByteOdd"),m!==f&&(p=se(-p)),new br(p,i,1n,$(p*i))}static fromHex(t,n){return br.fromBytes(Il(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=ml,n=gl,r=this;if(r.is0())return Ce("bad point: ZERO");let{X:s,Y:o,Z:i,T:a}=r,c=$(s*s),l=$(o*o),u=$(i*i),d=$(u*u),p=$(c*t),f=$(u*(p+l)),m=se(d+$(n*$(c*l)));if(f!==m)return Ce("bad point: equation left != right (1)");let h=$(s*o),w=$(i*a);return h!==w?Ce("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=hl(t),c=$(n*a),l=$(o*s),u=$(r*a),d=$(i*s);return c===l&&u===d}is0(){return this.equals(xr)}negate(){return new br(se(-this.X),this.Y,this.Z,se(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=ml,o=$(t*t),i=$(n*n),a=$(2n*r*r),c=$(s*o),l=se(t+n),u=se($(l*l)-o-i),d=se(c+i),p=se(d-a),f=se(c-i),m=$(u*p),h=$(d*f),w=$(u*f),C=$(p*d);return new br(m,h,C,w)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=hl(t),u=ml,d=gl,p=$(n*i),f=$(r*a),m=$($(o*d)*l),h=$(s*c),w=se($(se(n+r)*se(i+a))-p-f),C=se(h-m),b=se(h+m),v=se(f-$(u*p)),S=$(w*C),A=$(b*v),I=$(w*v),y=$(C*b);return new br(S,A,y,I)}subtract(t){return this.add(hl(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(_r(t,1n,Gi),!n&&this.is0()))return xr;if(t===1n)return this;if(this.equals(Cr))return uS(t).p;let r=xr,s=Cr;for(let o=this;t>0n;o=o.double(),t>>=1n)t&1n?r=r.add(o):n&&(s=s.add(o));return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(this.equals(xr))return{x:0n,y:1n};let s=sg(r,Yi);$(r*s)!==1n&&Ce("invalid inverse");let o=$(t*s),i=$(n*s);return{x:o,y:i}}toBytes(){let{x:t,y:n}=this.toAffine(),r=ag(n);return r[31]|=t&1n?128:0,r}toHex(){return Rl(this.toBytes())}clearCofactor(){return this.multiply(zi(Gw),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Gi/2n,!1).double();return Gi%2n&&(t=t.add(this)),t.is0()}},Cr=new lo(Am,Rm,1n,se(Am*Rm)),xr=new lo(0n,1n,1n,0n);lo.BASE=Cr;lo.ZERO=xr;ag=e=>Il(tg(_r(e,0n,Sl),64)).reverse(),cg=e=>zi("0x"+Rl(Al(en(e)).reverse())),kt=(e,t)=>{let n=e;for(;t-- >0n;)n=$(n*n);return n},Qw=e=>{let t=$(e*e),n=$(t*e),r=$(kt(n,2n)*n),s=$(kt(r,1n)*e),o=$(kt(s,5n)*s),i=$(kt(o,10n)*o),a=$(kt(i,20n)*i),c=$(kt(a,40n)*a),l=$(kt(c,80n)*c),u=$(kt(l,80n)*c),d=$(kt(u,10n)*o);return{pow_p_5_8:$(kt(d,2n)*e),b2:n}},Pm=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,eS=(e,t)=>{let n=$(t*$(t*t)),r=$($(n*n)*t),s=Qw($(e*r)).pow_p_5_8,o=$(e*$(n*s)),i=$(t*$(o*o)),a=o,c=$(o*Pm),l=i===e,u=i===se(-e),d=i===se(-e*Pm);return l&&(o=a),(u||d)&&(o=c),(se(o)&1n)===1n&&(o=se(-o)),{isValid:l||u,value:o}},xl=e=>rg(cg(e)),$l=(...e)=>Promise.resolve(og("sha512Async")(is(...e))).then(ig),tS=(...e)=>ig(og("sha512")(is(...e))),lg=e=>{let t=Al(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=xl(n),o=Cr.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},nS=e=>$l(en(e,ea)).then(lg),rS=e=>lg(tS(en(e,ea))),sS=e=>rS(e).pointBytes,oS=e=>$l(e.hashable).then(e.finish),iS=(e,t,n)=>{let{pointBytes:r,scalar:s}=e,o=xl(t),i=Cr.multiply(o).toBytes();return{hashable:is(i,r,n),finish:l=>{let u=rg(o+xl(l)*s);return en(is(i,ag(u)),64)}}},aS=async(e,t)=>{let n=en(e),r=await nS(t),s=await $l(r.prefix,n);return oS(iS(r,s,n))},Pl=Object.freeze({bytesToHex:Rl,hexToBytes:Il,concatBytes:is,mod:se,invert:sg,randomBytes:Zw}),ug={sha512Async:async e=>{let t=Xw(),n=is(e);return ta(await t.digest("SHA-512",n.buffer))},sha512:void 0},Ji=8,cS=256,dg=Math.ceil(cS/Ji)+1,Tl=2**(Ji-1),lS=()=>{let e=[],t=Cr,n=t;for(let r=0;r<dg;r++){n=t,e.push(n);for(let s=1;s<Tl;s++)n=n.add(t),e.push(n);t=n.double()}return e},Om=void 0,Mm=(e,t)=>{let n=t.negate();return e?n:t},uS=e=>{let t=Om||(Om=lS()),n=xr,r=Cr,s=2**Ji,o=s,i=zi(s-1),a=zi(Ji);for(let c=0;c<dg;c++){let l=Number(e&i);e>>=a,l>Tl&&(l-=o,e+=1n);let u=c*Tl,d=u,p=u+Math.abs(l)-1,f=c%2!==0,m=l<0;l===0?r=r.add(Mm(f,t[d])):n=n.add(Mm(m,t[p]))}return e!==0n&&Ce("invalid wnaf"),{p:n,f:r}};mg=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});gg=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=yl(this.buffer)}update(e){Nm(this),fg(e);let{view:t,buffer:n,blockLen:r}=this,s=e.length;for(let o=0;o<s;){let i=Math.min(r-this.pos,s-o);if(i===r){let a=yl(e);for(;r<=s-o;o+=r)this.process(a,o);continue}n.set(e.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Nm(this),fS(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,co(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let u=o;u<r;u++)t[u]=0;n.setBigUint64(r-8,BigInt(this.length*8),s),this.process(n,0);let i=yl(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<c;u++)i.setUint32(4*u,l[u],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:s,destroyed:o,pos:i}=this;return e.destroyed=o,e.finished=s,e.length=r,e.pos=i,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},In=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Oe=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Bi=BigInt(2**32-1),Lm=BigInt(32);Um=(e,t,n)=>e>>>n,Dm=(e,t,n)=>e<<32-n|t>>>n,ns=(e,t,n)=>e>>>n|t<<32-n,rs=(e,t,n)=>e<<32-n|t>>>n,Fi=(e,t,n)=>e<<64-n|t>>>n-32,Hi=(e,t,n)=>e>>>n-32|t<<64-n;yS=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),_S=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,bS=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),vS=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,wS=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),SS=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,xS=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]),$n=new Uint32Array(64),TS=class extends gg{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:r,E:s,F:o,G:i,H:a}=this;return[e,t,n,r,s,o,i,a]}set(e,t,n,r,s,o,i,a){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=s|0,this.F=o|0,this.G=i|0,this.H=a|0}process(e,t){for(let u=0;u<16;u++,t+=4)$n[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let d=$n[u-15],p=$n[u-2],f=Et(d,7)^Et(d,18)^d>>>3,m=Et(p,17)^Et(p,19)^p>>>10;$n[u]=m+$n[u-7]+f+$n[u-16]|0}let{A:n,B:r,C:s,D:o,E:i,F:a,G:c,H:l}=this;for(let u=0;u<64;u++){let d=Et(i,6)^Et(i,11)^Et(i,25),p=l+d+pS(i,a,c)+xS[u]+$n[u]|0,m=(Et(n,2)^Et(n,13)^Et(n,22))+mS(n,r,s)|0;l=c,c=a,a=i,i=o+p|0,o=s,s=r,r=n,n=p+m|0}n=n+this.A|0,r=r+this.B|0,s=s+this.C|0,o=o+this.D|0,i=i+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,s,o,i,a,c,l)}roundClean(){co($n)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),co(this.buffer)}},CS=class extends TS{A=In[0]|0;B=In[1]|0;C=In[2]|0;D=In[3]|0;E=In[4]|0;F=In[5]|0;G=In[6]|0;H=In[7]|0;constructor(){super(32)}},hg=hS(["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(e=>BigInt(e))),kS=hg[0],ES=hg[1],Pn=new Uint32Array(80),On=new Uint32Array(80),AS=class extends gg{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:s,Cl:o,Dh:i,Dl:a,Eh:c,El:l,Fh:u,Fl:d,Gh:p,Gl:f,Hh:m,Hl:h}=this;return[e,t,n,r,s,o,i,a,c,l,u,d,p,f,m,h]}set(e,t,n,r,s,o,i,a,c,l,u,d,p,f,m,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=s|0,this.Cl=o|0,this.Dh=i|0,this.Dl=a|0,this.Eh=c|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=p|0,this.Gl=f|0,this.Hh=m|0,this.Hl=h|0}process(e,t){for(let b=0;b<16;b++,t+=4)Pn[b]=e.getUint32(t),On[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let v=Pn[b-15]|0,S=On[b-15]|0,A=ns(v,S,1)^ns(v,S,8)^Um(v,S,7),I=rs(v,S,1)^rs(v,S,8)^Dm(v,S,7),y=Pn[b-2]|0,T=On[b-2]|0,Y=ns(y,T,19)^Fi(y,T,61)^Um(y,T,6),X=rs(y,T,19)^Hi(y,T,61)^Dm(y,T,6),H=bS(I,X,On[b-7],On[b-16]),_e=vS(H,A,Y,Pn[b-7],Pn[b-16]);Pn[b]=_e|0,On[b]=H|0}let{Ah:n,Al:r,Bh:s,Bl:o,Ch:i,Cl:a,Dh:c,Dl:l,Eh:u,El:d,Fh:p,Fl:f,Gh:m,Gl:h,Hh:w,Hl:C}=this;for(let b=0;b<80;b++){let v=ns(u,d,14)^ns(u,d,18)^Fi(u,d,41),S=rs(u,d,14)^rs(u,d,18)^Hi(u,d,41),A=u&p^~u&m,I=d&f^~d&h,y=wS(C,S,I,ES[b],On[b]),T=SS(y,w,v,A,kS[b],Pn[b]),Y=y|0,X=ns(n,r,28)^Fi(n,r,34)^Fi(n,r,39),H=rs(n,r,28)^Hi(n,r,34)^Hi(n,r,39),_e=n&s^n&i^s&i,re=r&o^r&a^o&a;w=m|0,C=h|0,m=p|0,h=f|0,p=u|0,f=d|0,{h:u,l:d}=Xt(c|0,l|0,T|0,Y|0),c=i|0,l=a|0,i=s|0,a=o|0,s=n|0,o=r|0;let J=yS(Y,H,re);n=_S(J,T,X,_e),r=J|0}({h:n,l:r}=Xt(this.Ah|0,this.Al|0,n|0,r|0)),{h:s,l:o}=Xt(this.Bh|0,this.Bl|0,s|0,o|0),{h:i,l:a}=Xt(this.Ch|0,this.Cl|0,i|0,a|0),{h:c,l}=Xt(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=Xt(this.Eh|0,this.El|0,u|0,d|0),{h:p,l:f}=Xt(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=Xt(this.Gh|0,this.Gl|0,m|0,h|0),{h:w,l:C}=Xt(this.Hh|0,this.Hl|0,w|0,C|0),this.set(n,r,s,o,i,a,c,l,u,d,p,f,m,h,w,C)}roundClean(){co(Pn,On)}destroy(){this.destroyed=!0,co(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},RS=class extends AS{Ah=Oe[0]|0;Al=Oe[1]|0;Bh=Oe[2]|0;Bl=Oe[3]|0;Ch=Oe[4]|0;Cl=Oe[5]|0;Dh=Oe[6]|0;Dl=Oe[7]|0;Eh=Oe[8]|0;El=Oe[9]|0;Fh=Oe[10]|0;Fl=Oe[11]|0;Gh=Oe[12]|0;Gl=Oe[13]|0;Hh=Oe[14]|0;Hl=Oe[15]|0;constructor(){super(64)}},IS=pg(()=>new CS,mg(1)),$S=pg(()=>new RS,mg(3)),jm=ug;jm.sha512||(jm.sha512=e=>$S(e));MS=Pl.bytesToHex,yg=Pl.hexToBytes;Pl.concatBytes;LS=new TextEncoder,US={subwayAgentMsgV1:"message_id;sender_peer_id;sender_name;timestamp_ms;message_type;payload_hash;nonce"};yg("302e020100300506032b657004220420");yg("302a300506032b6570032100");_g=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:Xi,n:Wi,Gx:Bm,Gy:Fm,a:_l,d:bl,h:FS}=_g,as=32,HS=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},ke=(e="")=>{let t=new Error(e);throw HS(t,ke),t},VS=e=>typeof e=="bigint",qS=e=>typeof e=="string",KS=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,Un=(e,t,n="")=>{let r=KS(e),s=e?.length,o=t!==void 0;if(!r||o&&s!==t){let i=n&&`"${n}" `,a=o?` of length ${t}`:"",c=r?`length=${s}`:`type=${typeof e}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):new TypeError(l)}return e},na=e=>new Uint8Array(e),Ol=e=>Uint8Array.from(e),bg=(e,t)=>e.toString(16).padStart(t,"0"),vg=e=>Array.from(Un(e)).map(t=>bg(t,2)).join(""),Zt={_0:48,_9:57,A:65,F:70,a:97,f:102},Hm=e=>{if(e>=Zt._0&&e<=Zt._9)return e-Zt._0;if(e>=Zt.A&&e<=Zt.F)return e-(Zt.A-10);if(e>=Zt.a&&e<=Zt.f)return e-(Zt.a-10)},wg=e=>{let t="hex invalid";if(!qS(e))return ke(t);let n=e.length,r=n/2;if(n%2)return ke(t);let s=na(r);for(let o=0,i=0;o<r;o++,i+=2){let a=Hm(e.charCodeAt(i)),c=Hm(e.charCodeAt(i+1));if(a===void 0||c===void 0)return ke(t);s[o]=a*16+c}return s},Sg=()=>globalThis?.crypto,GS=()=>Sg()?.subtle??ke("crypto.subtle must be defined, consider polyfill"),Ml=(...e)=>{let t=0;for(let s of e)t+=Un(s).length;let n=na(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},WS=(e=as)=>Sg().getRandomValues(na(e)),Zi=BigInt,vr=(e,t,n,r="bad number: out of range")=>{if(!VS(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},ie=(e,t=Xi)=>{let n=e%t;return n>=0n?n:t+n},Vm=(1n<<255n)-1n,P=e=>{e<0n&&ke("negative coordinate");let t=(e>>255n)*19n+(e&Vm);return t=(t>>255n)*19n+(t&Vm),t%Xi},YS=e=>ie(e,Wi),zS=(e,t)=>{(e===0n||t<=0n)&&ke("no inverse n="+e+" mod="+t);let n=ie(e,t),r=t,s=0n,o=1n;for(;n!==0n;){let i=r/n,a=r%n,c=s-o*i;r=n,n=a,s=o,o=c}return r===1n?ie(s,t):ke("no inverse")},xg=e=>{let t=Ag[e];return typeof t!="function"&&ke("hashes."+e+" not set"),t},Tg=e=>Un(e,64,"digest"),vl=e=>e instanceof uo?e:ke("Point expected"),Cl=2n**256n,uo=class wr{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=Cl;this.X=vr(t,0n,o),this.Y=vr(n,0n,o),this.Z=vr(r,1n,o),this.T=vr(s,0n,o),Object.freeze(this)}static CURVE(){return _g}static fromAffine(t){return new wr(t.x,t.y,1n,P(t.x*t.y))}static fromBytes(t,n=!1){let r=bl,s=Ol(Un(t,as)),o=t[31];s[31]=o&-129;let i=Cg(s);vr(i,0n,n?Cl:Xi);let c=P(i*i),l=ie(c-1n),u=P(r*c+1n),{isValid:d,value:p}=ZS(l,u);d||ke("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!n&&p===0n&&m&&ke("bad point: x==0, isLastByteOdd"),m!==f&&(p=ie(-p)),new wr(p,i,1n,P(p*i))}static fromHex(t,n){return wr.fromBytes(wg(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=_l,n=bl,r=this;if(r.is0())return ke("bad point: ZERO");let{X:s,Y:o,Z:i,T:a}=r,c=P(s*s),l=P(o*o),u=P(i*i),d=P(u*u),p=P(c*t),f=P(u*(p+l)),m=ie(d+P(n*P(c*l)));if(f!==m)return ke("bad point: equation left != right (1)");let h=P(s*o),w=P(i*a);return h!==w?ke("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=vl(t),c=P(n*a),l=P(o*s),u=P(r*a),d=P(i*s);return c===l&&u===d}is0(){return this.equals(Tr)}negate(){return new wr(ie(-this.X),this.Y,this.Z,ie(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=_l,o=P(t*t),i=P(n*n),a=P(2n*r*r),c=P(s*o),l=ie(t+n),u=ie(P(l*l)-o-i),d=ie(c+i),p=ie(d-a),f=ie(c-i),m=P(u*p),h=P(d*f),w=P(u*f),C=P(p*d);return new wr(m,h,C,w)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=vl(t),u=_l,d=bl,p=P(n*i),f=P(r*a),m=P(P(o*d)*l),h=P(s*c),w=ie(P(ie(n+r)*ie(i+a))-p-f),C=ie(h-m),b=ie(h+m),v=ie(f-P(u*p)),S=P(w*C),A=P(b*v),I=P(w*v),y=P(C*b);return new wr(S,A,y,I)}subtract(t){return this.add(vl(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(vr(t,1n,Wi),!n&&this.is0()))return Tr;if(t===1n)return this;if(this.equals(cs))return cx(t).p;let r=Tr,s=cs;for(let o=this;t>0n;o=o.double(),t>>=1n)t&1n?r=r.add(o):n&&(s=s.add(o));return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(this.equals(Tr))return{x:0n,y:1n};let s=zS(r,Xi);P(r*s)!==1n&&ke("invalid inverse");let o=P(t*s),i=P(n*s);return{x:o,y:i}}toBytes(){let{x:t,y:n}=this.toAffine(),r=JS(n);return r[31]|=t&1n?128:0,r}toHex(){return vg(this.toBytes())}clearCofactor(){return this.multiply(Zi(FS),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Wi/2n,!1).double();return Wi%2n&&(t=t.add(this)),t.is0()}},cs=new uo(Bm,Fm,1n,ie(Bm*Fm)),Tr=new uo(0n,1n,1n,0n);uo.BASE=cs;uo.ZERO=Tr;JS=e=>wg(bg(vr(e,0n,Cl),64)).reverse(),Cg=e=>Zi("0x"+vg(Ol(Un(e)).reverse())),At=(e,t)=>{let n=e;for(;t-- >0n;)n=P(n*n);return n},XS=e=>{let t=P(e*e),n=P(t*e),r=P(At(n,2n)*n),s=P(At(r,1n)*e),o=P(At(s,5n)*s),i=P(At(o,10n)*o),a=P(At(i,20n)*i),c=P(At(a,40n)*a),l=P(At(c,80n)*c),u=P(At(l,80n)*c),d=P(At(u,10n)*o);return{pow_p_5_8:P(At(d,2n)*e),b2:n}},qm=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,ZS=(e,t)=>{let n=P(t*P(t*t)),r=P(P(n*n)*t),s=XS(P(e*r)).pow_p_5_8,o=P(e*P(n*s)),i=P(t*P(o*o)),a=o,c=P(o*qm),l=i===e,u=i===ie(-e),d=i===ie(-e*qm);return l&&(o=a),(u||d)&&(o=c),(ie(o)&1n)===1n&&(o=ie(-o)),{isValid:l||u,value:o}},QS=e=>YS(Cg(e)),ex=(...e)=>Promise.resolve(xg("sha512Async")(Ml(...e))).then(Tg),tx=(...e)=>Tg(xg("sha512")(Ml(...e))),kg=e=>{let t=Ol(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=QS(n),o=cs.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},nx=e=>ex(Un(e,as)).then(kg),Eg=e=>kg(tx(Un(e,as))),rx=e=>Eg(e).pointBytes,Ag={sha512Async:async e=>{let t=GS(),n=Ml(e);return na(await t.digest("SHA-512",n.buffer))},sha512:void 0},sx=e=>(e=e===void 0?WS(as):e,Un(e,as)),ox=Object.freeze({getExtendedPublicKeyAsync:nx,getExtendedPublicKey:Eg,randomSecretKey:sx}),Qi=8,ix=256,Rg=Math.ceil(ix/Qi)+1,kl=2**(Qi-1),ax=()=>{let e=[],t=cs,n=t;for(let r=0;r<Rg;r++){n=t,e.push(n);for(let s=1;s<kl;s++)n=n.add(t),e.push(n);t=n.double()}return e},Km=void 0,Gm=(e,t)=>{let n=t.negate();return e?n:t},cx=e=>{let t=Km||(Km=ax()),n=Tr,r=cs,s=2**Qi,o=s,i=Zi(s-1),a=Zi(Qi);for(let c=0;c<Rg;c++){let l=Number(e&i);e>>=a,l>kl&&(l-=o,e+=1n);let u=c*kl,d=u,p=u+Math.abs(l)-1,f=c%2!==0,m=l<0;l===0?r=r.add(Gm(f,t[d])):n=n.add(Gm(m,t[p]))}return e!==0n&&ke("invalid wnaf"),{p:n,f:r}};fx=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),px=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=wl(this.buffer)}update(e){Wm(this),Ig(e);let{view:t,buffer:n,blockLen:r}=this,s=e.length;for(let o=0;o<s;){let i=Math.min(r-this.pos,s-o);if(i===r){let a=wl(e);for(;r<=s-o;o+=r)this.process(a,o);continue}n.set(e.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Wm(this),ux(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,El(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let u=o;u<r;u++)t[u]=0;n.setBigUint64(r-8,BigInt(this.length*8),s),this.process(n,0);let i=wl(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<c;u++)i.setUint32(4*u,l[u],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:s,destroyed:o,pos:i}=this;return e.destroyed=o,e.finished=s,e.length=r,e.pos=i,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Me=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Vi=BigInt(2**32-1),Ym=BigInt(32);zm=(e,t,n)=>e>>>n,Jm=(e,t,n)=>e<<32-n|t>>>n,ss=(e,t,n)=>e>>>n|t<<32-n,os=(e,t,n)=>e<<32-n|t>>>n,qi=(e,t,n)=>e<<64-n|t>>>n-32,Ki=(e,t,n)=>e>>>n-32|t<<64-n;hx=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),yx=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,_x=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),bx=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,vx=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),wx=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,$g=gx(["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(e=>BigInt(e))),Sx=$g[0],xx=$g[1],Mn=new Uint32Array(80),Nn=new Uint32Array(80),Tx=class extends px{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:s,Cl:o,Dh:i,Dl:a,Eh:c,El:l,Fh:u,Fl:d,Gh:p,Gl:f,Hh:m,Hl:h}=this;return[e,t,n,r,s,o,i,a,c,l,u,d,p,f,m,h]}set(e,t,n,r,s,o,i,a,c,l,u,d,p,f,m,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=s|0,this.Cl=o|0,this.Dh=i|0,this.Dl=a|0,this.Eh=c|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=p|0,this.Gl=f|0,this.Hh=m|0,this.Hl=h|0}process(e,t){for(let b=0;b<16;b++,t+=4)Mn[b]=e.getUint32(t),Nn[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let v=Mn[b-15]|0,S=Nn[b-15]|0,A=ss(v,S,1)^ss(v,S,8)^zm(v,S,7),I=os(v,S,1)^os(v,S,8)^Jm(v,S,7),y=Mn[b-2]|0,T=Nn[b-2]|0,Y=ss(y,T,19)^qi(y,T,61)^zm(y,T,6),X=os(y,T,19)^Ki(y,T,61)^Jm(y,T,6),H=_x(I,X,Nn[b-7],Nn[b-16]),_e=bx(H,A,Y,Mn[b-7],Mn[b-16]);Mn[b]=_e|0,Nn[b]=H|0}let{Ah:n,Al:r,Bh:s,Bl:o,Ch:i,Cl:a,Dh:c,Dl:l,Eh:u,El:d,Fh:p,Fl:f,Gh:m,Gl:h,Hh:w,Hl:C}=this;for(let b=0;b<80;b++){let v=ss(u,d,14)^ss(u,d,18)^qi(u,d,41),S=os(u,d,14)^os(u,d,18)^Ki(u,d,41),A=u&p^~u&m,I=d&f^~d&h,y=vx(C,S,I,xx[b],Nn[b]),T=wx(y,w,v,A,Sx[b],Mn[b]),Y=y|0,X=ss(n,r,28)^qi(n,r,34)^qi(n,r,39),H=os(n,r,28)^Ki(n,r,34)^Ki(n,r,39),_e=n&s^n&i^s&i,re=r&o^r&a^o&a;w=m|0,C=h|0,m=p|0,h=f|0,p=u|0,f=d|0,{h:u,l:d}=Qt(c|0,l|0,T|0,Y|0),c=i|0,l=a|0,i=s|0,a=o|0,s=n|0,o=r|0;let J=hx(Y,H,re);n=yx(J,T,X,_e),r=J|0}({h:n,l:r}=Qt(this.Ah|0,this.Al|0,n|0,r|0)),{h:s,l:o}=Qt(this.Bh|0,this.Bl|0,s|0,o|0),{h:i,l:a}=Qt(this.Ch|0,this.Cl|0,i|0,a|0),{h:c,l}=Qt(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=Qt(this.Eh|0,this.El|0,u|0,d|0),{h:p,l:f}=Qt(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=Qt(this.Gh|0,this.Gl|0,m|0,h|0),{h:w,l:C}=Qt(this.Hh|0,this.Hl|0,w|0,C|0),this.set(n,r,s,o,i,a,c,l,u,d,p,f,m,h,w,C)}roundClean(){El(Mn,Nn)}destroy(){this.destroyed=!0,El(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Cx=class extends Tx{Ah=Me[0]|0;Al=Me[1]|0;Bh=Me[2]|0;Bl=Me[3]|0;Ch=Me[4]|0;Cl=Me[5]|0;Dh=Me[6]|0;Dl=Me[7]|0;Eh=Me[8]|0;El=Me[9]|0;Fh=Me[10]|0;Fl=Me[11]|0;Gh=Me[12]|0;Gl=Me[13]|0;Hh=Me[14]|0;Hl=Me[15]|0;constructor(){super(64)}},kx=dx(()=>new Cx,fx(3)),Xm=Ag;Xm.sha512||(Xm.sha512=e=>kx(e));Px="ws://localhost:9001/ws",Ox=3e4,Og=class{transport;options;_peerId=null;_name;_keypair=null;messageHandlers=new Set;topicHandlers=new Map;rpcHandlers=new Map;defaultRpcHandler=null;pendingCalls=new Map;pendingSend=new Map;pendingResolve=new Map;eventListeners=new Map;registerPromise=null;hasConnectedOnce=!1;constructor(e){if(this._name=Sr(e.name),e.keyPath)try{this._keypair=Ix(e.keyPath)}catch{}this.options={name:this._name,url:e.url??Px,relay:e.relay??"",autoReconnect:e.autoReconnect??!0,reconnectInterval:e.reconnectInterval??1e3,maxReconnectAttempts:e.maxReconnectAttempts??10,rpcTimeout:e.rpcTimeout??Ox,pingInterval:e.pingInterval??3e4},this.transport=new Kw({url:this.options.url,autoReconnect:this.options.autoReconnect,reconnectInterval:this.options.reconnectInterval,maxReconnectAttempts:this.options.maxReconnectAttempts,pingInterval:this.options.pingInterval}),this.transport.onMessage(t=>this.handleBridgeMessage(t)),this.transport.onStatusChange(t=>this.handleStatusChange(t))}initKeypairFromSecret(e){try{let t=Buffer.from(e,"base64"),n=BS(new Uint8Array(t));n&&(this._keypair={privateKey:n,publicKey:PS(n)})}catch{}}get name(){return this._name}get peerId(){return this._peerId}get status(){return this.transport.status}async connect(){return await this.transport.connect(),new Promise((e,t)=>{this.registerPromise={resolve:e,reject:t};let n={type:"register",name:this._name};this.options.relay&&(n.relay=this.options.relay),this._keypair&&(n.public_key=Zm(this._keypair.publicKey));try{this.transport.send(n)}catch(r){this.registerPromise=null,t(r instanceof Error?r:new Pe(String(r)))}})}disconnect(){for(let[,e]of this.pendingCalls)clearTimeout(e.timer),e.reject(new Pe("Client disconnected"));this.pendingCalls.clear();for(let[,e]of this.pendingSend)e.reject(new Pe("Client disconnected"));this.pendingSend.clear();for(let[,e]of this.pendingResolve)e.reject(new Pe("Client disconnected"));this.pendingResolve.clear(),this.registerPromise&&(this.registerPromise.reject(new Pe("Client disconnected")),this.registerPromise=null),this.transport.disconnect(),this._peerId=null,this.hasConnectedOnce=!1}async send(e,t,n,r){let s=Sr(e),o=pl();return new Promise((i,a)=>{this.pendingSend.set(s,{resolve:i,reject:a});try{this.transport.send({type:"send",to:s,message_type:t,payload:n,metadata:r})}catch(c){this.pendingSend.delete(s),a(c instanceof Error?c:new Pe(String(c)))}setTimeout(()=>{this.pendingSend.has(s)&&(this.pendingSend.delete(s),i({messageId:o,to:s}))},5e3)})}async sendSigned(e,t,n,r){if(!this._keypair||!this._peerId)return this.send(e,t,n,r);let s=Sr(e),o=pl(),i=Date.now(),a=Math.floor(Math.random()*2**32),c=new TextEncoder().encode(n),{signature:l,signatureInput:u}=await $x(this._keypair.privateKey,o,this._peerId,this._name,i,t,c,a);return new Promise((d,p)=>{this.pendingSend.set(s,{resolve:d,reject:p});try{this.transport.send({type:"send_signed",to:s,message_id:o,sender_peer_id:this._peerId,sender_name:this._name,timestamp_ms:i,message_type:t,payload:n,metadata:r,signature:Buffer.from(l).toString("base64"),signature_input:u,nonce:a})}catch(f){this.pendingSend.delete(s),p(f instanceof Error?f:new Pe(String(f)))}setTimeout(()=>{this.pendingSend.has(s)&&(this.pendingSend.delete(s),d({messageId:o,to:s}))},5e3)})}async call(e,t,n,r){let s=Sr(e),o=r?.correlationId??pl(),i=r?.timeout??this.options.rpcTimeout;return new Promise((a,c)=>{let l=setTimeout(()=>{this.pendingCalls.delete(o),c(new ao(`RPC call to ${s}.${t} timed out after ${i}ms`))},i);this.pendingCalls.set(o,{resolve:a,reject:c,timer:l});try{this.transport.send({type:"call",to:s,method:t,payload:n??"",correlation_id:o})}catch(u){clearTimeout(l),this.pendingCalls.delete(o),c(u instanceof Error?u:new Pe(String(u)))}})}async broadcast(e,t,n){this.transport.send({type:"broadcast",topic:e,message_type:t,payload:n})}subscribe(e,t){let n=this.topicHandlers.get(e);if(!n){n=new Set,this.topicHandlers.set(e,n);try{this.transport.send({type:"subscribe",topic:e})}catch{}}return n.add(t),()=>{n.delete(t),n.size===0&&this.topicHandlers.delete(e)}}onMessage(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}onCall(e,t){return this.rpcHandlers.set(e,t),()=>this.rpcHandlers.delete(e)}onAnyCall(e){return this.defaultRpcHandler=e,()=>{this.defaultRpcHandler=null}}async resolve(e){let t=Sr(e);return new Promise((n,r)=>{this.pendingResolve.set(t,{resolve:n,reject:r});try{this.transport.send({type:"resolve",name:t})}catch(s){this.pendingResolve.delete(t),r(s instanceof Error?s:new Pe(String(s)))}setTimeout(()=>{this.pendingResolve.has(t)&&(this.pendingResolve.delete(t),r(new ao(`Resolve ${t} timed out`)))},1e4)})}on(e,t){let n=this.eventListeners.get(e);return n||(n=new Set,this.eventListeners.set(e,n)),n.add(t),()=>n.delete(t)}off(e,t){let n=this.eventListeners.get(e);n&&n.delete(t)}emit(e,...t){let n=this.eventListeners.get(e);if(n)for(let r of n)try{r(...t)}catch{}}handleBridgeMessage(e){switch(e.type){case"registered":this._peerId=e.peer_id,this._name=e.name,e.secret_key&&!this._keypair&&this.initKeypairFromSecret(e.secret_key),this.hasConnectedOnce=!0,this.registerPromise&&(this.registerPromise.resolve(),this.registerPromise=null),this.emit("connected",{name:e.name,peerId:e.peer_id}),this.resubscribeTopics();break;case"sent":{let t=this.pendingSend.get(e.to);t&&(this.pendingSend.delete(e.to),t.resolve({messageId:e.message_id,to:e.to}));break}case"call_result":{let t=this.pendingCalls.get(e.correlation_id);t&&(clearTimeout(t.timer),this.pendingCalls.delete(e.correlation_id),t.resolve({correlationId:e.correlation_id,success:e.success,payload:e.payload,error:e.error}));break}case"message":{let t={fromName:e.from_name,fromPeerId:e.from_peer_id,messageId:e.message_id,messageType:e.message_type,payload:e.payload,metadata:e.metadata??{},timestampMs:e.timestamp_ms,verified:e.verified,provenance:e.provenance?.map(n=>({signerName:n.signer_name,verified:n.verified})),attestation:e.attestation?{relayName:e.attestation.relay_name,verified:e.attestation.verified}:void 0,delegation:e.delegation?{parentName:e.delegation.parent_name,scope:e.delegation.scope,valid:e.delegation.valid,expired:e.delegation.expired}:void 0};for(let n of this.messageHandlers)try{n(t)}catch{}this.emit("message",t);break}case"inbound_call":this.handleInboundCall(e);break;case"broadcast_message":{let t={topic:e.topic,fromName:e.from_name,fromPeerId:e.from_peer_id,messageId:e.message_id,messageType:e.message_type,payload:e.payload,metadata:e.metadata??{},timestampMs:e.timestamp_ms,verified:e.verified,provenance:e.provenance?.map(r=>({signerName:r.signer_name,verified:r.verified})),attestation:e.attestation?{relayName:e.attestation.relay_name,verified:e.attestation.verified}:void 0,delegation:e.delegation?{parentName:e.delegation.parent_name,scope:e.delegation.scope,valid:e.delegation.valid,expired:e.delegation.expired}:void 0},n=this.topicHandlers.get(e.topic);if(n)for(let r of n)try{r(t)}catch{}this.emit("broadcast",t);break}case"resolved":{let t=this.pendingResolve.get(e.name);t&&(this.pendingResolve.delete(e.name),t.resolve({name:e.name,peerId:e.peer_id}));break}case"error":{let t=dl(e.code,e.message);this.registerPromise&&e.code==="register_failed"&&(this.registerPromise.reject(new ji(e.message)),this.registerPromise=null),this.emit("error",t);break}}}async handleInboundCall(e){let t={correlationId:e.correlation_id,fromName:e.from_name,fromPeerId:e.from_peer_id,method:e.method,payload:e.payload,verified:e.verified},n=this.rpcHandlers.get(e.method)??this.defaultRpcHandler,r;if(!n)r={success:!1,error:`No handler for method: ${e.method}`};else try{r=await n(t)}catch(s){r={success:!1,error:s instanceof Error?s.message:String(s)}}try{this.transport.send({type:"call_response",correlation_id:e.correlation_id,success:r.success,payload:r.payload??"",error:r.error??""})}catch{}}handleStatusChange(e){switch(e){case"disconnected":this._peerId=null,this.emit("disconnected");break;case"reconnecting":this.emit("reconnecting",this.transport.reconnectAttempt??0);break;case"connected":if(this.hasConnectedOnce){let t={type:"register",name:this.options.name};this.options.relay&&(t.relay=this.options.relay),this._keypair&&(t.public_key=Zm(this._keypair.publicKey));try{this.transport.send(t)}catch{}}break}}resubscribeTopics(){for(let e of this.topicHandlers.keys())try{this.transport.send({type:"subscribe",topic:e})}catch{}}};});function Qx(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function oh(e,t,n=""){let r=Qx(e),s=e?.length,o=t!==void 0;if(!r||o&&s!==t){let i=n&&`"${n}" `,a=o?` of length ${t}`:"",c=r?`length=${s}`:`type=${typeof e}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):new TypeError(l)}return e}function Fg(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function eT(e,t){oh(e,void 0,"digestInto() output");let n=t.outputLen;if(e.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function Vl(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function jl(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function tT(e,t={}){let n=(s,o)=>e(o).update(s).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=s=>e(s),Object.assign(n,t),Object.freeze(n)}function sT(e,t=!1){return t?{h:Number(e&ra),l:Number(e>>Hg&ra)}:{h:Number(e>>Hg&ra)|0,l:Number(e&ra)|0}}function oT(e,t=!1){let n=e.length,r=new Uint32Array(n),s=new Uint32Array(n);for(let o=0;o<n;o++){let{h:i,l:a}=sT(e[o],t);[r[o],s[o]]=[i,a]}return[r,s]}function nn(e,t,n,r){let s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}function yT(){return zx.randomSecretKey()}function da(e){return qx(e)}function ah(){let e=yT();return{secretKey:e,publicKey:da(e)}}function po(e,t){return Wx(t,e)}function _T(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function bT(e){let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function ps(e){return _T(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function vT(e){let t=e.length%4===0?0:4-e.length%4,n=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return bT(n)}function wT(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function lh(e){let t=da(e);return{kty:"OKP",crv:"Ed25519",x:ps(t),d:ps(e)}}function uh(e){return{kty:"OKP",crv:"Ed25519",x:ps(e)}}function mo(e){if(wT(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return vT(e.d)}var Gg,aa,ia,Mg,Ng,Ll,Ul,Mx,ds,Nx,Ee,Lx,Ux,Dx,It,ua,ql,Wg,Kl,tn,Lg,Gl,Yg,jx,fs,zg,ca,kr,oe,Ug,O,Jg,Xg,Zg,Qg,Dl,Bl,fo,Rr,Ar,eh,th,Rt,Bx,Dg,Fx,Fl,Hx,Wl,nh,Vx,Yl,qx,Kx,Gx,Wx,zl,rh,Yx,zx,la,Jx,sh,Hl,Xx,jg,Bg,Zx,nT,rT,Ne,ra,Hg,Vg,qg,ls,us,sa,oa,iT,aT,cT,lT,uT,dT,ih,fT,pT,Dn,jn,mT,gT,hT,Kg,MI,ch,NI,LI,UI,DI,fa=Nt(()=>{"use strict";Gg=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:aa,n:ia,Gx:Mg,Gy:Ng,a:Ll,d:Ul,h:Mx}=Gg,ds=32,Nx=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},Ee=(e="")=>{let t=new Error(e);throw Nx(t,Ee),t},Lx=e=>typeof e=="bigint",Ux=e=>typeof e=="string",Dx=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,It=(e,t,n="")=>{let r=Dx(e),s=e?.length,o=t!==void 0;if(!r||o&&s!==t){let i=n&&`"${n}" `,a=o?` of length ${t}`:"",c=r?`length=${s}`:`type=${typeof e}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):new TypeError(l)}return e},ua=e=>new Uint8Array(e),ql=e=>Uint8Array.from(e),Wg=(e,t)=>e.toString(16).padStart(t,"0"),Kl=e=>Array.from(It(e)).map(t=>Wg(t,2)).join(""),tn={_0:48,_9:57,A:65,F:70,a:97,f:102},Lg=e=>{if(e>=tn._0&&e<=tn._9)return e-tn._0;if(e>=tn.A&&e<=tn.F)return e-(tn.A-10);if(e>=tn.a&&e<=tn.f)return e-(tn.a-10)},Gl=e=>{let t="hex invalid";if(!Ux(e))return Ee(t);let n=e.length,r=n/2;if(n%2)return Ee(t);let s=ua(r);for(let o=0,i=0;o<r;o++,i+=2){let a=Lg(e.charCodeAt(i)),c=Lg(e.charCodeAt(i+1));if(a===void 0||c===void 0)return Ee(t);s[o]=a*16+c}return s},Yg=()=>globalThis?.crypto,jx=()=>Yg()?.subtle??Ee("crypto.subtle must be defined, consider polyfill"),fs=(...e)=>{let t=0;for(let s of e)t+=It(s).length;let n=ua(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},zg=(e=ds)=>Yg().getRandomValues(ua(e)),ca=BigInt,kr=(e,t,n,r="bad number: out of range")=>{if(!Lx(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},oe=(e,t=aa)=>{let n=e%t;return n>=0n?n:t+n},Ug=(1n<<255n)-1n,O=e=>{e<0n&&Ee("negative coordinate");let t=(e>>255n)*19n+(e&Ug);return t=(t>>255n)*19n+(t&Ug),t%aa},Jg=e=>oe(e,ia),Xg=(e,t)=>{(e===0n||t<=0n)&&Ee("no inverse n="+e+" mod="+t);let n=oe(e,t),r=t,s=0n,o=1n,i=1n,a=0n;for(;n!==0n;){let c=r/n,l=r%n,u=s-i*c,d=o-a*c;r=n,n=l,s=i,o=a,i=u,a=d}return r===1n?oe(s,t):Ee("no inverse")},Zg=e=>{let t=rh[e];return typeof t!="function"&&Ee("hashes."+e+" not set"),t},Qg=e=>It(e,64,"digest"),Dl=e=>e instanceof fo?e:Ee("Point expected"),Bl=2n**256n,fo=class Er{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=Bl;this.X=kr(t,0n,o),this.Y=kr(n,0n,o),this.Z=kr(r,1n,o),this.T=kr(s,0n,o),Object.freeze(this)}static CURVE(){return Gg}static fromAffine(t){return new Er(t.x,t.y,1n,O(t.x*t.y))}static fromBytes(t,n=!1){let r=Ul,s=ql(It(t,ds)),o=t[31];s[31]=o&-129;let i=th(s);kr(i,0n,n?Bl:aa);let c=O(i*i),l=oe(c-1n),u=O(r*c+1n),{isValid:d,value:p}=Fx(l,u);d||Ee("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!n&&p===0n&&m&&Ee("bad point: x==0, isLastByteOdd"),m!==f&&(p=oe(-p)),new Er(p,i,1n,O(p*i))}static fromHex(t,n){return Er.fromBytes(Gl(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Ll,n=Ul,r=this;if(r.is0())return Ee("bad point: ZERO");let{X:s,Y:o,Z:i,T:a}=r,c=O(s*s),l=O(o*o),u=O(i*i),d=O(u*u),p=O(c*t),f=O(u*(p+l)),m=oe(d+O(n*O(c*l)));if(f!==m)return Ee("bad point: equation left != right (1)");let h=O(s*o),w=O(i*a);return h!==w?Ee("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=Dl(t),c=O(n*a),l=O(o*s),u=O(r*a),d=O(i*s);return c===l&&u===d}is0(){return this.equals(Ar)}negate(){return new Er(oe(-this.X),this.Y,this.Z,oe(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=Ll,o=O(t*t),i=O(n*n),a=O(2n*r*r),c=O(s*o),l=oe(t+n),u=oe(O(l*l)-o-i),d=oe(c+i),p=oe(d-a),f=oe(c-i),m=O(u*p),h=O(d*f),w=O(u*f),C=O(p*d);return new Er(m,h,C,w)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=Dl(t),u=Ll,d=Ul,p=O(n*i),f=O(r*a),m=O(O(o*d)*l),h=O(s*c),w=oe(O(oe(n+r)*oe(i+a))-p-f),C=oe(h-m),b=oe(h+m),v=oe(f-O(u*p)),S=O(w*C),A=O(b*v),I=O(w*v),y=O(C*b);return new Er(S,A,y,I)}subtract(t){return this.add(Dl(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(kr(t,1n,ia),!n&&this.is0()))return Ar;if(t===1n)return this;if(this.equals(Rr))return Zx(t).p;let r=Ar,s=Rr;for(let o=this;t>0n;o=o.double(),t>>=1n)t&1n?r=r.add(o):n&&(s=s.add(o));return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(this.equals(Ar))return{x:0n,y:1n};let s=Xg(r,aa);O(r*s)!==1n&&Ee("invalid inverse");let o=O(t*s),i=O(n*s);return{x:o,y:i}}toBytes(){let{x:t,y:n}=this.toAffine(),r=eh(n);return r[31]|=t&1n?128:0,r}toHex(){return Kl(this.toBytes())}clearCofactor(){return this.multiply(ca(Mx),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(ia/2n,!1).double();return ia%2n&&(t=t.add(this)),t.is0()}},Rr=new fo(Mg,Ng,1n,oe(Mg*Ng)),Ar=new fo(0n,1n,1n,0n);fo.BASE=Rr;fo.ZERO=Ar;eh=e=>Gl(Wg(kr(e,0n,Bl),64)).reverse(),th=e=>ca("0x"+Kl(ql(It(e)).reverse())),Rt=(e,t)=>{let n=e;for(;t-- >0n;)n=O(n*n);return n},Bx=e=>{let t=O(e*e),n=O(t*e),r=O(Rt(n,2n)*n),s=O(Rt(r,1n)*e),o=O(Rt(s,5n)*s),i=O(Rt(o,10n)*o),a=O(Rt(i,20n)*i),c=O(Rt(a,40n)*a),l=O(Rt(c,80n)*c),u=O(Rt(l,80n)*c),d=O(Rt(u,10n)*o);return{pow_p_5_8:O(Rt(d,2n)*e),b2:n}},Dg=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,Fx=(e,t)=>{let n=O(t*O(t*t)),r=O(O(n*n)*t),s=Bx(O(e*r)).pow_p_5_8,o=O(e*O(n*s)),i=O(t*O(o*o)),a=o,c=O(o*Dg),l=i===e,u=i===oe(-e),d=i===oe(-e*Dg);return l&&(o=a),(u||d)&&(o=c),(oe(o)&1n)===1n&&(o=oe(-o)),{isValid:l||u,value:o}},Fl=e=>Jg(th(e)),Hx=(...e)=>Promise.resolve(Zg("sha512Async")(fs(...e))).then(Qg),Wl=(...e)=>Qg(Zg("sha512")(fs(...e))),nh=e=>{let t=ql(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=Fl(n),o=Rr.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},Vx=e=>Hx(It(e,ds)).then(nh),Yl=e=>nh(Wl(It(e,ds))),qx=e=>Yl(e).pointBytes,Kx=e=>e.finish(Wl(e.hashable)),Gx=(e,t,n)=>{let{pointBytes:r,scalar:s}=e,o=Fl(t),i=Rr.multiply(o).toBytes();return{hashable:fs(i,r,n),finish:l=>{let u=Jg(o+Fl(l)*s);return It(fs(i,eh(u)),64)}}},Wx=(e,t)=>{let n=It(e),r=Yl(t),s=Wl(r.prefix,n);return Kx(Gx(r,s,n))},zl=Object.freeze({bytesToHex:Kl,hexToBytes:Gl,concatBytes:fs,mod:oe,invert:Xg,randomBytes:zg}),rh={sha512Async:async e=>{let t=jx(),n=fs(e);return ua(await t.digest("SHA-512",n.buffer))},sha512:void 0},Yx=e=>(e=e===void 0?zg(ds):e,It(e,ds)),zx=Object.freeze({getExtendedPublicKeyAsync:Vx,getExtendedPublicKey:Yl,randomSecretKey:Yx}),la=8,Jx=256,sh=Math.ceil(Jx/la)+1,Hl=2**(la-1),Xx=()=>{let e=[],t=Rr,n=t;for(let r=0;r<sh;r++){n=t,e.push(n);for(let s=1;s<Hl;s++)n=n.add(t),e.push(n);t=n.double()}return e},jg=void 0,Bg=(e,t)=>{let n=t.negate();return e?n:t},Zx=e=>{let t=jg||(jg=Xx()),n=Ar,r=Rr,s=2**la,o=s,i=ca(s-1),a=ca(la);for(let c=0;c<sh;c++){let l=Number(e&i);e>>=a,l>Hl&&(l-=o,e+=1n);let u=c*Hl,d=u,p=u+Math.abs(l)-1,f=c%2!==0,m=l<0;l===0?r=r.add(Bg(f,t[d])):n=n.add(Bg(m,t[p]))}return e!==0n&&Ee("invalid wnaf"),{p:n,f:r}};nT=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),rT=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=jl(this.buffer)}update(e){Fg(this),oh(e);let{view:t,buffer:n,blockLen:r}=this,s=e.length;for(let o=0;o<s;){let i=Math.min(r-this.pos,s-o);if(i===r){let a=jl(e);for(;r<=s-o;o+=r)this.process(a,o);continue}n.set(e.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Fg(this),eT(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,Vl(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let u=o;u<r;u++)t[u]=0;n.setBigUint64(r-8,BigInt(this.length*8),s),this.process(n,0);let i=jl(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<c;u++)i.setUint32(4*u,l[u],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:s,destroyed:o,pos:i}=this;return e.destroyed=o,e.finished=s,e.length=r,e.pos=i,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Ne=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),ra=BigInt(2**32-1),Hg=BigInt(32);Vg=(e,t,n)=>e>>>n,qg=(e,t,n)=>e<<32-n|t>>>n,ls=(e,t,n)=>e>>>n|t<<32-n,us=(e,t,n)=>e<<32-n|t>>>n,sa=(e,t,n)=>e<<64-n|t>>>n-32,oa=(e,t,n)=>e>>>n-32|t<<64-n;iT=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),aT=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,cT=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),lT=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,uT=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),dT=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,ih=oT(["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(e=>BigInt(e))),fT=ih[0],pT=ih[1],Dn=new Uint32Array(80),jn=new Uint32Array(80),mT=class extends rT{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:s,Cl:o,Dh:i,Dl:a,Eh:c,El:l,Fh:u,Fl:d,Gh:p,Gl:f,Hh:m,Hl:h}=this;return[e,t,n,r,s,o,i,a,c,l,u,d,p,f,m,h]}set(e,t,n,r,s,o,i,a,c,l,u,d,p,f,m,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=s|0,this.Cl=o|0,this.Dh=i|0,this.Dl=a|0,this.Eh=c|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=p|0,this.Gl=f|0,this.Hh=m|0,this.Hl=h|0}process(e,t){for(let b=0;b<16;b++,t+=4)Dn[b]=e.getUint32(t),jn[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let v=Dn[b-15]|0,S=jn[b-15]|0,A=ls(v,S,1)^ls(v,S,8)^Vg(v,S,7),I=us(v,S,1)^us(v,S,8)^qg(v,S,7),y=Dn[b-2]|0,T=jn[b-2]|0,Y=ls(y,T,19)^sa(y,T,61)^Vg(y,T,6),X=us(y,T,19)^oa(y,T,61)^qg(y,T,6),H=cT(I,X,jn[b-7],jn[b-16]),_e=lT(H,A,Y,Dn[b-7],Dn[b-16]);Dn[b]=_e|0,jn[b]=H|0}let{Ah:n,Al:r,Bh:s,Bl:o,Ch:i,Cl:a,Dh:c,Dl:l,Eh:u,El:d,Fh:p,Fl:f,Gh:m,Gl:h,Hh:w,Hl:C}=this;for(let b=0;b<80;b++){let v=ls(u,d,14)^ls(u,d,18)^sa(u,d,41),S=us(u,d,14)^us(u,d,18)^oa(u,d,41),A=u&p^~u&m,I=d&f^~d&h,y=uT(C,S,I,pT[b],jn[b]),T=dT(y,w,v,A,fT[b],Dn[b]),Y=y|0,X=ls(n,r,28)^sa(n,r,34)^sa(n,r,39),H=us(n,r,28)^oa(n,r,34)^oa(n,r,39),_e=n&s^n&i^s&i,re=r&o^r&a^o&a;w=m|0,C=h|0,m=p|0,h=f|0,p=u|0,f=d|0,{h:u,l:d}=nn(c|0,l|0,T|0,Y|0),c=i|0,l=a|0,i=s|0,a=o|0,s=n|0,o=r|0;let J=iT(Y,H,re);n=aT(J,T,X,_e),r=J|0}({h:n,l:r}=nn(this.Ah|0,this.Al|0,n|0,r|0)),{h:s,l:o}=nn(this.Bh|0,this.Bl|0,s|0,o|0),{h:i,l:a}=nn(this.Ch|0,this.Cl|0,i|0,a|0),{h:c,l}=nn(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=nn(this.Eh|0,this.El|0,u|0,d|0),{h:p,l:f}=nn(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=nn(this.Gh|0,this.Gl|0,m|0,h|0),{h:w,l:C}=nn(this.Hh|0,this.Hl|0,w|0,C|0),this.set(n,r,s,o,i,a,c,l,u,d,p,f,m,h,w,C)}roundClean(){Vl(Dn,jn)}destroy(){this.destroyed=!0,Vl(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},gT=class extends mT{Ah=Ne[0]|0;Al=Ne[1]|0;Bh=Ne[2]|0;Bl=Ne[3]|0;Ch=Ne[4]|0;Cl=Ne[5]|0;Dh=Ne[6]|0;Dl=Ne[7]|0;Eh=Ne[8]|0;El=Ne[9]|0;Fh=Ne[10]|0;Fl=Ne[11]|0;Gh=Ne[12]|0;Gl=Ne[13]|0;Hh=Ne[14]|0;Hl=Ne[15]|0;constructor(){super(64)}},hT=tT(()=>new gT,nT(3)),Kg=rh;Kg.sha512||(Kg.sha512=e=>hT(e));MI=zl.bytesToHex,ch=zl.hexToBytes,NI=zl.concatBytes;LI=new TextEncoder;UI=ch("302e020100300506032b657004220420"),DI=ch("302a300506032b6570032100");});function ST(e){let t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return dh.createHash("sha256").update(t,"utf8").digest("base64url")}function xT(e,t,n){return`visa-agent-binding:v1:${e}:${t}:${n}`}function TT(e,t,n="visa",r=Math.floor(Date.now()/1e3)){let s=uh(da(e)),o=Buffer.from(xT(t,ST(s),r),"utf8"),i=Buffer.from(po(e,o)).toString("base64url");return{name:t,mesh:n,agent_pubkey:s,proof:{ts:r,sig:i}}}async function ph(e){let t=TT(e.seed,e.name,e.mesh??"visa",e.nowSec),n=e.fetchImpl??fetch,r=`${e.authUrl.replace(/\/+$/,"")}/v2/harness/agents`,s=await n(r,{method:"POST",headers:{"content-type":"application/json","x-api-key":e.apiKey},body:JSON.stringify(t)});if(!s.ok){let o="";try{o=(await s.json())?.error??""}catch{}throw new Error(`Visa binding issuance failed (${s.status})${o?`: ${o}`:""}`)}return await s.json()}function mh(e){return new Uint8Array(fh.readFileSync(e))}var dh,fh,gh=Nt(()=>{"use strict";dh=R(require("crypto")),fh=R(require("fs"));fa()});var ha={};No(ha,{MESH:()=>at,RELAY_URL:()=>yo,connectOrThrow:()=>hs,ensureMailbox:()=>ru,isSubwayEnabled:()=>Zl,listRegistered:()=>nu,loadRegistry:()=>go,makeClient:()=>gs,maybeMintVisaBinding:()=>vh,meshName:()=>$t,readInbox:()=>ET,registerName:()=>eu,resolveActingName:()=>ga,seedSubwayKeyFromTapAgent:()=>bh,sendMessage:()=>tu,sendVia:()=>AT,subwayKeyPath:()=>ma});function $t(e){return e.includes(".")?e:`${e}.${at}`}function Zl(e){if(process.env.VISA_DEV==="1")return!0;let t=e??"0.0.0";return t==="0.0.0"||t.startsWith("0.0.")?!0:/-rc\.|-beta\./.test(t)}function _h(){Ae.mkdirSync(Ql,{recursive:!0,mode:448})}function CT(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function ma(e){return ms.join(Ql,`${CT(e)}.key`)}function go(){if(!Ae.existsSync(Xl))return{};try{return JSON.parse(Ae.readFileSync(Xl,"utf8"))}catch{return{}}}function hh(e){_h(),Ae.writeFileSync(Xl,JSON.stringify(e,null,2),{mode:384})}function yh(){try{return ho.userInfo().username}catch{return"local"}}function bh(e){if(Ae.existsSync(e)||!Ae.existsSync(Jl))return null;let t=Ae.readdirSync(Jl).filter(r=>r.endsWith(".json"));if(t.length===0)return null;let n=t.map(r=>ms.join(Jl,r)).sort((r,s)=>Ae.statSync(s).mtimeMs-Ae.statSync(r).mtimeMs)[0];try{let r=JSON.parse(Ae.readFileSync(n,"utf8"));if(!r.private_key_jwk)return null;let s=mo(r.private_key_jwk);return _h(),Ae.writeFileSync(e,Buffer.from(s),{mode:384}),r.agent_id??null}catch{return null}}function gs(e,t={}){return new Og({name:$t(e),url:yo,keyPath:ma(e),autoReconnect:t.autoReconnect??!1})}async function hs(e,t=15e3){await Promise.race([e.connect(),new Promise((n,r)=>setTimeout(()=>r(new Error(`Subway relay connect timed out after ${t}ms (${yo})`)),t))])}function ga(e){if(e)return e;let t=Object.keys(go());if(t.length===1)return t[0];throw t.length===0?new Error("No Subway names registered yet. Run `visa register <name>` first."):new Error(`Multiple names registered (${t.join(", ")}). Pass --as <name>.`)}async function vh(e){if(at!=="visa")return null;let t=process.env.VISA_CLI_API_KEY?.trim();if(!t)return console.warn("[subway] .visa mesh needs a Visa Key (VISA_CLI_API_KEY) with a card on file to mint a binding; registering without one."),null;try{return await ph({authUrl:Ue(),apiKey:t,seed:mh(ma(e)),name:$t(e)})}catch(n){return console.warn(`[subway] Visa binding not minted: ${n instanceof Error?n.message:String(n)}`),null}}async function eu(e){let t=ma(e),n=bh(t),r=$t(e),s=await vh(e),o=s?{binding:s.binding,bindingExpiresAt:new Date(Date.now()+s.expires_in*1e3).toISOString()}:{};if(at==="visa"&&!process.env.SUBWAY_RELAY){let a=go();return a[e]={relayName:r,mesh:at,peerId:null,owner:yh(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},hh(a),{relayName:r,mesh:at,peerId:null,tapAgentId:n,...s?{binding:s.binding}:{},note:s?"Visa binding minted; relay admission pending a .visa relay (set SUBWAY_RELAY).":"No Visa binding minted; set VISA_CLI_API_KEY (card on file) and SUBWAY_RELAY for a .visa relay."}}let i=gs(e,{autoReconnect:!1});try{await hs(i);let a=go();return a[e]={relayName:r,mesh:at,peerId:i.peerId,owner:yh(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},hh(a),{relayName:r,mesh:at,peerId:i.peerId,tapAgentId:n,...s?{binding:s.binding}:{}}}finally{i.disconnect()}}async function tu(e,t,n){let r=gs(e,{autoReconnect:!1});try{await hs(r);let s=$t(t);return await r.sendSigned(s,"chat",n),{to:s,as:$t(e)}}finally{r.disconnect()}}function nu(){let e=go();return Object.entries(e).map(([t,n])=>({name:t,...n}))}async function ru(e){let t=pa.get(e);if(t)return{relayName:$t(e),peerId:t.client.peerId};let n=gs(e,{autoReconnect:!0}),r=[];return n.onMessage(s=>{r.push({from:s.fromName,text:s.payload,ts:s.timestampMs,verified:!!s.verified}),r.length>kT&&r.shift()}),pa.set(e,{client:n,buffer:r}),await hs(n),{relayName:$t(e),peerId:n.peerId}}async function ET(e,t=20,n=!1){await ru(e);let r=pa.get(e);if(!r)return[];let s=r.buffer.slice(-t);return n&&(r.buffer.length=0),s}async function AT(e,t,n){await ru(e);let r=pa.get(e);if(!r)throw new Error(`mailbox for ${e} unavailable`);let s=$t(t);return await r.client.sendSigned(s,"chat",n),{to:s,as:$t(e)}}var Ae,ho,ms,at,yo,Ql,Xl,Jl,pa,kT,_o=Nt(()=>{"use strict";Nl();fa();Ae=R(require("fs")),ho=R(require("os")),ms=R(require("path"));Ht();gh();at=process.env.SUBWAY_MESH??"relay",yo=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";Ql=ms.join(ho.homedir(),".visa-cli","subway"),Xl=ms.join(Ql,"registry.json"),Jl=ms.join(ho.homedir(),".visa-cli","agents");pa=new Map,kT=200});var Ia={};No(Ia,{initSentry:()=>sE,isSentryConfigured:()=>rE,reportFatal:()=>oE});function rE(){return!1}async function sE(){return null}async function oE(e,t){process.exit(t?.exitCode??1)}var $a=Nt(()=>{});var YE={};No(YE,{printGroupHelpAndExit:()=>pt});module.exports=Jy(YE);var Cy=require("commander"),Na=R(require("crypto")),ae=R(require("fs")),ne=R(require("os")),Qe=R(require("path")),ky=require("child_process"),Du=require("node:readline/promises"),Ey=require("util");var Do=require("child_process"),ad=require("util"),cn=R(require("fs")),jo=R(require("os")),Ya=R(require("path"));var td=R(require("crypto"));var Lt="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";var nd="VISA_ALLOW_INSECURE_MOCKS",Zu,Qu,ed;function Va(e){return`${e}-${td.randomBytes(24).toString("base64url")}`}function rd(e=process.env){return e.NODE_ENV==="test"||e[nd]==="true"}function on(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&rd(e)}function Nr(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&rd(e)}function qa(){return`Set ${nd}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function sd(){return Zu??=Va("mock-session"),Zu}function od(e=process.env){return e.NODE_ENV==="test"?Lt:(Qu??=Va("mock-rc"),Qu)}function id(){return ed??=Va("mock-signature"),ed}var mt=(0,ad.promisify)(Do.execFile),za=Ya.join(jo.homedir(),".visa-mcp"),Es=Ya.join(za,"session-token"),We="visa-cli",an="session-token",Lo="rc-access",Xy=5e3,Uo=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function Zy(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
10
10
  `)}function cd(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=Zy(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function Qy(){try{let{stdout:e}=await mt("security",["find-generic-password","-s",We,"-a",an,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(cd(e))throw new Uo("Unable to read Visa CLI credentials from macOS Keychain. In sandboxed agents such as Codex, rerun with keychain access or run this command outside the sandbox.");return null}}async function e_(e){try{try{await mt("security",["delete-generic-password","-s",We,"-a",an],{timeout:5e3})}catch{}return await mt("security",["add-generic-password","-s",We,"-a",an,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function t_(){try{await mt("security",["delete-generic-password","-s",We,"-a",an],{timeout:5e3})}catch{}}async function n_(){if(!Ja())return null;try{let{stdout:e}=await mt("secret-tool",["lookup","service",We,"account",an],{timeout:5e3});return e.trim()||null}catch{return null}}async function r_(e){if(!Ja())return!1;try{let t=(0,Do.execFile)("secret-tool",["store","--label",`${We} ${an}`,"service",We,"account",an]);return t.stdin?(t.stdin.write(e),t.stdin.end(),await Promise.race([new Promise((n,r)=>{t.on("exit",s=>s===0?n():r(new Error(`secret-tool exited ${s}`))),t.on("error",r)}),new Promise((n,r)=>setTimeout(()=>{t.kill(),r(new Error("secret-tool timed out"))},Xy))]),!0):!1}catch{return!1}}async function s_(){if(Ja())try{await mt("secret-tool",["clear","service",We,"account",an],{timeout:5e3})}catch{}}function Ja(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function o_(){try{let{stdout:e}=await mt("security",["find-generic-password","-s",We,"-a",Lo,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function i_(e){try{try{await mt("security",["delete-generic-password","-s",We,"-a",Lo],{timeout:5e3})}catch{}await mt("security",["add-generic-password","-s",We,"-a",Lo,"-w",e],{timeout:5e3})}catch{}}async function a_(){try{await mt("security",["delete-generic-password","-s",We,"-a",Lo],{timeout:5e3})}catch{}}function Ga(){try{return cn.readFileSync(Es,"utf-8").trim()||null}catch(e){if(cd(e))throw new Uo(`Unable to read Visa CLI credentials from ${Es}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function ld(e){cn.mkdirSync(za,{recursive:!0,mode:448}),cn.writeFileSync(Es,e,{mode:384}),process.platform==="win32"&&c_(Es)}function Wa(){try{cn.unlinkSync(Es)}catch{}}function c_(e){try{let t=jo.userInfo().username;(0,Do.execFile)("icacls",[e,"/inheritance:r","/grant:r",`${t}:F`],{timeout:5e3},n=>{n&&console.error(`[visa-cli] icacls ACL restriction failed: ${n.message}`)})}catch(t){console.error(`[visa-cli] Failed to invoke icacls: ${t instanceof Error?t.message:String(t)}`)}}function Ka(){switch(process.platform){case"darwin":return{get:Qy,store:e_,delete:t_};case"linux":return{get:n_,store:r_,delete:s_};default:return{get:async()=>Ga(),store:async e=>{try{return ld(e),!0}catch{return!1}},delete:async()=>Wa(),storesInSessionFile:!0}}}var K=class{static async getSessionToken(){if(on())return Promise.resolve(sd());let t=Ka(),n=await t.get();if(n)return n;let r=Ga();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(on())return;let n=Ka();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||Wa();return}await n.delete()}if(ld(t),Ga()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${za} is writable.`))}static async getRcAccessToken(){return on()?od():o_()}static async saveRcAccessToken(t){on()||await i_(t)}static async deleteSessionToken(){if(on())return;await Ka().delete(),Wa()}static async clearAll(){await this.deleteSessionToken(),await a_()}};var Bo=R(require("crypto")),Fo=R(require("tty")),Ho=R(require("fs"));function u_(e){return/-rc\.|-beta\./.test(e)}function Xa(e){return Bo.createHash("sha256").update(e.trim()).digest("hex")}function ud(e){return Lt==="SKIP"?!0:Bo.timingSafeEqual(Buffer.from(Xa(e)),Buffer.from(Lt))}function d_(){try{let e=Ho.openSync("/dev/tty","r+"),t=new Fo.ReadStream(e),n=new Fo.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{Ho.closeSync(e)}catch{}}}}}catch{if(!process.stdin.isTTY)throw new Error("No interactive terminal available. Set VISA_RC_CODE env var instead.");return{input:process.stdin,output:process.stderr,cleanupStreams:()=>{}}}}function f_(e){return new Promise((t,n)=>{let r;try{r=d_()}catch(u){n(u);return}let{input:s,output:o,cleanupStreams:i}=r,a=()=>{s.off("data",l);try{s.setRawMode?.(!1)}catch{}i()};o.write(e),s.setRawMode?.(!0),s.resume(),s.setEncoding("utf8");let c="",l=u=>{u==="\r"||u===`
11
11
  `?(o.write(`
12
12
  `),a(),t(c)):u===""?(o.write(`
@@ -109,7 +109,7 @@ ${h}`:f}function V_(e){let t=` ${ee("\u2502",Q.chrome)} `,n=[];if(typeof e.spent
109
109
  `)}catch{}}function Bd(){try{let e=js();if(!e)return;let t={...e,renderedAt:0};Br(fn(),JSON.stringify(t)+`
110
110
  `)}catch{}}function Kn(){try{W.unlinkSync(Md())}catch{}}function js(){let e=fn();if(!W.existsSync(e))return null;try{let t=JSON.parse(W.readFileSync(e,"utf-8"));return typeof t?.line=="string"&&ei(t.line)?null:t}catch{return null}}function ei(e){for(let t of e.split(`
111
111
  `)){let n=t.trim();if(n.length===0)continue;let r=n.replace(/\[[0-?]*[ -/]*[@-~]/g,"").trim();if(/^VISA\s*\|\s*loading\b/i.test(r)||/^VISA\s*\|\s*HUD\s+not\s+(ready|initialized)\b/i.test(r))return!0}return!1}function Fd(){return js()?.status??null}function J_(){if(process.env.JEST_WORKER_ID)return;let e=Md();try{if(W.mkdirSync(Z.dirname(e),{recursive:!0}),!sb(e))return;let t=process.argv[1]?Z.resolve(process.argv[1]):"";if(!t){Kn();return}let n=Wo(),r=(process.env.VISA_CLI_HUD_THEME??"").toLowerCase().trim(),s=n==="no-color"||r==="light"||r==="dark"?{}:{VISA_CLI_HUD_THEME:n},o=(0,Pd.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,...s,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});o.once("error",Kn),o.unref()}catch{Kn()}}function pn(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim()}var X_=/^\u001B\[(?:0|38;2;\d{1,3};\d{1,3};\d{1,3}|38;5;\d{1,3})m$/;function Z_(e){let t=[],n=`__VISA_CLI_HUD_SGR_${(0,ac.randomBytes)(8).toString("hex")}_`,r=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,o=>{if(!X_.test(o))return"";let i=`${n}${t.length}__`;return t.push(o),i}),s=new RegExp(`${n}(\\d+)__`,"g");return pn(r).replace(s,(o,i)=>t[Number(i)]??"")}function Q_(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${ee(r||"",Q.green)}${ee(s||"",Q.chrome)}`}function jr(e){return`$${e.toFixed(2)}`}function eb(e){let t=e;if(t.startsWith("/")&&(t=t.replace(/^\/(?:api\/)?v\d+\/fal\//,""),t=t.replace(/^\/(?:api\/)?v\d+\/(?:shortcuts|openrouter)\//,""),t.startsWith("/"))){let s=t.split("/").filter(Boolean);t=s[s.length-1]||t}return t=t.replace(/^fal-ai\//,""),t=t.replace(/^fal-/,""),t=t.replace(/^or-/,""),t=t.split("/").filter(Boolean).map(s=>s.replace(/^v\d+(?:\.\d+)?-?/,"")||null).filter(s=>s!==null&&s.length>0).join(" "),t=t.replace(/_card$/,""),t.length>28&&(t=t.slice(0,28).trimEnd()),t||e}function tb(e){let t=e.cards?.find(a=>a.isDefault)??e.cards?.[0];if(!t)return"card none";let n=typeof t.brand=="string"?t.brand:"card",r=typeof t.last4=="string"?t.last4:"????",s=pn(n.toUpperCase()),o=pn(r);return`${t.isDefault?"default":"active"} ${s} ****${o}`}var Q={get reset(){return Re().reset},get visaBlue(){return Re().visaBlue},get visaBlueSoft(){return Re().visaBlueSoft},get visaGold(){return Re().visaGold},get green(){return Re().green},get muted(){return Re().muted},get chrome(){return Re().chrome}};function ee(e,t){return e.length===0||process.env.NO_COLOR||Yo()?e:`${t}${e}${Q.reset}`}function $d(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function dc(){let e=Gn.homedir();if(!e||!Z.isAbsolute(e))throw new Error("unable to determine a valid home directory");return Z.resolve(e)}function nb(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function rb(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function sb(e){for(let t=0;t<2;t+=1){let n;try{return n=W.openSync(e,"wx"),W.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=W.statSync(e);if(Date.now()-s.mtimeMs<=U_)return!1;W.unlinkSync(e)}catch{}}finally{n!==void 0&&W.closeSync(n)}}return!1}function ic(e){return e instanceof Error?e.message:"unknown file system error"}function Br(e,t){W.mkdirSync(Z.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${(0,ac.randomBytes)(8).toString("hex")}.tmp`;try{W.writeFileSync(n,t),W.renameSync(n,e)}catch(r){try{W.unlinkSync(n)}catch{}throw r}}var ob=1440*60*1e3;function ni(e,t){ve.mkdirSync(Le.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${qd.randomBytes(8).toString("hex")}.tmp`;try{ve.writeFileSync(n,JSON.stringify(t,null,2)+`
112
- `),ve.renameSync(n,e)}catch(r){try{ve.unlinkSync(n)}catch{}throw r}}function Hd(e){return`'${e.replace(/'/g,"'\\''")}'`}var pc="# visa-cli-hud-v1";function ri(e,t){if(!e&&!t&&ib())return`visa-cli config statusline ${pc}`;let n=e??process.execPath,r=t??process.argv[1]??"",s=r?Le.resolve(r):"";return`${s?`${Hd(n)} ${Hd(s)} config statusline`:"visa-cli config statusline"} ${pc}`}function ib(){try{return(0,Kd.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function mn(e){return typeof e!="string"?!1:e.includes(pc)?!0:e.includes("visa-cli")&&e.includes("statusline")}function ab(){return"3.3.0"}function si(e){let t=Le.dirname(Le.resolve(e));return Le.basename(t)===".claude"?Le.dirname(t):Gd.homedir()}function ti(e,t){let n=Le.relative(t,e);return!n.startsWith("..")&&!Le.isAbsolute(n)?`~/${n}`:e}function cb(e){return Le.join(si(e),".visa-cli","hud-self-heal.json")}function lb(e,t,n,r){try{if(!ve.existsSync(e))return!1;let s=JSON.parse(ve.readFileSync(e,"utf-8"));return s.version===t&&typeof s.checkedAt=="number"&&n-s.checkedAt<r}catch{return!1}}function fc(e,t,n){try{ni(e,{version:t,checkedAt:n})}catch{}}function ub(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function mc(e,t={}){let n=t.now??Date.now(),r=t.version??ab(),s=t.stampPath??cb(e),o=t.minIntervalMs??ob,i=[],a=!1,c=!1;if(!t.force&&lb(s,r,n,o))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:i,skippedReason:"recently checked"};try{if(!ve.existsSync(e))return fc(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let l=JSON.parse(ve.readFileSync(e,"utf-8")),u=l.statusLine,d=u&&typeof u=="object"&&!Array.isArray(u)?u.command:"";if(!mn(d))return fc(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let p=(t.getCommand??ri)();if(d!==p&&(l.statusLine=ub(u,p),ni(e,l),a=!0,i.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!oi()){let f=si(e);if(Wn(f).length>0){let h=Ut(null,f);if(h.removed&&h.rcPaths&&h.rcPaths.length>0){let w=h.rcPaths.map(C=>ti(C,f)).join(", ");c=!0,i.push(`Cleaned legacy shell-prompt HUD block from ${w}.`)}}}return fc(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i}}catch(l){if(t.force){let u=l instanceof Error?l.message:"unknown error";try{process.stderr.write(`visa-cli: HUD self-heal skipped \u2014 ${u}. Run: visa-cli config hud doctor
112
+ `),ve.renameSync(n,e)}catch(r){try{ve.unlinkSync(n)}catch{}throw r}}function Hd(e){return`'${e.replace(/'/g,"'\\''")}'`}var pc="# visa-cli-hud-v1";function ri(e,t){if(!e&&!t&&ib())return`visa-cli config statusline ${pc}`;let n=e??process.execPath,r=t??process.argv[1]??"",s=r?Le.resolve(r):"";return`${s?`${Hd(n)} ${Hd(s)} config statusline`:"visa-cli config statusline"} ${pc}`}function ib(){try{return(0,Kd.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function mn(e){return typeof e!="string"?!1:e.includes(pc)?!0:e.includes("visa-cli")&&e.includes("statusline")}function ab(){return"3.3.1-rc.0"}function si(e){let t=Le.dirname(Le.resolve(e));return Le.basename(t)===".claude"?Le.dirname(t):Gd.homedir()}function ti(e,t){let n=Le.relative(t,e);return!n.startsWith("..")&&!Le.isAbsolute(n)?`~/${n}`:e}function cb(e){return Le.join(si(e),".visa-cli","hud-self-heal.json")}function lb(e,t,n,r){try{if(!ve.existsSync(e))return!1;let s=JSON.parse(ve.readFileSync(e,"utf-8"));return s.version===t&&typeof s.checkedAt=="number"&&n-s.checkedAt<r}catch{return!1}}function fc(e,t,n){try{ni(e,{version:t,checkedAt:n})}catch{}}function ub(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function mc(e,t={}){let n=t.now??Date.now(),r=t.version??ab(),s=t.stampPath??cb(e),o=t.minIntervalMs??ob,i=[],a=!1,c=!1;if(!t.force&&lb(s,r,n,o))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:i,skippedReason:"recently checked"};try{if(!ve.existsSync(e))return fc(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let l=JSON.parse(ve.readFileSync(e,"utf-8")),u=l.statusLine,d=u&&typeof u=="object"&&!Array.isArray(u)?u.command:"";if(!mn(d))return fc(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let p=(t.getCommand??ri)();if(d!==p&&(l.statusLine=ub(u,p),ni(e,l),a=!0,i.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!oi()){let f=si(e);if(Wn(f).length>0){let h=Ut(null,f);if(h.removed&&h.rcPaths&&h.rcPaths.length>0){let w=h.rcPaths.map(C=>ti(C,f)).join(", ");c=!0,i.push(`Cleaned legacy shell-prompt HUD block from ${w}.`)}}}return fc(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i}}catch(l){if(t.force){let u=l instanceof Error?l.message:"unknown error";try{process.stderr.write(`visa-cli: HUD self-heal skipped \u2014 ${u}. Run: visa-cli config hud doctor
113
113
  `)}catch{}}return{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i}}}function db(e,t){let n=si(t),r=Wn(n);if(r.length===0)return e;let s=r.map(o=>ti(o,n)).join(", ");return`${e}
114
114
  Note: a shell-prompt HUD block was detected in ${s}. If it is unintended, remove it with: visa-cli config hud disable shell`}function oi(e=process.env.VISA_HUD_KEEP_SHELL){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function Vd(e,t){let n=si(t),r=Wn(n);if(r.length===0)return e;let s=r.map(i=>ti(i,n)).join(", ");if(oi())return`${e}
115
115
  Note: a legacy shell-prompt HUD block was detected in ${s}. VISA_HUD_KEEP_SHELL set \u2014 leaving it in place. Remove it any time with: visa-cli config hud disable shell`;let o=Ut(null,n);if(o.removed&&o.rcPaths&&o.rcPaths.length>0){let i=o.rcPaths.map(a=>ti(a,n)).join(", ");return`${e}
@@ -129,7 +129,7 @@ ${a}`}function bb(e){if(typeof e!="number"||e<=0)return"";let n=(e>1e12?e:e*1e3)
129
129
  `)}var Sf="WARNING: This Visa Key is a bearer secret for headless API use. Touch ID will not be prompted when the key is used; anyone with the key can spend prepaid balance within the caps above until it expires or is revoked. Store it like a password and revoke it immediately if exposed.";function Ib(e){let t=Math.max(5,...e.map(([o])=>o.length)),n=Math.max(5,...e.map(([,o])=>o.length)),r=`+-${"-".repeat(t)}-+-${"-".repeat(n)}-+`,s=(o,i)=>`| ${o.padEnd(t)} | ${i.padEnd(n)} |`;return[r,s("Field","Value"),r,...e.map(([o,i])=>s(o,i)),r]}function xf(e,t={}){let n=t.authUrl??"https://auth.visacli.sh",r=[...Rb().split(`
130
130
  `),"","Visa Key active","Scoped agent spend credential ready for apps and agents","",...Ib([["Key",e.key],["Label",e.label],["Owner",e.owner],["Daily cap",`${vc(e.daily_cap_cents)}/day`],["Total cap",vf(e.total_cap_cents)],["Allowed tools",wf(e.allowed_tools)]]),"","Guardrails",`- Spend: ${vc(e.daily_cap_cents)}/day, ${vf(e.total_cap_cents)} total`,`- Tools: ${wf(e.allowed_tools)}`,"- Auth: X-Api-Key header; no OAuth handoff or per-call Touch ID","","Use it","Save this key now - it won't be shown again.","",`export VISAKEY_API_KEY=${e.key}`,"",`POST ${n}/v1/api/tools/{tool_name}/execute`,"Headers: X-Api-Key, Idempotency-Key, Content-Type: application/json"];return e.biometric_warning?r.push("",Sf,`Server warning: ${e.biometric_warning}`):e.biometric_enabled&&r.push("",Sf),`${r.join(`
131
131
  `)}
132
- `}function Tf(e){return e.json===!0||e.isTTY!==!0}function wc(e){if(!e)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error("--daily-cap must be a positive USD amount.");let n=Math.round(t*100);if(n<100||n>1e4)throw new Error("--daily-cap must be between 1 and 100 USD.");return n}function Sc(e){if(e===!1)return null;if(!e)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error("--total-cap must be a positive USD amount.");let n=Math.round(t*100);if(n<100||n>1e6)throw new Error("--total-cap must be between 1 and 10000 USD.");return n}function Cf(e,t){let n=wc(e);if(n!==void 0)return n;if(Tf(t))return 500}function kf(e,t){let n=Sc(e);if(n!==void 0)return n;if(Tf(t)||t.recommendedCapsAccepted===!0)return 2500}async function ht(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,s=setTimeout(()=>r.abort(),n);try{let{timeoutMs:o,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(s)}}var zn=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},Hr=class extends Error{code;budgetId;status;constructor(t,n,r={}){super(t),this.name="SessionInvalidError",this.code=n,this.budgetId=r.budgetId,this.status=r.status}},Bt=class extends Error{code="SESSION_LOCK_CONTENDED";retryAfterSecs;status;constructor(t,n=1,r){super(t),this.name="SessionLockContendedError",this.retryAfterSecs=n,this.status=r}},yt=class extends Error{code="PARENTLESS_NOT_ENABLED";status;serverErrorCode;constructor(t,n={}){super(t),this.name="ParentlessNotEnabledError",this.status=n.status,this.serverErrorCode=n.serverErrorCode}},ge=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(t,n,r,s,o,i,a,c){super(t),this.name="CardDeclinedError",this.retryable=n,this.code=r,this.reason=s,this.paymentErrorClass=o,this.correlationId=i,this.transactionId=a,this.retryAfter=c}},tt=class extends Error{code;transactionId;retryable;reconciliationRequired;constructor(t,n,r={}){super(t),this.name="TopupAmbiguousError",this.code=n,this.transactionId=r.transactionId,this.retryable=r.retryable??!1,this.reconciliationRequired=r.reconciliationRequired??!0}};var Ef={ENOTFOUND:"Cannot resolve the Visa CLI server hostname (DNS error). Check your internet connection or the auth.serverUrl setting.",EAI_AGAIN:"DNS lookup for the Visa CLI server failed temporarily. Check your internet connection and try again.",ECONNREFUSED:"The Visa CLI server refused the connection. The service may be down \u2014 check https://visacli.sh for status.",ECONNRESET:"The connection to the Visa CLI server was reset mid-request. Try again in a moment.",EHOSTUNREACH:"The Visa CLI server is unreachable from this network. Check your internet connection.",ETIMEDOUT:"The connection to the Visa CLI server timed out. Try again or check https://visacli.sh for status.",CERT_HAS_EXPIRED:"The Visa CLI server's TLS certificate is expired. Check https://visacli.sh for status; do not bypass the cert.",UND_ERR_CONNECT_TIMEOUT:"The connection to the Visa CLI server timed out before it could be established. Try again in a moment.",UND_ERR_SOCKET:"The connection to the Visa CLI server was interrupted. Try again in a moment."};function Vr(e){let t=e&&typeof e=="object"?e:{};if(t.name==="AbortError"||typeof t.message=="string"&&t.message.includes("aborted"))return"The request timed out. The server may be under heavy load. Please try again.";let n=(t.cause&&typeof t.cause=="object"?t.cause.code:void 0)??(typeof t.code=="string"?t.code:void 0);return n&&Ef[n]?Ef[n]:`Network error contacting the Visa CLI server (${n?`${n}: ${typeof t.message=="string"?t.message:"unknown"}`:typeof t.message=="string"&&t.message.length>0?t.message:"unknown error"}). Check https://visacli.sh for status.`}_t();var Nb=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function If(e,t){let n=Rf(e),r=Rf(t);if(!n||!r)return!1;for(let s=0;s<3;s++)if(n.main[s]!==r.main[s])return n.main[s]>r.main[s];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:Lb(n.pre,r.pre)>0}function Rf(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(Nb);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function Lb(e,t){let n=e.split("."),r=t.split("."),s=Math.max(n.length,r.length);for(let o=0;o<s;o++){if(o>=n.length)return-1;if(o>=r.length)return 1;let i=n[o],a=r[o],c=/^\d+$/.test(i),l=/^\d+$/.test(a);if(c&&l){let u=Number(i)-Number(a);if(u!==0)return u}else{if(c)return-1;if(l)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function bt(){return!!($f(process.env.VISA_CLI_NO_UPDATE_CHECK)||$f(process.env.CI)||process.env.NODE_ENV==="test")}function $f(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}Ht();var Gb="CARD_REENROLLMENT_REQUIRED",Wb="https://auth.visacli.sh/enroll-card";function Yb(){try{return new URL("/enroll-card",Ue()).toString()}catch{return Wb}}function zb(e){let t=Yb();if(typeof e!="string")return t;try{let n=new URL(e),r=new URL(t);if(n.origin===r.origin&&n.pathname==="/enroll-card")return n.toString()}catch{}return g.warn("card-reenroll:reenroll_url_rejected_fallback",{reason:"untrusted_or_malformed_reenroll_url",fallbackPath:"/enroll-card"}),t}var yn="3.3.0",Jb=/^(?:VisaKey_[A-Za-z0-9_-]{16,128}|visakey_[A-Za-z0-9_-]{16,128}|vk_[A-Za-z0-9_-]{32,128})$/;function Xb(e){if(typeof e!="string")return null;switch(e){case"BUDGET_CLOSED":case"BUDGET_NOT_FOUND":case"BUDGET_EXPIRED":return e;default:return null}}function Oc(e){return e==="TOPUP_CHARGE_AMBIGUOUS"||e==="TOPUP_RECONCILIATION_REQUIRED"?e:null}var Zb="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function qr(e){return typeof e=="string"?e.trim():""}function Ws(e){let t=e&&typeof e=="object"?e:{},n=qr(t.error)||qr(t.message);if(!n)return Zb;let r=qr(t.error_code),s=[["surface",qr(t.disabled_surface)],["flag",qr(t.flag)],["correlation_id",qr(t.correlation_id)]].filter(([,i])=>i).map(([i,a])=>`${i}=${a}`),o=s.length?` (${s.join(" ")})`:"";return r?`503 [${r}] ${n}${o}`:`503 ${n}${o}`}function Ys(e=process.env,t=process.stdin.isTTY){let n=["Not logged in. No local Visa CLI session credentials were found."],r=e.VISA_CLI_API_KEY?.trim();return r?Jb.test(r)?(n.push("VISA_CLI_API_KEY is set, but MCP bearer tools currently require a local session from visa-cli setup."),n.push("For headless API-key use, call the /v1/api/* HTTP routes with X-Api-Key instead of MCP bearer tools.")):(n.push("VISA_CLI_API_KEY is set but has invalid format (expected VisaKey_<...> or legacy vk_<...>)."),n.push("Create a new Visa Key with: visa-cli keys create <app-name>")):n.push("Run `visa-cli setup` in an interactive terminal to authenticate."),t===!1&&n.push("This process appears to be running without a TTY; complete setup in a normal terminal, then restart the MCP client."),n.join(`
132
+ `}function Tf(e){return e.json===!0||e.isTTY!==!0}function wc(e){if(!e)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error("--daily-cap must be a positive USD amount.");let n=Math.round(t*100);if(n<100||n>1e4)throw new Error("--daily-cap must be between 1 and 100 USD.");return n}function Sc(e){if(e===!1)return null;if(!e)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error("--total-cap must be a positive USD amount.");let n=Math.round(t*100);if(n<100||n>1e6)throw new Error("--total-cap must be between 1 and 10000 USD.");return n}function Cf(e,t){let n=wc(e);if(n!==void 0)return n;if(Tf(t))return 500}function kf(e,t){let n=Sc(e);if(n!==void 0)return n;if(Tf(t)||t.recommendedCapsAccepted===!0)return 2500}async function ht(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,s=setTimeout(()=>r.abort(),n);try{let{timeoutMs:o,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(s)}}var zn=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},Hr=class extends Error{code;budgetId;status;constructor(t,n,r={}){super(t),this.name="SessionInvalidError",this.code=n,this.budgetId=r.budgetId,this.status=r.status}},Bt=class extends Error{code="SESSION_LOCK_CONTENDED";retryAfterSecs;status;constructor(t,n=1,r){super(t),this.name="SessionLockContendedError",this.retryAfterSecs=n,this.status=r}},yt=class extends Error{code="PARENTLESS_NOT_ENABLED";status;serverErrorCode;constructor(t,n={}){super(t),this.name="ParentlessNotEnabledError",this.status=n.status,this.serverErrorCode=n.serverErrorCode}},ge=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(t,n,r,s,o,i,a,c){super(t),this.name="CardDeclinedError",this.retryable=n,this.code=r,this.reason=s,this.paymentErrorClass=o,this.correlationId=i,this.transactionId=a,this.retryAfter=c}},tt=class extends Error{code;transactionId;retryable;reconciliationRequired;constructor(t,n,r={}){super(t),this.name="TopupAmbiguousError",this.code=n,this.transactionId=r.transactionId,this.retryable=r.retryable??!1,this.reconciliationRequired=r.reconciliationRequired??!0}};var Ef={ENOTFOUND:"Cannot resolve the Visa CLI server hostname (DNS error). Check your internet connection or the auth.serverUrl setting.",EAI_AGAIN:"DNS lookup for the Visa CLI server failed temporarily. Check your internet connection and try again.",ECONNREFUSED:"The Visa CLI server refused the connection. The service may be down \u2014 check https://visacli.sh for status.",ECONNRESET:"The connection to the Visa CLI server was reset mid-request. Try again in a moment.",EHOSTUNREACH:"The Visa CLI server is unreachable from this network. Check your internet connection.",ETIMEDOUT:"The connection to the Visa CLI server timed out. Try again or check https://visacli.sh for status.",CERT_HAS_EXPIRED:"The Visa CLI server's TLS certificate is expired. Check https://visacli.sh for status; do not bypass the cert.",UND_ERR_CONNECT_TIMEOUT:"The connection to the Visa CLI server timed out before it could be established. Try again in a moment.",UND_ERR_SOCKET:"The connection to the Visa CLI server was interrupted. Try again in a moment."};function Vr(e){let t=e&&typeof e=="object"?e:{};if(t.name==="AbortError"||typeof t.message=="string"&&t.message.includes("aborted"))return"The request timed out. The server may be under heavy load. Please try again.";let n=(t.cause&&typeof t.cause=="object"?t.cause.code:void 0)??(typeof t.code=="string"?t.code:void 0);return n&&Ef[n]?Ef[n]:`Network error contacting the Visa CLI server (${n?`${n}: ${typeof t.message=="string"?t.message:"unknown"}`:typeof t.message=="string"&&t.message.length>0?t.message:"unknown error"}). Check https://visacli.sh for status.`}_t();var Nb=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function If(e,t){let n=Rf(e),r=Rf(t);if(!n||!r)return!1;for(let s=0;s<3;s++)if(n.main[s]!==r.main[s])return n.main[s]>r.main[s];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:Lb(n.pre,r.pre)>0}function Rf(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(Nb);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function Lb(e,t){let n=e.split("."),r=t.split("."),s=Math.max(n.length,r.length);for(let o=0;o<s;o++){if(o>=n.length)return-1;if(o>=r.length)return 1;let i=n[o],a=r[o],c=/^\d+$/.test(i),l=/^\d+$/.test(a);if(c&&l){let u=Number(i)-Number(a);if(u!==0)return u}else{if(c)return-1;if(l)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function bt(){return!!($f(process.env.VISA_CLI_NO_UPDATE_CHECK)||$f(process.env.CI)||process.env.NODE_ENV==="test")}function $f(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}Ht();var Gb="CARD_REENROLLMENT_REQUIRED",Wb="https://auth.visacli.sh/enroll-card";function Yb(){try{return new URL("/enroll-card",Ue()).toString()}catch{return Wb}}function zb(e){let t=Yb();if(typeof e!="string")return t;try{let n=new URL(e),r=new URL(t);if(n.origin===r.origin&&n.pathname==="/enroll-card")return n.toString()}catch{}return g.warn("card-reenroll:reenroll_url_rejected_fallback",{reason:"untrusted_or_malformed_reenroll_url",fallbackPath:"/enroll-card"}),t}var yn="3.3.1-rc.0",Jb=/^(?:VisaKey_[A-Za-z0-9_-]{16,128}|visakey_[A-Za-z0-9_-]{16,128}|vk_[A-Za-z0-9_-]{32,128})$/;function Xb(e){if(typeof e!="string")return null;switch(e){case"BUDGET_CLOSED":case"BUDGET_NOT_FOUND":case"BUDGET_EXPIRED":return e;default:return null}}function Oc(e){return e==="TOPUP_CHARGE_AMBIGUOUS"||e==="TOPUP_RECONCILIATION_REQUIRED"?e:null}var Zb="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function qr(e){return typeof e=="string"?e.trim():""}function Ws(e){let t=e&&typeof e=="object"?e:{},n=qr(t.error)||qr(t.message);if(!n)return Zb;let r=qr(t.error_code),s=[["surface",qr(t.disabled_surface)],["flag",qr(t.flag)],["correlation_id",qr(t.correlation_id)]].filter(([,i])=>i).map(([i,a])=>`${i}=${a}`),o=s.length?` (${s.join(" ")})`:"";return r?`503 [${r}] ${n}${o}`:`503 ${n}${o}`}function Ys(e=process.env,t=process.stdin.isTTY){let n=["Not logged in. No local Visa CLI session credentials were found."],r=e.VISA_CLI_API_KEY?.trim();return r?Jb.test(r)?(n.push("VISA_CLI_API_KEY is set, but MCP bearer tools currently require a local session from visa-cli setup."),n.push("For headless API-key use, call the /v1/api/* HTTP routes with X-Api-Key instead of MCP bearer tools.")):(n.push("VISA_CLI_API_KEY is set but has invalid format (expected VisaKey_<...> or legacy vk_<...>)."),n.push("Create a new Visa Key with: visa-cli keys create <app-name>")):n.push("Run `visa-cli setup` in an interactive terminal to authenticate."),t===!1&&n.push("This process appears to be running without a TTY; complete setup in a normal terminal, then restart the MCP client."),n.join(`
133
133
  `)}var Ve=class{constructor(t){this.getSessionToken=t;this.baseUrl=Ue()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!bt()){let r=t.headers.get("X-Latest-Version");r&&If(r,yn)&&(this.lastSignals.updateAvailable={currentVersion:yn,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return yn}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new zn(t.error||"Your biometric key is out of sync with the server.",typeof t.hint=="string"?t.hint:void 0)}async throwServerUnavailable(t){let n=null;try{n=await t.json()}catch{}throw new Error(Ws(n))}async request(t,n,r,s,o,i){let a=await this.getSessionToken();if(!a)throw new Error(Ys());let c={Authorization:`Bearer ${a}`};o&&(t==="GET"?c["X-User-Context"]=encodeURIComponent(o.replace(/[\r\n\0]/g," ").slice(0,1e3)):r={...r||{},user_context:o}),i&&(c["X-Visa-Meta-Tool"]=i),r&&(c["Content-Type"]="application/json");let l;try{l=await ht(`${this.baseUrl}${n}`,{method:t,headers:{...c,"X-Visa-CLI-Version":yn,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:s})}catch(d){throw new Error(Vr(d))}if(this.parseServerSignals(l),l.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(l.status===429){let d=l.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${d}s. Tip: use the batch tool to combine multiple requests into one.`)}l.status===503&&await this.throwServerUnavailable(l);let u;try{u=await l.json()}catch{throw l.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${n}. Try again.`)}if(!l.ok){if(l.status===500)throw new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(u),typeof u?.error_code=="string"&&u.error_code===Gb){let p=typeof u?.last4=="string"?u.last4:"",f=typeof u?.brand=="string"?u.brand:"card",m=zb(u?.reenroll_url),h=p?`${f} ending in ${p}`:"your card";throw new Error(`Please re-add ${h} to keep payments running. Open: ${m}`)}let d=Oc(u?.error_code);if(d)throw new tt(u?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",d,{transactionId:typeof u?.transactionId=="string"?u.transactionId:void 0,retryable:!!u?.retryable,reconciliationRequired:u?.reconciliation_required!==!1});if(u?.declined){let p=Number(u.retryAfter??l.headers.get("Retry-After"));throw new ge(u.error||"Your card was declined.",!!u.retryable,u.code,u.reason,u.payment_error_class,u.correlation_id,u.transactionId,Number.isFinite(p)&&p>0?p:void 0)}if(l.status===402){let p=u?.error||"Gateway returned 402",f=typeof u?.error_code=="string"?u.error_code:"";throw f==="SPENDING_LIMIT_EXCEEDED"||f==="DAILY_LIMIT_EXCEEDED"||f==="PER_TXN_LIMIT_EXCEEDED"?new Error(`${p}. Check your limits with get_status or run: visa-cli update-spending-controls`):new Error(p)}throw new Error(u?.error||`Request failed (${l.status}). Try again.`)}return u}async shortcut(t,n,r,s,o){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,s,o)}async shortcutWithSession(t,n,r,s,o,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error(Ys());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":yn,"X-Source":"cli","Content-Type":"application/json"};i&&(l["X-Visa-Meta-Tool"]=i);let u={...n,...r};o&&(u.user_context=o.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await ht(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(m){throw new Error(Vr(m))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let m=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${m}s. Tip: use the batch tool to combine multiple requests into one.`)}let p=d.headers.get("X-Voucher-Receipt"),f;try{f=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(f),d.status===503){if(f?.error_code==="SESSION_LOCK_CONTENDED"){let w=Number(d.headers.get("Retry-After"))||1;throw new Bt(f?.message||f?.error||"Session budget is being modified by another request. Retry shortly.",w,d.status)}throw new Error(Ws(f))}let m=Xb(f?.error_code);if(m||d.status===410){let w=m??"BUDGET_CLOSED";throw new Hr(f?.message||f?.error||"Your session was invalidated by the server.",w,{budgetId:n.session_budget_id,status:d.status})}if(f?.declined){let w=Number(f.retryAfter??d.headers.get("Retry-After"));throw new ge(f.error||"Your card was declined.",!!f.retryable,f.code,f.reason,f.payment_error_class,f.correlation_id,f.transactionId,Number.isFinite(w)&&w>0?w:void 0)}let h=Oc(f?.error_code);throw h?new tt(f?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",h,{transactionId:typeof f?.transactionId=="string"?f.transactionId:void 0,retryable:!!f?.retryable,reconciliationRequired:f?.reconciliation_required!==!1}):new Error(f?.error||`Request failed (${d.status}). Try again.`)}return{data:f,voucherReceiptHeader:p}}async shortcutParentless(t,n,r,s,o,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error(Ys());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":yn,"X-Source":"cli","Content-Type":"application/json"};i&&(l["X-Visa-Meta-Tool"]=i);let u={...r,...n.attestation?{attestation:n.attestation}:{},nonce:n.nonce,approved_max_cents:n.approved_max_cents,idempotency_key:n.idempotency_key,...n.stream===!0?{stream:!0}:{}};o&&(u.user_context=o.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await ht(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(m){throw new Error(Vr(m))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let m=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${m}s. Tip: use the batch tool to combine multiple requests into one.`)}let p=d.headers.get("X-Voucher-Receipt"),f;try{f=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):d.status===404?new yt("Parentless single-call is not available on this server.",{status:404}):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);this.throwIfAttestationDrift(f);let m=typeof f?.error_code=="string"?f.error_code:void 0;if(d.status===410&&m==="DIRECT_SHORTCUT_CARD_SURFACE_RETIRED")throw new yt(f?.error||"Parentless single-call is not enabled on this server.",{status:d.status,serverErrorCode:m});if(d.status===503){if(f?.error_code==="SESSION_LOCK_CONTENDED"){let w=Number(d.headers.get("Retry-After"))||1;throw new Bt(f?.message||f?.error||"Session budget is being modified by another request. Retry shortly.",w,d.status)}throw new Error(Ws(f))}if(f?.declined){let w=Number(f.retryAfter??d.headers.get("Retry-After"));throw new ge(f.error||"Your card was declined.",!!f.retryable,f.code,f.reason,f.payment_error_class,f.correlation_id,f.transactionId,Number.isFinite(w)&&w>0?w:void 0)}let h=Oc(f?.error_code);throw h?new tt(f?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",h,{transactionId:typeof f?.transactionId=="string"?f.transactionId:void 0,retryable:!!f?.retryable,reconciliationRequired:f?.reconciliation_required!==!1}):new Error(f?.error||`Request failed (${d.status}). Try again.`)}return{data:f,voucherReceiptHeader:p}}async batchOpen(t){let n="/v1/batch/open",r=await this.getSessionToken();if(!r)throw new Error(Ys());let s={Authorization:`Bearer ${r}`,"X-Visa-CLI-Version":yn,"X-Source":"cli","Content-Type":"application/json"},o={...t.attestation?{attestation:t.attestation}:{},nonce:t.nonce,approved_total_cents:t.approved_total_cents,batch_id:t.batch_id},i;try{i=await ht(`${this.baseUrl}${n}`,{method:"POST",headers:s,body:JSON.stringify(o),timeoutMs:void 0})}catch(u){throw new Error(Vr(u))}if(this.parseServerSignals(i),i.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(i.status===429){let u=i.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${u}s before opening another batch.`)}let a;try{a=await i.json()}catch{throw i.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):i.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):i.status===404?new yt("Parentless batch is not available on this server.",{status:404}):new Error(`Unexpected response from ${n}. Try again.`)}if(!i.ok){if(i.status===500)throw new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`);this.throwIfAttestationDrift(a);let u=typeof a?.error_code=="string"?a.error_code:void 0;if(i.status===410&&u==="DIRECT_SHORTCUT_CARD_SURFACE_RETIRED")throw new yt(a?.error||"Parentless batch is not enabled on this server.",{status:i.status,serverErrorCode:u});if(i.status===503)throw new Error(Ws(a));if(a?.declined){let d=Number(a.retryAfter??i.headers.get("Retry-After"));throw new ge(a.error||"Your card was declined.",!!a.retryable,a.code,a.reason,a.payment_error_class,a.correlation_id,a.transactionId,Number.isFinite(d)&&d>0?d:void 0)}throw new Error(a?.error||`Request failed (${i.status}). Try again.`)}let c=a?.parent_spend_execution_id??a?.batch_parent_id??a?.parent_id??a?.spend_execution_id,l=a?.idempotency_scope??a?.idempotency_key_scope??t.batch_id;if(typeof c!="string"||c.length===0)throw new Error(`Batch open returned no parent id from ${n}. Try again.`);return{batch_parent_id:c,idempotency_scope:String(l)}}async shortcutParentlessBatchItem(t,n,r,s,o,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error(Ys());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":yn,"X-Source":"cli","Content-Type":"application/json"};i&&(l["X-Visa-Meta-Tool"]=i);let u={...r,batch_parent_id:n.batch_parent_id,batch_id:n.batch_id,batch_index:n.batch_index,batch_request_hash:n.batch_request_hash,item_ceiling_cents:n.item_ceiling_cents,idempotency_key:n.idempotency_key,...n.stream===!0?{stream:!0}:{}};o&&(u.user_context=o.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await ht(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(m){throw new Error(Vr(m))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let m=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${m}s. Tip: use the batch tool to combine multiple requests into one.`)}let p=d.headers.get("X-Voucher-Receipt"),f;try{f=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(f),d.status===503){if(f?.error_code==="SESSION_LOCK_CONTENDED"){let m=Number(d.headers.get("Retry-After"))||1;throw new Bt(f?.message||f?.error||"Batch parent is being modified by another request. Retry shortly.",m,d.status)}throw new Error(Ws(f))}if(f?.declined){let m=Number(f.retryAfter??d.headers.get("Retry-After"));throw new ge(f.error||"Your card was declined.",!!f.retryable,f.code,f.reason,f.payment_error_class,f.correlation_id,f.transactionId,Number.isFinite(m)&&m>0?m:void 0)}throw new Error(f?.error||`Request failed (${d.status}). Try again.`)}return{data:f,voucherReceiptHeader:p}}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async catalogSearch(t,n,r,s){let o=r??"discover_tools",i=new URLSearchParams;t&&i.set("q",t),n&&i.set("category",n),s?.limit!=null&&i.set("limit",String(s.limit)),s?.offset!=null&&i.set("offset",String(s.offset));let a=i.toString();return this.request("GET",`/v1/catalog${a?`?${a}`:""}`,void 0,void 0,void 0,o)}async catalogTool(t,n){let r=n??"discover_tools";try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(t)}`,void 0,void 0,void 0,r)}catch{return null}}async discoverMerchantRoutes(t){try{return await this.request("GET",`/v1/platform/discover/${encodeURIComponent(t)}`)}catch{return null}}async listPublicMerchants(){try{let t=await ht(`${this.baseUrl}/v1/platform/merchants/public`,{method:"GET",timeoutMs:8e3});if(!t.ok)return[];let n=await t.json();return Array.isArray(n.merchants)?n.merchants:[]}catch{return[]}}async getPublicMerchantDiscover(t){try{let n=await ht(`${this.baseUrl}/v1/platform/discover/${encodeURIComponent(t)}`,{method:"GET",timeoutMs:8e3});return n.ok?await n.json():null}catch{return null}}async paymentPreview(t,n){return this.request("POST","/v1/payment-preview",t,void 0,n)}async getBalance(){return this.request("GET","/v1/balance")}async topupBalance(t){return this.request("POST","/v1/balance/topup",t)}async createEnrollCode(){return this.request("POST","/v1/enroll-code")}async getAutoTopup(){let t=await this.getBalance();return{success:t.success,targetCents:t.autoTopupCents??null,thresholdCents:t.autoTopupThresholdCents??0}}async disableAutoTopup(){return this.request("PATCH","/v1/balance/auto-topup",{auto_topup_cents:null})}async createSessionBudget(t){return this.request("POST","/v1/session-budget/create",{...t,mode:"prepaid"})}async closeSession(t){return this.request("POST","/v1/session/close",{session_budget_id:t})}async getSessionBudget(t){return this.request("GET",`/v1/session-budget/${encodeURIComponent(t)}`)}async getSessionLedger(t){return this.request("GET",`/v1/session/${encodeURIComponent(t)}/ledger`)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getVisaSmi(t,n){return this.request("POST","/v1/visa/smi",t,6e4,n)}async getTransactions(t,n){let r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.offset!=null&&r.set("offset",String(t.offset));let s=r.toString(),o=s?`/v1/transactions?${s}`:"/v1/transactions";return this.request("GET",o,void 0,void 0,n)}async updateSpendingControls(t,n){return this.request("POST","/v1/spending-controls",t,void 0,n)}async removeCard(t,n,r){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(t))}`,n,void 0,r)}async setDefaultCard(t,n,r){return this.request("POST",`/v1/cards/${encodeURIComponent(String(t))}/default`,n,void 0,r)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t,n){return this.request("POST","/v1/attestation-key",{publicKey:t,...n?{attestation:n}:{}})}async startAttestationRecovery(t,n){return this.request("POST","/v1/attestation-key/recovery/start",{state:t},void 0,n)}async setBiometricPreference(t,n){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,n)}async getPendingWebAuthenticators(t){return this.request("GET","/v1/webauthn/pending",void 0,void 0,t)}async authorizeWebAuthenticator(t,n){return this.request("POST","/v1/webauthn/authorize",t,void 0,n)}async logout(t,n){return this.request("POST","/v1/logout",t,void 0,n)}async feedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async createAppApiKey(t){return this.request("POST","/v1/api/keys",t)}async listAppApiKeys(t){let n=new URLSearchParams;t?.limit!=null&&n.set("limit",String(t.limit)),t?.startingAfter!=null&&n.set("starting_after",String(t.startingAfter)),t?.endingBefore!=null&&n.set("ending_before",String(t.endingBefore));let r=n.toString();return this.request("GET",r?`/v1/api/keys?${r}`:"/v1/api/keys")}async listAllAppApiKeys(){let t=[],n=new Set,r,s=null,o=0;for(;;){let i=await this.listAppApiKeys({limit:100,...r!==void 0?{startingAfter:r}:{}});if(o+=1,s=i,t.push(...i.keys??[]),!i.has_more)break;if(i.next_cursor==null)throw new Error("API key pagination response did not include next_cursor.");if(n.has(i.next_cursor))throw new Error("API key pagination cursor did not advance.");n.add(i.next_cursor),r=i.next_cursor}return{...s??{success:!0,keys:[]},keys:t,limit:100,has_more:!1,next_cursor:null,previous_cursor:null,pages:o}}async revokeAppApiKey(t){return this.request("DELETE",`/v1/api/keys/${encodeURIComponent(String(t))}`)}async feedSubmit(t){return this.request("POST","/v1/feed",t)}async feedList(t){let n=new URLSearchParams;t?.tab&&n.set("tab",t.tab),t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset));let r=n.toString();return this.request("GET",`/v1/feed${r?"?"+r:""}`)}async feedVote(t,n){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/vote`,{direction:n})}async feedApprove(t){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/approve`)}async feedDelete(t){return this.request("DELETE",`/v1/feed/${encodeURIComponent(t)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async getFeedback(t,n){let r=new URLSearchParams;t&&r.set("limit",String(t));let s=r.toString();return this.request("GET",`/v1/feedback${s?"?"+s:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}};function zs(e,t){return t||(typeof e!="number"||!Number.isFinite(e)?"price unknown":`$${(e/100).toFixed(2)}`)}function Kf(e){let t=e.inputSchema?.properties;return t&&typeof t=="object"&&!Array.isArray(t)?Object.keys(t).join(", ")||"none":Object.keys(e.inputSchema||{}).join(", ")||"none"}function qf(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function Qb(e){let t=new Map;for(let n of e){let r=n.category||"other",s=t.get(r)??[];s.push(n),t.set(r,s)}return new Map([...t.entries()].sort(([n],[r])=>n.localeCompare(r)))}function e0(e){return Math.max(4,e.reduce((t,n)=>Math.max(t,n.id.length),0))}function t0(e){return Math.max(8,Math.min(14,e.reduce((t,n)=>Math.max(t,(n.category||"").length),0)))}function n0(e,t,n){let r=typeof process.stdout.columns=="number"&&process.stdout.columns>0?process.stdout.columns:100;return Math.max(16,r-(e+t+n+10))}function Gf(e){let t=e0(e),n=7,r=t0(e),s=n0(t,n,r);console.log(` ${"Tool".padEnd(t)} ${"Price".padEnd(n)} ${"Category".padEnd(r)} Params`),console.log(` ${"\u2500".repeat(t)} ${"\u2500".repeat(n)} ${"\u2500".repeat(r)} ${"\u2500".repeat(Math.min(s,32))}`);for(let o of e)console.log(` ${o.id.padEnd(t)} ${zs(o.priceCents,o.priceDisplay).padEnd(n)} ${qf(o.category||"other",r).padEnd(r)} ${qf(Kf(o),s)}`)}function Wf(e){console.log(`
134
134
  Merchant tools
135
135
  `),Gf(e),console.log("\nUse `visa-cli describe <tool>` for full details (incl. parameter types)."),console.log('Shortcut: `visa-cli generate image "a lobster"`\n')}function Mc(e){console.log(`
@@ -139,9 +139,9 @@ Merchant tools
139
139
  ${e} tools
140
140
  `),Gf(t),console.log("\nUse `visa-cli describe <tool>` for full details (incl. parameter types)."),console.log(`Or scope it: \`visa-cli merchants ${e} describe <tool>\`
141
141
  `)}var _={};No(_,{BRAND:()=>A0,DIRTY:()=>Zn,EMPTY_PATH:()=>i0,INVALID:()=>D,NEVER:()=>fv,OK:()=>Ie,ParseStatus:()=>Te,Schema:()=>V,ZodAny:()=>vn,ZodArray:()=>Gt,ZodBigInt:()=>er,ZodBoolean:()=>tr,ZodBranded:()=>Xs,ZodCatch:()=>fr,ZodDate:()=>nr,ZodDefault:()=>dr,ZodDiscriminatedUnion:()=>yi,ZodEffects:()=>Je,ZodEnum:()=>lr,ZodError:()=>Be,ZodFirstPartyTypeKind:()=>j,ZodFunction:()=>bi,ZodIntersection:()=>ir,ZodIssueCode:()=>x,ZodLazy:()=>ar,ZodLiteral:()=>cr,ZodMap:()=>Jr,ZodNaN:()=>Zr,ZodNativeEnum:()=>ur,ZodNever:()=>rt,ZodNull:()=>sr,ZodNullable:()=>St,ZodNumber:()=>Qn,ZodObject:()=>Fe,ZodOptional:()=>Ye,ZodParsedType:()=>E,ZodPipeline:()=>Zs,ZodPromise:()=>wn,ZodReadonly:()=>pr,ZodRecord:()=>_i,ZodSchema:()=>V,ZodSet:()=>Xr,ZodString:()=>bn,ZodSymbol:()=>Yr,ZodTransformer:()=>Je,ZodTuple:()=>wt,ZodType:()=>V,ZodUndefined:()=>rr,ZodUnion:()=>or,ZodUnknown:()=>Kt,ZodVoid:()=>zr,addIssueToContext:()=>k,any:()=>U0,array:()=>F0,bigint:()=>P0,boolean:()=>op,coerce:()=>dv,custom:()=>np,date:()=>O0,datetimeRegex:()=>ep,defaultErrorMap:()=>Vt,discriminatedUnion:()=>K0,effect:()=>rv,enum:()=>ev,function:()=>X0,getErrorMap:()=>Kr,getParsedType:()=>vt,instanceof:()=>I0,intersection:()=>G0,isAborted:()=>gi,isAsync:()=>Gr,isDirty:()=>hi,isValid:()=>_n,late:()=>R0,lazy:()=>Z0,literal:()=>Q0,makeIssue:()=>Js,map:()=>z0,nan:()=>$0,nativeEnum:()=>tv,never:()=>j0,null:()=>L0,nullable:()=>ov,number:()=>sp,object:()=>H0,objectUtil:()=>Nc,oboolean:()=>uv,onumber:()=>lv,optional:()=>sv,ostring:()=>cv,pipeline:()=>av,preprocess:()=>iv,promise:()=>nv,quotelessJson:()=>r0,record:()=>Y0,set:()=>J0,setErrorMap:()=>o0,strictObject:()=>V0,string:()=>rp,symbol:()=>M0,transformer:()=>rv,tuple:()=>W0,undefined:()=>N0,union:()=>q0,unknown:()=>D0,util:()=>q,void:()=>B0});var q;(function(e){e.assertEqual=s=>{};function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{let o={};for(let i of s)o[i]=i;return o},e.getValidEnumValues=s=>{let o=e.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(let a of o)i[a]=s[a];return e.objectValues(i)},e.objectValues=s=>e.objectKeys(s).map(function(o){return s[o]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},e.find=(s,o)=>{for(let i of s)if(o(i))return i},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}e.joinValues=r,e.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(q||(q={}));var Nc;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Nc||(Nc={}));var E=q.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),vt=e=>{switch(typeof e){case"undefined":return E.undefined;case"string":return E.string;case"number":return Number.isNaN(e)?E.nan:E.number;case"boolean":return E.boolean;case"function":return E.function;case"bigint":return E.bigint;case"symbol":return E.symbol;case"object":return Array.isArray(e)?E.array:e===null?E.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?E.promise:typeof Map<"u"&&e instanceof Map?E.map:typeof Set<"u"&&e instanceof Set?E.set:typeof Date<"u"&&e instanceof Date?E.date:E.object;default:return E.unknown}};var x=q.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),r0=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),Be=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(o){return o.message},r={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(n(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return s(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,q.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];n[o]=n[o]||[],n[o].push(t(s))}else r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Be.create=e=>new Be(e);var s0=(e,t)=>{let n;switch(e.code){case x.invalid_type:e.received===E.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case x.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,q.jsonStringifyReplacer)}`;break;case x.unrecognized_keys:n=`Unrecognized key(s) in object: ${q.joinValues(e.keys,", ")}`;break;case x.invalid_union:n="Invalid input";break;case x.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${q.joinValues(e.options)}`;break;case x.invalid_enum_value:n=`Invalid enum value. Expected ${q.joinValues(e.options)}, received '${e.received}'`;break;case x.invalid_arguments:n="Invalid function arguments";break;case x.invalid_return_type:n="Invalid function return type";break;case x.invalid_date:n="Invalid date";break;case x.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:q.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case x.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case x.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case x.custom:n="Invalid input";break;case x.invalid_intersection_types:n="Intersection results could not be merged";break;case x.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case x.not_finite:n="Number must be finite";break;default:n=t.defaultError,q.assertNever(e)}return{message:n}},Vt=s0;var zf=Vt;function o0(e){zf=e}function Kr(){return zf}var Js=e=>{let{data:t,path:n,errorMaps:r,issueData:s}=e,o=[...n,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",c=r.filter(l=>!!l).slice().reverse();for(let l of c)a=l(i,{data:t,defaultError:a}).message;return{...s,path:o,message:a}},i0=[];function k(e,t){let n=Kr(),r=Js({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Vt?void 0:Vt].filter(s=>!!s)});e.common.issues.push(r)}var Te=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let s of n){if(s.status==="aborted")return D;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let s of n){let o=await s.key,i=await s.value;r.push({key:o,value:i})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let s of n){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return D;o.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(r[o.value]=i.value)}return{status:t.value,value:r}}},D=Object.freeze({status:"aborted"}),Zn=e=>({status:"dirty",value:e}),Ie=e=>({status:"valid",value:e}),gi=e=>e.status==="aborted",hi=e=>e.status==="dirty",_n=e=>e.status==="valid",Gr=e=>typeof Promise<"u"&&e instanceof Promise;var M;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(M||(M={}));var ze=class{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Jf=(e,t)=>{if(_n(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new Be(e.common.issues);return this._error=n,this._error}}};function B(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(i,a)=>{let{message:c}=e;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??n??a.defaultError}},description:s}}var V=class{get description(){return this._def.description}_getType(t){return vt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:vt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Te,ctx:{common:t.parent.common,data:t.data,parsedType:vt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Gr(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:vt(t)},s=this._parseSync({data:t,path:r.path,parent:r});return Jf(r,s)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:vt(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return _n(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(r=>_n(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(t,n){let r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:vt(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(Gr(s)?s:Promise.resolve(s));return Jf(r,o)}refine(t,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{let i=t(s),a=()=>o.addIssue({code:x.custom,...r(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new Je({schema:this,typeName:j.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Ye.create(this,this._def)}nullable(){return St.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Gt.create(this)}promise(){return wn.create(this,this._def)}or(t){return or.create([this,t],this._def)}and(t){return ir.create(this,t,this._def)}transform(t){return new Je({...B(this._def),schema:this,typeName:j.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new dr({...B(this._def),innerType:this,defaultValue:n,typeName:j.ZodDefault})}brand(){return new Xs({typeName:j.ZodBranded,type:this,...B(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new fr({...B(this._def),innerType:this,catchValue:n,typeName:j.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Zs.create(this,t)}readonly(){return pr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},a0=/^c[^\s-]{8,}$/i,c0=/^[0-9a-z]+$/,l0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,u0=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,d0=/^[a-z0-9_-]{21}$/i,f0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,p0=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,m0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,g0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Lc,h0=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,y0=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,_0=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,b0=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,v0=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,w0=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Zf="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",S0=new RegExp(`^${Zf}$`);function Qf(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function x0(e){return new RegExp(`^${Qf(e)}$`)}function ep(e){let t=`${Zf}T${Qf(e)}`,n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function T0(e,t){return!!((t==="v4"||!t)&&h0.test(e)||(t==="v6"||!t)&&_0.test(e))}function C0(e,t){if(!f0.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||t&&s.alg!==t)}catch{return!1}}function k0(e,t){return!!((t==="v4"||!t)&&y0.test(e)||(t==="v6"||!t)&&b0.test(e))}var bn=class e extends V{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==E.string){let o=this._getOrReturnCtx(t);return k(o,{code:x.invalid_type,expected:E.string,received:o.parsedType}),D}let r=new Te,s;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(s=this._getOrReturnCtx(t,s),k(s,{code:x.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")t.data.length>o.value&&(s=this._getOrReturnCtx(t,s),k(s,{code:x.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){let i=t.data.length>o.value,a=t.data.length<o.value;(i||a)&&(s=this._getOrReturnCtx(t,s),i?k(s,{code:x.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&k(s,{code:x.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")m0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"email",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")Lc||(Lc=new RegExp(g0,"u")),Lc.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"emoji",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")u0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"uuid",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")d0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"nanoid",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")a0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"cuid",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")c0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"cuid2",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")l0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"ulid",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),k(s,{validation:"url",code:x.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"regex",code:x.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(t,s),k(s,{code:x.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(s=this._getOrReturnCtx(t,s),k(s,{code:x.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(s=this._getOrReturnCtx(t,s),k(s,{code:x.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?ep(o).test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{code:x.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?S0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{code:x.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?x0(o).test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{code:x.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?p0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"duration",code:x.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?T0(t.data,o.version)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"ip",code:x.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?C0(t.data,o.alg)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"jwt",code:x.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?k0(t.data,o.version)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"cidr",code:x.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?v0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"base64",code:x.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?w0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"base64url",code:x.invalid_string,message:o.message}),r.dirty()):q.assertNever(o);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:x.invalid_string,...M.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...M.errToObj(t)})}url(t){return this._addCheck({kind:"url",...M.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...M.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...M.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...M.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...M.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...M.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...M.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...M.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...M.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...M.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...M.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...M.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...M.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...M.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...M.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...M.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...M.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...M.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...M.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...M.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...M.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...M.errToObj(n)})}nonempty(t){return this.min(1,M.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};bn.create=e=>new bn({checks:[],typeName:j.ZodString,coerce:e?.coerce??!1,...B(e)});function E0(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,o=Number.parseInt(e.toFixed(s).replace(".","")),i=Number.parseInt(t.toFixed(s).replace(".",""));return o%i/10**s}var Qn=class e extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==E.number){let o=this._getOrReturnCtx(t);return k(o,{code:x.invalid_type,expected:E.number,received:o.parsedType}),D}let r,s=new Te;for(let o of this._def.checks)o.kind==="int"?q.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),k(r,{code:x.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),k(r,{code:x.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),k(r,{code:x.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?E0(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),k(r,{code:x.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),k(r,{code:x.not_finite,message:o.message}),s.dirty()):q.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,M.toString(n))}gt(t,n){return this.setLimit("min",t,!1,M.toString(n))}lte(t,n){return this.setLimit("max",t,!0,M.toString(n))}lt(t,n){return this.setLimit("max",t,!1,M.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:M.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:M.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:M.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:M.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:M.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:M.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:M.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:M.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:M.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:M.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&q.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};Qn.create=e=>new Qn({checks:[],typeName:j.ZodNumber,coerce:e?.coerce||!1,...B(e)});var er=class e extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==E.bigint)return this._getInvalidInput(t);let r,s=new Te;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),k(r,{code:x.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),k(r,{code:x.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),k(r,{code:x.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):q.assertNever(o);return{status:s.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return k(n,{code:x.invalid_type,expected:E.bigint,received:n.parsedType}),D}gte(t,n){return this.setLimit("min",t,!0,M.toString(n))}gt(t,n){return this.setLimit("min",t,!1,M.toString(n))}lte(t,n){return this.setLimit("max",t,!0,M.toString(n))}lt(t,n){return this.setLimit("max",t,!1,M.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:M.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:M.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:M.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:M.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:M.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:M.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};er.create=e=>new er({checks:[],typeName:j.ZodBigInt,coerce:e?.coerce??!1,...B(e)});var tr=class extends V{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==E.boolean){let r=this._getOrReturnCtx(t);return k(r,{code:x.invalid_type,expected:E.boolean,received:r.parsedType}),D}return Ie(t.data)}};tr.create=e=>new tr({typeName:j.ZodBoolean,coerce:e?.coerce||!1,...B(e)});var nr=class e extends V{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==E.date){let o=this._getOrReturnCtx(t);return k(o,{code:x.invalid_type,expected:E.date,received:o.parsedType}),D}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return k(o,{code:x.invalid_date}),D}let r=new Te,s;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(s=this._getOrReturnCtx(t,s),k(s,{code:x.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(s=this._getOrReturnCtx(t,s),k(s,{code:x.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):q.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:M.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:M.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};nr.create=e=>new nr({checks:[],coerce:e?.coerce||!1,typeName:j.ZodDate,...B(e)});var Yr=class extends V{_parse(t){if(this._getType(t)!==E.symbol){let r=this._getOrReturnCtx(t);return k(r,{code:x.invalid_type,expected:E.symbol,received:r.parsedType}),D}return Ie(t.data)}};Yr.create=e=>new Yr({typeName:j.ZodSymbol,...B(e)});var rr=class extends V{_parse(t){if(this._getType(t)!==E.undefined){let r=this._getOrReturnCtx(t);return k(r,{code:x.invalid_type,expected:E.undefined,received:r.parsedType}),D}return Ie(t.data)}};rr.create=e=>new rr({typeName:j.ZodUndefined,...B(e)});var sr=class extends V{_parse(t){if(this._getType(t)!==E.null){let r=this._getOrReturnCtx(t);return k(r,{code:x.invalid_type,expected:E.null,received:r.parsedType}),D}return Ie(t.data)}};sr.create=e=>new sr({typeName:j.ZodNull,...B(e)});var vn=class extends V{constructor(){super(...arguments),this._any=!0}_parse(t){return Ie(t.data)}};vn.create=e=>new vn({typeName:j.ZodAny,...B(e)});var Kt=class extends V{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Ie(t.data)}};Kt.create=e=>new Kt({typeName:j.ZodUnknown,...B(e)});var rt=class extends V{_parse(t){let n=this._getOrReturnCtx(t);return k(n,{code:x.invalid_type,expected:E.never,received:n.parsedType}),D}};rt.create=e=>new rt({typeName:j.ZodNever,...B(e)});var zr=class extends V{_parse(t){if(this._getType(t)!==E.undefined){let r=this._getOrReturnCtx(t);return k(r,{code:x.invalid_type,expected:E.void,received:r.parsedType}),D}return Ie(t.data)}};zr.create=e=>new zr({typeName:j.ZodVoid,...B(e)});var Gt=class e extends V{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==E.array)return k(n,{code:x.invalid_type,expected:E.array,received:n.parsedType}),D;if(s.exactLength!==null){let i=n.data.length>s.exactLength.value,a=n.data.length<s.exactLength.value;(i||a)&&(k(n,{code:i?x.too_big:x.too_small,minimum:a?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(k(n,{code:x.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(k(n,{code:x.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>s.type._parseAsync(new ze(n,i,n.path,a)))).then(i=>Te.mergeArray(r,i));let o=[...n.data].map((i,a)=>s.type._parseSync(new ze(n,i,n.path,a)));return Te.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:M.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:M.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:M.toString(n)}})}nonempty(t){return this.min(1,t)}};Gt.create=(e,t)=>new Gt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:j.ZodArray,...B(t)});function Wr(e){if(e instanceof Fe){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Ye.create(Wr(r))}return new Fe({...e._def,shape:()=>t})}else return e instanceof Gt?new Gt({...e._def,type:Wr(e.element)}):e instanceof Ye?Ye.create(Wr(e.unwrap())):e instanceof St?St.create(Wr(e.unwrap())):e instanceof wt?wt.create(e.items.map(t=>Wr(t))):e}var Fe=class e extends V{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=q.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==E.object){let l=this._getOrReturnCtx(t);return k(l,{code:x.invalid_type,expected:E.object,received:l.parsedType}),D}let{status:r,ctx:s}=this._processInputParams(t),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof rt&&this._def.unknownKeys==="strip"))for(let l in s.data)i.includes(l)||a.push(l);let c=[];for(let l of i){let u=o[l],d=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new ze(s,d,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof rt){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(l==="strict")a.length>0&&(k(s,{code:x.unrecognized_keys,keys:a}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let d=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new ze(s,d,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,p=await u.value;l.push({key:d,value:p,alwaysSet:u.alwaysSet})}return l}).then(l=>Te.mergeObjectSync(r,l)):Te.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(t){return M.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:M.errToObj(t).message??s}:{message:s}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:j.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of q.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let r of q.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return Wr(this)}partial(t){let n={};for(let r of q.objectKeys(this.shape)){let s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let r of q.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof Ye;)o=o._def.innerType;n[r]=o}return new e({...this._def,shape:()=>n})}keyof(){return tp(q.objectKeys(this.shape))}};Fe.create=(e,t)=>new Fe({shape:()=>e,unknownKeys:"strip",catchall:rt.create(),typeName:j.ZodObject,...B(t)});Fe.strictCreate=(e,t)=>new Fe({shape:()=>e,unknownKeys:"strict",catchall:rt.create(),typeName:j.ZodObject,...B(t)});Fe.lazycreate=(e,t)=>new Fe({shape:e,unknownKeys:"strip",catchall:rt.create(),typeName:j.ZodObject,...B(t)});var or=class extends V{_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new Be(a.ctx.common.issues));return k(n,{code:x.invalid_union,unionErrors:i}),D}if(n.common.async)return Promise.all(r.map(async o=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let c of r){let l={...n,common:{...n.common,issues:[]},parent:null},u=c._parseSync({data:n.data,path:n.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(c=>new Be(c));return k(n,{code:x.invalid_union,unionErrors:a}),D}}get options(){return this._def.options}};or.create=(e,t)=>new or({options:e,typeName:j.ZodUnion,...B(t)});var qt=e=>e instanceof ar?qt(e.schema):e instanceof Je?qt(e.innerType()):e instanceof cr?[e.value]:e instanceof lr?e.options:e instanceof ur?q.objectValues(e.enum):e instanceof dr?qt(e._def.innerType):e instanceof rr?[void 0]:e instanceof sr?[null]:e instanceof Ye?[void 0,...qt(e.unwrap())]:e instanceof St?[null,...qt(e.unwrap())]:e instanceof Xs||e instanceof pr?qt(e.unwrap()):e instanceof fr?qt(e._def.innerType):[],yi=class e extends V{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==E.object)return k(n,{code:x.invalid_type,expected:E.object,received:n.parsedType}),D;let r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(k(n,{code:x.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),D)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let s=new Map;for(let o of n){let i=qt(o.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of i){if(s.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);s.set(a,o)}}return new e({typeName:j.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...B(r)})}};function Uc(e,t){let n=vt(e),r=vt(t);if(e===t)return{valid:!0,data:e};if(n===E.object&&r===E.object){let s=q.objectKeys(t),o=q.objectKeys(e).filter(a=>s.indexOf(a)!==-1),i={...e,...t};for(let a of o){let c=Uc(e[a],t[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===E.array&&r===E.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let o=0;o<e.length;o++){let i=e[o],a=t[o],c=Uc(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===E.date&&r===E.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var ir=class extends V{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=(o,i)=>{if(gi(o)||gi(i))return D;let a=Uc(o.value,i.value);return a.valid?((hi(o)||hi(i))&&n.dirty(),{status:n.value,value:a.data}):(k(r,{code:x.invalid_intersection_types}),D)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};ir.create=(e,t,n)=>new ir({left:e,right:t,typeName:j.ZodIntersection,...B(n)});var wt=class e extends V{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==E.array)return k(r,{code:x.invalid_type,expected:E.array,received:r.parsedType}),D;if(r.data.length<this._def.items.length)return k(r,{code:x.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),D;!this._def.rest&&r.data.length>this._def.items.length&&(k(r,{code:x.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...r.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new ze(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>Te.mergeArray(n,i)):Te.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};wt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new wt({items:e,typeName:j.ZodTuple,rest:null,...B(t)})};var _i=class e extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==E.object)return k(r,{code:x.invalid_type,expected:E.object,received:r.parsedType}),D;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in r.data)s.push({key:o._parse(new ze(r,a,r.path,a)),value:i._parse(new ze(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?Te.mergeObjectAsync(n,s):Te.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof V?new e({keyType:t,valueType:n,typeName:j.ZodRecord,...B(r)}):new e({keyType:bn.create(),valueType:t,typeName:j.ZodRecord,...B(n)})}},Jr=class extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==E.map)return k(r,{code:x.invalid_type,expected:E.map,received:r.parsedType}),D;let s=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([a,c],l)=>({key:s._parse(new ze(r,a,r.path,[l,"key"])),value:o._parse(new ze(r,c,r.path,[l,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return D;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let c of i){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return D;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}}}};Jr.create=(e,t,n)=>new Jr({valueType:t,keyType:e,typeName:j.ZodMap,...B(n)});var Xr=class e extends V{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==E.set)return k(r,{code:x.invalid_type,expected:E.set,received:r.parsedType}),D;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(k(r,{code:x.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(k(r,{code:x.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let o=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return D;u.status==="dirty"&&n.dirty(),l.add(u.value)}return{status:n.value,value:l}}let a=[...r.data.values()].map((c,l)=>o._parse(new ze(r,c,r.path,l)));return r.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(t,n){return new e({...this._def,minSize:{value:t,message:M.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:M.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};Xr.create=(e,t)=>new Xr({valueType:e,minSize:null,maxSize:null,typeName:j.ZodSet,...B(t)});var bi=class e extends V{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==E.function)return k(n,{code:x.invalid_type,expected:E.function,received:n.parsedType}),D;function r(a,c){return Js({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Kr(),Vt].filter(l=>!!l),issueData:{code:x.invalid_arguments,argumentsError:c}})}function s(a,c){return Js({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Kr(),Vt].filter(l=>!!l),issueData:{code:x.invalid_return_type,returnTypeError:c}})}let o={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof wn){let a=this;return Ie(async function(...c){let l=new Be([]),u=await a._def.args.parseAsync(c,o).catch(f=>{throw l.addIssue(r(c,f)),l}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,o).catch(f=>{throw l.addIssue(s(d,f)),l})})}else{let a=this;return Ie(function(...c){let l=a._def.args.safeParse(c,o);if(!l.success)throw new Be([r(c,l.error)]);let u=Reflect.apply(i,this,l.data),d=a._def.returns.safeParse(u,o);if(!d.success)throw new Be([s(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:wt.create(t).rest(Kt.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new e({args:t||wt.create([]).rest(Kt.create()),returns:n||Kt.create(),typeName:j.ZodFunction,...B(r)})}},ar=class extends V{get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};ar.create=(e,t)=>new ar({getter:e,typeName:j.ZodLazy,...B(t)});var cr=class extends V{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return k(n,{received:n.data,code:x.invalid_literal,expected:this._def.value}),D}return{status:"valid",value:t.data}}get value(){return this._def.value}};cr.create=(e,t)=>new cr({value:e,typeName:j.ZodLiteral,...B(t)});function tp(e,t){return new lr({values:e,typeName:j.ZodEnum,...B(t)})}var lr=class e extends V{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return k(n,{expected:q.joinValues(r),received:n.parsedType,code:x.invalid_type}),D}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return k(n,{received:n.data,code:x.invalid_enum_value,options:r}),D}return Ie(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};lr.create=tp;var ur=class extends V{_parse(t){let n=q.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==E.string&&r.parsedType!==E.number){let s=q.objectValues(n);return k(r,{expected:q.joinValues(s),received:r.parsedType,code:x.invalid_type}),D}if(this._cache||(this._cache=new Set(q.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let s=q.objectValues(n);return k(r,{received:r.data,code:x.invalid_enum_value,options:s}),D}return Ie(t.data)}get enum(){return this._def.values}};ur.create=(e,t)=>new ur({values:e,typeName:j.ZodNativeEnum,...B(t)});var wn=class extends V{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==E.promise&&n.common.async===!1)return k(n,{code:x.invalid_type,expected:E.promise,received:n.parsedType}),D;let r=n.parsedType===E.promise?n.data:Promise.resolve(n.data);return Ie(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};wn.create=(e,t)=>new wn({type:e,typeName:j.ZodPromise,...B(t)});var Je=class extends V{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===j.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,o={addIssue:i=>{k(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(r.data,o);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return D;let c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?D:c.status==="dirty"?Zn(c.value):n.value==="dirty"?Zn(c.value):c});{if(n.value==="aborted")return D;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?D:a.status==="dirty"?Zn(a.value):n.value==="dirty"?Zn(a.value):a}}if(s.type==="refinement"){let i=a=>{let c=s.refinement(a,o);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?D:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?D:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(s.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!_n(i))return D;let a=s.transform(i.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>_n(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:n.value,value:a})):D);q.assertNever(s)}};Je.create=(e,t,n)=>new Je({schema:e,typeName:j.ZodEffects,effect:t,...B(n)});Je.createWithPreprocess=(e,t,n)=>new Je({schema:t,effect:{type:"preprocess",transform:e},typeName:j.ZodEffects,...B(n)});var Ye=class extends V{_parse(t){return this._getType(t)===E.undefined?Ie(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ye.create=(e,t)=>new Ye({innerType:e,typeName:j.ZodOptional,...B(t)});var St=class extends V{_parse(t){return this._getType(t)===E.null?Ie(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};St.create=(e,t)=>new St({innerType:e,typeName:j.ZodNullable,...B(t)});var dr=class extends V{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===E.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};dr.create=(e,t)=>new dr({innerType:e,typeName:j.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...B(t)});var fr=class extends V{_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Gr(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Be(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Be(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};fr.create=(e,t)=>new fr({innerType:e,typeName:j.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...B(t)});var Zr=class extends V{_parse(t){if(this._getType(t)!==E.nan){let r=this._getOrReturnCtx(t);return k(r,{code:x.invalid_type,expected:E.nan,received:r.parsedType}),D}return{status:"valid",value:t.data}}};Zr.create=e=>new Zr({typeName:j.ZodNaN,...B(e)});var A0=Symbol("zod_brand"),Xs=class extends V{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Zs=class e extends V{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?D:o.status==="dirty"?(n.dirty(),Zn(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?D:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:j.ZodPipeline})}},pr=class extends V{_parse(t){let n=this._def.innerType._parse(t),r=s=>(_n(s)&&(s.value=Object.freeze(s.value)),s);return Gr(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};pr.create=(e,t)=>new pr({innerType:e,typeName:j.ZodReadonly,...B(t)});function Xf(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function np(e,t={},n){return e?vn.create().superRefine((r,s)=>{let o=e(r);if(o instanceof Promise)return o.then(i=>{if(!i){let a=Xf(t,r),c=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=Xf(t,r),a=i.fatal??n??!0;s.addIssue({code:"custom",...i,fatal:a})}}):vn.create()}var R0={object:Fe.lazycreate},j;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(j||(j={}));var I0=(e,t={message:`Input not instance of ${e.name}`})=>np(n=>n instanceof e,t),rp=bn.create,sp=Qn.create,$0=Zr.create,P0=er.create,op=tr.create,O0=nr.create,M0=Yr.create,N0=rr.create,L0=sr.create,U0=vn.create,D0=Kt.create,j0=rt.create,B0=zr.create,F0=Gt.create,H0=Fe.create,V0=Fe.strictCreate,q0=or.create,K0=yi.create,G0=ir.create,W0=wt.create,Y0=_i.create,z0=Jr.create,J0=Xr.create,X0=bi.create,Z0=ar.create,Q0=cr.create,ev=lr.create,tv=ur.create,nv=wn.create,rv=Je.create,sv=Ye.create,ov=St.create,iv=Je.createWithPreprocess,av=Zs.create,cv=()=>rp().optional(),lv=()=>sp().optional(),uv=()=>op().optional(),dv={string:(e=>bn.create({...e,coerce:!0})),number:(e=>Qn.create({...e,coerce:!0})),boolean:(e=>tr.create({...e,coerce:!0})),bigint:(e=>er.create({...e,coerce:!0})),date:(e=>nr.create({...e,coerce:!0}))};var fv=D;var pv=/^[A-Za-z0-9._-]+$/,mv=/^[A-Za-z0-9._-]+(\|[A-Za-z0-9._-]+)*$/,ip=new Set([".",".."]),De=class extends Error{pattern;constructor(t,n){super(`Invalid freeReadPathPattern ${JSON.stringify(n)}: ${t}`),this.pattern=n,this.name="FreePathPatternError"}};function gv(e,t){if(e==="*")return{raw:e,kind:"single"};if(e==="**")return{raw:e,kind:"multi"};if(e.startsWith("(")){let n=e.endsWith(")?"),r=e.endsWith(")");if(!n&&!r)throw new De(`malformed alternation segment ${JSON.stringify(e)}`,t);let s=n?e.slice(1,-2):e.slice(1,-1);if(!mv.test(s))throw new De(`malformed alternation segment ${JSON.stringify(e)}`,t);let o=s.split("|");if(o.some(i=>ip.has(i)))throw new De(`alternation segment ${JSON.stringify(e)} may not contain '.' or '..'`,t);return{raw:e,kind:n?"alt-optional":"alt",alternatives:o}}if(pv.test(e)){if(ip.has(e))throw new De(`literal segment ${JSON.stringify(e)} is not permitted`,t);return{raw:e,kind:"literal"}}throw new De(`segment ${JSON.stringify(e)} must be '*', '**', a [A-Za-z0-9._-]+ literal, or (a|b) alternation`,t)}function hv(e){if(typeof e!="string"||e.length===0)throw new De("must be a non-empty string",String(e));if(!e.startsWith("/"))throw new De("must start with '/'",e);if(e.slice(1).includes("//"))throw new De("empty segments ('//') are not permitted",e);if(e.length>1&&e.endsWith("/"))throw new De("must not end with '/'",e);let n=e.slice(1).split("/").map(o=>gv(o,e));if(n.filter(o=>o.kind==="multi").length>1)throw new De("at most one '**' is permitted per pattern",e);if(n[0]?.kind==="multi")throw new De("'**' may not be the first segment (a literal prefix anchor is required)",e);let s=n.findIndex(o=>o.kind==="alt-optional");if(s!==-1&&s!==n.length-1)throw new De("optional alternation '(...)?' is only allowed as the final segment",e);return n}function Dc(e){hv(e)}var ap=["tempo","mpp_self","merchant_self"],cp=["catalog_static","fal_direct","fal_queue","openrouter_chat","openrouter_image","platform_proxy","tempo_gateway","x402_gateway"],lp=["image","audio","queued_audio","video","queued_video","model_3d","llm","transcription","utility"],up=["images[0].url","image.url","audio.url","audio_file.url","audio_url","video.url","model_mesh.url","text","choices[0].message.content","choices[0].message.images[0].image_url.url","request_id"];var Bc=_.object({inputPerMillion:_.number().positive(),outputPerMillion:_.number().positive(),contextWindow:_.number().int().positive().optional(),maxOutput:_.number().int().positive().optional(),perRequestFeeCents:_.number().nonnegative().optional()}),yv=_.object({strategy:_.enum(["flat","token","band"]).optional(),pricingModel:_.enum(["per-call","per-token","band"]).optional(),priceCents:_.number().nonnegative().optional(),currency:_.string().optional(),display:_.string().optional(),estimate:_.boolean().optional(),source:_.string().optional(),priceBand:_.record(_.unknown()).optional(),tokenPricing:Bc.optional()}).passthrough(),Fc=_.discriminatedUnion("type",[_.object({type:_.literal("shortcut"),routedPath:_.string().min(1).startsWith("/")}),_.object({type:_.literal("custom"),merchantSlug:_.string().min(1),subPath:_.string().optional()}),_.object({type:_.literal("local"),fn:_.string().min(1)}),_.object({type:_.literal("read")})]),Hc=_.object({amount:_.number().nonnegative(),currency:_.string().length(3).optional(),display:_.string().optional(),free:_.boolean().optional(),batchDiscount:_.number().min(0).max(100).optional()}),dp=_.object({attestation:_.boolean().optional(),rateLimitMs:_.number().positive().optional()}),fp=_.object({displayName:_.string().optional(),feedbackEligible:_.boolean().optional(),suggestionEligible:_.boolean().optional(),batchable:_.boolean().optional()}),pp=_.object({enabled:_.boolean().optional(),gatewayPath:_.string().min(1).startsWith("/").optional(),method:_.enum(["GET","POST","PUT","PATCH","DELETE"]).optional(),timeoutMs:_.number().int().positive().max(12e4).optional()}).strict(),_v=_.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),bv=120,vv=120,wv=1200,Sv=/^[^\u0000-\u001F\u007F]+$/;function jc(e,t){return _.string().min(1).max(e).regex(Sv,`${t} must not contain control characters`)}var Vc={id:_.string().min(1),name:jc(bv,"name"),description:jc(wv,"description"),provider:_.string().min(1),model:_.string().min(1),category:_v,priceCents:_.number().nonnegative(),inputSchema:_.record(_.unknown()),gatewayUrl:_.string().min(1),merchantName:jc(vv,"merchantName"),isAsync:_.boolean().optional(),pollUrl:_.string().optional(),pollInterval:_.number().positive().optional(),pollTimeout:_.number().positive().optional(),tags:_.array(_.string()).optional(),tokenPricing:Bc.optional(),priceDisplay:_.string().optional(),pricingModel:_.enum(["per-call","per-token","band"]).optional(),pricingInfo:yv.optional(),status:_.enum(["available","unavailable"]).optional(),handler:Fc.optional(),pricing:Hc.optional(),security:dp.optional(),engagement:fp.optional(),gatewayConfig:pp.optional(),freeReadPathPattern:_.string().optional().superRefine((e,t)=>{if(e!==void 0)try{Dc(e)}catch(n){t.addIssue({code:_.ZodIssueCode.custom,message:n instanceof Error?n.message:String(n)})}}),enabled:_.boolean().optional(),beta:_.boolean().optional(),deprecated:_.boolean().optional(),internal:_.boolean().optional(),employeeOnly:_.boolean().optional(),employeeOnlyRolloutFlag:_.string().min(1).max(100).optional(),replacementTool:_.string().optional(),minCliVersion:_.string().optional(),sunsetAt:_.string().optional(),rail:_.enum(ap).optional(),executionKind:_.enum(cp).optional(),resultKind:_.enum(lp).optional(),extractionMode:_.enum(up).optional(),pricingStrategy:_.enum(["flat","token","band"]).optional()},mp=_.object({...Vc,dispatch:_.literal("routed"),routedPath:_.string().min(1).startsWith("/")}).strict(),gp=_.object({...Vc,dispatch:_.literal("enveloped")}).strict(),hp=_.object({...Vc,handler:Fc,pricing:Hc}).strict(),yp=_.union([_.discriminatedUnion("dispatch",[mp,gp]),hp]);var qc=/^[a-z0-9][a-z0-9_-]*$/;var Cv="https://fal.run",wp="https://openrouter.mpp.tempo.xyz",Gc=1024,wi=8192,kv=4096,Ev=10;function Av(e){return e>=Ev?kv:wi}function Sp(e,t){let n=typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):Gc;return Math.min(n,t)}var Rv=["num_images","num_outputs","num_samples","num_videos","batch_size","n"];function xp(e){for(let t of Rv)delete e[t];return e}function Iv(e){let{attestation:t,tool_id:n,...r}=e;return xp(r)}var _p={"1:1":"square_hd","16:9":"landscape_16_9","9:16":"portrait_16_9","4:3":"landscape_4_3","3:4":"portrait_4_3"};function vi(e){let{attestation:t,tool_id:n,aspect_ratio:r,image_size:s,...o}=e,i=xp({...o});return typeof s=="string"&&s.length>0?(i.image_size=s,i):(typeof r=="string"&&_p[r]&&(i.image_size=_p[r]),i)}function $v(e){let{attestation:t,tool_id:n,...r}=e;return r}function bp(e){let t={chain:e.chain,token_address:e.token_address};if(e.start_timestamp){let n=e.end_timestamp||new Date().toISOString(),r=e.time_granularity;if(!r){let s=new Date(e.start_timestamp).getTime();(new Date(n).getTime()-s)/(1e3*60*60*24)<=2?r="1h":r="1d"}return{addresses:[t],start_timestamp:e.start_timestamp,end_timestamp:n,time_granularity:r}}return[t]}function Pv(e,t,n,r,s,o,i,a,c){return{id:e,name:t,description:n,provider:r,model:s.replace(/^\//,""),category:o,gatewayUrl:`https://${r}${s}`,merchantName:t,inputSchema:a,handler:{type:"custom",merchantSlug:r,subPath:s},pricing:{amount:i,currency:"USD",display:`$${(i/100).toFixed(2)}`},priceCents:i,tags:[],...c}}function Ov(e,t,n,r,s,o,i,a){return Pv(e,t,n,"suno-ai",r,s,o,i,{merchantName:"Suno AI",...a})}function he(e,t,n,r,s,o,i,a){return{dispatch:"routed",id:e,name:t,description:n,provider:"fal",model:r,category:s,priceCents:o,inputSchema:i,routedPath:`/api/v1/fal/${r}`,gatewayUrl:`${Cv}/${r}`,merchantName:"fal.ai",buildBody:Iv,tags:[],...a}}function Tp(e,t=wi){return n=>{let{attestation:r,tool_id:s,model:o,prompt:i,system_prompt:a,max_tokens:c,max_completion_tokens:l,n:u,messages:d,temperature:p,...f}=n;return typeof o=="string"&&o.length>0&&o!==e&&console.warn("[catalog] openrouterBuildBody: caller model override ignored",{catalogModel:e,callerModel:o}),{messages:Array.isArray(d)?d:[...a?[{role:"system",content:a}]:[],{role:"user",content:i}],temperature:p??.7,...f,model:e,max_tokens:Sp(c??l,t)}}}function Cp(e,t=wi){return n=>{let{attestation:r,tool_id:s,prompt:o,image_url:i,aspect_ratio:a,max_tokens:c,max_completion_tokens:l,n:u,model:d,messages:p,image_config:f,temperature:m,...h}=n,w=[{type:"text",text:o}];return typeof i=="string"&&i.length>0&&w.push({type:"image_url",image_url:{url:i}}),{messages:Array.isArray(p)?p:[{role:"user",content:w}],temperature:m??.7,...h,model:e,...typeof a=="string"&&a.length>0?{image_config:{aspect_ratio:a}}:{},max_tokens:Sp(c??l,t)}}}function le(e,t,n,r,s,o,i){let a=i?.maxOutputTokens??Av(o),c=i?.perRequestFeeCents??0,l=500/1e6*s*100,u=500/1e6*o*100,d=Math.max(1,Math.ceil(l+u+c)),{perRequestFeeCents:p,maxOutputTokens:f,...m}=i??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"llm",priceCents:d,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The prompt or question to send to the model"},system_prompt:{type:"string",description:"Optional system prompt to set model behavior"},max_tokens:{type:"integer",description:`Maximum tokens in response (default: ${Gc}); values above ${a} are clamped to ${a}`,minimum:1,maximum:a},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${wp}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:Tp(r,a),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:s,outputPerMillion:o,...c>0?{perRequestFeeCents:c}:{}},...m}}function Kc(e,t,n,r,s,o){let i=o?.maxOutputTokens??wi,{maxOutputTokens:a,...c}=o??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"image",pricingStrategy:"band",priceCents:s,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate or edit"},image_url:{type:"string",description:"Optional source image URL for edits"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"1:1"},max_tokens:{type:"integer",description:`Maximum text tokens in response metadata (default: ${Gc}); values above ${i} are clamped to ${i}`,minimum:1,maximum:i},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${wp}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:Cp(r,i),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...c}}var Wc=[he("fal-flux-pro-ultra","FLUX Pro Ultra","Highest quality image generation. Best for detailed, photorealistic images.","fal-ai/flux-pro/v1.1-ultra","image",6,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},{tags:["image","flux","photorealistic","high-quality"]}),he("fal-flux-pro","FLUX Pro","Fast, high-quality image generation. Good balance of speed and quality.","fal-ai/flux-pro/v1.1","image",4,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},{tags:["image","flux","fast"],buildBody:vi}),he("fal-flux-dev","FLUX Dev","Open-source image generation. Cheaper, good for experimentation.","fal-ai/flux/dev","image",3,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["image","flux","open-source","cheap"],buildBody:vi}),he("fal-flux-schnell","FLUX Schnell","Fastest image generation. Ultra-cheap, great for drafts and iteration.","fal-ai/flux/schnell","image",1,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["image","flux","fast","cheap","draft"],buildBody:vi}),he("fal-recraft-v3","Recraft V3","Design-focused image generation. Great for illustrations, icons, and graphic design.","fal-ai/recraft/v3/text-to-image","image",5,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},style:{type:"string",description:"Style preset: realistic_image, digital_illustration, vector_illustration, icon"}},required:["prompt"]},{tags:["image","design","illustration","icon","vector"]}),Kc("or-gemini-nano-banana","Nano Banana","Google Gemini 2.5 Flash Image via OpenRouter for image generation and edits.","google/gemini-2.5-flash-image",4),Kc("or-gemini-nano-banana-2","Nano Banana 2","Google Gemini 3.1 Flash Image Preview via OpenRouter for fast image generation and edits.","google/gemini-3.1-flash-image-preview",5,{tags:["image","gemini","google","nano-banana","edit","fast"],tokenPricing:{inputPerMillion:.5,outputPerMillion:3}}),Kc("or-gemini-nano-banana-pro","Nano Banana Pro","Google Gemini 3 Pro Image Preview via OpenRouter for professional image generation, edits, and text rendering.","google/gemini-3-pro-image-preview",8,{tags:["image","gemini","google","nano-banana","pro","text-rendering"],tokenPricing:{inputPerMillion:2,outputPerMillion:12}}),he("fal-ideogram-v2","Ideogram V2","Excellent text rendering in images. Best for logos, posters, and text-heavy visuals.","fal-ai/ideogram/v2","image",8,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"1:1"}},required:["prompt"]},{tags:["image","text-rendering","logo","poster","typography"]}),he("fal-ideogram-v2-turbo","Ideogram V2 Turbo","Fast text rendering in images. Good balance of speed and text accuracy.","fal-ai/ideogram/v2/turbo","image",5,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"1:1"}},required:["prompt"]},{tags:["image","text-rendering","fast"]}),he("fal-fast-sdxl","Fast SDXL","Ultra-fast Stable Diffusion. 4-step inference, cheapest option.","fal-ai/fast-sdxl","image",1,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"}},required:["prompt"]},{tags:["image","stable-diffusion","fast","cheap"]}),he("fal-wan-video","Wan Video","Text-to-video generation. Create short video clips from text descriptions.","fal-ai/wan/v2.1/1.3b/text-to-video","video",10,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"},num_frames:{type:"number",description:"Number of frames (default: 81)"}},required:["prompt"]},{tags:["video","text-to-video","wan"]}),he("fal-minimax-video","MiniMax Video","High-quality video generation with excellent motion and coherence.","fal-ai/minimax-video/video-01-live","video",15,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"}},required:["prompt"]},{tags:["video","text-to-video","high-quality"]}),he("fal-kling-video","Kling Video","Professional video generation with cinematic quality.","fal-ai/kling-video/v2/master/text-to-video","video",20,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"},duration:{type:"string",description:"Duration: 5 or 10 seconds",default:"5"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["video","text-to-video","cinematic","professional"]}),he("fal-kling-i2v","Kling Image-to-Video","Animate a still image into a 5\u201310s video clip. Cinematic motion quality.","fal-ai/kling-video/v1.6/standard/image-to-video","video",35,{type:"object",properties:{image_url:{type:"string",description:"URL of the source image (jpg, png, webp, gif, avif)"},prompt:{type:"string",description:"Text description of the motion to animate"},duration:{type:"string",description:"Duration: 5 or 10 seconds",default:"5"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 9:16, 1:1)",default:"16:9"},negative_prompt:{type:"string",description:"Elements to avoid in the generated motion"},cfg_scale:{type:"number",description:"Classifier-free guidance (default 0.5)",default:.5}},required:["image_url","prompt"]},{tags:["video","image-to-video","kling","cinematic"]}),he("fal-stable-audio","Stable Audio","Generate sound effects and ambient audio from text descriptions.","fal-ai/stable-audio","audio",4,{type:"object",properties:{prompt:{type:"string",description:"Description of the audio to generate"},seconds_total:{type:"number",description:"Duration in seconds (max 47)",default:30}},required:["prompt"]},{tags:["audio","sound-effects","ambient"]}),he("fal-ace-step-music","ACE-Step Music","Generate full music tracks from a prompt, with optional vocals or instrumentals.","fal-ai/ace-step/prompt-to-audio","audio",2,{type:"object",properties:{prompt:{type:"string",description:"Description of the song, genre, mood, instruments, and lyrics direction"},instrumental:{type:"boolean",description:"Generate instrumental music without vocals",default:!1},duration:{type:"number",description:"Duration in seconds",default:60}},required:["prompt"]},{tags:["music","song","vocals","instrumental","ace-step"]}),Ov("suno-music","Suno Music","AI music generation. Create full songs with vocals or instrumentals.","/suno/generate-music","audio",10,{type:"object",properties:{prompt:{type:"string",description:"Description of the song (genre, mood, instruments)"},instrumental:{type:"boolean",description:"Instrumental only, no vocals",default:!1}},required:["prompt"]},{isAsync:!0,pollUrl:"https://api.sunoapi.org/suno/get-music-status",deprecated:!0,tags:["music","song","vocals","instrumental"],buildBody:e=>{let{attestation:t,tool_id:n,prompt:r,instrumental:s,...o}=e;return{prompt:r,customMode:!1,instrumental:typeof s=="boolean"?s:!1,model:"V4",...o}}}),he("fal-trellis-3d","Trellis 3D","Generate 3D models from images. Upload a photo, get a 3D asset.","fal-ai/trellis","3d",8,{type:"object",properties:{image_url:{type:"string",description:"URL of the image to convert to 3D"}},required:["image_url"]},{tags:["3d","model","image-to-3d"]}),he("fal-aura-sr","Aura SR","Upscale images to higher resolution. 4x upscaling with detail enhancement.","fal-ai/aura-sr","upscale",3,{type:"object",properties:{image_url:{type:"string",description:"URL of the image to upscale"}},required:["image_url"]},{tags:["upscale","super-resolution","enhance"]}),he("fal-metavoice","MetaVoice Voice Cloning","Voice cloning TTS \u2014 clone any voice from an audio sample. Provide text and a voice sample URL.","fal-ai/metavoice-v1","tts",3,{type:"object",properties:{text:{type:"string",description:"Text to convert to speech"},audio_url:{type:"string",description:"URL of the voice sample to clone"}},required:["text","audio_url"]},{tags:["tts","voice","voice-cloning","speech"]}),he("fal-whisper","Whisper Transcription","Transcribe audio to text. Supports multiple languages.","fal-ai/whisper","transcription",2,{type:"object",properties:{audio_url:{type:"string",description:"URL of the audio to transcribe"},language:{type:"string",description:"Language code (e.g. en, es, fr)"}},required:["audio_url"]},{tags:["transcription","speech-to-text","whisper"]}),le("or-gpt-4o","GPT-4o","OpenAI's flagship multimodal model. Best for complex reasoning and analysis.","openai/gpt-4o",2.5,10,{tags:["llm","gpt","openai","multimodal","reasoning"]}),le("or-gpt-55","GPT-5.5","OpenAI frontier model for complex professional reasoning, coding, and long-context analysis.","openai/gpt-5.5",5,30,{tags:["llm","gpt","openai","frontier","reasoning","coding","long-context"]}),le("or-gpt-55-pro","GPT-5.5 Pro","OpenAI high-capability frontier model optimized for deep reasoning and high-stakes workloads.","openai/gpt-5.5-pro",30,180,{tags:["llm","gpt","openai","frontier","pro","deep-reasoning","coding","long-context"]}),le("or-gpt-4o-mini","GPT-4o Mini","Fast, affordable GPT-4o. Great for everyday tasks, chat, and simple analysis.","openai/gpt-4o-mini",.15,.6,{tags:["llm","gpt","openai","fast","cheap"]}),le("or-claude-opus","Claude Opus 4.7","Anthropic's most capable model. 1M context, reasoning, best for complex tasks.","anthropic/claude-opus-4.7",15,75,{tags:["llm","claude","anthropic","reasoning","coding"]}),le("or-claude-sonnet","Claude Sonnet 4.6","Anthropic's best balance of intelligence and speed. Excellent for coding and analysis.","anthropic/claude-sonnet-4.6",3,15,{tags:["llm","claude","anthropic","coding","analysis"]}),le("or-claude-opus-fast","Claude Opus 4.6 Fast","Fast Opus variant with lower latency.","anthropic/claude-opus-4.6-fast",15,75,{tags:["llm","claude","anthropic","fast"]}),le("or-claude-haiku","Claude 3.5 Haiku","Anthropic's fastest model. Great for quick tasks, chat, and simple reasoning.","anthropic/claude-3.5-haiku",.8,4,{tags:["llm","claude","anthropic","fast"]}),le("or-gemini-pro","Gemini 2.0 Flash","Google's fast multimodal model. Good for general tasks with long context.","google/gemini-2.0-flash-001",.1,.4,{tags:["llm","gemini","google","multimodal","fast","cheap"]}),le("or-gemini-3-flash","Gemini 3 Flash","Google's high-speed thinking model for agentic workflows, coding, and multimodal tasks.","google/gemini-3-flash-preview",.5,3,{tags:["llm","gemini","google","agentic","coding","fast"]}),le("or-gemini-3-pro","Gemini 3 Pro","Google's flagship frontier model for deep reasoning, multimodal analysis, and agentic coding.","google/gemini-3-pro-preview",2,12,{tags:["llm","gemini","google","reasoning","coding","multimodal"]}),le("or-gemini-35-flash","Gemini 3.5 Flash","Google frontier Flash model for multimodal reasoning, coding, and parallel agentic workflows.","google/gemini-3.5-flash",1.5,9,{tags:["llm","gemini","google","frontier","multimodal","reasoning","coding","fast"]}),le("or-gemini-3-lite","Gemini 3.1 Flash Lite","Google's efficient multimodal model optimized for low-latency, high-volume agent workloads.","google/gemini-3.1-flash-lite",.25,1.5,{tags:["llm","gemini","google","fast","cheap","multimodal"]}),le("or-llama-70b","Llama 3.3 70B","Meta's best open model. Strong reasoning, fully open-source.","meta-llama/llama-3.3-70b-instruct",.3,.4,{tags:["llm","llama","meta","open-source","reasoning"]}),le("or-llama-8b","Llama 3.1 8B","Fast, lightweight open model. Great for simple tasks at minimal cost.","meta-llama/llama-3.1-8b-instruct",.05,.08,{tags:["llm","llama","meta","open-source","fast","cheap"]}),le("or-mistral-large","Mistral Large","Mistral's flagship model. Strong at multilingual and European languages.","mistralai/mistral-large-2411",2,6,{tags:["llm","mistral","multilingual","european"]}),le("or-mistral-small","Mistral Small","Fast, efficient Mistral model. Good for everyday tasks.","mistralai/mistral-small-3.1-24b-instruct",.1,.3,{tags:["llm","mistral","fast","cheap"]}),le("or-deepseek-chat","DeepSeek Chat V3","Strong reasoning model at very low cost. Excellent for coding and math.","deepseek/deepseek-chat-v3-0324",.3,.88,{tags:["llm","deepseek","coding","math","cheap","reasoning"]}),le("or-deepseek-r1","DeepSeek R1","Advanced reasoning model with chain-of-thought. Best for complex problems.","deepseek/deepseek-r1",.55,2.19,{tags:["llm","deepseek","reasoning","chain-of-thought","math"]}),le("or-qwen-72b","Qwen 2.5 72B","Alibaba's large model. Strong at coding, math, and multilingual tasks.","qwen/qwen-2.5-72b-instruct",.3,.4,{tags:["llm","qwen","alibaba","coding","multilingual"]}),le("or-phi-4","Phi-4","Microsoft's compact reasoning model. Punches above its weight for size.","microsoft/phi-4",.07,.14,{tags:["llm","phi","microsoft","compact","cheap","reasoning"]}),le("or-perplexity-sonar","Perplexity Sonar","Search-augmented LLM. Answers with real-time web sources and citations.","perplexity/sonar",1,1,{perRequestFeeCents:.5,tags:["llm","perplexity","search","web","citations","real-time"]}),{dispatch:"enveloped",id:"query_onchain_prices",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly and daily granularity.",provider:"allium",model:"allium-prices",category:"onchain",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly) or '1d' (daily). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",internal:!0,executionKind:"x402_gateway",resultKind:"utility",gatewayConfig:{enabled:!1,gatewayPath:"/gateway",method:"POST",timeoutMs:3e4},buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:bp,tags:["onchain","prices","allium","crypto"]},{dispatch:"enveloped",id:"parallel-search-tempo",name:"Parallel Search (Tempo)",description:"Internal Tempo gateway route for Parallel's paid search endpoint.",provider:"parallel",model:"search",category:"utility",priceCents:1,inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query. Mapped by Parallel to objective when provided."},objective:{type:"string",description:"Search objective. Use with search_queries for advanced requests."},search_queries:{type:"array",items:{type:"string"},description:"Optional explicit search query list."},mode:{type:"string",enum:["one-shot","fast"],description:"Parallel search mode.",default:"one-shot"}},anyOf:[{required:["query"]},{required:["objective"]}]},gatewayUrl:"https://parallelmpp.dev/api/search",merchantName:"Parallel",internal:!0,rail:"tempo",executionKind:"tempo_gateway",resultKind:"utility",gatewayConfig:{enabled:!1,gatewayPath:"/gateway",method:"POST",timeoutMs:3e4},buildBody:$v,tags:["search","parallel","tempo","internal"]},{dispatch:"enveloped",id:"generate_image_card",name:"Generate Image (Ultra)",description:"Generate a high-quality AI image (FLUX Pro Ultra, 2K, ~$0.06).",provider:"fal",model:"fal-ai/flux-pro/v1.1-ultra",category:"image",priceCents:6,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1-ultra",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro-ultra",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),t},tags:["image","flux","ultra","legacy"]},{dispatch:"enveloped",id:"generate_image_fast_card",name:"Generate Image (Fast)",description:"Generate an AI image (FLUX Pro v1.1, 1K, ~$0.04).",provider:"fal",model:"fal-ai/flux-pro/v1.1",category:"image",priceCents:4,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro",buildBody:e=>vi({prompt:e.prompt,aspect_ratio:e.aspect_ratio}),tags:["image","flux","legacy"]},{dispatch:"enveloped",id:"generate_image_schnell_card",name:"Generate Image (Cheap)",description:"Cheap, fast FLUX image generation (~$0.01).",provider:"fal",model:"fal-ai/flux/schnell",category:"image",priceCents:1,inputSchema:{type:"object",properties:{prompt:{type:"string"},image_size:{type:"string"},num_inference_steps:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux/schnell",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-schnell",buildBody:e=>{let t={prompt:e.prompt};return e.image_size&&(t.image_size=e.image_size),e.num_inference_steps!==void 0&&(t.num_inference_steps=e.num_inference_steps),e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","flux","schnell","legacy"]},{dispatch:"enveloped",id:"generate_image_recraft_card",name:"Generate Image (Recraft)",description:"Recraft V3 image generation with style control.",provider:"fal",model:"fal-ai/recraft-v3",category:"image",priceCents:5,inputSchema:{type:"object",properties:{prompt:{type:"string"},style:{type:"string"},image_size:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/recraft-v3",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-recraft-v3",buildBody:e=>{let t={prompt:e.prompt};return e.style&&(t.style=e.style),e.image_size&&(t.image_size=e.image_size),t},tags:["image","recraft","legacy"]},{dispatch:"enveloped",id:"generate_image_ideogram_card",name:"Generate Image (Ideogram)",description:"Ideogram V2 image generation, strong with text rendering.",provider:"fal",model:"fal-ai/ideogram/v2",category:"image",priceCents:8,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},style_type:{type:"string"},negative_prompt:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/ideogram/v2",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-ideogram-v2",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.style_type&&(t.style_type=e.style_type),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),t},tags:["image","ideogram","text","legacy"]},he("upscale_image_card","Upscale Image","Upscale an image using ESRGAN.","fal-ai/esrgan","upscale",2,{type:"object",properties:{image_url:{type:"string"},scale:{type:"number"}},required:["image_url"]},{buildBody:e=>{let t={image_url:e.image_url};return e.scale!==void 0&&(t.scale=e.scale),t},tags:["upscale","esrgan"],deprecated:!0,replacementTool:"fal-aura-sr"}),he("edit_image_seed_card","Edit Image (SeedEdit)","Inpaint/edit an image with a prompt using SeedEdit.","fal-ai/bytedance/seededit","image",5,{type:"object",properties:{image_url:{type:"string"},prompt:{type:"string"},seed:{type:"number"}},required:["image_url","prompt"]},{buildBody:e=>{let t={image_url:e.image_url,prompt:e.prompt};return e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","edit","inpaint","seededit"],deprecated:!0,replacementTool:"or-gemini-nano-banana"}),{dispatch:"enveloped",id:"generate_video_tempo_card",name:"Generate Video (Grok)",description:"Generate a video from a text prompt using Grok Imagine Video.",provider:"fal",model:"xai/grok-imagine-video/text-to-video",category:"video",priceCents:30,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/xai/grok-imagine-video/text-to-video",merchantName:"Grok Video via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),t},tags:["video","grok","legacy"]},{dispatch:"enveloped",id:"generate_video_kling_card",name:"Generate Video (Kling)",description:"Generate a video using Kling v1.6 (async, ~$0.40).",provider:"fal",model:"fal-ai/kling-video/v1.6/standard/text-to-video",category:"video",priceCents:40,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/kling-video/v1.6/standard/text-to-video",merchantName:"Kling via fal.ai",deprecated:!0,replacementTool:"fal-kling-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","kling","legacy"]},{dispatch:"enveloped",id:"generate_video_wan_card",name:"Generate Video (Wan)",description:"Generate a video using Wan T2V (async, ~$0.25).",provider:"fal",model:"fal-ai/wan/t2v-1.3b",category:"video",priceCents:25,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/wan/t2v-1.3b",merchantName:"Wan T2V via fal.ai",deprecated:!0,replacementTool:"fal-wan-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","wan","legacy"]},{dispatch:"enveloped",id:"generate_video_minimax_card",name:"Generate Video (MiniMax)",description:"Generate a video using MiniMax (async, ~$0.35).",provider:"fal",model:"fal-ai/minimax/video-01",category:"video",priceCents:35,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/minimax/video-01",merchantName:"MiniMax via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","minimax","legacy"]},{id:"check_fal_status",name:"Check fal Async Job Status",description:"Poll an async fal.ai queue job for completion. Free.",provider:"fal",model:"queue-status",category:"image",priceCents:0,inputSchema:{type:"object",properties:{model_path:{type:"string",description:"Model path (e.g. fal-ai/kling-video/v1.6/standard/text-to-video)"},request_id:{type:"string"}},required:["model_path","request_id"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue",merchantName:"fal.ai",handler:{type:"local",fn:"check_fal_status"},pricing:{amount:0,currency:"USD",display:"$0.00",free:!0},freeReadPathPattern:"/api/v1/fal/**/requests/*/(status)?",tags:["status","fal","async"]},{dispatch:"enveloped",id:"generate_3d_card",name:"Generate 3D Model",description:"Generate a 3D mesh from a text prompt using Meshy (async, ~$0.50).",provider:"fal",model:"fal-ai/meshy-ai/text-to-3d",category:"3d",priceCents:50,inputSchema:{type:"object",properties:{object_prompt:{type:"string"},style_prompt:{type:"string"},negative_prompt:{type:"string"},art_style:{type:"string"},seed:{type:"number"}},required:["object_prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/meshy-ai/text-to-3d",merchantName:"Meshy via fal.ai",deprecated:!0,replacementTool:"fal-trellis-3d",buildBody:e=>{let t={object_prompt:e.object_prompt};return e.style_prompt&&(t.style_prompt=e.style_prompt),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.art_style&&(t.art_style=e.art_style),e.seed!==void 0&&(t.seed=e.seed),t},tags:["3d","mesh","meshy","legacy"]},{dispatch:"enveloped",id:"generate_speech_card",name:"Generate Speech",description:"Text-to-speech using F5-TTS with optional voice cloning.",provider:"fal",model:"fal-ai/f5-tts",category:"tts",priceCents:3,inputSchema:{type:"object",properties:{gen_text:{type:"string",description:"Text to synthesize"},ref_audio_url:{type:"string",description:"Reference audio URL (for voice cloning)"},ref_text:{type:"string",description:"Transcription of ref audio"},remove_silence:{type:"boolean"}},required:["gen_text"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/f5-tts",merchantName:"fal.ai",buildBody:e=>{let t={gen_text:e.gen_text};return e.ref_audio_url&&(t.ref_audio_url=e.ref_audio_url),e.ref_text&&(t.ref_text=e.ref_text),e.remove_silence!==void 0&&(t.remove_silence=e.remove_silence),t},deprecated:!0,replacementTool:"fal-metavoice",tags:["tts","speech","f5-tts","legacy"]},{dispatch:"enveloped",id:"generate_music_tempo_card",name:"Generate Music (Suno) \u2014 retired",description:"[Retired] Suno music generation. Use `generate_music` (ACE-Step) instead.",enabled:!1,sunsetAt:"2026-06-25",provider:"suno",model:"suno-v4",category:"audio",priceCents:50,inputSchema:{type:"object",properties:{prompt:{type:"string"},instrumental:{type:"boolean"},model:{type:"string",default:"V4"}},required:["prompt"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/generate-music",merchantName:"Suno via Tempo",buildBody:e=>({prompt:e.prompt,customMode:!1,instrumental:e.instrumental??!1,model:e.model||"V4"}),isAsync:!0,pollUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",pollInterval:15e3,pollTimeout:3e5,deprecated:!0,replacementTool:"fal-ace-step-music",tags:["music","audio","suno","async","legacy"]},{dispatch:"enveloped",id:"check_music_status_tempo_card",name:"Check Music Status (Suno) \u2014 retired",description:"[Retired] Suno status poll. No replacement; ACE-Step jobs poll via `check_fal_status`.",enabled:!1,sunsetAt:"2026-06-25",provider:"suno",model:"suno-status",category:"audio",priceCents:0,inputSchema:{type:"object",properties:{taskId:{type:"string"}},required:["taskId"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",merchantName:"Suno Status",buildBody:e=>({taskId:e.taskId}),deprecated:!0,tags:["music","status","suno","legacy"]},{dispatch:"enveloped",id:"query_onchain_prices_card",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly, daily, and weekly granularity.",provider:"allium",model:"allium-prices",category:"llm",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly), '1d' (daily), or '1w' (weekly). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",deprecated:!0,replacementTool:"query_onchain_prices",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:bp,tags:["onchain","prices","allium","crypto","legacy"]}];function Qr(e){return Wc.find(t=>t.id===e)}var kp=1,Ep=["pick_one","fan_out"],Ap=["concat","dedupe_by_url","top_k_by_score"],Lv=8,Uv=_.object({type:_.string().min(1),description:_.string().min(1),enum:_.array(_.string()).optional(),default:_.unknown().optional(),minimum:_.number().optional(),maximum:_.number().optional()}),Dv=_.object({toolId:_.string().min(1),notes:_.string().min(1)}),jv=_.string().regex(/^[a-z0-9_-]{1,32}$/,"tier key must be 1-32 chars [a-z0-9_-]"),Bv=_.object({providers:_.array(_.string().min(1)).min(1).max(Lv),merge:_.enum(Ap),maxResults:_.number().int().positive().optional()}),Rp=_.object({mode:_.enum(Ep).default("pick_one"),intro:_.string().min(1),defaultTier:_.string().min(1),tiers:_.record(jv,Dv).refine(e=>Object.keys(e).length>0,{message:"must have at least one tier"}),fanOut:Bv.optional(),guidance:_.string().min(1),inputProperties:_.record(_.string(),Uv),required:_.array(_.string())}).refine(e=>e.tiers[e.defaultTier]!==void 0,{message:"defaultTier must exist in tiers",path:["defaultTier"]}).refine(e=>e.mode!=="fan_out"||e.fanOut!==void 0,{message:"fan_out mode requires fanOut config",path:["fanOut"]}).refine(e=>e.required.every(t=>t in e.inputProperties),{message:"required entries must exist in inputProperties",path:["required"]}),Fv=_.object({version:_.literal(kp),generatedAt:_.string().datetime(),tools:_.record(_.string().regex(qc,"tool name must match MCP naming rules"),Rp).refine(e=>Object.keys(e).length>0,{message:"manifest must have at least one tool"})});var Sa=R(es());var Ci=require("child_process"),Bp=require("util"),Fp=R(require("crypto")),te=R(require("fs")),Hp=R(require("os")),$e=R(require("path"));_t();var st=(0,Bp.promisify)(Ci.execFile),aw=6e4,cw=()=>process.platform==="darwin",Sn=()=>process.platform==="win32",xn=$e.join(Hp.homedir(),".visa-mcp","bin"),mr=$e.join(xn,"Visa CLI"),Yt=$e.join(xn,"visa-keychain-win.exe"),Vp=$e.join(__dirname,"..","native"),$p="6",Pp=$e.join(xn,"visa-keychain.version"),Op=$e.join(xn,"visa-keychain.sha256"),Mp="1",Np=$e.join(xn,"visa-keychain-win.version"),Lp=$e.join(xn,"visa-keychain-win.sha256"),qp=[$e.join(Vp,"bin","win32-x64","visa-keychain-win.exe"),$e.resolve(__dirname,"..","..","native","bin","win32-x64","visa-keychain-win.exe"),$e.resolve(__dirname,"..","native","bin","win32-x64","visa-keychain-win.exe")];function Si(e){let t=te.readFileSync(e);return Fp.createHash("sha256").update(t).digest("hex")}function lw(e){let t=e.trim();if(t.startsWith("OK:"))return t.slice(3);if(t==="OK")return;let n=t.startsWith("ERROR:")?t.slice(6):"Unknown error";throw new Error(n)}function Up(e){let t=typeof e?.message=="string"?e.message:"";return e?.code==="ETIMEDOUT"||e?.killed===!0||/timed out|timeout/i.test(t)}function Dp(e){let t=Math.max(1,Math.round(e/1e3));return new Error(`Timed out waiting for Touch ID/device approval after ${t}s.`)}async function Yc(){try{if(te.readFileSync(Pp,"utf-8").trim()===$p&&te.existsSync(mr)){let r=te.readFileSync(Op,"utf-8").trim();if(Si(mr)!==r)g.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),te.unlinkSync(mr);else return mr}}catch{}let e=$e.join(Vp,"visa-keychain.m");if(te.existsSync(e)||(e=$e.resolve(__dirname,"..","..","native","visa-keychain.m")),te.existsSync(e)||(e=$e.resolve(__dirname,"..","native","visa-keychain.m")),!te.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");te.mkdirSync(xn,{recursive:!0,mode:448});try{await st("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",mr,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=Si(mr);return te.writeFileSync(Op,t,{mode:384}),te.writeFileSync(Pp,$p,{mode:384}),mr}function Kp(){for(let e of qp)if(te.existsSync(e))return e;return null}async function ts(){try{if(te.readFileSync(Np,"utf-8").trim()===Mp&&te.existsSync(Yt)){let r=te.readFileSync(Lp,"utf-8").trim();if(Si(Yt)!==r)g.warn("binary:hash-mismatch:win32",{message:"Windows binary hash mismatch. Redeploying."}),te.unlinkSync(Yt);else return Yt}}catch{}let e=Kp();if(!e)throw new Error(`visa-keychain-win.exe not found in package. Reinstall @visa/cli.
142
- If building from source, run native/build-win.bat first.`);te.mkdirSync(xn,{recursive:!0}),te.copyFileSync(e,Yt);let t=Si(Yt);return te.writeFileSync(Lp,t,{mode:384}),te.writeFileSync(Np,Mp,{mode:384}),Yt}async function uw(){return Sn()?ts():Yc()}var xi="visa-cli",Ti="attestation-key";async function dw(e){try{await st("security",["delete-generic-password","-s",xi,"-a",Ti],{timeout:5e3})}catch{}await st("security",["add-generic-password","-s",xi,"-a",Ti,"-w",e],{timeout:5e3})}function fw(e){let t=typeof e?.code=="number"?e.code:void 0,n=typeof e?.stderr=="string"?e.stderr:"",r=typeof e?.stdout=="string"?e.stdout:"",s=[n,r,e?.message].filter(Boolean).join(" ").trim();return t===44||/could not be found|item(?: was)? not found|no such keychain item|not found/i.test(s)?{state:"absent",usable:!1,message:"No local attestation key was found."}:/user interaction is not allowed|user canceled|user cancelled|authorization failed|interaction not allowed|keychain.*locked|denied|not authorized/i.test(s)?{state:"denied",usable:!1,message:"The local attestation key exists but Keychain access was denied or unavailable."}:{state:"error",usable:!1,message:s||"Could not read the local attestation key from Keychain."}}async function pw(){try{let{stdout:e}=await st("security",["find-generic-password","-s",xi,"-a",Ti,"-w"],{timeout:5e3}),t=e.trim();return t?{key:t,status:{state:"present",usable:!0}}:{key:null,status:{state:"absent",usable:!1,message:"No local attestation key was found."}}}catch(e){return{key:null,status:fw(e)}}}async function zc(){let e=await pw();if(e.key)return e.key;if(e.status.state==="absent")return null;throw new Error(e.status.message||"Could not read the local attestation key from Keychain.")}async function Gp(e){let t=await uw(),n;try{n=(await st(t,e,{timeout:6e4})).stdout}catch(r){n=r.stdout||"";let s=n.trim();throw s.startsWith("ERROR:")?new Error(s.slice(6)):new Error(r.stderr?.trim()||r.message||"Unknown error")}return lw(n)}var jp=!1;function mw(){if(!Sn())return!1;try{return te.existsSync(Yt)||Kp()!==null?!0:(jp||(jp=!0,g.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:Yt,searchedPrebuiltPaths:qp})),!1)}catch{return!1}}function ue(){return Nr()||cw()?!0:Sn()?mw():!1}async function ki(){if(Sn()){let s=await ts(),{stdout:o}=await st(s,["generate-key"],{timeout:3e4}),i=o.trim();if(i.startsWith("OK:"))return i.slice(3);throw new Error(i.startsWith("ERROR:")?i.slice(6):"Key generation failed")}let e=await Gp(["generate-key"]);if(!e)throw new Error("Key generation returned no output");let t=e.indexOf(":");if(t<0)throw new Error("Unexpected generate-key output format");let n=e.slice(0,t),r=e.slice(t+1);return await dw(n),r}async function Ei(){if(Sn())try{let e=await ts(),{stdout:t}=await st(e,["public-key"],{timeout:1e4});return t.trim().startsWith("OK:")}catch{return!1}return await zc()!==null}async function Wp(){if(Nr())return"mock-public-key-spki";if(Sn()){let n=await ts(),{stdout:r}=await st(n,["public-key"],{timeout:6e4}),s=r.trim();if(s.startsWith("OK:"))return s.slice(3);throw new Error(s.startsWith("ERROR:")?s.slice(6):"Attestation key not found. Run setup to generate a new key.")}let e=await zc();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await Yc();return new Promise((n,r)=>{let s=(0,Ci.execFile)(t,["public-key"],{timeout:6e4},(o,i)=>{let a=(i||"").trim();if(o){a.startsWith("ERROR:")?r(new Error(a.slice(6))):r(new Error(o.stderr?.trim()||o.message||"Unknown error"));return}a.startsWith("OK:")?n(a.slice(3)):r(new Error(a.startsWith("ERROR:")?a.slice(6):"Unknown error"))});s.stdin.write(e),s.stdin.end()})}async function Tn(e,t,n={}){if(Nr())return Promise.resolve(id());let r=n.timeoutMs??aw;if(Sn()){let a=await ts(),c=["sign",e];t&&c.push(t);let l;try{l=(await st(a,c,{timeout:r})).stdout}catch(d){throw Up(d)?Dp(r):d}let u=l.trim();if(u.startsWith("OK:"))return u.slice(3);throw new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error")}let s=await zc();if(!s)throw new Error("Attestation key not found. Run setup to generate a new key.");let o=await Yc(),i=["sign",e];return t&&i.push(t),new Promise((a,c)=>{let l=(0,Ci.execFile)(o,i,{timeout:r},(u,d)=>{let p=(d||"").trim();if(u){p.startsWith("ERROR:")?c(new Error(p.slice(6))):Up(u)?c(Dp(r)):c(new Error(u.stderr?.trim()||u.message||"Unknown error"));return}p.startsWith("OK:")?a(p.slice(3)):c(new Error(p.startsWith("ERROR:")?p.slice(6):"Unknown error"))});l.stdin.write(s),l.stdin.end()})}async function Ai(){if(Sn()){try{let e=await ts();await st(e,["delete-key"],{timeout:1e4})}catch{}return}try{await st("security",["delete-generic-password","-s",xi,"-a",Ti],{timeout:5e3})}catch{}try{await Gp(["delete-key"])}catch{}}_t();var gw=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],hw=[...gw.map(e=>({id:`legacy.${e}`,match:{kind:"exact_tool",toolId:e},targetToolId:e,rail:"tempo",reason:"Preserve legacy Tempo _card target while the top-level MCP surface is opt-in."}))];function Xc(e,t=hw){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=Jc(e.intentText);for(let r of t)if(r.match.kind==="intent"&&r.match.metaTool===e.metaTool&&!(r.match.tier&&r.match.tier!==e.tier)&&!(r.match.provider&&!n.includes(Jc(r.match.provider)))&&r.match.keywords.every(s=>n.includes(Jc(s))))return r.targetToolId;return null}function Jc(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}_t();Ht();var eo={generate_image:{intro:'Generate an AI image from a text prompt \u2014 useful for hero shots, marketing assets, social posts, blog covers, app mockups, or any time the user asks for art, a logo, an icon, a thumbnail, or "a picture of \u2026". From $0.01 (fast) to $0.06 (pro), returns a hosted PNG/JPG URL. Default tier: balanced ($0.04, 1K, ~10s).',tiers:{balanced:{toolId:"fal-flux-pro",notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",notes:"Recraft V3 \u2014 vector/flat/illustration styles"}},guidance:"If the user didn't specify a tier, pick 'balanced' unless the prompt clearly signals otherwise (text \u2192 text_heavy, logo/icon \u2192 vector, quick test \u2192 fast, hero/print \u2192 pro).",inputProperties:{prompt:{type:"string",description:"Text description of the image to generate."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9", "1:1", "9:16".',default:"16:9"}},required:["prompt"]},generate_video:{intro:'Generate a short AI video from a text prompt \u2014 useful for product demos, social clips, mood reels, ad concepts, or any "make me a video of \u2026" request. $0.10\u2013$0.40 per ~6s clip depending on tier. Async: returns a request_id; use execute_tool with tool_id "check_fal_status" to resolve it (60\u2013180s).',tiers:{balanced:{toolId:"fal-minimax-video",notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",notes:"Kling \u2014 highest quality, cinematic"}},guidance:'Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate and are processed asynchronously. The response includes a request_id and model_path. Poll with execute_tool using tool_id "check_fal_status" and the exact request_id/model_path returned by the async response. Do not substitute the catalog model path manually. Do not poll more than once per 30 seconds.',inputProperties:{prompt:{type:"string",description:"Text description of the video scene."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9" or "9:16".',default:"16:9"}},required:["prompt"]},generate_music:{intro:'Generate an original music track from a prompt via ACE-Step. ~$0.02 for the default 60s track. Use for songs, backing tracks, jingles, vocal music, instrumental music, or any "make a song/music/track" request. Takes ~60-90s and may return a request_id to poll with check_fal_status. For SFX, chimes, ambient beds, or TTS, use generate_audio instead.',tiers:{ace_step:{toolId:"fal-ace-step-music",notes:"ACE-Step \u2014 prompt-to-music with vocals or instrumentals"}},guidance:"Use for songs and music tracks. Takes ~60-90s and may return a request_id to poll with check_fal_status. For sound effects, chimes, ambient beds, or TTS, use generate_audio instead.",inputProperties:{prompt:{type:"string",description:"Musical style, mood, instruments, subject, and lyrics direction."},instrumental:{type:"boolean",description:"True for instrumental music with no vocals; false for vocal tracks.",default:!1},duration:{type:"number",description:"Duration in seconds.",default:60}},required:["prompt"]},generate_audio:{intro:'Generate sound effects from a text prompt (sfx tier \u2014 default), or voice-cloned speech from text + a reference audio URL (tts tier). $0.03\u2013$0.04. Use for SFX, chimes, UI sounds, ambient audio (default sfx), or voice cloning when a reference audio URL is available (pass tier:"tts"). Default tier is sfx; pass tier:"tts" for voice cloning.',tiers:{sfx:{toolId:"fal-stable-audio",notes:"Stable Audio \u2014 sound effects and ambient from a prompt"},tts:{toolId:"fal-metavoice",notes:"MetaVoice \u2014 voice cloning TTS (requires a voice sample URL)"}},guidance:'Default tier is sfx: pass prompt describing the sound. For tts (voice cloning): pass tier:"tts" + text + audio_url.',inputProperties:{prompt:{type:"string",description:"Description of sound to generate (sfx tier, default)."},text:{type:"string",description:"Text to speak aloud (tts tier)."},audio_url:{type:"string",description:"URL of a voice sample to clone (tts tier, required for voice cloning)."}},required:[]},generate_3d:{intro:"Generate a 3D mesh (GLB) from an image URL via Trellis. ~$0.08, ~30\u201360s. Use when the user shares an image and asks for a 3D model, asset, AR-ready mesh, or game-ready GLB.",tiers:{trellis:{toolId:"fal-trellis-3d",notes:"Trellis \u2014 image-to-3D, returns a GLB mesh URL"}},guidance:"Pass an image URL. Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{image_url:{type:"string",description:"URL of the image to convert to a 3D model."}},required:["image_url"]},upscale_image:{intro:'Upscale an image to 4\xD7 resolution via Aura SR (preserves detail without hallucination). ~$0.03. Use whenever the user shares a low-res image and asks to "upscale", "make this higher resolution", "4x this", "enhance", or to print/export at larger size.',tiers:{aura:{toolId:"fal-aura-sr",notes:"Aura SR \u2014 default; preserves detail without hallucination"}},guidance:"Pass the existing image URL. Returns an upscaled version.",inputProperties:{image_url:{type:"string",description:"URL of the image to upscale."}},required:["image_url"]},transcribe_audio:{intro:'Transcribe speech in an audio or video file (URL) to text via OpenAI Whisper. ~$0.02 per file, multilingual, handles long files. Use whenever the user asks to "transcribe this", "what does this audio say", "make subtitles", "convert this to text", or shares an audio/video URL with no other clear intent.',tiers:{whisper:{toolId:"fal-whisper",notes:"OpenAI Whisper \u2014 fast, multilingual"}},guidance:"Pass the URL. Returns the transcript text.",inputProperties:{audio_url:{type:"string",description:"URL of the audio or video file to transcribe."}},required:["audio_url"]},run_llm:{intro:"Run a text prompt through a different LLM (GPT-4o-mini, Claude Sonnet, DeepSeek R1/V3, Perplexity Sonar with web search, or Llama 70B). Token-metered, typically ~$0.01\u2013$0.10 per call. Use for: web-grounded answers (search tier), second-opinion reasoning (reasoning tier), code generation in a different family (coding tier), deep math/logic (deep_reasoning tier), or fast cheap text cleanup (fast tier). Pair with batch for multi-model councils.",tiers:{fast:{toolId:"or-gpt-4o-mini",notes:"GPT-4o Mini. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",notes:"Claude Sonnet. Strong reasoning, long-context. Warn user it is materially pricier than `fast`."},frontier_openai:{toolId:"or-gpt-55",notes:"GPT-5.5. OpenAI frontier model for complex professional reasoning."},frontier_openai_pro:{toolId:"or-gpt-55-pro",notes:"GPT-5.5 Pro. Highest-capability OpenAI frontier tier; materially more expensive."},frontier_anthropic:{toolId:"or-claude-opus",notes:"Claude Opus 4.7. Anthropic frontier model for complex tasks."},frontier_google:{toolId:"or-gemini-35-flash",notes:"Gemini 3.5 Flash. Google frontier Flash model for multimodal reasoning and coding."},deep_reasoning:{toolId:"or-deepseek-r1",notes:"DeepSeek R1. Deep chain-of-thought reasoning, mid-range pricing."},search:{toolId:"or-perplexity-sonar",notes:"Perplexity Sonar. Search-augmented, web-grounded with citations."},open_source:{toolId:"or-llama-70b",notes:"Llama 3.3 70B. Open-source large model."},coding:{toolId:"or-deepseek-chat",notes:"DeepSeek Chat V3. Strong at code generation."}},guidance:"Pick based on the user's need: fast (most questions, cheapest), reasoning (complex analysis; warn user it is materially pricier than fast), frontier_* (top-model council / highest quality; warn user these are materially pricier), search (questions about current events), coding (code generation), deep_reasoning (hard math/logic problems).",inputProperties:{prompt:{type:"string",description:"The user query."},system_prompt:{type:"string",description:"Optional system prompt to set model behavior."},max_tokens:{type:"number",description:"Maximum output tokens.",default:1024,minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature \u2014 0 is deterministic, higher is more creative.",default:.7,minimum:0,maximum:2}},required:["prompt"]}};function Cn(e,t,n){if(!zp(e))return vw(e,n);let r=Yp[e];if(!r)return e;let s=Object.keys(r.tiers),o=t||s[0],i=ww(e,o,n);return i||Sw(e,r,o,s)}function vw(e,t){return Xc({requestedTool:e,intentText:t})??e}function ww(e,t,n){return Xc({requestedTool:e,metaTool:e,tier:t,intentText:n})}function Sw(e,t,n,r){let s=t.tiers[n];if(!s)throw new Error(`Unknown tier '${n}' for ${e}. Valid tiers: ${r.join(", ")}`);return s.toolId}var Yp=eo;function zp(e){return e in Yp}var to=Object.keys(eo);function Zc(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function Jp(e=process.env){return Zc(e)!==null}var xw=new Set(["false","0","no","off","disable","disabled"]),Tw=new Set(["true","1","yes","on","enable","enabled"]);function Xp(e){let t=(e??"").trim().toLowerCase();return t?xw.has(t)?!1:!!Tw.has(t):!0}function Zp(e=process.env){return Xp(e.VISA_CLI_PARENTLESS_SINGLE_CALL)}function Qp(e=process.env){return Xp(e.VISA_CLI_PARENTLESS_BATCH)}var Mh=require("child_process"),Se=R(require("crypto")),lt=R(require("fs")),wo=R(require("os")),xa=R(require("path"));function xt(e,t={}){if(!e||typeof e!="object")return e;let n=e,r=t.tag??(typeof n.merchantName=="string"?n.merchantName:"media"),s=n.content?.[0]?.text,o=typeof s=="string"?Lr(s):null,i=Array.isArray(n.urls)?n.urls[0]:void 0,c=typeof i=="string"&&i.startsWith("data:")?Lr(i):null;if(!o&&!c)return e;let l=o??c,u=o?"content":"urls",d;try{d=Rs(l,{tag:Cw(r,n)})}catch(f){return{...n,_inline_media_warning:`Failed to persist inline media to disk: ${f instanceof Error?f.message:String(f)}`}}let p={...n,filePath:d.filePath,mime:d.mime,bytes:d.bytes};return u==="urls"?p.urls=void 0:(p.content=Array.isArray(n.content)?[...n.content]:[{}],p.content[0]={...p.content[0]??{},text:`[inline media saved to ${d.filePath}]`}),p}function Cw(e,t){let n=typeof t.transactionId=="string"?t.transactionId:typeof t.transaction_id=="string"?t.transaction_id:null;return n?`${e}-${n}`:e}_t();var em=!1;async function gr(e,t,n){try{return await t()}catch(r){if(!(r.message==="Invalid signature"||r.code==="ATTESTATION_KEY_DRIFT"||r.error_code==="ATTESTATION_KEY_DRIFT"||r.name==="AttestationDriftError")||!ue())throw r;if(g.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(em)throw g.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;em=!0,g.info("attestation:starting-browser-recovery");try{let o=await n();if(!o.success)throw g.error("attestation:browser-recovery-failed",{message:o.message}),r;let i=await ki();return await e.registerAttestationKey(i),await e.setBiometricPreference({required:!0}),g.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),g.info("attestation:key-reregistered-after-recovery"),await t()}catch(o){throw g.error("attestation:recovery-failure",{error:o.message}),r}}throw r}}function Tt(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}async function Ri(e,t){if(!ue())return{ok:!1,code:"TOUCH_ID_UNAVAILABLE",message:"Touch ID is not available in this process. Run `visa-cli setup` from an interactive macOS terminal before enabling Touch ID."};if(!await Ei())return{ok:!1,code:"LOCAL_ATTESTATION_KEY_MISSING",message:"No local attestation key found on this device. Run `visa-cli setup` before enabling Touch ID; otherwise payments and biometric off can require a key this device cannot produce."};let n=await e.getStatus(t);return Tt(n)?{ok:!0,status:n}:{ok:!1,code:"SERVER_ATTESTATION_KEY_MISSING",message:"No server attestation key is registered for this account. Run `visa-cli setup` before enabling Touch ID."}}Ht();var tm="3.3.0";function Qc(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function Ii(e,t,n){let r=process.env[e];if(r!==void 0)return{value:n==="opt-in"?r==="true":r!=="false",source:{kind:"env",var:e}};let s=fi(t);return s!==void 0?{value:s,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function qe(e){return e==null?"\u2014":e?"yes":"no"}function $i(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function kw(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function Ew(){let e=process.env.VISA_CREDIT_SESSION_CAP_CENTS;if(e!==void 0){let n=Number(e);if(Number.isFinite(n)&&n>=10&&n<=1e4)return{value:Math.floor(n),source:{kind:"env",var:"VISA_CREDIT_SESSION_CAP_CENTS"}}}let t=Pc("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:Ic,source:{kind:"default"}}}async function no(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(y){n=y?.message||"unknown error"}let r=[],s=process.env.VISA_AUTH_URL,o=$c("auth.serverUrl"),i=Ue(),a=s!==void 0&&s!==""?{kind:"env",var:"VISA_AUTH_URL"}:o!==void 0?{kind:"settings"}:{kind:"default"};r.push({key:"auth.serverUrl",value:i,formatted:i,source:a,hint:a.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),r.push({key:"account.enrolled",value:t?.enrolled??null,formatted:qe(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),t?.githubUser&&r.push({key:"account.githubUser",value:t.githubUser,formatted:t.githubUser,source:{kind:"server"}}),t?.userId&&r.push({key:"account.userId",value:t.userId,formatted:t.userId,source:{kind:"server"},hint:"Opaque stable account id used for account-scoped local credentials."});let c=t?t.attestationRequired!==!1:void 0;r.push({key:"biometric.required",value:c,formatted:qe(c),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"},hint:c===!1?"Touch ID prompts are suppressed. Re-enable with `visa-cli config biometric on`.":void 0}),r.push({key:"biometric.keyRegistered",value:t?.hasAttestationKey??null,formatted:qe(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:ue(),formatted:qe(ue()),source:{kind:"device"}});let l=t?.spendingControls,u=l?l.max_transaction_amount??l.maxTransactionAmount??null:null,d=l?l.daily_limit??l.dailyLimit??null:null;r.push({key:"spending.maxPerTxn",value:u,formatted:$i(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:$i(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:$i(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:$i(t?.dailyRemaining),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"cards.count",value:t?.cardCount??null,formatted:t?.cardCount!=null?String(t.cardCount):"\u2014",source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}});let p=t?.cards?.find(y=>y.isDefault)??t?.cards?.[0];p&&r.push({key:"cards.default",value:{brand:p.brand??null,last4:p.last4},formatted:`${p.brand||"card"} \u2022\u2022\u2022\u2022 ${p.last4}`,source:{kind:"server"}});let f=Ew();r.push({key:"credit.sessionCapCents",value:f.value,formatted:kw(f.value),source:f.source});let m=Bf();m.length>0&&r.push({key:"settings.retired",value:m.map(y=>y.key),formatted:m.map(y=>y.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${m.map(y=>`visa-cli config unset ${y.key}`).join(" && ")}`});let h=Ii("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:h.value,formatted:qe(h.value),source:h.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let w=Ii("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:w.value,formatted:qe(w.value),source:w.source});let C=bt(),b;process.env.VISA_CLI_NO_UPDATE_CHECK?b={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?b={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?b={kind:"env",var:"NODE_ENV"}:b={kind:"default"},r.push({key:"ui.updateCheck",value:!C,formatted:qe(!C),source:b});let v=Ii("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:v.value,formatted:qe(v.value),source:v.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let S=Ii("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:S.value,formatted:qe(S.value),source:S.source});let A=process.env.VISA_DRY_RUN,I=Jp();if(r.push({key:"tools.dryRun",value:I,formatted:qe(I),source:A===void 0?{kind:"default"}:{kind:"env",var:"VISA_DRY_RUN"},hint:"VISA_DRY_RUN=true|1|mock returns deterministic paid-tool fixtures (no card, no upstream). VISA_DRY_RUN=preflight makes a real zero-cost OpenRouter call for LLM tools (image/video still mocked)."}),r.push({key:"client.version",value:tm,formatted:tm,source:{kind:"default"}}),e.includeDev){let y=process.env.VISA_MOCK_KEYCHAIN,T=on();r.push({key:"dev.mockKeychain",value:T,formatted:qe(T),source:Qc("VISA_MOCK_KEYCHAIN",!!y),hint:qa()});let Y=process.env.VISA_MOCK_TOUCHID,X=Nr();r.push({key:"dev.mockTouchid",value:X,formatted:qe(X),source:Qc("VISA_MOCK_TOUCHID",!!Y),hint:qa()});let H=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!H,formatted:qe(!!H),source:Qc("VISA_CLI_DEBUG",!!H)})}return{entries:r,statusError:n}}function Aw(e){switch(e.kind){case"default":return"default";case"env":return`env ${e.var}`;case"settings":return"settings.json";case"server":return"server";case"device":return"device";case"unset":return"unset";case"unknown":return`unknown (${e.reason})`}}function nm(e,t={}){if(e.length===0)return"";let n=Math.max(...e.map(o=>o.key.length)),r=Math.max(...e.map(o=>o.formatted.length)),s=[];for(let o of e){let i=o.key.padEnd(n+2),a=o.formatted.padEnd(r+2);s.push(`${i}${a}(${Aw(o.source)})`),t.verbose&&o.hint&&s.push(` ${"\u21B3".padStart(n)} ${o.hint}`)}return s.join(`
142
+ If building from source, run native/build-win.bat first.`);te.mkdirSync(xn,{recursive:!0}),te.copyFileSync(e,Yt);let t=Si(Yt);return te.writeFileSync(Lp,t,{mode:384}),te.writeFileSync(Np,Mp,{mode:384}),Yt}async function uw(){return Sn()?ts():Yc()}var xi="visa-cli",Ti="attestation-key";async function dw(e){try{await st("security",["delete-generic-password","-s",xi,"-a",Ti],{timeout:5e3})}catch{}await st("security",["add-generic-password","-s",xi,"-a",Ti,"-w",e],{timeout:5e3})}function fw(e){let t=typeof e?.code=="number"?e.code:void 0,n=typeof e?.stderr=="string"?e.stderr:"",r=typeof e?.stdout=="string"?e.stdout:"",s=[n,r,e?.message].filter(Boolean).join(" ").trim();return t===44||/could not be found|item(?: was)? not found|no such keychain item|not found/i.test(s)?{state:"absent",usable:!1,message:"No local attestation key was found."}:/user interaction is not allowed|user canceled|user cancelled|authorization failed|interaction not allowed|keychain.*locked|denied|not authorized/i.test(s)?{state:"denied",usable:!1,message:"The local attestation key exists but Keychain access was denied or unavailable."}:{state:"error",usable:!1,message:s||"Could not read the local attestation key from Keychain."}}async function pw(){try{let{stdout:e}=await st("security",["find-generic-password","-s",xi,"-a",Ti,"-w"],{timeout:5e3}),t=e.trim();return t?{key:t,status:{state:"present",usable:!0}}:{key:null,status:{state:"absent",usable:!1,message:"No local attestation key was found."}}}catch(e){return{key:null,status:fw(e)}}}async function zc(){let e=await pw();if(e.key)return e.key;if(e.status.state==="absent")return null;throw new Error(e.status.message||"Could not read the local attestation key from Keychain.")}async function Gp(e){let t=await uw(),n;try{n=(await st(t,e,{timeout:6e4})).stdout}catch(r){n=r.stdout||"";let s=n.trim();throw s.startsWith("ERROR:")?new Error(s.slice(6)):new Error(r.stderr?.trim()||r.message||"Unknown error")}return lw(n)}var jp=!1;function mw(){if(!Sn())return!1;try{return te.existsSync(Yt)||Kp()!==null?!0:(jp||(jp=!0,g.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:Yt,searchedPrebuiltPaths:qp})),!1)}catch{return!1}}function ue(){return Nr()||cw()?!0:Sn()?mw():!1}async function ki(){if(Sn()){let s=await ts(),{stdout:o}=await st(s,["generate-key"],{timeout:3e4}),i=o.trim();if(i.startsWith("OK:"))return i.slice(3);throw new Error(i.startsWith("ERROR:")?i.slice(6):"Key generation failed")}let e=await Gp(["generate-key"]);if(!e)throw new Error("Key generation returned no output");let t=e.indexOf(":");if(t<0)throw new Error("Unexpected generate-key output format");let n=e.slice(0,t),r=e.slice(t+1);return await dw(n),r}async function Ei(){if(Sn())try{let e=await ts(),{stdout:t}=await st(e,["public-key"],{timeout:1e4});return t.trim().startsWith("OK:")}catch{return!1}return await zc()!==null}async function Wp(){if(Nr())return"mock-public-key-spki";if(Sn()){let n=await ts(),{stdout:r}=await st(n,["public-key"],{timeout:6e4}),s=r.trim();if(s.startsWith("OK:"))return s.slice(3);throw new Error(s.startsWith("ERROR:")?s.slice(6):"Attestation key not found. Run setup to generate a new key.")}let e=await zc();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await Yc();return new Promise((n,r)=>{let s=(0,Ci.execFile)(t,["public-key"],{timeout:6e4},(o,i)=>{let a=(i||"").trim();if(o){a.startsWith("ERROR:")?r(new Error(a.slice(6))):r(new Error(o.stderr?.trim()||o.message||"Unknown error"));return}a.startsWith("OK:")?n(a.slice(3)):r(new Error(a.startsWith("ERROR:")?a.slice(6):"Unknown error"))});s.stdin.write(e),s.stdin.end()})}async function Tn(e,t,n={}){if(Nr())return Promise.resolve(id());let r=n.timeoutMs??aw;if(Sn()){let a=await ts(),c=["sign",e];t&&c.push(t);let l;try{l=(await st(a,c,{timeout:r})).stdout}catch(d){throw Up(d)?Dp(r):d}let u=l.trim();if(u.startsWith("OK:"))return u.slice(3);throw new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error")}let s=await zc();if(!s)throw new Error("Attestation key not found. Run setup to generate a new key.");let o=await Yc(),i=["sign",e];return t&&i.push(t),new Promise((a,c)=>{let l=(0,Ci.execFile)(o,i,{timeout:r},(u,d)=>{let p=(d||"").trim();if(u){p.startsWith("ERROR:")?c(new Error(p.slice(6))):Up(u)?c(Dp(r)):c(new Error(u.stderr?.trim()||u.message||"Unknown error"));return}p.startsWith("OK:")?a(p.slice(3)):c(new Error(p.startsWith("ERROR:")?p.slice(6):"Unknown error"))});l.stdin.write(s),l.stdin.end()})}async function Ai(){if(Sn()){try{let e=await ts();await st(e,["delete-key"],{timeout:1e4})}catch{}return}try{await st("security",["delete-generic-password","-s",xi,"-a",Ti],{timeout:5e3})}catch{}try{await Gp(["delete-key"])}catch{}}_t();var gw=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],hw=[...gw.map(e=>({id:`legacy.${e}`,match:{kind:"exact_tool",toolId:e},targetToolId:e,rail:"tempo",reason:"Preserve legacy Tempo _card target while the top-level MCP surface is opt-in."}))];function Xc(e,t=hw){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=Jc(e.intentText);for(let r of t)if(r.match.kind==="intent"&&r.match.metaTool===e.metaTool&&!(r.match.tier&&r.match.tier!==e.tier)&&!(r.match.provider&&!n.includes(Jc(r.match.provider)))&&r.match.keywords.every(s=>n.includes(Jc(s))))return r.targetToolId;return null}function Jc(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}_t();Ht();var eo={generate_image:{intro:'Generate an AI image from a text prompt \u2014 useful for hero shots, marketing assets, social posts, blog covers, app mockups, or any time the user asks for art, a logo, an icon, a thumbnail, or "a picture of \u2026". From $0.01 (fast) to $0.06 (pro), returns a hosted PNG/JPG URL. Default tier: balanced ($0.04, 1K, ~10s).',tiers:{balanced:{toolId:"fal-flux-pro",notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",notes:"Recraft V3 \u2014 vector/flat/illustration styles"}},guidance:"If the user didn't specify a tier, pick 'balanced' unless the prompt clearly signals otherwise (text \u2192 text_heavy, logo/icon \u2192 vector, quick test \u2192 fast, hero/print \u2192 pro).",inputProperties:{prompt:{type:"string",description:"Text description of the image to generate."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9", "1:1", "9:16".',default:"16:9"}},required:["prompt"]},generate_video:{intro:'Generate a short AI video from a text prompt \u2014 useful for product demos, social clips, mood reels, ad concepts, or any "make me a video of \u2026" request. $0.10\u2013$0.40 per ~6s clip depending on tier. Async: returns a request_id; use execute_tool with tool_id "check_fal_status" to resolve it (60\u2013180s).',tiers:{balanced:{toolId:"fal-minimax-video",notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",notes:"Kling \u2014 highest quality, cinematic"}},guidance:'Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate and are processed asynchronously. The response includes a request_id and model_path. Poll with execute_tool using tool_id "check_fal_status" and the exact request_id/model_path returned by the async response. Do not substitute the catalog model path manually. Do not poll more than once per 30 seconds.',inputProperties:{prompt:{type:"string",description:"Text description of the video scene."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9" or "9:16".',default:"16:9"}},required:["prompt"]},generate_music:{intro:'Generate an original music track from a prompt via ACE-Step. ~$0.02 for the default 60s track. Use for songs, backing tracks, jingles, vocal music, instrumental music, or any "make a song/music/track" request. Takes ~60-90s and may return a request_id to poll with check_fal_status. For SFX, chimes, ambient beds, or TTS, use generate_audio instead.',tiers:{ace_step:{toolId:"fal-ace-step-music",notes:"ACE-Step \u2014 prompt-to-music with vocals or instrumentals"}},guidance:"Use for songs and music tracks. Takes ~60-90s and may return a request_id to poll with check_fal_status. For sound effects, chimes, ambient beds, or TTS, use generate_audio instead.",inputProperties:{prompt:{type:"string",description:"Musical style, mood, instruments, subject, and lyrics direction."},instrumental:{type:"boolean",description:"True for instrumental music with no vocals; false for vocal tracks.",default:!1},duration:{type:"number",description:"Duration in seconds.",default:60}},required:["prompt"]},generate_audio:{intro:'Generate sound effects from a text prompt (sfx tier \u2014 default), or voice-cloned speech from text + a reference audio URL (tts tier). $0.03\u2013$0.04. Use for SFX, chimes, UI sounds, ambient audio (default sfx), or voice cloning when a reference audio URL is available (pass tier:"tts"). Default tier is sfx; pass tier:"tts" for voice cloning.',tiers:{sfx:{toolId:"fal-stable-audio",notes:"Stable Audio \u2014 sound effects and ambient from a prompt"},tts:{toolId:"fal-metavoice",notes:"MetaVoice \u2014 voice cloning TTS (requires a voice sample URL)"}},guidance:'Default tier is sfx: pass prompt describing the sound. For tts (voice cloning): pass tier:"tts" + text + audio_url.',inputProperties:{prompt:{type:"string",description:"Description of sound to generate (sfx tier, default)."},text:{type:"string",description:"Text to speak aloud (tts tier)."},audio_url:{type:"string",description:"URL of a voice sample to clone (tts tier, required for voice cloning)."}},required:[]},generate_3d:{intro:"Generate a 3D mesh (GLB) from an image URL via Trellis. ~$0.08, ~30\u201360s. Use when the user shares an image and asks for a 3D model, asset, AR-ready mesh, or game-ready GLB.",tiers:{trellis:{toolId:"fal-trellis-3d",notes:"Trellis \u2014 image-to-3D, returns a GLB mesh URL"}},guidance:"Pass an image URL. Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{image_url:{type:"string",description:"URL of the image to convert to a 3D model."}},required:["image_url"]},upscale_image:{intro:'Upscale an image to 4\xD7 resolution via Aura SR (preserves detail without hallucination). ~$0.03. Use whenever the user shares a low-res image and asks to "upscale", "make this higher resolution", "4x this", "enhance", or to print/export at larger size.',tiers:{aura:{toolId:"fal-aura-sr",notes:"Aura SR \u2014 default; preserves detail without hallucination"}},guidance:"Pass the existing image URL. Returns an upscaled version.",inputProperties:{image_url:{type:"string",description:"URL of the image to upscale."}},required:["image_url"]},transcribe_audio:{intro:'Transcribe speech in an audio or video file (URL) to text via OpenAI Whisper. ~$0.02 per file, multilingual, handles long files. Use whenever the user asks to "transcribe this", "what does this audio say", "make subtitles", "convert this to text", or shares an audio/video URL with no other clear intent.',tiers:{whisper:{toolId:"fal-whisper",notes:"OpenAI Whisper \u2014 fast, multilingual"}},guidance:"Pass the URL. Returns the transcript text.",inputProperties:{audio_url:{type:"string",description:"URL of the audio or video file to transcribe."}},required:["audio_url"]},run_llm:{intro:"Run a text prompt through a different LLM (GPT-4o-mini, Claude Sonnet, DeepSeek R1/V3, Perplexity Sonar with web search, or Llama 70B). Token-metered, typically ~$0.01\u2013$0.10 per call. Use for: web-grounded answers (search tier), second-opinion reasoning (reasoning tier), code generation in a different family (coding tier), deep math/logic (deep_reasoning tier), or fast cheap text cleanup (fast tier). Pair with batch for multi-model councils.",tiers:{fast:{toolId:"or-gpt-4o-mini",notes:"GPT-4o Mini. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",notes:"Claude Sonnet. Strong reasoning, long-context. Warn user it is materially pricier than `fast`."},frontier_openai:{toolId:"or-gpt-55",notes:"GPT-5.5. OpenAI frontier model for complex professional reasoning."},frontier_openai_pro:{toolId:"or-gpt-55-pro",notes:"GPT-5.5 Pro. Highest-capability OpenAI frontier tier; materially more expensive."},frontier_anthropic:{toolId:"or-claude-opus",notes:"Claude Opus 4.7. Anthropic frontier model for complex tasks."},frontier_google:{toolId:"or-gemini-35-flash",notes:"Gemini 3.5 Flash. Google frontier Flash model for multimodal reasoning and coding."},deep_reasoning:{toolId:"or-deepseek-r1",notes:"DeepSeek R1. Deep chain-of-thought reasoning, mid-range pricing."},search:{toolId:"or-perplexity-sonar",notes:"Perplexity Sonar. Search-augmented, web-grounded with citations."},open_source:{toolId:"or-llama-70b",notes:"Llama 3.3 70B. Open-source large model."},coding:{toolId:"or-deepseek-chat",notes:"DeepSeek Chat V3. Strong at code generation."}},guidance:"Pick based on the user's need: fast (most questions, cheapest), reasoning (complex analysis; warn user it is materially pricier than fast), frontier_* (top-model council / highest quality; warn user these are materially pricier), search (questions about current events), coding (code generation), deep_reasoning (hard math/logic problems).",inputProperties:{prompt:{type:"string",description:"The user query."},system_prompt:{type:"string",description:"Optional system prompt to set model behavior."},max_tokens:{type:"number",description:"Maximum output tokens.",default:1024,minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature \u2014 0 is deterministic, higher is more creative.",default:.7,minimum:0,maximum:2}},required:["prompt"]}};function Cn(e,t,n){if(!zp(e))return vw(e,n);let r=Yp[e];if(!r)return e;let s=Object.keys(r.tiers),o=t||s[0],i=ww(e,o,n);return i||Sw(e,r,o,s)}function vw(e,t){return Xc({requestedTool:e,intentText:t})??e}function ww(e,t,n){return Xc({requestedTool:e,metaTool:e,tier:t,intentText:n})}function Sw(e,t,n,r){let s=t.tiers[n];if(!s)throw new Error(`Unknown tier '${n}' for ${e}. Valid tiers: ${r.join(", ")}`);return s.toolId}var Yp=eo;function zp(e){return e in Yp}var to=Object.keys(eo);function Zc(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function Jp(e=process.env){return Zc(e)!==null}var xw=new Set(["false","0","no","off","disable","disabled"]),Tw=new Set(["true","1","yes","on","enable","enabled"]);function Xp(e){let t=(e??"").trim().toLowerCase();return t?xw.has(t)?!1:!!Tw.has(t):!0}function Zp(e=process.env){return Xp(e.VISA_CLI_PARENTLESS_SINGLE_CALL)}function Qp(e=process.env){return Xp(e.VISA_CLI_PARENTLESS_BATCH)}var Mh=require("child_process"),Se=R(require("crypto")),lt=R(require("fs")),wo=R(require("os")),xa=R(require("path"));function xt(e,t={}){if(!e||typeof e!="object")return e;let n=e,r=t.tag??(typeof n.merchantName=="string"?n.merchantName:"media"),s=n.content?.[0]?.text,o=typeof s=="string"?Lr(s):null,i=Array.isArray(n.urls)?n.urls[0]:void 0,c=typeof i=="string"&&i.startsWith("data:")?Lr(i):null;if(!o&&!c)return e;let l=o??c,u=o?"content":"urls",d;try{d=Rs(l,{tag:Cw(r,n)})}catch(f){return{...n,_inline_media_warning:`Failed to persist inline media to disk: ${f instanceof Error?f.message:String(f)}`}}let p={...n,filePath:d.filePath,mime:d.mime,bytes:d.bytes};return u==="urls"?p.urls=void 0:(p.content=Array.isArray(n.content)?[...n.content]:[{}],p.content[0]={...p.content[0]??{},text:`[inline media saved to ${d.filePath}]`}),p}function Cw(e,t){let n=typeof t.transactionId=="string"?t.transactionId:typeof t.transaction_id=="string"?t.transaction_id:null;return n?`${e}-${n}`:e}_t();var em=!1;async function gr(e,t,n){try{return await t()}catch(r){if(!(r.message==="Invalid signature"||r.code==="ATTESTATION_KEY_DRIFT"||r.error_code==="ATTESTATION_KEY_DRIFT"||r.name==="AttestationDriftError")||!ue())throw r;if(g.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(em)throw g.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;em=!0,g.info("attestation:starting-browser-recovery");try{let o=await n();if(!o.success)throw g.error("attestation:browser-recovery-failed",{message:o.message}),r;let i=await ki();return await e.registerAttestationKey(i),await e.setBiometricPreference({required:!0}),g.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),g.info("attestation:key-reregistered-after-recovery"),await t()}catch(o){throw g.error("attestation:recovery-failure",{error:o.message}),r}}throw r}}function Tt(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}async function Ri(e,t){if(!ue())return{ok:!1,code:"TOUCH_ID_UNAVAILABLE",message:"Touch ID is not available in this process. Run `visa-cli setup` from an interactive macOS terminal before enabling Touch ID."};if(!await Ei())return{ok:!1,code:"LOCAL_ATTESTATION_KEY_MISSING",message:"No local attestation key found on this device. Run `visa-cli setup` before enabling Touch ID; otherwise payments and biometric off can require a key this device cannot produce."};let n=await e.getStatus(t);return Tt(n)?{ok:!0,status:n}:{ok:!1,code:"SERVER_ATTESTATION_KEY_MISSING",message:"No server attestation key is registered for this account. Run `visa-cli setup` before enabling Touch ID."}}Ht();var tm="3.3.1-rc.0";function Qc(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function Ii(e,t,n){let r=process.env[e];if(r!==void 0)return{value:n==="opt-in"?r==="true":r!=="false",source:{kind:"env",var:e}};let s=fi(t);return s!==void 0?{value:s,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function qe(e){return e==null?"\u2014":e?"yes":"no"}function $i(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function kw(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function Ew(){let e=process.env.VISA_CREDIT_SESSION_CAP_CENTS;if(e!==void 0){let n=Number(e);if(Number.isFinite(n)&&n>=10&&n<=1e4)return{value:Math.floor(n),source:{kind:"env",var:"VISA_CREDIT_SESSION_CAP_CENTS"}}}let t=Pc("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:Ic,source:{kind:"default"}}}async function no(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(y){n=y?.message||"unknown error"}let r=[],s=process.env.VISA_AUTH_URL,o=$c("auth.serverUrl"),i=Ue(),a=s!==void 0&&s!==""?{kind:"env",var:"VISA_AUTH_URL"}:o!==void 0?{kind:"settings"}:{kind:"default"};r.push({key:"auth.serverUrl",value:i,formatted:i,source:a,hint:a.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),r.push({key:"account.enrolled",value:t?.enrolled??null,formatted:qe(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),t?.githubUser&&r.push({key:"account.githubUser",value:t.githubUser,formatted:t.githubUser,source:{kind:"server"}}),t?.userId&&r.push({key:"account.userId",value:t.userId,formatted:t.userId,source:{kind:"server"},hint:"Opaque stable account id used for account-scoped local credentials."});let c=t?t.attestationRequired!==!1:void 0;r.push({key:"biometric.required",value:c,formatted:qe(c),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"},hint:c===!1?"Touch ID prompts are suppressed. Re-enable with `visa-cli config biometric on`.":void 0}),r.push({key:"biometric.keyRegistered",value:t?.hasAttestationKey??null,formatted:qe(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:ue(),formatted:qe(ue()),source:{kind:"device"}});let l=t?.spendingControls,u=l?l.max_transaction_amount??l.maxTransactionAmount??null:null,d=l?l.daily_limit??l.dailyLimit??null:null;r.push({key:"spending.maxPerTxn",value:u,formatted:$i(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:$i(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:$i(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:$i(t?.dailyRemaining),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"cards.count",value:t?.cardCount??null,formatted:t?.cardCount!=null?String(t.cardCount):"\u2014",source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}});let p=t?.cards?.find(y=>y.isDefault)??t?.cards?.[0];p&&r.push({key:"cards.default",value:{brand:p.brand??null,last4:p.last4},formatted:`${p.brand||"card"} \u2022\u2022\u2022\u2022 ${p.last4}`,source:{kind:"server"}});let f=Ew();r.push({key:"credit.sessionCapCents",value:f.value,formatted:kw(f.value),source:f.source});let m=Bf();m.length>0&&r.push({key:"settings.retired",value:m.map(y=>y.key),formatted:m.map(y=>y.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${m.map(y=>`visa-cli config unset ${y.key}`).join(" && ")}`});let h=Ii("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:h.value,formatted:qe(h.value),source:h.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let w=Ii("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:w.value,formatted:qe(w.value),source:w.source});let C=bt(),b;process.env.VISA_CLI_NO_UPDATE_CHECK?b={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?b={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?b={kind:"env",var:"NODE_ENV"}:b={kind:"default"},r.push({key:"ui.updateCheck",value:!C,formatted:qe(!C),source:b});let v=Ii("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:v.value,formatted:qe(v.value),source:v.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let S=Ii("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:S.value,formatted:qe(S.value),source:S.source});let A=process.env.VISA_DRY_RUN,I=Jp();if(r.push({key:"tools.dryRun",value:I,formatted:qe(I),source:A===void 0?{kind:"default"}:{kind:"env",var:"VISA_DRY_RUN"},hint:"VISA_DRY_RUN=true|1|mock returns deterministic paid-tool fixtures (no card, no upstream). VISA_DRY_RUN=preflight makes a real zero-cost OpenRouter call for LLM tools (image/video still mocked)."}),r.push({key:"client.version",value:tm,formatted:tm,source:{kind:"default"}}),e.includeDev){let y=process.env.VISA_MOCK_KEYCHAIN,T=on();r.push({key:"dev.mockKeychain",value:T,formatted:qe(T),source:Qc("VISA_MOCK_KEYCHAIN",!!y),hint:qa()});let Y=process.env.VISA_MOCK_TOUCHID,X=Nr();r.push({key:"dev.mockTouchid",value:X,formatted:qe(X),source:Qc("VISA_MOCK_TOUCHID",!!Y),hint:qa()});let H=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!H,formatted:qe(!!H),source:Qc("VISA_CLI_DEBUG",!!H)})}return{entries:r,statusError:n}}function Aw(e){switch(e.kind){case"default":return"default";case"env":return`env ${e.var}`;case"settings":return"settings.json";case"server":return"server";case"device":return"device";case"unset":return"unset";case"unknown":return`unknown (${e.reason})`}}function nm(e,t={}){if(e.length===0)return"";let n=Math.max(...e.map(o=>o.key.length)),r=Math.max(...e.map(o=>o.formatted.length)),s=[];for(let o of e){let i=o.key.padEnd(n+2),a=o.formatted.padEnd(r+2);s.push(`${i}${a}(${Aw(o.source)})`),t.verbose&&o.hint&&s.push(` ${"\u21B3".padStart(n)} ${o.hint}`)}return s.join(`
143
143
  `)}function rm(e){return JSON.stringify({config:e.entries.map(t=>({key:t.key,value:t.value,source:t.source,hint:t.hint})),statusError:e.statusError},null,2)}function sm(e){if(e<=0)return null;let t=(e/100).toFixed(2);return{_credits_prompt:{message:`You've got $${t} in free credits \u2014 enough for about ${Math.floor(e/6)} images. Try something now, or save them for later.`,balanceUsd:t,examples:[{tool:"generate_image",cost:"$0.06",what:"an AI image"},{tool:"run_llm",cost:"token-priced",what:"a quick model call"},{tool:"generate_music",cost:"$0.02",what:"a music track"}]}}}Ht();_t();var kn=require("fs"),im=require("os"),el=require("path"),Rw=(0,el.join)((0,im.homedir)(),".visa-mcp"),om=(0,el.join)(Rw,"mcp-session-budget.json");function Pi(){try{(0,kn.existsSync)(om)&&(0,kn.unlinkSync)(om)}catch{}}var nl=require("crypto"),it=R(es()),yr=null,Ke=0,An=0,He=0,En=null,rl=null,sl=null,hr=Promise.resolve();function Iw(e){return Number((0,it.fromCents)(e))}function cm(e){return(0,it.toCents)((0,it.micros)(BigInt(e)))}function am(e){return(0,it.toWire)((0,it.fromCents)(e))}function tl(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Oi(e){return typeof e=="string"&&/^\d+$/.test(e)}var $w=43,Pw=new RegExp(`^[A-Za-z0-9_-]{${$w}}$`);function Ow(e){return typeof e=="string"&&Pw.test(e)}function Mw(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||yr&&e.session_id!==yr||typeof e.nonce!="string"||e.nonce.length===0||!Ow(e.server_signature)||!tl(e.cumulative)||!tl(e.remaining)||!tl(e.delta)||e.cumulative<Ke||He>0&&e.cumulative>He||He>0&&e.remaining>He||e.cumulative_micros!==void 0&&!Oi(e.cumulative_micros)||e.remaining_micros!==void 0&&!Oi(e.remaining_micros)||e.delta_micros!==void 0&&!Oi(e.delta_micros)||e.reserved_micros!==void 0&&!Oi(e.reserved_micros))}function zt(e){yr=e,Ke=0,An=0,He=0,En=null,rl=null,sl=null,hr=Promise.resolve()}function ro(e){He=Math.max(0,Math.floor(e))}function ol(){return yr}function il(e){if(!yr)return null;let t=Ke+An;return He>0&&t>He&&(t=He),{session_budget_id:yr,cumulative_micros:Iw(t),nonce:(0,nl.randomUUID)(),idempotency_key:e||(0,nl.randomUUID)()}}function so(e){if(!e)return null;let t;try{t=Buffer.from(e,"base64").toString("utf-8")}catch{return null}let n;try{n=JSON.parse(t)}catch{return null}if(!n||typeof n!="object")return null;let r=n;return Mw(r)?(Ke=Math.max(Ke,r.cumulative),An=0,En=r,r):null}function lm(){return En}function al(e){let t=cm(e.cumulative_micros);Ke=Math.max(Ke,t),An=0;let n={status:"accepted",session_id:e.session_budget_id,cumulative:Ke,remaining:Math.max(0,He-Ke),delta:0,cumulative_micros:am(Ke),remaining_micros:am(Math.max(0,He-Ke)),delta_micros:"0",nonce:e.nonce};return En=n,n}function oo(e){if(!e||typeof e!="object")return;let t=e.cumulative_micros;if(typeof t!="string"||!/^\d+$/.test(t))return;let n;try{n=BigInt(t)}catch{return}if(n<0n)return;let r=(0,it.toCents)((0,it.micros)(n));if(!Number.isFinite(r)||r<0)return;rl=t;let s=e,o=typeof s.session_id=="string"?s.session_id:yr??"";En?(typeof s.remaining_micros=="string"&&/^\d+$/.test(s.remaining_micros)&&(En.remaining_micros=s.remaining_micros),typeof s.charged_micros=="string"&&/^\d+$/.test(s.charged_micros)&&(En.delta_micros=s.charged_micros)):En={session_id:o,cumulative:r,remaining:0,delta:0,nonce:typeof s.transaction_id=="string"?s.transaction_id:"",remaining_micros:typeof s.remaining_micros=="string"&&/^\d+$/.test(s.remaining_micros)?s.remaining_micros:void 0,delta_micros:typeof s.charged_micros=="string"&&/^\d+$/.test(s.charged_micros)?s.charged_micros:void 0}}function um(e){let t=e.receipt??null;sl={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:cm(e.voucher.cumulative_micros),estimatedCumulativeCents:Mi(),receiptDeltaCents:typeof t?.delta=="number"?t.delta:null,receiptCumulativeCents:typeof t?.cumulative=="number"?t.cumulative:null,receiptRemainingCents:typeof t?.remaining=="number"?t.remaining:null,receiptDeltaMicros:typeof t?.delta_micros=="string"?t.delta_micros:null,receiptCumulativeMicros:typeof t?.cumulative_micros=="string"?t.cumulative_micros:null,receiptRemainingMicros:typeof t?.remaining_micros=="string"?t.remaining_micros:null,recordedAt:new Date().toISOString()}}function dm(){return sl}function fm(){return Ke}function pm(){return rl}function Mi(){let e=Ke+An;return He>0&&e>He&&(e=He),e}function cl(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return hr=hr.then(()=>{An+=t}),hr}function io(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return hr=hr.then(()=>{An=Math.max(0,An-t)}),hr}var Nw=10,Lw=1,de=null,mm=Promise.resolve();function ll(e){let t=mm.catch(()=>{}).then(e);return mm=t.then(()=>{},()=>{}),t}var we=class extends Error{balanceCents;minRequiredCents;constructor(t,n){super(`Prepaid balance is $${(t/100).toFixed(2)}; at least $${(n/100).toFixed(2)} required to open a credit session. Top up via the buy_credits tool first.`),this.name="InsufficientBalanceError"}};async function ul(e,t,n){return ll(()=>gm(e,t,n))}async function gm(e,t,n){if(Pi(),de&&new Date(de.expiresAt).getTime()>Date.now())return ol()!==de.budgetId&&(zt(de.budgetId),ro(de.totalCents)),g.info("mcp-session:active-hit",{budgetId:de.budgetId,tool:n.toolName,remainingEstimatedCents:de.totalCents-Mi()}),{budgetId:de.budgetId,isFresh:!1,totalCents:de.totalCents,requestedCapCents:de.totalCents,appliedCapCents:de.totalCents,clampedReason:null};de&&(de=null,zt(null));let r=await e.getBalance();if(!r.success)throw new Error(`Could not read balance: ${r.error||"unknown error"}`);let s=n.sessionKind??"explicit",o=s==="one_shot"?Lw:Nw,i=Math.max(o,Math.ceil(n.minRequiredCents??o));if(r.balanceCents<i)throw new we(r.balanceCents,i);let a=n.capCentsOverride??Vf(),c=Math.min(a,r.balanceCents),l=c<a?"balance":null,u=await t("session_create",c,"Visa CLI Session",`open credit-model session with $${(c/100).toFixed(2)} cap`,n.userContext),d=await e.createSessionBudget({total_cents:c,session_kind:s,...u?{attestation:u}:{}});if(!d.success||!d.budget){let f=d.error||"unknown error";throw new Error(`Failed to open credit session: ${f}`)}let p={budgetId:d.budget.id,expiresAt:d.budget.expiresAt,totalCents:d.budget.totalCents,createdAt:d.budget.createdAt};return de=p,zt(p.budgetId),ro(p.totalCents),g.info("mcp-session:opened",{budgetId:p.budgetId,capCents:p.totalCents,requestedCapCents:a,clampedReason:l,sessionKind:s,expiresAt:p.expiresAt,tool:n.toolName}),{budgetId:p.budgetId,isFresh:!0,totalCents:p.totalCents,requestedCapCents:a,appliedCapCents:p.totalCents,clampedReason:l}}async function hm(e,t,n){return ll(async()=>{let s=Rn()?await ym(e):null,o=await gm(e,t,n);return{budgetId:o.budgetId,totalCents:o.totalCents,closedPrevious:s,requestedCapCents:o.requestedCapCents,appliedCapCents:o.appliedCapCents,clampedReason:o.clampedReason}})}async function ym(e){let n=Rn()?.budgetId??ol(),r=!1,s,o;if(n)try{let i=await e.closeSession(n);r=!!i?.success,typeof i?.finalCumulativeCents=="number"&&(s=i.finalCumulativeCents),typeof i?.finalCumulativeMicros=="string"&&(o=i.finalCumulativeMicros)}catch(i){g.warn("mcp-session:close-server-failed",{budgetId:n,error:i?.message||String(i)})}return Pi(),de=null,zt(null),{closedServerSide:r,budgetId:n,finalCumulativeCents:s,finalCumulativeMicros:o}}async function Ni(e){return ll(()=>ym(e))}function Rn(){return Pi(),de?new Date(de.expiresAt).getTime()<=Date.now()?(de=null,zt(null),null):{budgetId:de.budgetId,totalCents:de.totalCents,lastReceiptCumulative:fm(),lastReceiptCumulativeMicros:lm()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:pm(),estimatedCumulative:Mi(),lastToolSpend:dm(),expiresAt:de.expiresAt}:null}var bm=R(es()),_m=10000n;function Uw(e){return e<=0n?0:Number((e+_m-1n)/_m)}function vm(e){return Uw((0,bm.fromUsd)(e))}var Li=R(es()),Dw=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;function Ui(e){if(typeof e!="string"||!Dw.test(e))return{ok:!1,error:"amount must be a USD amount with at most two decimal places"};let[t,n=""]=e.split("."),r=BigInt(t)*100n+BigInt(n.padEnd(2,"0"));if(r>BigInt(Number.MAX_SAFE_INTEGER))return{ok:!1,error:"amount is too large"};let s=Number(r);return s<=0?{ok:!1,error:"amount must be greater than $0.00"}:{ok:!0,cents:s,displayUsd:(0,Li.toDisplay)((0,Li.fromCents)(s),{symbol:""})}}var Di="Buying credits requires local biometric attestation from a Touch ID-capable Mac or a Windows Hello-capable PC running the Visa CLI. This device cannot create the required attestation, so no card charge was attempted. Credits are account-level, so you can top up this account from any interactive biometric-capable CLI, then use the balance from this remote server.",wm="Tell the user that buying credits requires a local CLI/MCP process with Touch ID (Mac) or Windows Hello (PC) today. Credits are account-level: suggest topping up the same account from any interactive biometric-capable CLI, then continuing on this remote server. Do not retry buy_credits from this process; it cannot produce the required card-charge attestation.";Ht();var wh=Promise.resolve();function RT(e,t){if(e)try{let n=(0,Sa.fromWire)(e),r=n%10000n===0n?2:6;return(0,Sa.toDisplay)(n,{decimals:r})}catch{}return`$${(t/100).toFixed(2)}`}var Sh=!1,xh=!1,Th=!1;function Ta(e){let t=wh.catch(()=>{}).then(e);return wh=t.then(()=>{},()=>{}),t}async function Nh(e){let t=await xe(()=>ul(U,Ze,{toolName:e.toolId,userContext:e.userContext}));await cl(e.estimatedAmountCents);let n=il(e.idempotencyKey);if(!n)throw await io(e.estimatedAmountCents),new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await UT(),s,o,i=async()=>U.shortcutWithSession(e.toolId,n,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);try{try{({data:s,voucherReceiptHeader:o}=await i())}catch(u){if(u instanceof Bt){let d=Math.min(Math.max(u.retryAfterSecs,0),5)*1e3;g.warn("mcp-session:lock-contended-retrying",{tool:e.toolId,retryAfterSecs:u.retryAfterSecs}),await new Promise(p=>setTimeout(p,d)),{data:s,voucherReceiptHeader:o}=await i()}else throw u}}catch(u){if(await io(e.estimatedAmountCents),u instanceof Hr){if(g.warn("mcp-session:server-invalidated-budget",{code:u.code,budgetId:u.budgetId??t.budgetId,tool:e.toolId}),await Ni(U),process.env.VISA_REQUIRE_EXPLICIT_SESSION==="true")throw new Error(`Your session was closed by another process (${u.code}). Restart MCP or run start_session again.`);return Th||(Th=!0,console.error(`[visa-cli] Your session was closed by another process; reopened automatically as pay-as-you-go.
144
- To require an explicit session approval instead, set VISA_REQUIRE_EXPLICIT_SESSION=true.`)),g.info("mcp-session:falling-back-to-payg",{code:u.code,tool:e.toolId}),Lh(e)}throw u instanceof Bt?(g.warn("mcp-session:lock-contended-give-up",{tool:e.toolId}),new Error("Another paid call is currently in progress on this session. Wait a moment and try again.")):u}let a=so(o)??(n?al(n):null);if(oo(s?.receipt_v2),um({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),lu(s))return xt(s);let c=await cu();if(e.idempotencyKey&&uu(s,c,e.idempotencyKey))return xt(s);let l=c?bo(c):null;return xt(du(s,r,l))}function Xe(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function ba(e){if(e===null||typeof e!="object"){let n=JSON.stringify(e);return n===void 0?String(e):n}return Array.isArray(e)?`[${e.map(ba).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${ba(r)}`).join(",")}}`}function au(e,t,n,r){let s=Se.createHash("sha256").update(`${n}:${ba(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${s}`}function IT(e,t){return`${e}:${t}`}function $T(e){if(e==null)return;let t=String(e);if(t.length!==0)return t.startsWith("ledger_")?t:/^\d+$/.test(t)?`ledger_${t}`:t}function va(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,s=ct(r),o=s!==null?s.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=$T(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),c=i!=null?String(i):a;return{batch_id:e,item_id:IT(e,t),index:t,...c!==void 0?{transaction_id:c}:{},...a!==void 0?{ledger_id:a}:{},...o?{amountMicros:o,amount_micros:o,cost_micros:o}:{}}}async function Lh(e){return xe(()=>OT(e))}async function Uh(e,t,n){if(lu(e))return xt(e);let r=await cu();if(n&&uu(e,r,n))return xt(e);let s=r?bo(r):null;return xt(du(e,t,s))}async function PT(e){let t=e.cap,n=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (call cap $${(t/100).toFixed(2)})`,r=await Ze("shortcut_call",t,e.toolId,n,e.userContext);g.info("parentless-single-call:attempt",{tool:e.toolId,approvedMaxCents:t,attested:!!r});let s=r?.nonce??(await U.getAttestationChallenge()).nonce,{data:o,voucherReceiptHeader:i}=await U.shortcutParentless(e.toolId,{...r?{attestation:r}:{},nonce:s,approved_max_cents:t,idempotency_key:e.idempotencyKey},e.toolParams,e.timeoutMs,e.userContext,e.metaTool);return so(i),oo(o?.receipt_v2),g.info("parentless-single-call:completed",{tool:e.toolId}),Uh(o,e.beforeBalanceMicros,e.idempotencyKey)}async function OT(e){let t=Math.max(1,Math.ceil(e.estimatedAmountCents)),n=await U.getBalance();if(!n.success)throw new Error(`Could not read balance: ${n.error||"unknown error"}`);if(n.balanceCents<t)throw new we(n.balanceCents,t);let r=t,s=bo(n);if(Zp()&&!Sh){let u=e.idempotencyKey??Se.randomUUID();try{return await PT({toolId:e.toolId,toolParams:e.toolParams,estimatedAmountCents:e.estimatedAmountCents,cap:r,beforeBalanceMicros:s,userContext:e.userContext,metaTool:e.metaTool,timeoutMs:e.timeoutMs,idempotencyKey:u})}catch(d){if(d instanceof yt)Sh=!0,g.info("parentless-single-call:falling-back-to-session",{tool:e.toolId,status:d.status,serverErrorCode:d.serverErrorCode});else throw d}}let o=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(r/100).toFixed(2)})`,i=await Ze("session_create",r,"Visa CLI Session",o,e.userContext),a=await U.createSessionBudget({total_cents:r,session_kind:"one_shot",...i?{attestation:i}:{}});if(!a.success||!a.budget)throw new Error(`Failed to open on-demand session: ${a.error||"unknown error"}`);let c=a.budget.id;zt(c),ro(a.budget.totalCents),g.info("on-demand-session:opened",{budgetId:c,capCents:a.budget.totalCents,tool:e.toolId});let l=!1;try{await cl(e.estimatedAmountCents);let u=il(e.idempotencyKey);if(!u)throw await io(e.estimatedAmountCents),new Error(`Internal: mintVoucher returned null after on-demand session-open ${c}`);let{data:d,voucherReceiptHeader:p}=await U.shortcutWithSession(e.toolId,u,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(so(p)||al(u),l=!0,oo(d?.receipt_v2),lu(d))return xt(d);let f=await cu();if(e.idempotencyKey&&uu(d,f,e.idempotencyKey))return xt(d);let m=f?bo(f):null;return xt(du(d,s,m))}catch(u){throw l||await io(e.estimatedAmountCents),u}finally{try{await U.closeSession(c)}catch(u){g.warn("on-demand-session:close-failed",{budgetId:c,error:u?.message||String(u)})}zt(null),g.info("on-demand-session:closed",{budgetId:c,tool:e.toolId})}}async function Fn(e){return Ta(async()=>Rn()?Nh(e):Lh(e))}function Ca(){return Ue()}var U=new Ve(()=>K.getSessionToken());function ct(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function bo(e){return ct(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function MT(e){if(e<0n&&(e=0n),e>=1000000n){let r=(e+5000n)/10000n,s=r/100n,o=r%100n;return`$${s.toString()}.${o.toString().padStart(2,"0")}`}let t=e%1000000n;return t===0n?"$0.00":`$0.${t.toString().padStart(6,"0").replace(/0+$/,"")}`}function NT(e){let t=ct(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=ct(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=ct(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function ya(e,t="INVALID_TOOL_PARAMS",n){return{success:!1,error_code:t,code:t,error:e,message:e,...n??{}}}function LT(e){return{success:!1,error_code:"TOOL_EXECUTION_FAILED",code:"TOOL_EXECUTION_FAILED",error:e.message||"Tool execution failed.",message:e.message||"Tool execution failed.",tool_id:e.toolId,surface:e.surface,merchantName:e.merchantName,amount:e.amount,payment_finalized:!1,charged:!1}}async function UT(){try{let e=await U.getBalance();return e.success?bo(e):null}catch{return null}}async function cu(){try{let e=await U.getBalance();return e.success?e:null}catch{return null}}function lu(e){if(!e||e.success===!1)return!1;let t=ct(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=ct(e.amountMicros??e.amount_micros??e.charged_micros),r=t??n;if(r===null||r<=0n)return!1;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,e.charged_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),!0}function uu(e,t,n){if(!e||e.success===!1||!t||!Array.isArray(t.ledger))return!1;let r=t.ledger.find(a=>a.idempotencyKey===n);if(!r)return!1;let s=ct(r.deltaMicros)??BigInt(r.deltaCents)*10000n,o=s<0n?-s:s;if(o<=0n)return!1;let i=o.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(o)/1e6),!0}function du(e,t,n){if(!e||e.success===!1||t===null||n===null)return e;let r=t-n;if(r<=0n)return e;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),e}var DT="3.3.0",v2=["","","You're ready to go! Try:","","Core:",'\u2022 "Show my account status" \u2192 get_status','\u2022 "List my enrolled cards" \u2192 get_cards','\u2022 "Show my paid tool use history" \u2192 transaction_history','\u2022 "Set my daily top-up limit to $50" \u2192 update_spending_controls','\u2022 "Generate 3 variations in parallel" \u2192 batch',"","Category tools:",'\u2022 "Generate an image of a sunset over Tokyo" \u2192 generate_image','\u2022 "Make a 4-second video of a penguin juggling" \u2192 generate_video','\u2022 "Make a song about coding late at night" \u2192 generate_music','\u2022 "Create a sound effect for a checkout chime" \u2192 generate_audio','\u2022 "Create a 3D asset from this product sketch" \u2192 generate_3d','\u2022 "Upscale this product image" \u2192 upscale_image','\u2022 "Transcribe this meeting recording" \u2192 transcribe_audio','\u2022 "Run a reasoning model on this prompt" \u2192 run_llm',"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
144
+ To require an explicit session approval instead, set VISA_REQUIRE_EXPLICIT_SESSION=true.`)),g.info("mcp-session:falling-back-to-payg",{code:u.code,tool:e.toolId}),Lh(e)}throw u instanceof Bt?(g.warn("mcp-session:lock-contended-give-up",{tool:e.toolId}),new Error("Another paid call is currently in progress on this session. Wait a moment and try again.")):u}let a=so(o)??(n?al(n):null);if(oo(s?.receipt_v2),um({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),lu(s))return xt(s);let c=await cu();if(e.idempotencyKey&&uu(s,c,e.idempotencyKey))return xt(s);let l=c?bo(c):null;return xt(du(s,r,l))}function Xe(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function ba(e){if(e===null||typeof e!="object"){let n=JSON.stringify(e);return n===void 0?String(e):n}return Array.isArray(e)?`[${e.map(ba).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${ba(r)}`).join(",")}}`}function au(e,t,n,r){let s=Se.createHash("sha256").update(`${n}:${ba(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${s}`}function IT(e,t){return`${e}:${t}`}function $T(e){if(e==null)return;let t=String(e);if(t.length!==0)return t.startsWith("ledger_")?t:/^\d+$/.test(t)?`ledger_${t}`:t}function va(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,s=ct(r),o=s!==null?s.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=$T(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),c=i!=null?String(i):a;return{batch_id:e,item_id:IT(e,t),index:t,...c!==void 0?{transaction_id:c}:{},...a!==void 0?{ledger_id:a}:{},...o?{amountMicros:o,amount_micros:o,cost_micros:o}:{}}}async function Lh(e){return xe(()=>OT(e))}async function Uh(e,t,n){if(lu(e))return xt(e);let r=await cu();if(n&&uu(e,r,n))return xt(e);let s=r?bo(r):null;return xt(du(e,t,s))}async function PT(e){let t=e.cap,n=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (call cap $${(t/100).toFixed(2)})`,r=await Ze("shortcut_call",t,e.toolId,n,e.userContext);g.info("parentless-single-call:attempt",{tool:e.toolId,approvedMaxCents:t,attested:!!r});let s=r?.nonce??(await U.getAttestationChallenge()).nonce,{data:o,voucherReceiptHeader:i}=await U.shortcutParentless(e.toolId,{...r?{attestation:r}:{},nonce:s,approved_max_cents:t,idempotency_key:e.idempotencyKey},e.toolParams,e.timeoutMs,e.userContext,e.metaTool);return so(i),oo(o?.receipt_v2),g.info("parentless-single-call:completed",{tool:e.toolId}),Uh(o,e.beforeBalanceMicros,e.idempotencyKey)}async function OT(e){let t=Math.max(1,Math.ceil(e.estimatedAmountCents)),n=await U.getBalance();if(!n.success)throw new Error(`Could not read balance: ${n.error||"unknown error"}`);if(n.balanceCents<t)throw new we(n.balanceCents,t);let r=t,s=bo(n);if(Zp()&&!Sh){let u=e.idempotencyKey??Se.randomUUID();try{return await PT({toolId:e.toolId,toolParams:e.toolParams,estimatedAmountCents:e.estimatedAmountCents,cap:r,beforeBalanceMicros:s,userContext:e.userContext,metaTool:e.metaTool,timeoutMs:e.timeoutMs,idempotencyKey:u})}catch(d){if(d instanceof yt)Sh=!0,g.info("parentless-single-call:falling-back-to-session",{tool:e.toolId,status:d.status,serverErrorCode:d.serverErrorCode});else throw d}}let o=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(r/100).toFixed(2)})`,i=await Ze("session_create",r,"Visa CLI Session",o,e.userContext),a=await U.createSessionBudget({total_cents:r,session_kind:"one_shot",...i?{attestation:i}:{}});if(!a.success||!a.budget)throw new Error(`Failed to open on-demand session: ${a.error||"unknown error"}`);let c=a.budget.id;zt(c),ro(a.budget.totalCents),g.info("on-demand-session:opened",{budgetId:c,capCents:a.budget.totalCents,tool:e.toolId});let l=!1;try{await cl(e.estimatedAmountCents);let u=il(e.idempotencyKey);if(!u)throw await io(e.estimatedAmountCents),new Error(`Internal: mintVoucher returned null after on-demand session-open ${c}`);let{data:d,voucherReceiptHeader:p}=await U.shortcutWithSession(e.toolId,u,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(so(p)||al(u),l=!0,oo(d?.receipt_v2),lu(d))return xt(d);let f=await cu();if(e.idempotencyKey&&uu(d,f,e.idempotencyKey))return xt(d);let m=f?bo(f):null;return xt(du(d,s,m))}catch(u){throw l||await io(e.estimatedAmountCents),u}finally{try{await U.closeSession(c)}catch(u){g.warn("on-demand-session:close-failed",{budgetId:c,error:u?.message||String(u)})}zt(null),g.info("on-demand-session:closed",{budgetId:c,tool:e.toolId})}}async function Fn(e){return Ta(async()=>Rn()?Nh(e):Lh(e))}function Ca(){return Ue()}var U=new Ve(()=>K.getSessionToken());function ct(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function bo(e){return ct(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function MT(e){if(e<0n&&(e=0n),e>=1000000n){let r=(e+5000n)/10000n,s=r/100n,o=r%100n;return`$${s.toString()}.${o.toString().padStart(2,"0")}`}let t=e%1000000n;return t===0n?"$0.00":`$0.${t.toString().padStart(6,"0").replace(/0+$/,"")}`}function NT(e){let t=ct(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=ct(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=ct(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function ya(e,t="INVALID_TOOL_PARAMS",n){return{success:!1,error_code:t,code:t,error:e,message:e,...n??{}}}function LT(e){return{success:!1,error_code:"TOOL_EXECUTION_FAILED",code:"TOOL_EXECUTION_FAILED",error:e.message||"Tool execution failed.",message:e.message||"Tool execution failed.",tool_id:e.toolId,surface:e.surface,merchantName:e.merchantName,amount:e.amount,payment_finalized:!1,charged:!1}}async function UT(){try{let e=await U.getBalance();return e.success?bo(e):null}catch{return null}}async function cu(){try{let e=await U.getBalance();return e.success?e:null}catch{return null}}function lu(e){if(!e||e.success===!1)return!1;let t=ct(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=ct(e.amountMicros??e.amount_micros??e.charged_micros),r=t??n;if(r===null||r<=0n)return!1;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,e.charged_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),!0}function uu(e,t,n){if(!e||e.success===!1||!t||!Array.isArray(t.ledger))return!1;let r=t.ledger.find(a=>a.idempotencyKey===n);if(!r)return!1;let s=ct(r.deltaMicros)??BigInt(r.deltaCents)*10000n,o=s<0n?-s:s;if(o<=0n)return!1;let i=o.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(o)/1e6),!0}function du(e,t,n){if(!e||e.success===!1||t===null||n===null)return e;let r=t-n;if(r<=0n)return e;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),e}var DT="3.3.1-rc.0",v2=["","","You're ready to go! Try:","","Core:",'\u2022 "Show my account status" \u2192 get_status','\u2022 "List my enrolled cards" \u2192 get_cards','\u2022 "Show my paid tool use history" \u2192 transaction_history','\u2022 "Set my daily top-up limit to $50" \u2192 update_spending_controls','\u2022 "Generate 3 variations in parallel" \u2192 batch',"","Category tools:",'\u2022 "Generate an image of a sunset over Tokyo" \u2192 generate_image','\u2022 "Make a 4-second video of a penguin juggling" \u2192 generate_video','\u2022 "Make a song about coding late at night" \u2192 generate_music','\u2022 "Create a sound effect for a checkout chime" \u2192 generate_audio','\u2022 "Create a 3D asset from this product sketch" \u2192 generate_3d','\u2022 "Upscale this product image" \u2192 upscale_image','\u2022 "Transcribe this meeting recording" \u2192 transcribe_audio','\u2022 "Run a reasoning model on this prompt" \u2192 run_llm',"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
145
145
  `);function ut(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=Ms(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(Ff())return{opened:!1,url:t,blockedReason:"suppressed"};let n=rc();if(n.headless)return g.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let r=wd(t,Ca());if(!r)return g.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let s=xd(r);return s?((0,Mh.execFile)(s.cmd,s.args,o=>{o&&g.warn(`Browser open failed: ${o.message}. URL: ${r}`)}),{opened:!0,url:r}):(g.info(`No browser command for platform "${wo.platform()}". URL: ${r}`),{opened:!1,url:r,blockedReason:"unsupported_platform"})}async function xe(e){return gr(U,e,Gh)}var Dh="get_cards",jh="set_default_card";function jT(e,t=60){return`The processor returned a transient decline (code ${e??"unknown"}). This is not a permanent failure \u2014 it usually clears within ~${t} seconds and is most often triggered by rapid successive charges on the same card. Tell the user the call was temporarily declined and that you will retry shortly, then wait at least ${t} seconds before retrying the SAME call exactly once. Do not retry more than once. Do not assume the user has run out of funds. IMPORTANT: If the retry also fails, do NOT retry again \u2014 instead tell the user their default card may be temporarily locked by the processor and suggest switching to a different card. They can run '${Dh}' to see enrolled cards and '${jh}' to switch, then retry the original request.`}function BT(e,t){return`The processor returned a non-retryable decline (code ${e??"unknown"}). Stop the current task and tell the user their card was declined for ${t||"the merchant"}. Suggest they check their card status or available balance. If they want to try a different default card, they can run '${Dh}' to see enrolled cards and '${jh}' to switch. Do not retry automatically.`}function dt(e,t){let n=e.retryable?jT(e.code,e.retryAfter):BT(e.code,t.merchantName);return{success:!1,declined:!0,retryable:e.retryable,code:e.code,reason:e.reason,payment_error_class:e.paymentErrorClass,correlation_id:e.correlationId,transactionId:e.transactionId,retryAfter:e.retryAfter,merchantName:t.merchantName,amount:t.amount,message:e.message,agent_guidance:n}}function FT(e){return{success:!1,error:e.message,error_code:e.code,transactionId:e.transactionId,reconciliation_required:e.reconciliationRequired,retryable:e.retryable,agent_guidance:"The top-up charge outcome is ambiguous. Tell the user not to retry with a new idempotency key or start another top-up. They should check transaction_history in a few minutes or contact support with the transactionId."}}var _s=null,HT=3e4;function Bh(){_s=null}var Bn=class extends Error{constructor(n){super(`${wa()} attestation is required for this action, but it is not available in this MCP process. `+fu());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function ka(e,t){return{success:!1,error:e.code,message:e.message,action:t,agent_guidance:`Biometric attestation is required for ${t}, but this MCP process cannot create a local attestation. `+fu()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function VT(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:Di,agent_guidance:wm}}function wa(){return process.platform==="darwin"?"Touch ID":"local biometric"}function fu(){return process.platform==="darwin"?"Run the action from an interactive terminal with Touch ID access, or use reset with confirm:true to clear stale server biometric state through GitHub re-authentication.":"This platform cannot create Visa CLI Touch ID attestations. Use reset with confirm:true to clear stale server biometric state through GitHub re-authentication."}async function qT(e){let t=Date.now();if(_s&&_s.expiresAt>t)return{required:_s.required,hasRegisteredKey:_s.hasRegisteredKey};try{let n=await U.getStatus(e),r=n.attestationRequired!==!1,s=Tt(n);return _s={required:r,hasRegisteredKey:s,expiresAt:t+HT},{required:r,hasRegisteredKey:s}}catch{return{required:!0,hasRegisteredKey:!0}}}async function Ze(e,t,n,r,s,o){if(!o?.forceRequired){let i=await qT(s);if(!i.required){g.info("attestation:skipped-by-server-policy",{context:e});return}if(!i.hasRegisteredKey){g.info("attestation:skipped-no-registered-key",{context:e});return}}if(!ue())throw g.warn("attestation:unavailable",{context:e}),new Bn(e);g.info("attestation:attempt",{context:e,amount:t,merchant:n});try{let{nonce:i}=await U.getAttestationChallenge(),a=Buffer.from(JSON.stringify({nonce:i,amount:t,merchant:n,context:e})).toString("base64");g.info("touchid:prompt",{context:e,amount:t,merchant:n});let c=await Tn(a,r);return g.info("attestation:success",{context:e,amount:t,merchant:n}),{signature:c,nonce:i,amount:t,merchant:n}}catch(i){throw g.error("attestation:failure",{context:e,amount:t,merchant:n,error:i.message}),i}}var Ch="[dry-run] https://placeholder.visa-cli.dev/image.png",KT=new Set(["generate_image_card","generate_image_fast_card","generate_image_schnell_card","generate_image_recraft_card","generate_image_ideogram_card","edit_image_seed_card","fal-flux-pro-ultra","fal-flux-pro","fal-flux-dev","fal-flux-schnell","fal-ideogram-v2","fal-ideogram-v2-turbo","fal-recraft-v3","fal-fast-sdxl"]),GT=new Set(["generate_video_tempo_card","generate_video_kling_card","generate_video_wan_card","generate_video_minimax_card","fal-kling-video","fal-wan-video","fal-kling-i2v","fal-minimax-video"]);function WT(e,t){return t==="run_llm"||e.startsWith("or-")?"llm":t==="generate_image"||KT.has(e)?"image":t==="generate_video"||GT.has(e)?"video":YT(e)?"media":null}function YT(e){let t=Qr(e);return t?!gu(t):!1}function zT(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function JT(e){return e==="llm"?"OpenRouter":"fal.ai"}function bs(e,t,n,r){let s={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:JT(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${zT(n)}`;return{...s,content:i,data:{content:i,model:t,dry_run:!0}}}return{...s,urls:[Ch],data:{[e==="video"?"videoUrl":e==="image"?"imageUrl":"url"]:Ch,metadata:{dry_run:!0}}}}async function su(e){let t=e.mode??"mock",n=t==="preflight"?"/v1/telemetry/preflight":"/v1/telemetry/dry-run",r=t==="preflight"?"preflight":null;try{await U.emitTelemetry([{id:Se.randomUUID(),timestamp:new Date().toISOString(),tool_name:e.toolName,user_prompt:e.userContext??"",tool_params:JSON.stringify(e.toolParams),result_success:!0,result_error:null,result_json:JSON.stringify(e.result),payment_rail:r,payment_amount:0,payment_currency:"USD",merchant_name:e.result.merchantName,transaction_id:e.result.transactionId,tx_hash:null,protocol:null,http_status:200,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",event_kind:"mcp_tool",endpoint:n,resolved_model:e.resolvedModel,session_budget_id:null}])}catch(s){g.warn("dry_run:telemetry_failed",{tool:e.toolName,error:s?.message||String(s),mode:t})}}var XT="https://openrouter.ai/api/v1/chat/completions",ZT="openrouter/free",QT=50,eC=15e3;function tC(e){let t=[e.prompt,e.user_prompt,e.input,e.text];for(let n of t)if(typeof n=="string"&&n.trim().length>0)return n;return"preflight"}async function nC(e,t,n){let r=process.env.OPENROUTER_API_KEY;if(!r)return g.warn("preflight:no_openrouter_key_falling_back_to_mock",{tool:e}),{result:bs("llm",e,t,n),degraded:!0,resolvedModel:null};let s=tC(t),o;try{o=await ht(XT,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json","HTTP-Referer":"https://visacli.sh/preflight","X-Title":"Visa CLI Preflight"},body:JSON.stringify({model:ZT,messages:[{role:"user",content:s}],max_tokens:QT}),timeoutMs:eC})}catch(u){return g.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:bs("llm",e,t,n),degraded:!0,resolvedModel:null}}if(!o.ok){let u=await o.text().catch(()=>"");return g.warn("preflight:openrouter_http_error_falling_back_to_mock",{tool:e,status:o.status,bodyExcerpt:u.slice(0,200)}),{result:bs("llm",e,t,n),degraded:!0,resolvedModel:null}}let i;try{i=await o.json()}catch(u){return g.warn("preflight:openrouter_invalid_json_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:bs("llm",e,t,n),degraded:!0,resolvedModel:null}}let a=typeof i?.choices?.[0]?.message?.content=="string"?i.choices[0].message.content:"",c=typeof i?.model=="string"?i.model:null;return{result:{success:!0,transactionId:`preflight:${n??e}`,amount:0,rail:"preflight",merchantName:"OpenRouter",dry_run:!0,preflight:!0,metadata:{dry_run:!0,preflight:!0,model_used:c},content:a,data:{content:a,model:c??e,dry_run:!0,preflight:!0}},degraded:!1,resolvedModel:c}}async function So(e,t,n,r){let s=Zc();if(!s)return null;let o=WT(e,r);if(!o)return null;let i=Date.now();if(s==="mock"){let l=bs(o,e,t,r);return await su({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:l,userContext:n,startedAt:i,mode:"mock"}),g.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:o,mode:s}),l}if(o!=="llm"){g.warn("preflight:not_supported_for_kind_falling_back_to_mock",{tool:e,kind:o});let l=bs(o,e,t,r);return await su({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:l,userContext:n,startedAt:i,mode:"preflight"}),l}let{result:a,resolvedModel:c}=await nC(e,t,r);return await su({toolName:r??e,resolvedModel:c??(r&&r!==e?e:null),toolParams:t,result:a,userContext:n,startedAt:i,mode:"preflight"}),g.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:o,mode:s}),a}async function rn(e,t,n){let r=await U.paymentPreview({tool:e,url:t},n);if(!r||!r.merchantName||r.amount===void 0||r.amount===null||r.amount<0)throw new Error("Could not determine payment amount and merchant. Try again.");if(!Number.isFinite(r.amount)||r.amount<0||r.amount>999999)throw new Error(`Invalid payment amount: ${r.amount}. Payment rejected for safety.`);return r}function sn(e){return vm(e.amount)}function rC(e,t,n){return n.has(e.resolvedTool)?0:Math.max(1,sn(t[e.resolvedTool]))}function sC(){return xa.join(wo.homedir(),".visa-mcp","allium-results")}var w2=16*1024,S2=50*1024*1024;function oC(){let e=sC();try{if(!lt.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=lt.readdirSync(e),n=0,r=0;for(let s of t)try{let o=lt.statSync(xa.join(e,s));o.isFile()&&(n+=o.size,r++)}catch{}return{file_count:r,size_bytes:n,path:e}}catch(t){return g.warn("allium:disk_usage_error",{error:t.message}),{file_count:0,size_bytes:0,path:e}}}var kh=3600*1e3,ou=0;function iC(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function xo(e){if(!Hf()&&!(Date.now()<ou))try{if(!await K.getSessionToken())return;await U.feedSubmit({prompt:e.prompt,tool:e.tool,media_url:e.mediaUrl,media_type:e.mediaType,cost:e.cost,transaction_id:e.transactionId,auto:!0,...e.userContext&&{user_context:e.userContext}}),g.info("feed:submitted",{tool:e.tool,mediaType:e.mediaType,transactionId:e.transactionId})}catch(t){if(iC(t)){let n=ou===0;ou=Date.now()+kh,n&&g.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:kh});return}g.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function aC(e,t){let n=(e.state||"").trim().toUpperCase(),r=(e.county||"").trim(),s=(e.start_date||"").trim(),o=(e.end_date||s).trim();if(!/^[A-Z]{2}$/.test(n))throw new Error('state must be a 2-letter US state code (e.g. "VA").');if(!r)throw new Error("county is required.");if(!/^\d{4}-\d{2}$/.test(s))throw new Error('start_date must be YYYY-MM (e.g. "2025-08").');if(o&&!/^\d{4}-\d{2}$/.test(o))throw new Error("end_date must be YYYY-MM.");let i="Visa SMI",a=.1,c=`Pay $0.10 to ${i} for SMI data (${n} / ${r})`;g.info("payment:attempt",{tool:"get_visa_smi",amount:a,merchant:i});try{return await xe(async()=>{let l=await Ze("get_visa_smi",a,i,c),u=await U.getVisaSmi({state:n,county:r,start_date:s,end_date:o,attestation:l,idempotencyKey:Se.randomUUID()},t);return u.success?g.info("payment:success",{tool:"get_visa_smi",merchant:i,charged_cents:u.charged_cents}):g.warn("payment:declined",{tool:"get_visa_smi",merchant:i,message:u.error}),u})}catch(l){if(l instanceof ge)return g.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:l.code,retryable:l.retryable}),dt(l,{amount:a,merchantName:i,description:"Visa SMI data"});throw g.error("payment:failure",{tool:"get_visa_smi",merchant:i,error:l.message}),l}}async function cC(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await So("generate_image_card",e,t);if(n)return n;let r=await rn("generate_image_card",void 0,t),s=Se.randomUUID();g.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await xe(async()=>{let o;try{o=await Fn({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:sn(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof we)return Xe(i);throw i}return g.info("payment:success",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>ut(i)),xo({prompt:e.prompt,tool:"generate_image_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):g.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof ge)return g.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),dt(o,r);throw g.error("payment:failure",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,error:o.message}),o}}async function lC(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await So("generate_image_fast_card",e,t);if(n)return n;let r=await rn("generate_image_fast_card",void 0,t),s=Se.randomUUID();g.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await xe(async()=>{let o;try{o=await Fn({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:sn(r),userContext:t,timeoutMs:6e4,idempotencyKey:s})}catch(i){if(i instanceof we)return Xe(i);throw i}return g.info("payment:success",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>ut(i)),xo({prompt:e.prompt,tool:"generate_image_fast_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):g.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof ge)return g.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),dt(o,r);throw g.error("payment:failure",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,error:o.message}),o}}async function uC(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await So("generate_video_tempo_card",e,t);if(n)return n;let r=await rn("generate_video_tempo_card",void 0,t),s=Se.randomUUID();g.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await xe(async()=>{let o;try{o=await Fn({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:sn(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof we)return Xe(i);throw i}return g.info("payment:success",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>ut(i)),xo({prompt:e.prompt,tool:"generate_video_tempo_card",mediaUrl:o.urls[0],mediaType:"video",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):g.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof ge)return g.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),dt(o,r);throw g.error("payment:failure",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,error:o.message}),o}}async function dC(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await rn("generate_music_tempo_card",void 0,t),r=Se.randomUUID();g.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await xe(async()=>{let s;try{s=await Fn({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:sn(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(o){if(o instanceof we)return Xe(o);throw o}return g.info("payment:success",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),s.urls?.length&&s.status!=="processing"?(s.urls.forEach(o=>ut(o)),xo({prompt:e.prompt,tool:"generate_music_tempo_card",mediaUrl:s.urls[0],mediaType:"audio",cost:s.amount??n.amount,transactionId:s.transactionId,userContext:t})):s.urls?.length&&s.status==="processing"?(s._preliminary_urls=s.urls,delete s.urls,g.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):g.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof ge)return g.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),dt(s,n);throw g.error("payment:failure",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,error:s.message}),s}}async function fC(e,t){let n=await rn("check_music_status_tempo_card",void 0,t),r=Se.randomUUID();g.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await xe(async()=>{let s;try{s=await Fn({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:sn(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof we)return Xe(o);throw o}return g.info("payment:success",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),s.urls?.length&&s.urls.forEach(o=>ut(o)),s})}catch(s){if(s instanceof ge)return g.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),dt(s,n);throw g.error("payment:failure",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,error:s.message}),s}}async function pC(e,t){if(!e.chain||!e.chain.trim())throw new Error('A chain is required (e.g., "ethereum", "solana").');if(!e.token_address||!e.token_address.trim())throw new Error("A token address is required. Provide the contract address for the token.");let n=await rn("query_onchain_prices",void 0,t),r=Se.randomUUID();g.info("payment:attempt",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName});try{return await xe(async()=>{let s;try{s=await Fn({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:sn(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof we)return Xe(o);throw o}if(g.info("payment:success",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,mode:"session"}),Array.isArray(s?.data))s.data=s.data.map(o=>{if("mint"in o&&!("address"in o)){let{mint:i,...a}=o;return{address:i,...a}}return o});else if(s&&"mint"in s&&!("address"in s)){let{mint:o,...i}=s;return{address:o,...i}}return s})}catch(s){if(s instanceof ge)return g.warn("payment:declined",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),dt(s,n);throw g.error("payment:failure",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,error:s.message}),s}}var mC=["generate_music_tempo_card"],ys=10,Eh=5,Ah=new Map;function Rh(e){let t=Ah.get(e);if(t!==void 0)return t;let r=Qr(e)?.isAsync===!0||mC.includes(e);return Ah.set(e,r),r}var gC=36e4,hC=18e4,yC=15e3,_C=12e4,bC=2e3;function iu(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}function vC(e,t){return Se.createHash("sha256").update(`${e}:${ba(t)}`).digest("hex")}function wC(e){let{results:t,batchId:n,index:r,item:s,itemResult:o,preview:i,isFree:a,catalogName:c}=e;a&&o&&typeof o=="object"&&!Array.isArray(o)&&o.merchantName==null&&(o.merchantName=c??s.resolvedTool),t.push({success:o?.success!==!1,tool:s.resolvedTool,...o,...va(n,r,o)});let l=0,u=0n;if(o?.success!==!1){let d=ct(o?.amountMicros??o?.amount_micros),p=typeof o?.amount=="number"?o.amount:i?.amount??0;d!==null&&d>0n?u+=d:u+=BigInt(Math.round(p*1e6)),l+=p}return o?.urls&&o.urls.forEach(d=>ut(d)),{deltaCharged:l,deltaMicros:u}}function SC(e){let{results:t,resolvedItems:n,uniqueTools:r,isHomogeneous:s,primaryTool:o,merchantNames:i,totalAmount:a,totalCharged:c,totalChargedMicros:l,batchId:u,mode:d}=e,p=t.filter(C=>C?.success===!1).length,f=t.length-p,m=t.flatMap(C=>Array.isArray(C?.urls)?C.urls:[]),h=l>0n?Number(l)/1e6:Math.round((c+Number.EPSILON)*100)/100,w=f===0?"failure":p===0?"success":"partial";return g.info("payment:success",{tool:"batch",batchTool:o,count:n.length,totalAmount:a,totalCharged:h,merchant:i,successCount:f,failedCount:p,outcome:w,mode:d,batchId:u}),{success:f>0,outcome:w,batch_id:u,tool:s?r[0]:o,count:n.length,successCount:f,failedCount:p,totalCharged:h,...l>0n?{totalChargedMicros:l.toString(),amountMicros:l.toString(),amount_micros:l.toString()}:{},merchantName:i,results:t,...m.length?{urls:m}:{}}}async function xC(e){let{resolvedItems:t,previews:n,freeTools:r,catalogEntries:s,itemCeilingCents:o,batchCeilingCents:i,uniqueTools:a,isHomogeneous:c,primaryTool:l,merchantNames:u,totalAmount:d,timeoutMs:p,batchId:f,userContext:m}=e,h=i,w=await U.getBalance();if(!w.success)throw new Error(`Could not read balance: ${w.error||"unknown error"}`);if(w.balanceCents<h)throw new we(w.balanceCents,h);let C=`batch-${f}`,b=`spend up to $${(h/100).toFixed(2)} across a batch of ${t.length}`,{batchParentId:v}=await xe(async()=>{let y=await Ze("batch_open",h,C,b,m,{forceRequired:!0}),T=y?.nonce??(await U.getAttestationChallenge()).nonce;g.info("parentless-batch:open-attempt",{batchTool:l,count:t.length,approvedTotalCents:h,attested:!!y});let{batch_parent_id:Y}=await U.batchOpen({...y?{attestation:y}:{},nonce:T,approved_total_cents:h,batch_id:f});return{batchParentId:Y}});g.info("parentless-batch:opened",{batchTool:l,count:t.length,batchParentId:v});let S=[],A=0,I=0n;try{for(let y=0;y<t.length;y+=1){let T=t[y],Y=n[T.resolvedTool],X=r.has(T.resolvedTool);try{let H;if(X)H=await U.shortcut(T.resolvedTool,T.params,p,m,"batch");else{let{data:J,voucherReceiptHeader:Cs}=await U.shortcutParentlessBatchItem(T.resolvedTool,{batch_parent_id:v,batch_id:f,batch_index:y,batch_request_hash:vC(T.resolvedTool,T.params),item_ceiling_cents:o[y],idempotency_key:au(f,y,T.resolvedTool,T.params)},T.params,p,m,"batch");so(Cs),oo(J?.receipt_v2),H=await Uh(J,null,au(f,y,T.resolvedTool,T.params))}let{deltaCharged:_e,deltaMicros:re}=wC({results:S,batchId:f,index:y,item:T,itemResult:H,preview:Y,isFree:X,catalogName:s[T.resolvedTool]?.name});A+=_e,I+=re}catch(H){if(H instanceof we&&S.length===0)return Xe(H);g.warn("payment:batch-item-failed",{tool:T.resolvedTool,index:y,error:H?.message||String(H)}),S.push({success:!1,tool:T.resolvedTool,...va(f,y),error:H?.message||String(H)})}}return SC({results:S,resolvedItems:t,uniqueTools:a,isHomogeneous:c,primaryTool:l,merchantNames:u,totalAmount:d,totalCharged:A,totalChargedMicros:I,batchId:f,mode:"parentless"})}catch(y){if(y instanceof ge)return g.warn("payment:declined",{tool:"batch",batchTool:l,count:t.length,totalAmount:d,merchant:u,code:y.code,retryable:y.retryable}),dt(y,{amount:d,merchantName:u});throw g.error("payment:failure",{tool:"batch",batchTool:l,count:t.length,totalAmount:d,merchant:u,error:y.message}),y}}async function TC(e,t){let n;if(Array.isArray(e.requests)&&e.requests.length>ys)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${ys} items. Please split into smaller batches.`};if(e.requests?.some(y=>y.tool||y.tool_id)&&e.requests)n=e.requests.map(y=>{let T=y.tool||y.tool_id||e.tool;if(!T)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let Y=Cn(T,y.tier||e.tier,y.prompt??t),{tool:X,tool_id:H,tier:_e,params:re,...J}=y,Cs=re&&typeof re=="object"?{...re,...J}:J;return{resolvedTool:Y,params:Cs}});else if(e.tool){let y=Cn(e.tool,e.tier,e.params?.prompt??t);if(e.count!==void 0){if(!Number.isSafeInteger(e.count)||e.count<1)return iu("BATCH_INVALID_COUNT","Batch count must be a positive integer.");if(e.count>ys)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${ys} items. Please split into smaller batches.`}}n=(e.requests||(e.count!==void 0&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(Y=>({resolvedTool:y,params:Y}))}else return iu("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return iu("BATCH_EMPTY","Batch requires at least one item.");if(n.length>ys)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${ys} items. Please split into smaller batches.`};if([...new Set(n.map(y=>y.resolvedTool))].some(Rh)&&n.length>Eh)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${Eh} items. Please use multiple batches for more.`};let i=[...new Set(n.map(y=>y.resolvedTool))],a=i.length===1,c={};for(let y of i)c[y]=await Wh(y);let l=new Set(i.filter(y=>c[y]&&gu(c[y]))),u={};for(let y of i)l.has(y)||(u[y]=await rn(y,void 0,t));let d=0;for(let y of n)d+=u[y.resolvedTool]?.amount??0;let p=n.map(y=>rC(y,u,l)),f=p.reduce((y,T)=>y+T,0),m=[...new Set([...Object.values(u).map(y=>y.merchantName),...i.filter(y=>l.has(y)).map(y=>c[y]?.name??y)])].join(", "),h=a?i[0]:"mixed";g.info("payment:attempt",{tool:"batch",batchTool:h,count:n.length,totalAmount:d,merchant:m,heterogeneous:!a});let w=n.some(y=>Rh(y.resolvedTool)),C=n.some(y=>y.resolvedTool.startsWith("or-")||y.resolvedTool==="run_llm"||y.resolvedTool==="execute_tool"),b=w?gC:C?hC+n.length*yC:_C+n.length*bC,v=Se.randomUUID(),S=[],A=0,I=0n;return Ta(async()=>{let y=!Rn();if(Qp()&&!xh&&y&&f>0)try{return await xC({resolvedItems:n,previews:u,freeTools:l,catalogEntries:c,itemCeilingCents:p,batchCeilingCents:f,uniqueTools:i,isHomogeneous:a,primaryTool:h,merchantNames:m,totalAmount:d,timeoutMs:b,batchId:v,userContext:t})}catch(T){if(T instanceof yt)xh=!0,g.info("parentless-batch:falling-back-to-session",{batchTool:h,count:n.length,status:T.status,serverErrorCode:T.serverErrorCode});else{if(T instanceof we)return Xe(T);throw T}}if(y&&f>0)try{let T=f;await xe(()=>ul(U,Ze,{toolName:"batch",userContext:t,sessionKind:"one_shot",minRequiredCents:T,capCentsOverride:T}))}catch(T){return T instanceof we?Xe(T):(g.warn("payment:batch-prewarm-failed",{batchTool:h,count:n.length,error:T?.message||String(T)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:T?.message||"Failed to authenticate batch session",tool:h,count:n.length,failedCount:n.length,results:[]})}try{for(let re=0;re<n.length;re+=1){let J=n[re],Cs=u[J.resolvedTool];try{let ce=l.has(J.resolvedTool)?await U.shortcut(J.resolvedTool,J.params,b,t,"batch"):await Nh({toolId:J.resolvedTool,toolParams:J.params,estimatedAmountCents:p[re],userContext:t,metaTool:"batch",timeoutMs:b,idempotencyKey:au(v,re,J.resolvedTool,J.params)});if(l.has(J.resolvedTool)&&ce&&typeof ce=="object"&&!Array.isArray(ce)&&ce.merchantName==null&&(ce.merchantName=c[J.resolvedTool]?.name??J.resolvedTool),S.push({success:ce?.success!==!1,tool:J.resolvedTool,...ce,...va(v,re,ce)}),ce?.success!==!1){let ks=ct(ce?.amountMicros??ce?.amount_micros),zu=typeof ce?.amount=="number"?ce.amount:Cs?.amount??0;ks!==null&&ks>0n?I+=ks:I+=BigInt(Math.round(zu*1e6)),A+=zu}ce?.urls&&ce.urls.forEach(ks=>ut(ks))}catch(ce){if(ce instanceof we&&S.length===0)return Xe(ce);g.warn("payment:batch-item-failed",{tool:J.resolvedTool,index:re,error:ce?.message||String(ce)}),S.push({success:!1,tool:J.resolvedTool,...va(v,re),error:ce?.message||String(ce)})}}let T=S.filter(re=>re?.success===!1).length,Y=S.length-T,X=S.flatMap(re=>Array.isArray(re?.urls)?re.urls:[]),H=I>0n?Number(I)/1e6:Math.round((A+Number.EPSILON)*100)/100,_e=Y===0?"failure":T===0?"success":"partial";return g.info("payment:success",{tool:"batch",batchTool:h,count:n.length,totalAmount:d,totalCharged:H,merchant:m,successCount:Y,failedCount:T,outcome:_e,mode:"session",batchId:v}),{success:Y>0,outcome:_e,batch_id:v,tool:a?i[0]:h,count:n.length,successCount:Y,failedCount:T,totalCharged:H,...I>0n?{totalChargedMicros:I.toString(),amountMicros:I.toString(),amount_micros:I.toString()}:{},merchantName:m,results:S,...X.length?{urls:X}:{}}}catch(T){if(T instanceof ge)return g.warn("payment:declined",{tool:"batch",batchTool:h,count:n.length,totalAmount:d,merchant:m,code:T.code,retryable:T.retryable}),dt(T,{amount:d,merchantName:m});throw g.error("payment:failure",{tool:"batch",batchTool:h,count:n.length,totalAmount:d,merchant:m,error:T.message}),T}finally{if(y){let T=await Ni(U);g.info("batch-session:closed",{budgetId:T.budgetId,closedServerSide:T.closedServerSide})}}})}function CC(){let e=!1,t;try{let r=xa.join(wo.homedir(),".claude","settings.json");if(lt.existsSync(r)){let s=JSON.parse(lt.readFileSync(r,"utf-8")),o=typeof s.statusLine=="object"?s.statusLine.command:"";e=mn(o)}}catch{}let n=Xo();return n||(t="visa-cli config hud enable"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function kC(e){let[t,n]=await Promise.all([U.getStatus(e),U.getBalance().catch(o=>(g.warn("get_status:balance_fetch_failed",{error:o?.message||String(o)}),null))]);typeof t?.dailyRemaining=="number"&&(t.dailyRemaining=Math.round(t.dailyRemaining*100)/100);let r=oC();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=CC(),!t.hud.statusLine&&!t.hud.shellHud&&(t._hud_nudge="The user has no HUD surfaces enabled. Mention once, naturally, that they can enable a live spend dashboard with `visa-cli config hud enable` \u2014 it shows balance, active tools, and spend on every prompt."),t.version=DT,Array.isArray(t.cards)&&(t.cards=t.cards.map(o=>({...o,displayName:pu(o)})),t.cardIdGuidance="cardId values are opaque tool parameters only; refer to cards by brand and last four digits."),n&&n.success&&(t.balanceCents=n.balanceCents,t.balanceMicros=n.balanceMicros,t.amountUsd=n.amountUsd);let s=Rn();if(t.sessionMode=!!s,s){let o=Math.max(0,s.totalCents-s.estimatedCumulative);t.activeSession={budgetId:s.budgetId,capCents:s.totalCents,capUsd:s.totalCents/100,lastReceiptCumulativeCents:s.lastReceiptCumulative,estimatedCumulativeCents:s.estimatedCumulative,spentCents:s.estimatedCumulative,spentUsd:s.estimatedCumulative/100,estimatedRemainingCents:o,estimatedRemainingUsd:o/100,...s.lastToolSpend?{lastToolSpend:{toolName:s.lastToolSpend.toolName,resolvedToolId:s.lastToolSpend.resolvedToolId,estimatedAmountCents:s.lastToolSpend.estimatedAmountCents,estimatedAmountUsd:s.lastToolSpend.estimatedAmountCents/100,voucherCumulativeCents:s.lastToolSpend.voucherCumulativeCents,estimatedCumulativeCents:s.lastToolSpend.estimatedCumulativeCents,receiptDeltaCents:s.lastToolSpend.receiptDeltaCents,receiptCumulativeCents:s.lastToolSpend.receiptCumulativeCents,receiptRemainingCents:s.lastToolSpend.receiptRemainingCents,recordedAt:s.lastToolSpend.recordedAt}}:{},expiresAt:s.expiresAt}}return t}function pu(e){let t=typeof e.brand=="string"&&e.brand.trim().length>0?e.brand.trim():"card",n=t.charAt(0).toUpperCase()+t.slice(1).toLowerCase(),r=typeof e.last4=="string"&&e.last4.trim().length>0?e.last4.trim():"unknown",s=e.isDefault===!0?" (default)":"";return`${n} ending in ${r}${s}`}async function Fh(e,t){try{let r=((await U.getStatus(t)).cards||[]).find(s=>s?.id===e);if(r)return pu(r)}catch(n){g.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function EC(e){let n=(await U.getStatus(e)).cards||[];return n.length===0?{cards:[],message:"No cards enrolled. Use the add_card tool to add a payment card."}:n.some(s=>!Number.isInteger(s?.id)||s.id<=0)?{success:!1,cards:[],message:"Card action handles are unavailable right now, so remove_card and set_default_card are temporarily disabled."}:{cards:n.map(s=>({...s,displayName:pu(s)})),message:"Use cardId only as an opaque tool parameter. When speaking to the user, refer to cards by brand and last four digits, not by card id."}}async function AC(e,t){return await U.getTransactions({limit:e.limit,offset:e.offset},t)}async function RC(e,t){return await U.feedback(e.message,e.transaction_id,t)}async function IC(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Ir("MISSING_CONFIRMATION","Please confirm by setting confirm: true to charge your enrolled card for credits.");if(!e.amount||!Number.isFinite(e.amount)||e.amount<=0)return{success:!1,error:"amount must be a positive number in USD (e.g. 5.00)"};let n=Ui(String(e.amount));if(n.ok===!1)return{success:!1,error:n.error};let r=n.cents,s=r/100,o=Se.randomUUID();g.info("buy_credits:attempt",{amountCents:r});try{return await xe(async()=>{let i=await Ze("balance-topup",s,"Visa CLI Balance",`top up balance with $${n.displayUsd}`,t,{forceRequired:!0}),a=await U.topupBalance({amount_cents:r,idempotency_key:o,attestation:i});if(a.success){g.info("buy_credits:success",{amountCents:r,balanceCents:a.balanceCents,balanceMicros:a.balanceMicros});let c=RT(a.balanceMicros,a.balanceCents??0),l=(r/100).toFixed(2);return{...a,amount:r/100,amountMicros:String(r*1e4),merchantName:"Visa CLI Balance",message:`Added $${l} \u2014 balance is now ${c}`}}return g.warn("buy_credits:failed",{amountCents:r,error:a.error}),a})}catch(i){if(i instanceof Bn)return VT();if(i instanceof tt)return g.warn("buy_credits:ambiguous",{amountCents:r,code:i.code,transactionId:i.transactionId}),FT(i);throw g.error("buy_credits:failure",{amountCents:r,error:i.message}),i}}function Ir(e,t){return{success:!1,error:t,code:e,message:t}}async function $C(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Ir("MISSING_CONFIRMATION","Please confirm by setting confirm: true to update spending controls.");if(e.maxTransactionAmount!==void 0&&(typeof e.maxTransactionAmount!="number"||!Number.isFinite(e.maxTransactionAmount)||e.maxTransactionAmount<.01))return Ir("INVALID_VALUE","maxTransactionAmount must be at least $0.01");if(e.dailyLimit!==void 0&&(typeof e.dailyLimit!="number"||!Number.isFinite(e.dailyLimit)||e.dailyLimit<1))return Ir("INVALID_VALUE","dailyLimit must be at least $1");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return Ir("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");g.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await xe(async()=>{let n=await Ze("spending-controls",0,"","update spending controls"),r=await U.updateSpendingControls({maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit,confirm:!0,attestation:n},t);return g.info("spending_controls:success",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit}),r})}catch(n){if(g.error("spending_controls:failure",{error:n.message}),n instanceof Bn)return ka(n,"update_spending_controls");if(String(n?.message||n).includes("Attestation required"))return Ir("ATTESTATION_REQUIRED","Changing spending controls requires local attestation, even when payment biometric prompts are disabled.");throw n}}async function PC(e){let t=await no({api:U,includeDev:!!e.includeDev});return{config:t.entries.map(n=>({key:n.key,value:n.value,source:n.source,hint:n.hint})),statusError:t.statusError}}var mu=new Set(["auth.serverUrl"]);function vo(){return Object.keys(Xn).filter(e=>!mu.has(e)).sort()}function Hh(e,t){let n=t==="set"?`visa-cli config set ${e}=<value>`:`visa-cli config unset ${e}`;return{success:!1,error:`${e} cannot be changed via MCP. Run \`${n}\` directly from a shell instead.`,code:"MCP_FORBIDDEN_KEY",reason:"auth-trust-boundary key \u2014 a prompt-injected agent could redirect bearer-auth API calls to an attacker host (codex CLI-001 #752).",settableKeys:vo()}}async function OC(e){if(!e.key||typeof e.key!="string")return{success:!1,error:"key is required. Call config_list first to see available keys."};if(e.value===void 0)return{success:!1,error:"value is required. Use config_unset to remove a setting."};if(mu.has(e.key))return g.warn("config:set:rejected:mcp-forbidden",{key:e.key}),Hh(e.key,"set");g.info("config:set",{key:e.key});try{let t=pi(e.key,e.value);return g.info("config:set:success",{key:t.key,requiresRestart:t.requiresRestart}),{success:!0,key:t.key,value:t.value,requiresRestart:t.requiresRestart,path:t.path,message:t.requiresRestart?`Saved ${t.key}. Restart Claude Code for the change to take effect.`:`Saved ${t.key}.`}}catch(t){let n=t instanceof nt?"UNKNOWN_KEY":t instanceof Ft?"SERVER_CONTROLLED":t instanceof gn?"RETIRED_KEY":"INVALID_VALUE",r=t instanceof nt?`Unknown setting "${e.key}". MCP-settable keys: ${vo().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return g.warn("config:set:rejected",{key:e.key,code:n,error:r}),{success:!1,error:r,code:n,settableKeys:vo()}}}async function MC(e){if(!e.key||typeof e.key!="string")return{success:!1,error:"key is required. Call config_list first to see which keys are currently set via settings.json."};if(mu.has(e.key))return g.warn("config:unset:rejected:mcp-forbidden",{key:e.key}),Hh(e.key,"unset");g.info("config:unset",{key:e.key});try{let t=mi(e.key);return g.info("config:unset:success",{key:t.key,removed:t.removed}),{success:!0,key:t.key,removed:t.removed,requiresRestart:t.requiresRestart,path:t.path,message:t.removed?t.requiresRestart?`Removed ${t.key}. Restart Claude Code for the change to take effect.`:`Removed ${t.key}.`:`${t.key} was not set in settings.json \u2014 nothing to remove.`}}catch(t){let n=t instanceof nt?"UNKNOWN_KEY":t instanceof Ft?"SERVER_CONTROLLED":t instanceof gn?"RETIRED_KEY":"INVALID_VALUE",r=t instanceof nt?`Unknown setting "${e.key}". MCP-settable keys: ${vo().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return g.warn("config:unset:rejected",{key:e.key,code:n,error:r}),{success:!1,error:r,code:n,settableKeys:vo()}}}async function NC(e){let t=await U.getStatus(e),n=t.attestationRequired!==!1,r=Tt(t),s=ue(),o=n?r?s?`${wa()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${wa()} is not available in this process. ${fu()}`:"Biometric attestation is enabled on the account, but no attestation key is registered. Payments on this device proceed without a biometric signature; processor declines such as INVALID_OR_MISSING_CONFIG are card/account configuration issues, not something biometric setup fixes.":"Biometric attestation is NOT required for payments. Payments will proceed without biometric confirmation.";return{required:n,hasAttestationKey:!!t.hasAttestationKey,hasTelegramAttestationKey:!!t.hasTelegramAttestationKey,hasAnyAttestationKey:r,touchIdAvailable:s,platform:process.platform,effectiveRequiredOnThisDevice:n&&r&&s,canDisableFromThisDevice:!n||!r||s,message:o}}async function LC(e){g.info("biometric:on");let t=await Ri(U,e);if(t.ok===!1)return{success:!1,error:t.code,error_code:t.code,message:t.message,agent_guidance:`${t.message} Do not call biometric_on again until the user has completed setup in an interactive terminal.`};let n=await U.setBiometricPreference({required:!0},e);return n.success?(Bh(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:n.error||"unknown error"}}async function UC(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Ir("MISSING_CONFIRMATION","Please confirm by setting confirm: true. Disabling Touch ID is a security downgrade \u2014 the user will be prompted for one final Touch ID confirmation before the change takes effect.");g.info("biometric:off");try{return await xe(async()=>{let n=await U.getStatus(t),r;if(Tt(n)&&(r=await Ze("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${wa()} confirmation required to disable \u2014 not available on this device.`);let s=await U.setBiometricPreference({required:!1,attestation:r},t);if(!s.success)throw new Error(s.error||"unknown error");return Bh(),{success:!0,required:!1,message:"Touch ID is no longer required for payments."}})}catch(n){if(g.error("biometric:off:failure",{error:n.message}),n instanceof Bn)return ka(n,"biometric_off");throw n}}var Ih=3e4,DC=3e5;async function Vh(e,t,n="login"){let r=Se.randomUUID(),s=`${e}${e.includes("?")?"&":"?"}state=${r}`,o=ut(s);return!o.opened&&o.blockedReason!=="non_internal_host"&&o.blockedReason!=="invalid_url"?qh(s,o,n):o.opened?{...await Kh(r,t,n),browserUrl:s}:{success:!1,browserUrl:s,message:`Could not open the browser URL safely. Please check the configured auth server and try again. URL: ${s}`}}function qh(e,t,n){let r=n==="enrollment"?"card enrollment":n==="attestation-recovery"?"biometric reset":"login",s=t.blockedReason==="suppressed"?"browser auto-open is suppressed":t.blockedReason==="headless"?"this process appears to be headless":t.blockedReason==="unsupported_platform"?"this platform has no configured browser opener":"browser auto-open is unavailable";return{success:!1,requiresBrowser:!0,browserUrl:e,message:`Browser auto-open was skipped because ${s}. Open this URL to continue ${r}: ${e}`}}async function Kh(e,t,n="login"){let r=Date.now()+DC;for(;Date.now()<r;)try{let o=await fetch(`${Ca()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:Ih,...t&&{user_context:t}}),signal:AbortSignal.timeout(Ih+5e3)});if(!o.ok){await dn(o,a=>{g.warn("auth_status:retry_after_http_error",{status:o.status,delayMs:a})});continue}let i=await o.json();if(i.status==="pending")continue;if(i.status==="expired")return{success:!1,message:"Session expired. Please try again."};if(i.status==="error")return{success:!1,message:i.error||"Authentication failed. Please try again."};if(i.status==="complete"){if(n==="attestation-recovery"||i.attestationCleared)return g.info("auth:attestation_recovery_complete",{user:i.user||""}),{success:!0,message:"Server-side biometric state cleared. Run visa-cli setup to register a fresh key before reenabling Touch ID."};let a=i.welcomeBonusCents??0,c=sm(a);if(n!=="enrollment"&&i.sessionToken){await K.saveSessionToken(i.sessionToken);let u=i.user||"",d=i.last4||"****";return g.info("auth:login_complete",{user:u,last4:d,bonusCents:a}),{success:!0,message:`Signed in as ${u}. Card ending in ${d} enrolled and ready for payments.`,...c||{}}}let l=i.last4||"****";return g.info("auth:card_added",{last4:l,bonusCents:a}),{success:!0,message:`Card ending in ${l} enrolled and ready for payments.`,...c||{}}}}catch{await dn(void 0,o=>{g.warn("auth_status:retry_after_network_error",{delayMs:o})})}return{success:!1,message:n==="enrollment"?"Card enrollment timed out. Please try again.":n==="attestation-recovery"?"Biometric reset timed out. Please try reset again.":"Login timed out. Please try again."}}async function Gh(e){let t=Se.randomUUID(),n;try{n=await U.startAttestationRecovery(t,e)}catch(o){return{success:!1,message:`Could not start biometric reset: ${o?.message||"unknown error"}`}}if(!n.success||!n.recoveryUrl)return{success:!1,message:n.error||"Could not start biometric reset. Please try again."};let r=ut(n.recoveryUrl);return!r.opened&&r.blockedReason!=="non_internal_host"&&r.blockedReason!=="invalid_url"?qh(n.recoveryUrl,r,"attestation-recovery"):r.opened?{...await Kh(t,e,"attestation-recovery"),browserUrl:n.recoveryUrl}:{success:!1,browserUrl:n.recoveryUrl,message:`Could not open the browser URL safely. Please check the configured auth server and try again. URL: ${n.recoveryUrl}`}}async function jC(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to remove this card."};let n=e.cardId;if(!Number.isInteger(n)||n<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to get the opaque cardId for the card you want to remove."};g.info("cards:remove_attempt",{cardId:n});let r=`remove-card:${n}`,s=`remove ${await Fh(n,t)}`;try{return await xe(async()=>{let o=await Ze(r,0,"",s,t,{forceRequired:!0}),i=await U.removeCard(n,{attestation:o},t);return g.info("cards:remove_success",{cardId:n,promotedId:i?.promotedId??null}),i})}catch(o){if(g.error("cards:remove_failure",{cardId:n,error:o.message}),o instanceof Bn)return ka(o,"remove_card");throw o}}async function BC(e,t){let n=e.cardId;if(!Number.isInteger(n)||n<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to get the opaque cardId for the card you want to make default."};g.info("cards:set_default_attempt",{cardId:n});let r=`set-default-card:${n}`,s=`set ${await Fh(n,t)} as default`;try{return await xe(async()=>{let o=await Ze(r,0,"",s,t,{forceRequired:!0}),i=await U.setDefaultCard(n,{attestation:o},t);return g.info("cards:set_default_success",{cardId:n}),i})}catch(o){if(g.error("cards:set_default_failure",{cardId:n,error:o.message}),o instanceof Bn)return ka(o,"set_default_card");throw o}}async function FC(e){return g.info("auth:login_attempt"),Vh(`${Ca()}/login`,e)}function HC(e){if(e.capCents!==void 0){let t=Number(e.capCents);if(!Number.isFinite(t)||t<10||t>1e4)throw new Error("capCents must be between 10 ($0.10) and 10000 ($100)");return Math.floor(t)}if(e.capUsd!==void 0){let t=Number(e.capUsd);if(!Number.isFinite(t)||t<.1||t>100)throw new Error("capUsd must be between 0.10 and 100");return Math.floor(t*100)}}async function VC(e={},t){let n;try{n=HC(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return Ta(async()=>{let r=await xe(()=>hm(U,Ze,{toolName:"start_session",userContext:t,capCentsOverride:n}));g.info("session:started",{budgetId:r.budgetId,totalCents:r.totalCents,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious});let s=(r.appliedCapCents/100).toFixed(2),o=(r.requestedCapCents/100).toFixed(2),i=`Session started with a $${s} cap. Paid calls will use this approval window until you close it, it expires, or this MCP process restarts.`,a=r.clampedReason==="balance"?`${i} Note: requested cap of $${o} was clamped to your prepaid balance of $${s}. Run buy_credits to top up if you need a larger session.`:i;return{success:!0,budgetId:r.budgetId,totalCents:r.totalCents,amountUsd:r.totalCents/100,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious,message:a}})}async function qC(){let e=Rn();if(!e)return{success:!0,active:!1,message:"No active explicit approval window. Paid calls use a one-shot session in pay-as-you-go mode; see transaction_history for records."};let t=Math.max(0,e.totalCents-e.estimatedCumulative);return{success:!0,active:!0,budgetId:e.budgetId,totalCents:e.totalCents,estimatedCumulativeCents:e.estimatedCumulative,estimatedRemainingCents:t,expiresAt:e.expiresAt,lastToolSpend:e.lastToolSpend,message:`Active explicit approval window: about $${(t/100).toFixed(2)} remaining of $${(e.totalCents/100).toFixed(2)}.`}}async function KC(){return Ta(async()=>{let e=Rn();if(!e)return{success:!0,message:"No active explicit approval window to close. Paid calls remain pay-as-you-go.",closed:!1};let t=await Ni(U);g.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=NT(e),r=ct(t.finalCumulativeMicros),s=r??(typeof t.finalCumulativeCents=="number"?BigInt(Math.max(0,t.finalCumulativeCents))*10000n:n.micros),o=Number(s/10000n);return g.info("session:closed:final-spend",{budgetId:t.budgetId,closedServerSide:t.closedServerSide,finalSpendMicros:s.toString(),finalSpendCents:o,finalSpendSource:r!==null?"server.finalCumulativeMicros":typeof t.finalCumulativeCents=="number"?"server.finalCumulativeCents":n.source,totalCents:e.totalCents}),{success:!0,closed:!0,closedServerSide:t.closedServerSide,budgetId:t.budgetId,finalEstimatedCumulativeCents:o,finalEstimatedCumulativeMicros:s.toString(),totalCents:e.totalCents,message:t.closedServerSide?`Explicit approval window closed. Spent ${MT(s)} of $${(e.totalCents/100).toFixed(2)} cap. Future paid calls are pay-as-you-go until you start a new explicit approval window.`:"Explicit approval window cleared locally; server-side close call did not succeed (likely already closed). Future paid calls are pay-as-you-go until you start a new explicit approval window."}})}async function GC(e){if(g.info("auth:add_card_attempt"),!await K.getSessionToken())return{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."};let{code:n}=await U.createEnrollCode();return Vh(`${Ca()}/enroll-card?code=${encodeURIComponent(n)}`,e,"enrollment")}async function $h(){if(await K.clearAll(),ue())try{await Ai()}catch{}}async function WC(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};if(g.info("reset:attempt"),e.localOnly)return await $h(),g.info("reset:success",{localOnly:!0}),{success:!0,message:"Device reset locally. Local credentials and keys have been removed; server-side session and biometric state were not changed. Use the login tool or visa-cli setup to sign in with the GitHub account you want to use."};let n=!1;try{let r=await U.getStatus(t);if(r&&Tt(r)){let s=await Gh(t);if(!s.success)return s;n=!0}}catch(r){let s=r?.message||"unknown error";if(!/not logged in|session.*expired|no local credentials/i.test(s))return{success:!1,message:`Could not check server biometric state: ${s}`};g.warn("reset:server_attestation_status_unavailable",{error:s})}try{await U.logout(void 0,t)}catch{}return await $h(),g.info("reset:success"),{success:!0,message:n?"Device reset. Server-side biometric state and local credentials have been cleared. Use the login tool or visa-cli setup to re-enroll.":"Device reset. Local credentials and keys have been removed. Use the login tool or visa-cli setup to re-enroll."}}async function YC(e){let t=e.query?.trim()||void 0,n=e.category?.trim()||void 0,r=!t&&!n;g.info("catalog:discover",{query:t,category:n,browseAll:r});try{let o=(await U.catalogSearch(t,n)).tools||[];if(o.length===0)return{content:[{type:"text",text:r?"The tool catalog is currently empty.":`No tools found for "${t||n}". Try a different search term.`}]};if(r){let a={};for(let l of o){let u=l.category||"other";(a[u]??=[]).push(l)}let c=Object.keys(a).sort().map(l=>{let u=a[l].map((p,f)=>`${f+1}. **${p.name}** (${p.id})
146
146
  ${p.description}
147
147
  Provider: ${p.provider} | Price: ${Ph(p)}${Oh(p)}
@@ -169,7 +169,7 @@ Use execute_tool with the tool id and required params to run any of these.`}],_t
169
169
  `),!0}function zh(e){let t=Array.isArray(e.inputSchema?.required)?e.inputSchema.required.filter(s=>typeof s=="string"):[],n=e.inputSchema?.properties&&typeof e.inputSchema.properties=="object"?e.inputSchema.properties:{};if(t.length===0)return{prompt:"a lobster"};let r={};for(let s of t)r[s]=sk(s,n[s]?.description);return r}function sk(e,t){let n=e.toLowerCase();return n==="prompt"?"a lobster":n==="text"?"Hello from Visa CLI.":n.endsWith("image_url")||n==="image_url"?"https://example.com/sample.jpg":n.endsWith("audio_url")||n==="audio_url"?"https://example.com/sample.wav":n.endsWith("video_url")||n==="video_url"?"https://example.com/sample.mp4":n==="taskid"||n==="task_id"?"task_abc123":n==="request_id"||n==="requestid"?"req_abc123":n==="model_path"||n==="model"?"fal-ai/flux/schnell":n==="language"?"en":t&&/\bUR?L\b|https?:\/\//i.test(t)?"https://example.com/sample":"example"}function ok(e){let t=Pt(e.referralCode,"");if(!t)return[];let n=["Referrals",` Your code ${t}`],r=Pt(e.referralLink,"");if(r&&n.push(` Your link ${r}`),typeof e.referralCount=="number"&&Number.isFinite(e.referralCount)){let s=Math.max(0,Math.trunc(e.referralCount));n.push(` Joined ${s} ${s===1?"person":"people"} via your link`)}return n}var ik=20;function Xh(e,t,n,r){let s=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=pk(e.spendingControls).dailyLimit,a=Math.max(0,To(e.dailyCardFundedTopupSpent??e.dailySpent)),c=i>0?Math.min(i,Math.max(0,To(e.dailyCardFundedTopupRemaining??e.dailyRemaining??i-a))):0,l=i>0?Math.min(1,a/i):0,d=(Array.isArray(t)?t:[]).filter(lk),p=d.slice(0,3),f=uk(d,3),m=(e.cards??[]).slice(0,3),h=r.latestVersion?$r(r.latestVersion):"",w=r.updateCheckDisabled?"update checks disabled":h?`update ready: v${h}`:"up to date",C=Math.round(l*100),b=Pt(e.status,e.enrolled?"approved":"not enrolled"),S=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${b} | touch id: ${n?"ready":"unavailable"}`,`Version: v${s} | ${w}`,`Top-up meter: ${Jh(l)} ${String(C).padStart(3," ")}% | remaining ${vs(c)}/day | daily top-up cap ${vs(i)}`,"","Card top-ups",` Remaining ${vs(c)} / ${vs(i)}`,` Usage ${Jh(l)} ${C}%`,` Top-ups today ${vs(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...m.length>0?m.map(I=>` ${fk(I)}`):[" No cards enrolled"],"","Last 3 services",...f.length>0?f.map((I,y)=>` ${y+1}. ${I}`):[" No paid services yet"],"","Recent receipts",...p.length>0?p.map(I=>` ${dk(I)}`):[" No receipts yet"]],A=ok(e);return A.length>0&&S.push("",...A),h&&!r.updateCheckDisabled?(S.push("",`Update: v${h} ready \u2014 run \`visa-cli update\``),r.updateMessage&&S.push(` ${$r(r.updateMessage)}`)):r.updateMessage&&S.push("",`Update: ${$r(r.updateMessage)}`),`${S.join(`
170
170
  `)}
171
171
  `}function ak(e){return e.tool_name!=null}function ck(e){return To(e.amount)===0&&e.status==="failed"}function lk(e){return ak(e)&&!ck(e)}function uk(e,t=1/0){let n=new Set,r=[];for(let s of e){if(r.length>=t)break;let o=Pt(s.merchant_name,"Unknown merchant"),i=Pt(s.tool_name,"unknown_tool"),a=`${o} :: ${i}`;n.has(a)||(n.add(a),r.push(`${o} [${i}]`))}return r}function dk(e){let t=Pt(e.merchant_name,"Unknown merchant"),n=Pt(e.tool_name,"unknown_tool"),r=vs(To(e.amount)),s=Pt(e.status,"unknown"),o=mk(e.created_at);return`${r} ${s.padEnd(9)} ${t} [${n}] ${o}`}function fk(e){let t=Pt(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function pk(e){return{dailyLimit:To(e?.daily_limit??e?.dailyLimit??0)}}function To(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function vs(e){return`$${e.toFixed(2)}`}function Jh(e,t=ik){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function Pt(e,t){let n=$r(e??"").trim();return n.length>0?n:t}function mk(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?Pt(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function $r(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ")}var gk=/^[1-9]\d{0,9}$/;function hu(e){if(!gk.test(e))throw new Error("card id must be a positive integer with up to 10 digits. Run `visa-cli cards list` first.");return Number(e)}function Zh(e){let t=$r(e.brand||"Visa"),n=$r(e.last4||"unknown");return{id:Number.isInteger(e.id)?String(e.id):"-",brand:t.charAt(0).toUpperCase()+t.slice(1).toLowerCase(),card:`****${n}`,default:e.isDefault?"yes":""}}var Ot=R(require("fs")),ye=R(require("path")),hk=["npm","pnpm","yarn","bun"],yk=/\s+/,_k=process.platform==="win32"?"visa-cli.cmd":"visa-cli",yu=["node_modules","@visa","cli"];function bk(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(yk)[0]??"",r=n.indexOf("/"),s=r===-1?n:n.slice(0,r);return hk.includes(s)?s:void 0}function _u(e){if(!e)return;let t=e;try{t=Ot.realpathSync(e)}catch{}let n=t.replace(/\\/g,"/").toLowerCase();if(n.includes("/pnpm/")||n.includes("/.pnpm/"))return"pnpm";if(n.includes("/yarn/")||n.includes("/.yarn/"))return"yarn";if(n.includes("/bun/")||n.includes("/.bun/"))return"bun";if(n.includes("/npm/")||n.includes("/node_modules/@visa/cli/"))return"npm"}function vk(e=process.argv[1]){return bk()??_u(process.env.npm_execpath)??_u(process.env.npm_node_execpath)??_u(e)}function wk(e=process.env.PATH??""){let t=[];for(let n of e.split(ye.delimiter))n&&t.push(n);return t}function Sk(e=process.env.PATH??""){let t=new Set,n=[];for(let r of wk(e))try{let s=ye.join(r,_k);Ot.accessSync(s,Ot.constants.X_OK);let o=ye.resolve(s);t.has(o)||(t.add(o),n.push(s))}catch{}return n}function Qh(e){try{let t=Ot.readFileSync(ye.join(e,"package.json"),"utf-8"),n=JSON.parse(t);if(n.name==="@visa/cli"&&typeof n.version=="string")return n.version}catch{}}function xk(e){let t=ye.resolve(e).split(ye.sep);for(let n=t.length-yu.length;n>=0;n--)if(yu.every((r,s)=>t[n+s]===r)){let r=t.slice(0,n+yu.length).join(ye.sep)||ye.sep;if(Qh(r))return r}}function Tk(e){if(!e)return;let t=ye.normalize(e),n=t.split(ye.sep),r=o=>o.every((a,c)=>n[n.length-o.length+c]===a)?n.slice(0,-o.length).join(ye.sep)||ye.parse(t).root:void 0,s=r(["lib","node_modules","@visa","cli"]);if(s)return s;if(process.platform==="win32")return r(["node_modules","@visa","cli"])}function Ck(e,t){let n=ye.resolve(e);try{n=Ot.realpathSync(e)}catch{}let r=xk(n);return{binPath:e,realPath:n,packageRoot:r,version:r?Qh(r):void 0,prefix:Tk(r),isActive:n===t}}function kk(e,t=process.env.PATH??""){let n=e??process.argv[1],r=n?ye.resolve(n):"";try{n&&(r=Ot.realpathSync(n))}catch{}let s=e?[e]:[n,...Sk(t)].filter(Boolean),o=new Map;for(let d of s){let p=Ck(d,r),f=o.get(p.realPath);o.set(p.realPath,f?{...p,binPath:f.binPath}:p)}let i=[...o.values()],a=i.find(d=>d.isActive);!a&&i.length>0&&!e&&(a={...i[0],isActive:!0},i[0]=a);let c=new Set(i.map(d=>d.packageRoot).filter(Boolean)),l=!!a?.packageRoot&&c.size>1,u=a?.prefix;return{active:a,installs:i,hasConflictingInstalls:l,recommendedPrefix:u}}function Ek(e,t=process.platform){return/^[A-Za-z0-9_./:@+-]+$/.test(e)?e:t==="win32"?`"${e.replace(/"/g,'""')}"`:`'${e.replace(/'/g,"'\\''")}'`}function bu(e,t,n,r={}){let s=t??vk(n)??"npm",o=r.withDiagnostics?kk(n):void 0,a=`@visa/cli@${e??"latest"}`;switch(s){case"npm":if(o?.hasConflictingInstalls&&o.recommendedPrefix){let c=o.recommendedPrefix;return{packageManager:s,command:"npm",args:["install","-g","--prefix",c,a],display:`npm install -g --prefix ${Ek(c)} ${a}`,diagnostics:o}}return{packageManager:s,command:"npm",args:["install","-g",a],display:`npm install -g ${a}`,diagnostics:o};case"pnpm":return{packageManager:s,command:"pnpm",args:["add","-g",a],display:`pnpm add -g ${a}`,diagnostics:o};case"yarn":return{packageManager:s,command:"yarn",args:["global","add",a],display:`yarn global add ${a}`,diagnostics:o};case"bun":return{packageManager:s,command:"bun",args:["add","-g",a],display:`bun add -g ${a}`,diagnostics:o}}}function Ak(e){let t=e.isActive?" (active)":"",n=e.version?` v${e.version}`:" version unknown",r=e.prefix?` via ${e.prefix}`:"";return` - ${e.binPath}${t}: ${n}${r}`}function vu(e,t){if(!e.hasConflictingInstalls)return null;let n=["Multiple Visa CLI installs detected.",...e.installs.map(Ak)];return t&&(e.recommendedPrefix?n.push("The update command below targets the active install so your shell actually picks up the new version."):n.push("The update command is shown below; remove duplicate installs if your shell still picks up an older version."),n.push(` ${t}`)),n.join(`
172
- `)}var La=R(es());function Rk(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function ey(e){if(!e)return{canContinue:!1,message:"Biometric attestation is unavailable and Visa CLI could not verify server attestation policy.",hint:"Re-run setup from an interactive device with Touch ID (Mac) or Windows Hello (PC) before using payment commands."};let t=Rk(e);return e.attestationRequired!==!1||t?{canContinue:!1,message:"Biometric attestation is unavailable, but this account requires a registered local attestation key.",hint:"Re-run setup from an interactive device with Touch ID (Mac) or Windows Hello (PC), or use an already-registered device to recover or change biometric policy."}:{canContinue:!0,message:"Biometric attestation is unavailable; continuing only because server biometric policy is disabled and no attestation key is registered."}}async function ty(){await K.deleteSessionToken()}var sy=R(require("crypto"));fa();var Ge=R(require("fs")),Ea=R(require("os")),ws=R(require("path")),oy=R(require("node:readline")),wu="3.3.0",Ik=process.env.PORTER_API_URL??"https://porter-travel.up.railway.app",$k=process.env.TAP_REGISTRY_URL??"https://tap-production-eff9.up.railway.app",Co=ws.join(Ea.homedir(),".visa-cli","agents");function Pk(){return!!(process.env.VISA_DEV==="1"||wu==="0.0.0"||wu.startsWith("0.0.")||/-rc\.|-beta\./.test(wu))}function Ok(){Ge.mkdirSync(Co,{recursive:!0,mode:448})}function Tu(e){return ws.join(Co,`${e}.json`)}function Su(){return Ge.existsSync(Co)?Ge.readdirSync(Co).filter(e=>e.endsWith(".json")).map(e=>ws.join(Co,e)):[]}function Mk(e){let t=Tu(e);return Ge.existsSync(t)?JSON.parse(Ge.readFileSync(t,"utf8")):null}function Nk(e){Ok();let t=Tu(e.agent_id);Ge.writeFileSync(t,JSON.stringify(e,null,2),{mode:384})}async function xu(e,t,n,r){let s=`${e.replace(/\/+$/,"")}${n}`,o=await fetch(s,{method:t,headers:{"Content-Type":"application/json"},body:r!==void 0?JSON.stringify(r):void 0}),i=await o.json().catch(()=>({}));if(!o.ok||i.errors?.length){let a=i.errors?.[0];throw new Error(`${t} ${s} failed (${o.status}): ${a?.code??"unknown"} \u2014 ${a?.message??"no message"}`)}if(i.data===void 0)throw new Error(`${t} ${s}: empty response data`);return i.data}var ny=xu;function Lk(){let{secretKey:e}=ah(),t=lh(e);return{publicKeyB64url:t.x,privateJwk:t}}function iy(e,t){let n=mo(t);return ps(po(n,new TextEncoder().encode(e)))}async function Uk(e){let{publicKeyB64url:t,privateJwk:n}=Lk(),r=new Date().toISOString(),s=`tap:register:v1:${e.name}:${r}`,o=iy(s,n),i=await xu(e.registryUrl,"POST","/api/v1/agents",{name:e.name,public_key:t,signed_at:r,signature:o,visibility:"public",capabilities:["porter:book","visa:authorize_payment"]}),a=await xu(e.porterUrl,"POST","/api/v1/tap/accounts",{public_key:t,name:e.name}),c={agent_id:i.agent_id,tap_registry_url:e.registryUrl,porter_url:e.porterUrl,tap_account_id:a.id,public_key_b64url:t,private_key_jwk:n,name:e.name,created_at:new Date().toISOString()};return Nk(c),c}async function ay(e){let t=await ny(e.porter_url,"GET",`/api/v1/tap/challenge?public_key=${encodeURIComponent(e.public_key_b64url)}`),n=iy(t.challenge,e.private_key_jwk),r=await ny(e.porter_url,"POST","/api/v1/tap/verify",{public_key:e.public_key_b64url,challenge:t.challenge,signature:n});return{token:r.token,expiresInSeconds:r.expires_in}}function Dk(e,t,n){let r=JSON.stringify(t),s=JSON.stringify(n),o=Buffer.from(r).toString("base64url"),i=Buffer.from(s).toString("base64url"),a=`${o}.${i}`,c=mo(e),l=po(c,new TextEncoder().encode(a));return`${a}.${ps(l)}`}var jk=["visa_authorize_payment"],Bk={name:"visa_authorize_payment",description:["Mint a signed payment-authorization JWT (visa_payment_id) for a merchant.","Pass the returned JWT into the merchant's checkout/booking call (e.g. porter_checkout).","The signing key is the agent's Ed25519 keypair held by visa-cli (kernel-sealed in production).","No money is moved here \u2014 the JWT only authorizes the merchant to settle later for up to `amount`."].join(" "),inputSchema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",additionalProperties:!1,properties:{merchant:{type:"string",description:'Merchant identifier \u2014 must match the merchant\'s `aud` claim. Today: "porter".'},amount:{type:"integer",minimum:1,description:"Amount in minor units (cents for USD). MUST equal or exceed the merchant transaction total."},currency:{type:"string",minLength:3,maxLength:3,description:'ISO 4217 currency code, e.g. "USD".'},idem_key:{type:"string",description:"Merchant-stable transaction binding. For porter: the cart_id from porter_add_to_cart."},description:{type:"string",description:'Human-readable purpose of the payment, e.g. "JFK\u2192CDG business 2026-09-15".'}},required:["merchant","amount","currency","idem_key"]}};function Fk(e){if(e===null||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"visa_authorize_payment: arguments must be an object"};let t=e;return typeof t.merchant!="string"||t.merchant.length===0?{ok:!1,error:"visa_authorize_payment: merchant must be a non-empty string"}:typeof t.idem_key!="string"||t.idem_key.length===0?{ok:!1,error:"visa_authorize_payment: idem_key must be a non-empty string"}:typeof t.currency!="string"||!/^[A-Za-z]{3}$/.test(t.currency)?{ok:!1,error:"visa_authorize_payment: currency must be a 3-letter ISO 4217 code"}:typeof t.amount!="number"||!Number.isFinite(t.amount)||!Number.isSafeInteger(t.amount)||t.amount<1?{ok:!1,error:"visa_authorize_payment: amount must be a positive safe-integer (minor units, \u22651)"}:{ok:!0,value:{merchant:t.merchant,amount:t.amount,currency:t.currency,idem_key:t.idem_key,description:typeof t.description=="string"?t.description:void 0}}}function Hk(e,t){let n=Math.floor(Date.now()/1e3),r=n+300,s=`vpid_${sy.randomBytes(16).toString("hex")}`,o=process.env.VISACLI_ISSUER??e.tap_registry_url??e.porter_url;return{jwt:Dk(e.private_key_jwk,{alg:"EdDSA",typ:"JWT",kid:e.agent_id},{iss:o,aud:t.merchant,sub:e.agent_id,amount:t.amount,currency:t.currency.toUpperCase(),idem_key:t.idem_key,iat:n,nbf:n,exp:r,jti:s}),jti:s,expiresAt:r}}async function Vk(e){let t=`${e.porter_url.replace(/\/+$/,"")}/api/mcp`,n=null,r=0;async function s(p=!1){if(!p&&n&&Date.now()<r-6e4)return n;let{token:f,expiresInSeconds:m}=await ay(e);return n=f,r=Date.now()+m*1e3,f}function o(p){process.stdout.write(JSON.stringify(p)+`
172
+ `)}var La=R(es());function Rk(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function ey(e){if(!e)return{canContinue:!1,message:"Biometric attestation is unavailable and Visa CLI could not verify server attestation policy.",hint:"Re-run setup from an interactive device with Touch ID (Mac) or Windows Hello (PC) before using payment commands."};let t=Rk(e);return e.attestationRequired!==!1||t?{canContinue:!1,message:"Biometric attestation is unavailable, but this account requires a registered local attestation key.",hint:"Re-run setup from an interactive device with Touch ID (Mac) or Windows Hello (PC), or use an already-registered device to recover or change biometric policy."}:{canContinue:!0,message:"Biometric attestation is unavailable; continuing only because server biometric policy is disabled and no attestation key is registered."}}async function ty(){await K.deleteSessionToken()}var sy=R(require("crypto"));fa();var Ge=R(require("fs")),Ea=R(require("os")),ws=R(require("path")),oy=R(require("node:readline")),wu="3.3.1-rc.0",Ik=process.env.PORTER_API_URL??"https://porter-travel.up.railway.app",$k=process.env.TAP_REGISTRY_URL??"https://tap-production-eff9.up.railway.app",Co=ws.join(Ea.homedir(),".visa-cli","agents");function Pk(){return!!(process.env.VISA_DEV==="1"||wu==="0.0.0"||wu.startsWith("0.0.")||/-rc\.|-beta\./.test(wu))}function Ok(){Ge.mkdirSync(Co,{recursive:!0,mode:448})}function Tu(e){return ws.join(Co,`${e}.json`)}function Su(){return Ge.existsSync(Co)?Ge.readdirSync(Co).filter(e=>e.endsWith(".json")).map(e=>ws.join(Co,e)):[]}function Mk(e){let t=Tu(e);return Ge.existsSync(t)?JSON.parse(Ge.readFileSync(t,"utf8")):null}function Nk(e){Ok();let t=Tu(e.agent_id);Ge.writeFileSync(t,JSON.stringify(e,null,2),{mode:384})}async function xu(e,t,n,r){let s=`${e.replace(/\/+$/,"")}${n}`,o=await fetch(s,{method:t,headers:{"Content-Type":"application/json"},body:r!==void 0?JSON.stringify(r):void 0}),i=await o.json().catch(()=>({}));if(!o.ok||i.errors?.length){let a=i.errors?.[0];throw new Error(`${t} ${s} failed (${o.status}): ${a?.code??"unknown"} \u2014 ${a?.message??"no message"}`)}if(i.data===void 0)throw new Error(`${t} ${s}: empty response data`);return i.data}var ny=xu;function Lk(){let{secretKey:e}=ah(),t=lh(e);return{publicKeyB64url:t.x,privateJwk:t}}function iy(e,t){let n=mo(t);return ps(po(n,new TextEncoder().encode(e)))}async function Uk(e){let{publicKeyB64url:t,privateJwk:n}=Lk(),r=new Date().toISOString(),s=`tap:register:v1:${e.name}:${r}`,o=iy(s,n),i=await xu(e.registryUrl,"POST","/api/v1/agents",{name:e.name,public_key:t,signed_at:r,signature:o,visibility:"public",capabilities:["porter:book","visa:authorize_payment"]}),a=await xu(e.porterUrl,"POST","/api/v1/tap/accounts",{public_key:t,name:e.name}),c={agent_id:i.agent_id,tap_registry_url:e.registryUrl,porter_url:e.porterUrl,tap_account_id:a.id,public_key_b64url:t,private_key_jwk:n,name:e.name,created_at:new Date().toISOString()};return Nk(c),c}async function ay(e){let t=await ny(e.porter_url,"GET",`/api/v1/tap/challenge?public_key=${encodeURIComponent(e.public_key_b64url)}`),n=iy(t.challenge,e.private_key_jwk),r=await ny(e.porter_url,"POST","/api/v1/tap/verify",{public_key:e.public_key_b64url,challenge:t.challenge,signature:n});return{token:r.token,expiresInSeconds:r.expires_in}}function Dk(e,t,n){let r=JSON.stringify(t),s=JSON.stringify(n),o=Buffer.from(r).toString("base64url"),i=Buffer.from(s).toString("base64url"),a=`${o}.${i}`,c=mo(e),l=po(c,new TextEncoder().encode(a));return`${a}.${ps(l)}`}var jk=["visa_authorize_payment"],Bk={name:"visa_authorize_payment",description:["Mint a signed payment-authorization JWT (visa_payment_id) for a merchant.","Pass the returned JWT into the merchant's checkout/booking call (e.g. porter_checkout).","The signing key is the agent's Ed25519 keypair held by visa-cli (kernel-sealed in production).","No money is moved here \u2014 the JWT only authorizes the merchant to settle later for up to `amount`."].join(" "),inputSchema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",additionalProperties:!1,properties:{merchant:{type:"string",description:'Merchant identifier \u2014 must match the merchant\'s `aud` claim. Today: "porter".'},amount:{type:"integer",minimum:1,description:"Amount in minor units (cents for USD). MUST equal or exceed the merchant transaction total."},currency:{type:"string",minLength:3,maxLength:3,description:'ISO 4217 currency code, e.g. "USD".'},idem_key:{type:"string",description:"Merchant-stable transaction binding. For porter: the cart_id from porter_add_to_cart."},description:{type:"string",description:'Human-readable purpose of the payment, e.g. "JFK\u2192CDG business 2026-09-15".'}},required:["merchant","amount","currency","idem_key"]}};function Fk(e){if(e===null||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"visa_authorize_payment: arguments must be an object"};let t=e;return typeof t.merchant!="string"||t.merchant.length===0?{ok:!1,error:"visa_authorize_payment: merchant must be a non-empty string"}:typeof t.idem_key!="string"||t.idem_key.length===0?{ok:!1,error:"visa_authorize_payment: idem_key must be a non-empty string"}:typeof t.currency!="string"||!/^[A-Za-z]{3}$/.test(t.currency)?{ok:!1,error:"visa_authorize_payment: currency must be a 3-letter ISO 4217 code"}:typeof t.amount!="number"||!Number.isFinite(t.amount)||!Number.isSafeInteger(t.amount)||t.amount<1?{ok:!1,error:"visa_authorize_payment: amount must be a positive safe-integer (minor units, \u22651)"}:{ok:!0,value:{merchant:t.merchant,amount:t.amount,currency:t.currency,idem_key:t.idem_key,description:typeof t.description=="string"?t.description:void 0}}}function Hk(e,t){let n=Math.floor(Date.now()/1e3),r=n+300,s=`vpid_${sy.randomBytes(16).toString("hex")}`,o=process.env.VISACLI_ISSUER??e.tap_registry_url??e.porter_url;return{jwt:Dk(e.private_key_jwk,{alg:"EdDSA",typ:"JWT",kid:e.agent_id},{iss:o,aud:t.merchant,sub:e.agent_id,amount:t.amount,currency:t.currency.toUpperCase(),idem_key:t.idem_key,iat:n,nbf:n,exp:r,jti:s}),jti:s,expiresAt:r}}async function Vk(e){let t=`${e.porter_url.replace(/\/+$/,"")}/api/mcp`,n=null,r=0;async function s(p=!1){if(!p&&n&&Date.now()<r-6e4)return n;let{token:f,expiresInSeconds:m}=await ay(e);return n=f,r=Date.now()+m*1e3,f}function o(p){process.stdout.write(JSON.stringify(p)+`
173
173
  `)}function i(p,f,m){o({jsonrpc:"2.0",id:p??null,error:{code:f,message:m}})}function a(p,f,m){if(f==="visa_authorize_payment"){let h=Fk(m);if(!h.ok){i(p,-32602,h.error);return}let w=h.value;try{let{jwt:C,jti:b,expiresAt:v}=Hk(e,w);o({jsonrpc:"2.0",id:p,result:{content:[{type:"text",text:["\u2713 Payment authorized \u2014 pass this JWT as visa_payment_id at checkout:","",C,"",` agent: ${e.agent_id}`,` merchant: ${w.merchant}`,` amount: ${w.amount} ${w.currency.toUpperCase()}`,` jti: ${b}`,` expires: ${new Date(v*1e3).toISOString()}`].join(`
174
174
  `)},{type:"text",text:JSON.stringify({visa_payment_id:C,jti:b,agent_id:e.agent_id,amount:w.amount,currency:w.currency.toUpperCase(),merchant:w.merchant,expires_at:v})}]}})}catch(C){i(p,-32603,`failed to sign visa_payment_id: ${C instanceof Error?C.message:String(C)}`)}return}i(p,-32601,`unknown synthetic tool: ${f}`)}async function c(p){if(p.method==="tools/call"){let m=p.params??{};if(typeof m.name=="string"&&jk.includes(m.name)){a(p.id,m.name,m.arguments??{});return}}let f=0;for(;f<2;){f+=1;let m=await s(f>1),h;try{h=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","X-TAP-Token":m},body:JSON.stringify(p)})}catch(C){i(p.id,-32e3,`network error talking to porter: ${C instanceof Error?C.message:String(C)}`);return}if(h.status===401&&f===1){n=null;continue}if(!h.ok){let C=await h.text().catch(()=>"");i(p.id,-32e3,`porter returned ${h.status}: ${C.slice(0,400)}`);return}if((h.headers.get("content-type")??"").includes("text/event-stream"))await u(h,p);else{let C=await h.text();if(C.trim()){let b=JSON.parse(C);l(p,b),o(b)}}return}}function l(p,f){if(p.method!=="tools/list")return;let m=f.result;!m||!Array.isArray(m.tools)||m.tools.some(h=>h.name==="visa_authorize_payment")||m.tools.push(Bk)}async function u(p,f){let m=p.body?.getReader();if(!m)return;let h=new TextDecoder,w="";for(;;){let{done:C,value:b}=await m.read();if(C)break;w+=h.decode(b,{stream:!0});let v;for(;(v=w.indexOf(`
175
175
 
@@ -184,7 +184,7 @@ ${n}`)}return JSON.parse(Ge.readFileSync(t[0],"utf8"))}function cy(e){if(!Pk())r
184
184
  `)}catch(r){process.stderr.write(`agent token failed: ${r instanceof Error?r.message:String(r)}
185
185
  `),process.exit(1)}}),t.command("proxy").description("Run as a stdio MCP server that proxies to porter. Inject X-TAP-Token automatically. Used by AI clients (claude mcp add porter -- visa-cli agent proxy).").option("--agent <id>","Specific agent_id (required if more than one is registered)").action(async n=>{try{let r=ry(n.agent);await Vk(r)}catch(r){process.stderr.write(`agent proxy failed: ${r instanceof Error?r.message:String(r)}
186
186
  `),process.exit(1)}}),t.command("list").description("List registered agents.").action(()=>{let n=Su();if(n.length===0){process.stdout.write("No agents registered. Run `visa-cli agent register` to add one.\n");return}for(let r of n){let s=JSON.parse(Ge.readFileSync(r,"utf8"));process.stdout.write(`${s.agent_id} ${s.porter_url} ${s.name}
187
- `)}})}Nl();_o();var qk="3.3.0";async function ly(e){let t=await eu(e);console.log(`\u2713 registered "${t.relayName}" on the "${t.mesh}" mesh`),console.log(` peer: ${t.peerId??"(pending)"}`),console.log(` identity: ${t.tapAgentId?`reused TAP key ${t.tapAgentId}`:"stable Subway key (no TAP agent found)"}`),console.log(` relay: ${yo} (mesh="${t.mesh}")`),console.log(` chat: visa subway listen --as ${e} | visa subway send --as ${e} <to> "<text>"`)}var Aa=(e,t)=>{console.error(`\u2717 ${e} failed: ${t instanceof Error?t.message:String(t)}`),process.exitCode=1};function uy(e){if(!Zl(qk))return;e.command("register <name>").description(`Register a name on the "${at}" Subway mesh (reuses your CLI agent key \u2014 no TAP setup needed).`).action(async n=>{try{await ly(n)}catch(r){Aa("register",r)}});let t=e.command("subway").description("Subway agent-to-agent messaging over the Visa CLI.");t.command("register <name>").description("Alias of `visa register <name>`.").action(async n=>{try{await ly(n)}catch(r){Aa("register",r)}}),t.command("send <to> <text>").description("Send a direct signed message to another agent.").option("--as <name>","Registered name to send as (default: the only one registered)").action(async(n,r,s)=>{try{let o=ga(s.as),i=await tu(o,n,r);console.log(`\u2713 sent to ${i.to} as ${i.as}`)}catch(o){Aa("send",o)}}),t.command("listen").description("Stay connected and print inbound messages (Ctrl-C to stop).").option("--as <name>","Registered name to listen as (default: the only one registered)").option("--room <topic>","Also subscribe to a room topic").action(async n=>{try{let r=ga(n.as),s=gs(r,{autoReconnect:!0});await hs(s);let o=a=>new Date(a).toLocaleTimeString();s.onMessage(a=>{let c=a.verified?"":" (unverified)";console.log(`[${o(a.timestampMs)}] ${a.fromName}${c}: ${a.payload}`)}),n.room&&s.subscribe(n.room,a=>{console.log(`[${o(a.timestampMs)}] #${a.topic} ${a.fromName}: ${a.payload}`)}),console.log(`\u2026 listening as ${Sr(r)} on "${at}" mesh${n.room?` (room #${n.room})`:""}. Ctrl-C to stop.`);let i=()=>{s.disconnect(),process.exit(0)};process.on("SIGINT",i),process.on("SIGTERM",i),await new Promise(()=>{})}catch(r){Aa("listen",r)}}),t.command("whoami").description("List names this CLI has registered on the relay.").action(()=>{let n=nu();if(n.length===0){console.log("No Subway names registered. Run `visa register <name>`.");return}for(let r of n)console.log(`${r.relayName} mesh=${r.mesh} peer=${r.peerId??"?"} ${r.tapAgentId?`tap=${r.tapAgentId}`:"(standalone key)"} registered=${r.registeredAt}`)})}_t();Ht();var Kk=["get_status","add_card","pay","get_visa_smi","get_cards","remove_card","set_default_card","buy_credits","transaction_history","update_spending_controls","config_list","config_set","config_unset","biometric_status","biometric_on","biometric_off","reset","login","start_session","close_session","get_session_status","set_session_mode","generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card","feedback","suggest_meme_templates","batch","discover_tools","execute_tool"];function Gk(){let e=new Set;for(let t of Kk)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of to)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var Y2=Gk();var Cu=new Set(["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"]);var Q2=new Set(to),e$=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...Cu,...to]);Ht();var G=R(require("fs")),F=R(require("path")),dy=R(require("os")),fe=dy.homedir(),Wk=["Claude_","Anthropic.ClaudeDesktop_"],Ss=class extends Error{constructor(n,r,s){super(zk(n,r,s));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function fy(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
187
+ `)}})}Nl();_o();var qk="3.3.1-rc.0";async function ly(e){let t=await eu(e);console.log(`\u2713 registered "${t.relayName}" on the "${t.mesh}" mesh`),console.log(` peer: ${t.peerId??"(pending)"}`),console.log(` identity: ${t.tapAgentId?`reused TAP key ${t.tapAgentId}`:"stable Subway key (no TAP agent found)"}`),console.log(` relay: ${yo} (mesh="${t.mesh}")`),console.log(` chat: visa subway listen --as ${e} | visa subway send --as ${e} <to> "<text>"`)}var Aa=(e,t)=>{console.error(`\u2717 ${e} failed: ${t instanceof Error?t.message:String(t)}`),process.exitCode=1};function uy(e){if(!Zl(qk))return;e.command("register <name>").description(`Register a name on the "${at}" Subway mesh (reuses your CLI agent key \u2014 no TAP setup needed).`).action(async n=>{try{await ly(n)}catch(r){Aa("register",r)}});let t=e.command("subway").description("Subway agent-to-agent messaging over the Visa CLI.");t.command("register <name>").description("Alias of `visa register <name>`.").action(async n=>{try{await ly(n)}catch(r){Aa("register",r)}}),t.command("send <to> <text>").description("Send a direct signed message to another agent.").option("--as <name>","Registered name to send as (default: the only one registered)").action(async(n,r,s)=>{try{let o=ga(s.as),i=await tu(o,n,r);console.log(`\u2713 sent to ${i.to} as ${i.as}`)}catch(o){Aa("send",o)}}),t.command("listen").description("Stay connected and print inbound messages (Ctrl-C to stop).").option("--as <name>","Registered name to listen as (default: the only one registered)").option("--room <topic>","Also subscribe to a room topic").action(async n=>{try{let r=ga(n.as),s=gs(r,{autoReconnect:!0});await hs(s);let o=a=>new Date(a).toLocaleTimeString();s.onMessage(a=>{let c=a.verified?"":" (unverified)";console.log(`[${o(a.timestampMs)}] ${a.fromName}${c}: ${a.payload}`)}),n.room&&s.subscribe(n.room,a=>{console.log(`[${o(a.timestampMs)}] #${a.topic} ${a.fromName}: ${a.payload}`)}),console.log(`\u2026 listening as ${Sr(r)} on "${at}" mesh${n.room?` (room #${n.room})`:""}. Ctrl-C to stop.`);let i=()=>{s.disconnect(),process.exit(0)};process.on("SIGINT",i),process.on("SIGTERM",i),await new Promise(()=>{})}catch(r){Aa("listen",r)}}),t.command("whoami").description("List names this CLI has registered on the relay.").action(()=>{let n=nu();if(n.length===0){console.log("No Subway names registered. Run `visa register <name>`.");return}for(let r of n)console.log(`${r.relayName} mesh=${r.mesh} peer=${r.peerId??"?"} ${r.tapAgentId?`tap=${r.tapAgentId}`:"(standalone key)"} registered=${r.registeredAt}`)})}_t();Ht();var Kk=["get_status","add_card","pay","get_visa_smi","get_cards","remove_card","set_default_card","buy_credits","transaction_history","update_spending_controls","config_list","config_set","config_unset","biometric_status","biometric_on","biometric_off","reset","login","start_session","close_session","get_session_status","set_session_mode","generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card","feedback","suggest_meme_templates","batch","discover_tools","execute_tool"];function Gk(){let e=new Set;for(let t of Kk)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of to)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var Y2=Gk();var Cu=new Set(["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"]);var Q2=new Set(to),e$=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...Cu,...to]);Ht();var G=R(require("fs")),F=R(require("path")),dy=R(require("os")),fe=dy.homedir(),Wk=["Claude_","Anthropic.ClaudeDesktop_"],Ss=class extends Error{constructor(n,r,s){super(zk(n,r,s));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function fy(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
188
188
  `)}function Yk(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=fy(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function zk(e,t,n){let r=t.replace(fe,"~"),s=fy(n).split(`
189
189
  `).find(Boolean),o=s?` (${s})`:"";return e.id==="codex"?`Could not update Codex MCP config at ${r}: filesystem access was denied${o}. In Codex, rerun with elevated filesystem access or run \`visa-cli install codex\` outside the sandbox.`:`Could not update ${e.displayName} MCP config at ${r}: filesystem access was denied${o}.`}function ko(){return process.env.APPDATA||F.join(fe,"AppData","Roaming")}function Jk(){return process.env.LOCALAPPDATA||F.join(fe,"AppData","Local")}function ku(e){return process.platform==="win32"?e.win32:e.posix}function py(){if(process.platform!=="win32")return;let e=F.join(Jk(),"Packages");if(G.existsSync(e))try{let t=G.readdirSync(e,"utf-8");for(let n of Wk){let r=t.filter(s=>s.startsWith(n)).sort()[0];if(r)return F.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function my(){if(process.platform==="win32"){let e=py();return e?F.join(e,"claude_desktop_config.json"):F.join(ko(),"Claude","claude_desktop_config.json")}return F.join(fe,"Library","Application Support","Claude","claude_desktop_config.json")}function gy(){if(process.platform!=="win32")return[F.join(fe,"Library","Application Support","Claude")];let e=[F.join(ko(),"Claude")],t=py();return t&&e.push(t),e}function Ra(e){return e.id==="claude-desktop"?my():e.globalConfigPath}function Xk(e){return e.id==="claude-desktop"?gy():e.detectPaths}var ft=[{id:"claude",displayName:"Claude Code",globalConfigPath:F.join(fe,".claude.json"),configKey:"mcpServers",detectPaths:[F.join(fe,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:my(),configKey:"mcpServers",detectPaths:gy(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:F.join(fe,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[F.join(fe,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:F.join(fe,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[F.join(fe,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:F.join(fe,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[F.join(fe,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:ku({win32:F.join(ko(),"Roo","mcp_settings.json"),posix:F.join(fe,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[F.join(fe,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:F.join(fe,".vscode","mcp.json"),configKey:"servers",detectPaths:[F.join(fe,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:ku({win32:F.join(ko(),"Zed","settings.json"),posix:F.join(fe,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:ku({win32:[F.join(ko(),"Zed")],posix:[F.join(fe,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:F.join(fe,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[F.join(fe,".codex")],postInstallHint:"Restart Codex to connect."}];function Eu(e){return ft.find(t=>t.id===e)}function Eo(e){return Xk(e).some(t=>{if(t.includes("*")){let n=F.dirname(t),r=F.basename(t).replaceAll("*","");if(!G.existsSync(n))return!1;try{return G.readdirSync(n).some(s=>s.startsWith(r))}catch{return!1}}return G.existsSync(t)})}function hy(){return{command:"node",args:[F.resolve(__dirname,"mcp-server/index.js")]}}function Au(e,t){return t==="project"?"json":e.configFormat??"json"}function Zk(e){if(e=e.trim(),e==="true")return!0;if(e==="false")return!1;if(e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);if(e.startsWith("[")&&e.endsWith("]")){let n=e.slice(1,-1).trim();return n.length===0?[]:n.split(",").map(r=>r.trim()).filter(Boolean).map(r=>r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1):r)}let t=Number(e);return isNaN(t)?e:t}function Ru(e,t){let n=`[mcp_servers.${t}]`,r=e.findIndex(o=>o.trim()===n);if(r===-1)return;let s=r+1;for(;s<e.length&&!e[s].trim().startsWith("[");)s++;return{start:r,end:s}}function Iu(e,t){let n=e.split(`
190
190
  `),r=Ru(n,t);if(!r)return;let s={};for(let o=r.start+1;o<r.end;o++){let i=n[o].trim().match(/^(\w+)\s*=\s*(.+)$/);i&&(s[i[1]]=Zk(i[2]))}return Object.keys(s).length>0?s:void 0}function Qk(e,t,n){let r=`[${n.args.map(c=>`"${c}"`).join(", ")}]`,s=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],o=e.split(`