@visa/cli 3.4.7-rc.1 → 3.4.8-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,16 +1,16 @@
1
- "use strict";var U_=Object.create;var Ko=Object.defineProperty;var D_=Object.getOwnPropertyDescriptor;var j_=Object.getOwnPropertyNames;var B_=Object.getPrototypeOf,F_=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 ec=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},Br=(e,t)=>{for(var n in t)Ko(e,n,{get:t[n],enumerable:!0})},Ad=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of j_(t))!F_.call(e,s)&&s!==n&&Ko(e,s,{get:()=>t[s],enumerable:!(r=D_(t,s))||r.enumerable});return e};var R=(e,t,n)=>(n=e!=null?U_(B_(e)):{},Ad(t||!e||!e.__esModule?Ko(n,"default",{value:e,enumerable:!0}):n,e)),H_=e=>Ad(Ko({},"__esModule",{value:!0}),e);var Us=ec((y1,tb)=>{tb.exports={name:"@visa/cli",version:"3.4.7-rc.1",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js",visa:"./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"},optionalDependencies:{libp2p:"^3.3.4","@libp2p/tcp":"^11.0.22","@libp2p/crypto":"^5.1.20","@chainsafe/libp2p-noise":"^17.0.0","@chainsafe/libp2p-yamux":"^8.0.1","@multiformats/multiaddr":"^13.0.3",uint8arrays:"^6.1.1"},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.1","@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.9.3","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 T0(){Be.existsSync(Uc)||Be.mkdirSync(Uc,{recursive:!0,mode:448})}function k0(){if(!Lc){if(T0(),Be.existsSync(Qs)&&Be.statSync(Qs).size>x0){let t=Qs+".1";Be.existsSync(t)&&Be.unlinkSync(t),Be.renameSync(Qs,t)}Lc=Be.createWriteStream(Qs,{flags:"a"})}return Lc}function A0(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function bi(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
- `;A0(e)&&process.stderr.write(s),k0().write(s)}var Be,Dc,sm,Uc,Qs,x0,Lc,h,wt=nt(()=>{"use strict";Be=R(require("fs")),Dc=R(require("path")),sm=R(require("os")),Uc=Dc.join(sm.homedir(),".visa-mcp"),Qs=Dc.join(Uc,"mcp-server.log"),x0=5*1024*1024,Lc=null;h={debug:(...e)=>bi("DEBUG",...e),info:(...e)=>bi("INFO",...e),warn:(...e)=>bi("WARN",...e),error:(...e)=>bi("ERROR",...e)}});var vi,cm,lm,jc,eo,um=nt(()=>{"use strict";vi=R(require("fs")),cm=R(require("path")),lm=R(require("os")),jc=cm.join(lm.homedir(),".visa-mcp"),eo=class{static ensureConfigDir(){vi.existsSync(jc)||vi.mkdirSync(jc,{recursive:!0,mode:448})}static getConfigDir(){return jc}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 dm(e){let t=fm.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function to(){return mm.join(eo.getConfigDir(),R0)}function pm(e){if((0,Hc.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function $0(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 pm(s)}function P0(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,Hc.isIP)(t);return n===4?pm(t):n===6?t==="::1"||$0(t):!1}function Bc(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:"&&P0(n.hostname)))throw new Error(`${t} ${I0}`)}function tr(){let e=to();if(!wn.existsSync(e))return{};try{let t=wn.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?(h.warn("settings:corrupt",{path:dm(e),reason:"not_object"}),{}):n}catch(t){return h.warn("settings:corrupt",{path:dm(e),error:t?.message||String(t)}),{}}}function Fc(e){eo.ensureConfigDir();let t=to(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
3
- `;wn.writeFileSync(n,r,{mode:384}),wn.renameSync(n,t)}function qc(e){let t=tr()[e];return typeof t=="string"?t:void 0}function Si(e){let t=tr()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function Kc(e){let t=tr()[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 xi(e,t){if(gm.some(o=>e.startsWith(o)))throw new Vt(e);if(e in wi)throw new vn(e);let n=nr[e];if(!n)throw new ot(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=tr();return s[e]=r,Fc(s),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:to()}}function Ti(e){if(gm.some(o=>e.startsWith(o)))throw new Vt(e);let t=nr[e];if(e in wi){let o=tr(),i=e in o;return i&&(delete o[e],Fc(o)),{key:e,removed:i,requiresRestart:!1,path:to()}}if(!t)throw new ot(e);let r=tr(),s=e in r;return s&&(delete r[e],Fc(r)),{key:e,removed:s,requiresRestart:s&&!!t.requiresRestart,path:to()}}function hm(){let e=tr();return Object.entries(wi).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}function N0(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function L0(){try{let e=Us();return N0(e.version)}catch{return!1}}function U0(e){return e.envVar!==void 0&&e.envVar!==""?(Bc(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(Bc(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?M0:O0}function $e(){return U0({envVar:process.env.VISA_AUTH_URL,settingValue:qc("auth.serverUrl"),isPrerelease:L0()})}function ym(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":Si("ui.suppressBrowser")??!1}function _m(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":Si("ui.suppressFeed")??!1}function bm(){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=Kc("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):Vc}var wn,Hc,fm,mm,R0,I0,nr,Vc,wi,ot,Vt,vn,gm,O0,M0,qt=nt(()=>{"use strict";wn=R(require("fs")),Hc=require("node:net"),fm=R(require("os")),mm=R(require("path"));um();wt();R0="settings.json",I0="must use https unless it points at localhost/loopback for local development";nr={"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");Bc(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)")}}},Vc=500,wi={"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."};ot=class extends Error{constructor(t){let n=Object.keys(nr).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"}},Vt=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"}},vn=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+wi[t]),this.name="RetiredSettingKeyError"}},gm=["biometric.","spending.","account.","cards.","biometric"];O0="https://auth.visacli.sh",M0="https://auth-visa-code-preview.up.railway.app"});var cp=ec(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.formatCents=ap;at.formatUsd=jw;at.formatMicros=Pi;at.formatMicrosWire=Bw;at.formatTxAmount=Fw;at.formatDate=Hw;at.formatRelativeTime=Vw;at.formatTime=qw;at.formatAge=Kw;var ip=1e6,Dw=100;function ap(e,t={}){let n=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return n;let s=(e/Dw).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${s}`:s}function jw(e,t={}){let n=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return n;let r=e.toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${r}`:r}function Pi(e,t={}){let n=t.fallback??"\u2014",r=typeof e=="string"?e===""?null:Number(e):e;if(r==null||!Number.isFinite(r))return n;let o=(r/ip).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??6});return t.showPlusSign&&r>0?`+${o}`:o}function Bw(e,t,n={}){return e&&/^-?\d+$/.test(e)?Pi(e,n):t!=null&&Number.isFinite(t)?ap(t,n):n.fallback??"\u2014"}function Fw(e,t={}){let n=Number(e.amount_micros);if(Number.isFinite(n)&&e.amount_micros!=null&&e.amount_micros!=="")return Pi(n,t);let r=Number(String(e.amount).replace(/^\$/,""));return Number.isFinite(r)?Pi(r*ip,t):t.fallback??"\u2014"}function Hw(e,t={}){let n=t.fallback??"\u2014";if(!e)return n;let r=new Date(e);return Number.isNaN(r.getTime())?n:r.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:t.timeZone??"UTC"})}function Vw(e,t=Date.now()){if(!e)return"\u2014";let n=Date.parse(e);if(Number.isNaN(n))return"\u2014";let r=t-n,s=r>=0,o=Math.abs(r),i=Math.floor(o/1e3),a=Math.floor(i/60),c=Math.floor(a/60),l=Math.floor(c/24),u=Math.floor(l/7),d=Math.floor(l/30),f=Math.floor(l/365);return i<45?"just now":a<1?s?"a minute ago":"in a minute":a<60?is(r,s,a,"minute"):c<24?is(r,s,c,"hour"):l===1?s?"yesterday":"tomorrow":l<7?is(r,s,l,"day"):u<4?is(r,s,u,"week"):d<12?is(r,s,d,"month"):is(r,s,f,"year")}function is(e,t,n,r){let s=n!==1?"s":"";return t?`${n} ${r}${s} ago`:`in ${n} ${r}${s}`}function qw(e,t={}){let n=t.fallback??"\u2014";if(!e)return n;let r=new Date(e);return Number.isNaN(r.getTime())?n:r.toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",timeZone:t.timeZone??"UTC"})}function Kw(e,t){if(!e)return"";let n=Date.parse(e);if(Number.isNaN(n))return"";let r=Math.max(0,t-n),s=Math.floor(r/1e3);if(s<45)return"just now";let o=Math.floor(s/60);if(o<60)return`${o}m ago`;let i=Math.floor(o/60);if(i<24)return`${i}h ago`;let a=Math.floor(i/24);if(a<30)return`${a}d ago`;let c=Math.floor(a/30);return c<12?`${c}mo ago`:`${Math.floor(a/365)}y ago`}});var as=ec(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.formatAge=K.formatTime=K.formatRelativeTime=K.formatDate=K.formatTxAmount=K.formatMicrosWire=K.formatMicros=K.formatUsd=K.formatCents=void 0;K.micros=Gw;K.fromCents=Ww;K.fromUsdc=Yw;K.fromUsd=zw;K.toCents=Jw;K.toCentsForAcquirer=Xw;K.toUsdc=Zw;K.toWire=Qw;K.fromWire=eS;K.toDisplay=tS;K.toUsdRounded2dp=nS;K.add=rS;K.sub=sS;K.clampNonNegative=oS;K.isNonNegative=iS;K.max=aS;K.min=cS;var zt=10000n,lp=1000000n;function Gw(e){return e}function Ww(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*zt}function Yw(e){return e}function zw(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function Jw(e){if(e>=0n)return Number(e/zt);let t=e/zt,n=e%zt;return Number(n===0n?t:t-1n)}function Xw(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/zt)}function Zw(e){return e}function Qw(e){return e.toString()}function eS(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 tS(e,t={}){let n=t.decimals??2,r=t.symbol??"$",s=e<0n,o=s?-e:e,i=o/lp,a=o%lp,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 nS(e){let t=e<0n,n=t?-e:e,r=n/zt,o=n%zt*2n,i;o<zt?i=r:o>zt?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function rS(e,t){return e+t}function sS(e,t){return e-t}function oS(e){return e<0n?0n:e}function iS(e){return e>=0n}function aS(e,t){return e>t?e:t}function cS(e,t){return e<t?e:t}var Jt=cp();Object.defineProperty(K,"formatCents",{enumerable:!0,get:function(){return Jt.formatCents}});Object.defineProperty(K,"formatUsd",{enumerable:!0,get:function(){return Jt.formatUsd}});Object.defineProperty(K,"formatMicros",{enumerable:!0,get:function(){return Jt.formatMicros}});Object.defineProperty(K,"formatMicrosWire",{enumerable:!0,get:function(){return Jt.formatMicrosWire}});Object.defineProperty(K,"formatTxAmount",{enumerable:!0,get:function(){return Jt.formatTxAmount}});Object.defineProperty(K,"formatDate",{enumerable:!0,get:function(){return Jt.formatDate}});Object.defineProperty(K,"formatRelativeTime",{enumerable:!0,get:function(){return Jt.formatRelativeTime}});Object.defineProperty(K,"formatTime",{enumerable:!0,get:function(){return Jt.formatTime}});Object.defineProperty(K,"formatAge",{enumerable:!0,get:function(){return Jt.formatAge}})});function El(e,t){switch(e){case"name_not_found":return new eg(t);case"delivery_failed":return new tg(t);case"timeout":return new yo(t);case"not_registered":return new ng;case"register_failed":return new Ji(t);case"invalid_message":return new rg(t);case"rate_limited":return new sg(t);default:return new Ct(e,t)}}var Ct,eg,tg,yo,ng,Me,rg,Ji,sg,Cl=nt(()=>{"use strict";Ct=class extends Error{code;constructor(e,t){super(t),this.name="SubwayError",this.code=e}},eg=class extends Ct{constructor(e){super("name_not_found",`Agent not registered: ${e}`),this.name="NameNotFoundError"}},tg=class extends Ct{constructor(e){super("delivery_failed",e),this.name="DeliveryFailedError"}},yo=class extends Ct{constructor(e="RPC call timed out"){super("timeout",e),this.name="TimeoutError"}},ng=class extends Ct{constructor(){super("not_registered","Client has not registered with the bridge"),this.name="NotRegisteredError"}},Me=class extends Ct{constructor(e){super("connection_failed",e),this.name="ConnectionError"}},rg=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"}},sg=class extends Ct{constructor(e="Rate limited"){super("rate_limited",e),this.name="RateLimitedError"}}});var og,Rl=nt(()=>{"use strict";og=(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')})});function Er(e){return e.includes(".")?e:`${e}.relay`}function Il(){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 FS(){if(typeof WebSocket<"u")return WebSocket;try{let e=og("ws");return e.default??e}catch{return}}function HS(e,t,n){return Math.min(Math.max(e,t),n)}function mx(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function qg(e,t,n=""){let r=mx(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 mg(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 px(e,t){qg(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 _o(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ml(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function It(e,t){return e<<32-t|e>>>t}function Kg(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 gx(e,t,n){return e&t^~e&n}function hx(e,t,n){return e&t^e&n^t&n}function yx(e,t=!1){return t?{h:Number(e&Xi),l:Number(e>>pg&Xi)}:{h:Number(e>>pg&Xi)|0,l:Number(e&Xi)|0}}function _x(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}=yx(e[o],t);[r[o],s[o]]=[i,a]}return[r,s]}function en(e,t,n,r){let s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}function Mx(e){return ix(e)}function Nx(e,t){return lx(t,e)}function Ux(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Bx(e){let t=Lx(Px(e.payload)),n=`${e.messageId}
1
+ "use strict";var D_=Object.create;var Go=Object.defineProperty;var j_=Object.getOwnPropertyDescriptor;var B_=Object.getOwnPropertyNames;var F_=Object.getPrototypeOf,H_=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 tc=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},Br=(e,t)=>{for(var n in t)Go(e,n,{get:t[n],enumerable:!0})},Cd=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of B_(t))!H_.call(e,s)&&s!==n&&Go(e,s,{get:()=>t[s],enumerable:!(r=j_(t,s))||r.enumerable});return e};var R=(e,t,n)=>(n=e!=null?D_(F_(e)):{},Cd(t||!e||!e.__esModule?Go(n,"default",{value:e,enumerable:!0}):n,e)),V_=e=>Cd(Go({},"__esModule",{value:!0}),e);var Us=tc((_1,nb)=>{nb.exports={name:"@visa/cli",version:"3.4.8-rc.0",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js",visa:"./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"},optionalDependencies:{libp2p:"^3.3.4","@libp2p/tcp":"^11.0.22","@libp2p/crypto":"^5.1.20","@chainsafe/libp2p-noise":"^17.0.0","@chainsafe/libp2p-yamux":"^8.0.1","@multiformats/multiaddr":"^13.0.3",uint8arrays:"^6.1.1"},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.1","@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.9.3","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 A0(){Be.existsSync(Dc)||Be.mkdirSync(Dc,{recursive:!0,mode:448})}function k0(){if(!Uc){if(A0(),Be.existsSync(Qs)&&Be.statSync(Qs).size>T0){let t=Qs+".1";Be.existsSync(t)&&Be.unlinkSync(t),Be.renameSync(Qs,t)}Uc=Be.createWriteStream(Qs,{flags:"a"})}return Uc}function C0(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function vi(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
+ `;C0(e)&&process.stderr.write(s),k0().write(s)}var Be,jc,om,Dc,Qs,T0,Uc,h,wt=nt(()=>{"use strict";Be=R(require("fs")),jc=R(require("path")),om=R(require("os")),Dc=jc.join(om.homedir(),".visa-mcp"),Qs=jc.join(Dc,"mcp-server.log"),T0=5*1024*1024,Uc=null;h={debug:(...e)=>vi("DEBUG",...e),info:(...e)=>vi("INFO",...e),warn:(...e)=>vi("WARN",...e),error:(...e)=>vi("ERROR",...e)}});var wi,lm,um,Bc,eo,dm=nt(()=>{"use strict";wi=R(require("fs")),lm=R(require("path")),um=R(require("os")),Bc=lm.join(um.homedir(),".visa-mcp"),eo=class{static ensureConfigDir(){wi.existsSync(Bc)||wi.mkdirSync(Bc,{recursive:!0,mode:448})}static getConfigDir(){return Bc}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 fm(e){let t=mm.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function to(){return pm.join(eo.getConfigDir(),I0)}function gm(e){if((0,Vc.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function $0(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 gm(s)}function O0(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,Vc.isIP)(t);return n===4?gm(t):n===6?t==="::1"||$0(t):!1}function Fc(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:"&&O0(n.hostname)))throw new Error(`${t} ${P0}`)}function tr(){let e=to();if(!wn.existsSync(e))return{};try{let t=wn.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?(h.warn("settings:corrupt",{path:fm(e),reason:"not_object"}),{}):n}catch(t){return h.warn("settings:corrupt",{path:fm(e),error:t?.message||String(t)}),{}}}function Hc(e){eo.ensureConfigDir();let t=to(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
3
+ `;wn.writeFileSync(n,r,{mode:384}),wn.renameSync(n,t)}function Kc(e){let t=tr()[e];return typeof t=="string"?t:void 0}function xi(e){let t=tr()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function Gc(e){let t=tr()[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 Ti(e,t){if(hm.some(o=>e.startsWith(o)))throw new Vt(e);if(e in Si)throw new vn(e);let n=nr[e];if(!n)throw new ot(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=tr();return s[e]=r,Hc(s),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:to()}}function Ai(e){if(hm.some(o=>e.startsWith(o)))throw new Vt(e);let t=nr[e];if(e in Si){let o=tr(),i=e in o;return i&&(delete o[e],Hc(o)),{key:e,removed:i,requiresRestart:!1,path:to()}}if(!t)throw new ot(e);let r=tr(),s=e in r;return s&&(delete r[e],Hc(r)),{key:e,removed:s,requiresRestart:s&&!!t.requiresRestart,path:to()}}function ym(){let e=tr();return Object.entries(Si).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}function L0(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function U0(){try{let e=Us();return L0(e.version)}catch{return!1}}function D0(e){return e.envVar!==void 0&&e.envVar!==""?(Fc(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(Fc(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?N0:M0}function Pe(){return D0({envVar:process.env.VISA_AUTH_URL,settingValue:Kc("auth.serverUrl"),isPrerelease:U0()})}function _m(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":xi("ui.suppressBrowser")??!1}function bm(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":xi("ui.suppressFeed")??!1}function vm(){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=Gc("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):qc}var wn,Vc,mm,pm,I0,P0,nr,qc,Si,ot,Vt,vn,hm,M0,N0,qt=nt(()=>{"use strict";wn=R(require("fs")),Vc=require("node:net"),mm=R(require("os")),pm=R(require("path"));dm();wt();I0="settings.json",P0="must use https unless it points at localhost/loopback for local development";nr={"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");Fc(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)")}}},qc=500,Si={"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."};ot=class extends Error{constructor(t){let n=Object.keys(nr).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"}},Vt=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"}},vn=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+Si[t]),this.name="RetiredSettingKeyError"}},hm=["biometric.","spending.","account.","cards.","biometric"];M0="https://auth.visacli.sh",N0="https://auth-visa-code-preview.up.railway.app"});var lp=tc(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.formatCents=cp;at.formatUsd=Bw;at.formatMicros=Oi;at.formatMicrosWire=Fw;at.formatTxAmount=Hw;at.formatDate=Vw;at.formatRelativeTime=qw;at.formatTime=Kw;at.formatAge=Gw;var ap=1e6,jw=100;function cp(e,t={}){let n=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return n;let s=(e/jw).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${s}`:s}function Bw(e,t={}){let n=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return n;let r=e.toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${r}`:r}function Oi(e,t={}){let n=t.fallback??"\u2014",r=typeof e=="string"?e===""?null:Number(e):e;if(r==null||!Number.isFinite(r))return n;let o=(r/ap).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??6});return t.showPlusSign&&r>0?`+${o}`:o}function Fw(e,t,n={}){return e&&/^-?\d+$/.test(e)?Oi(e,n):t!=null&&Number.isFinite(t)?cp(t,n):n.fallback??"\u2014"}function Hw(e,t={}){let n=Number(e.amount_micros);if(Number.isFinite(n)&&e.amount_micros!=null&&e.amount_micros!=="")return Oi(n,t);let r=Number(String(e.amount).replace(/^\$/,""));return Number.isFinite(r)?Oi(r*ap,t):t.fallback??"\u2014"}function Vw(e,t={}){let n=t.fallback??"\u2014";if(!e)return n;let r=new Date(e);return Number.isNaN(r.getTime())?n:r.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:t.timeZone??"UTC"})}function qw(e,t=Date.now()){if(!e)return"\u2014";let n=Date.parse(e);if(Number.isNaN(n))return"\u2014";let r=t-n,s=r>=0,o=Math.abs(r),i=Math.floor(o/1e3),a=Math.floor(i/60),c=Math.floor(a/60),l=Math.floor(c/24),u=Math.floor(l/7),d=Math.floor(l/30),f=Math.floor(l/365);return i<45?"just now":a<1?s?"a minute ago":"in a minute":a<60?is(r,s,a,"minute"):c<24?is(r,s,c,"hour"):l===1?s?"yesterday":"tomorrow":l<7?is(r,s,l,"day"):u<4?is(r,s,u,"week"):d<12?is(r,s,d,"month"):is(r,s,f,"year")}function is(e,t,n,r){let s=n!==1?"s":"";return t?`${n} ${r}${s} ago`:`in ${n} ${r}${s}`}function Kw(e,t={}){let n=t.fallback??"\u2014";if(!e)return n;let r=new Date(e);return Number.isNaN(r.getTime())?n:r.toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",timeZone:t.timeZone??"UTC"})}function Gw(e,t){if(!e)return"";let n=Date.parse(e);if(Number.isNaN(n))return"";let r=Math.max(0,t-n),s=Math.floor(r/1e3);if(s<45)return"just now";let o=Math.floor(s/60);if(o<60)return`${o}m ago`;let i=Math.floor(o/60);if(i<24)return`${i}h ago`;let a=Math.floor(i/24);if(a<30)return`${a}d ago`;let c=Math.floor(a/30);return c<12?`${c}mo ago`:`${Math.floor(a/365)}y ago`}});var as=tc(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.formatAge=K.formatTime=K.formatRelativeTime=K.formatDate=K.formatTxAmount=K.formatMicrosWire=K.formatMicros=K.formatUsd=K.formatCents=void 0;K.micros=Ww;K.fromCents=Yw;K.fromUsdc=zw;K.fromUsd=Jw;K.toCents=Xw;K.toCentsForAcquirer=Zw;K.toUsdc=Qw;K.toWire=eS;K.fromWire=tS;K.toDisplay=nS;K.toUsdRounded2dp=rS;K.add=sS;K.sub=oS;K.clampNonNegative=iS;K.isNonNegative=aS;K.max=cS;K.min=lS;var zt=10000n,up=1000000n;function Ww(e){return e}function Yw(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*zt}function zw(e){return e}function Jw(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function Xw(e){if(e>=0n)return Number(e/zt);let t=e/zt,n=e%zt;return Number(n===0n?t:t-1n)}function Zw(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/zt)}function Qw(e){return e}function eS(e){return e.toString()}function tS(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 nS(e,t={}){let n=t.decimals??2,r=t.symbol??"$",s=e<0n,o=s?-e:e,i=o/up,a=o%up,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 rS(e){let t=e<0n,n=t?-e:e,r=n/zt,o=n%zt*2n,i;o<zt?i=r:o>zt?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function sS(e,t){return e+t}function oS(e,t){return e-t}function iS(e){return e<0n?0n:e}function aS(e){return e>=0n}function cS(e,t){return e>t?e:t}function lS(e,t){return e<t?e:t}var Jt=lp();Object.defineProperty(K,"formatCents",{enumerable:!0,get:function(){return Jt.formatCents}});Object.defineProperty(K,"formatUsd",{enumerable:!0,get:function(){return Jt.formatUsd}});Object.defineProperty(K,"formatMicros",{enumerable:!0,get:function(){return Jt.formatMicros}});Object.defineProperty(K,"formatMicrosWire",{enumerable:!0,get:function(){return Jt.formatMicrosWire}});Object.defineProperty(K,"formatTxAmount",{enumerable:!0,get:function(){return Jt.formatTxAmount}});Object.defineProperty(K,"formatDate",{enumerable:!0,get:function(){return Jt.formatDate}});Object.defineProperty(K,"formatRelativeTime",{enumerable:!0,get:function(){return Jt.formatRelativeTime}});Object.defineProperty(K,"formatTime",{enumerable:!0,get:function(){return Jt.formatTime}});Object.defineProperty(K,"formatAge",{enumerable:!0,get:function(){return Jt.formatAge}})});function El(e,t){switch(e){case"name_not_found":return new tg(t);case"delivery_failed":return new ng(t);case"timeout":return new _o(t);case"not_registered":return new rg;case"register_failed":return new Xi(t);case"invalid_message":return new sg(t);case"rate_limited":return new og(t);default:return new Et(e,t)}}var Et,tg,ng,_o,rg,Me,sg,Xi,og,Rl=nt(()=>{"use strict";Et=class extends Error{code;constructor(e,t){super(t),this.name="SubwayError",this.code=e}},tg=class extends Et{constructor(e){super("name_not_found",`Agent not registered: ${e}`),this.name="NameNotFoundError"}},ng=class extends Et{constructor(e){super("delivery_failed",e),this.name="DeliveryFailedError"}},_o=class extends Et{constructor(e="RPC call timed out"){super("timeout",e),this.name="TimeoutError"}},rg=class extends Et{constructor(){super("not_registered","Client has not registered with the bridge"),this.name="NotRegisteredError"}},Me=class extends Et{constructor(e){super("connection_failed",e),this.name="ConnectionError"}},sg=class extends Et{constructor(e){super("invalid_message",e),this.name="InvalidMessageError"}},Xi=class extends Et{constructor(e){super("register_failed",e),this.name="RegisterFailedError"}},og=class extends Et{constructor(e="Rate limited"){super("rate_limited",e),this.name="RateLimitedError"}}});var ig,Il=nt(()=>{"use strict";ig=(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')})});function Cr(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 HS(){if(typeof WebSocket<"u")return WebSocket;try{let e=ig("ws");return e.default??e}catch{return}}function VS(e,t,n){return Math.min(Math.max(e,t),n)}function px(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Kg(e,t,n=""){let r=px(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 pg(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 gx(e,t){Kg(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 bo(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Nl(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function It(e,t){return e<<32-t|e>>>t}function Gg(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 hx(e,t,n){return e&t^~e&n}function yx(e,t,n){return e&t^e&n^t&n}function _x(e,t=!1){return t?{h:Number(e&Zi),l:Number(e>>gg&Zi)}:{h:Number(e>>gg&Zi)|0,l:Number(e&Zi)|0}}function bx(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}=_x(e[o],t);[r[o],s[o]]=[i,a]}return[r,s]}function en(e,t,n,r){let s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}function Nx(e){return ax(e)}function Lx(e,t){return ux(t,e)}function Dx(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Fx(e){let t=Ux(Ox(e.payload)),n=`${e.messageId}
4
4
  ${e.senderPeerId}
5
5
  ${e.senderName}
6
6
  ${e.timestampMs}
7
7
  ${e.messageType}
8
8
  ${t}
9
- ${e.nonce}`;return Dx.encode(n)}function Fx(e,t,n,r,s,o,i){return Bx({messageId:e,senderPeerId:t,senderName:n,timestampMs:r,messageType:s,payload:o,nonce:i})}function Hx(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 dT(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function ch(e,t,n=""){let r=dT(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 kg(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 fT(e,t){ch(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 ql(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Dl(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function mT(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 hT(e,t=!1){return t?{h:Number(e&ea),l:Number(e>>Ag&ea)}:{h:Number(e>>Ag&ea)|0,l:Number(e&ea)|0}}function yT(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}=hT(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 RT(){return aT.randomSecretKey()}function uh(e){return oT(e)}function IT(){let e=RT();return{secretKey:e,publicKey:uh(e)}}function $T(e){if((0,Fn.existsSync)(e)){let n=(0,Fn.readFileSync)(e),r=new Uint8Array(n.buffer.slice(n.byteOffset,n.byteOffset+32));return{secretKey:r,publicKey:uh(r)}}let t=IT();return(0,Fn.mkdirSync)((0,$g.dirname)(e),{recursive:!0}),(0,Fn.writeFileSync)(e,new Uint8Array(t.secretKey)),t}function PT(e){let{secretKey:t,publicKey:n}=$T(e);return{privateKey:t,publicKey:n}}async function OT(e,t,n,r,s,o,i,a){let c=Fx(t,n,r,s,o,i,a);return{signature:await Nx(e,c),signatureInput:jx.subwayAgentMsgV1}}function Ig(e){return Ux(e)}var Fn,$g,VS,qS,KS,GS,WS,Pg,oa,ra,ig,ag,$l,Pl,YS,da,zS,Ae,JS,XS,ZS,rn,fa,Kl,Og,Gl,Qt,cg,Wl,Mg,QS,ms,ex,ia,xr,oe,lg,$,Ng,Lg,Ug,Dg,Ol,jl,bo,Ir,Cr,jg,Bg,Rt,tx,ug,nx,Bl,Yl,rx,Fg,sx,ox,ix,ax,cx,lx,zl,Hg,aa,ux,Vg,Fl,dx,dg,fg,fx,Gg,Wg,Nn,Ne,Xi,pg,gg,hg,ls,us,Zi,Qi,bx,vx,wx,Sx,xx,Tx,kx,Ln,Ax,Ex,Yg,Cx,Rx,Un,Dn,Ix,$x,Px,Ox,yg,Lx,zg,Dx,jx,Jg,ca,sa,_g,bg,Nl,Ll,Vx,ps,qx,Ee,Kx,Gx,Wx,Hn,ma,Jl,Xg,Zg,tn,vg,Qg,eh,Yx,Xl,zx,la,kr,ae,wg,P,Jx,Xx,th,nh,Ul,Hl,vo,gs,Rr,Zx,rh,$t,Qx,Sg,eT,tT,nT,rT,sh,sT,oh,oT,ih,iT,aT,ua,cT,ah,Vl,lT,xg,Tg,uT,pT,gT,Le,ea,Ag,Eg,Cg,ds,fs,ta,na,_T,bT,vT,wT,ST,xT,lh,TT,kT,jn,Bn,AT,ET,CT,Rg,MT,NT,dh,Zl=nt(()=>{"use strict";Cl();Cl();Rl();Fn=require("fs"),$g=require("path");VS=1e3,qS=10,KS=3e4,GS=3e4,WS=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??VS,this.maxReconnectAttempts=e.maxReconnectAttempts??qS,this.pingInterval=e.pingInterval??KS}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=FS();if(!n){t(new Me('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 Me(`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 Me("WebSocket closed before connection established")))},this.ws.onerror=()=>{r||(r=!0,t(new Me(`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 Me("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=HS(this.reconnectInterval*Math.pow(2,this.reconnectAttempt),this.reconnectInterval,GS);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)}}},Pg=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:oa,n:ra,Gx:ig,Gy:ag,a:$l,d:Pl,h:YS}=Pg,da=32,zS=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},Ae=(e="")=>{let t=new Error(e);throw zS(t,Ae),t},JS=e=>typeof e=="bigint",XS=e=>typeof e=="string",ZS=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,rn=(e,t,n="")=>{let r=ZS(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},fa=e=>new Uint8Array(e),Kl=e=>Uint8Array.from(e),Og=(e,t)=>e.toString(16).padStart(t,"0"),Gl=e=>Array.from(rn(e)).map(t=>Og(t,2)).join(""),Qt={_0:48,_9:57,A:65,F:70,a:97,f:102},cg=e=>{if(e>=Qt._0&&e<=Qt._9)return e-Qt._0;if(e>=Qt.A&&e<=Qt.F)return e-(Qt.A-10);if(e>=Qt.a&&e<=Qt.f)return e-(Qt.a-10)},Wl=e=>{let t="hex invalid";if(!XS(e))return Ae(t);let n=e.length,r=n/2;if(n%2)return Ae(t);let s=fa(r);for(let o=0,i=0;o<r;o++,i+=2){let a=cg(e.charCodeAt(i)),c=cg(e.charCodeAt(i+1));if(a===void 0||c===void 0)return Ae(t);s[o]=a*16+c}return s},Mg=()=>globalThis?.crypto,QS=()=>Mg()?.subtle??Ae("crypto.subtle must be defined, consider polyfill"),ms=(...e)=>{let t=0;for(let s of e)t+=rn(s).length;let n=fa(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},ex=(e=da)=>Mg().getRandomValues(fa(e)),ia=BigInt,xr=(e,t,n,r="bad number: out of range")=>{if(!JS(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},oe=(e,t=oa)=>{let n=e%t;return n>=0n?n:t+n},lg=(1n<<255n)-1n,$=e=>{e<0n&&Ae("negative coordinate");let t=(e>>255n)*19n+(e&lg);return t=(t>>255n)*19n+(t&lg),t%oa},Ng=e=>oe(e,ra),Lg=(e,t)=>{(e===0n||t<=0n)&&Ae("no inverse n="+e+" mod="+t);let n=oe(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?oe(s,t):Ae("no inverse")},Ug=e=>{let t=Hg[e];return typeof t!="function"&&Ae("hashes."+e+" not set"),t},Dg=e=>rn(e,64,"digest"),Ol=e=>e instanceof bo?e:Ae("Point expected"),jl=2n**256n,bo=class Tr{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=jl;this.X=xr(t,0n,o),this.Y=xr(n,0n,o),this.Z=xr(r,1n,o),this.T=xr(s,0n,o),Object.freeze(this)}static CURVE(){return Pg}static fromAffine(t){return new Tr(t.x,t.y,1n,$(t.x*t.y))}static fromBytes(t,n=!1){let r=Pl,s=Kl(rn(t,da)),o=t[31];s[31]=o&-129;let i=Bg(s);xr(i,0n,n?jl:oa);let c=$(i*i),l=oe(c-1n),u=$(r*c+1n),{isValid:d,value:f}=nx(l,u);d||Ae("bad point: y not sqrt");let m=(f&1n)===1n,p=(o&128)!==0;return!n&&f===0n&&p&&Ae("bad point: x==0, isLastByteOdd"),p!==m&&(f=oe(-f)),new Tr(f,i,1n,$(f*i))}static fromHex(t,n){return Tr.fromBytes(Wl(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=$l,n=Pl,r=this;if(r.is0())return Ae("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),f=$(c*t),m=$(u*(f+l)),p=oe(d+$(n*$(c*l)));if(m!==p)return Ae("bad point: equation left != right (1)");let g=$(s*o),v=$(i*a);return g!==v?Ae("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=Ol(t),c=$(n*a),l=$(o*s),u=$(r*a),d=$(i*s);return c===l&&u===d}is0(){return this.equals(Cr)}negate(){return new Tr(oe(-this.X),this.Y,this.Z,oe(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=$l,o=$(t*t),i=$(n*n),a=$(2n*r*r),c=$(s*o),l=oe(t+n),u=oe($(l*l)-o-i),d=oe(c+i),f=oe(d-a),m=oe(c-i),p=$(u*f),g=$(d*m),v=$(u*m),k=$(f*d);return new Tr(p,g,k,v)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=Ol(t),u=$l,d=Pl,f=$(n*i),m=$(r*a),p=$($(o*d)*l),g=$(s*c),v=oe($(oe(n+r)*oe(i+a))-f-m),k=oe(g-p),b=oe(g+p),w=oe(m-$(u*f)),S=$(v*k),C=$(b*w),I=$(v*w),y=$(k*b);return new Tr(S,C,y,I)}subtract(t){return this.add(Ol(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(xr(t,1n,ra),!n&&this.is0()))return Cr;if(t===1n)return this;if(this.equals(Ir))return fx(t).p;let r=Cr,s=Ir;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(Cr))return{x:0n,y:1n};let s=Lg(r,oa);$(r*s)!==1n&&Ae("invalid inverse");let o=$(t*s),i=$(n*s);return{x:o,y:i}}toBytes(){let{x:t,y:n}=this.toAffine(),r=jg(n);return r[31]|=t&1n?128:0,r}toHex(){return Gl(this.toBytes())}clearCofactor(){return this.multiply(ia(YS),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(ra/2n,!1).double();return ra%2n&&(t=t.add(this)),t.is0()}},Ir=new bo(ig,ag,1n,oe(ig*ag)),Cr=new bo(0n,1n,1n,0n);bo.BASE=Ir;bo.ZERO=Cr;jg=e=>Wl(Og(xr(e,0n,jl),64)).reverse(),Bg=e=>ia("0x"+Gl(Kl(rn(e)).reverse())),Rt=(e,t)=>{let n=e;for(;t-- >0n;)n=$(n*n);return n},tx=e=>{let t=$(e*e),n=$(t*e),r=$(Rt(n,2n)*n),s=$(Rt(r,1n)*e),o=$(Rt(s,5n)*s),i=$(Rt(o,10n)*o),a=$(Rt(i,20n)*i),c=$(Rt(a,40n)*a),l=$(Rt(c,80n)*c),u=$(Rt(l,80n)*c),d=$(Rt(u,10n)*o);return{pow_p_5_8:$(Rt(d,2n)*e),b2:n}},ug=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,nx=(e,t)=>{let n=$(t*$(t*t)),r=$($(n*n)*t),s=tx($(e*r)).pow_p_5_8,o=$(e*$(n*s)),i=$(t*$(o*o)),a=o,c=$(o*ug),l=i===e,u=i===oe(-e),d=i===oe(-e*ug);return l&&(o=a),(u||d)&&(o=c),(oe(o)&1n)===1n&&(o=oe(-o)),{isValid:l||u,value:o}},Bl=e=>Ng(Bg(e)),Yl=(...e)=>Promise.resolve(Ug("sha512Async")(ms(...e))).then(Dg),rx=(...e)=>Dg(Ug("sha512")(ms(...e))),Fg=e=>{let t=Kl(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=Bl(n),o=Ir.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},sx=e=>Yl(rn(e,da)).then(Fg),ox=e=>Fg(rx(rn(e,da))),ix=e=>ox(e).pointBytes,ax=e=>Yl(e.hashable).then(e.finish),cx=(e,t,n)=>{let{pointBytes:r,scalar:s}=e,o=Bl(t),i=Ir.multiply(o).toBytes();return{hashable:ms(i,r,n),finish:l=>{let u=Ng(o+Bl(l)*s);return rn(ms(i,jg(u)),64)}}},lx=async(e,t)=>{let n=rn(e),r=await sx(t),s=await Yl(r.prefix,n);return ax(cx(r,s,n))},zl=Object.freeze({bytesToHex:Gl,hexToBytes:Wl,concatBytes:ms,mod:oe,invert:Lg,randomBytes:ex}),Hg={sha512Async:async e=>{let t=QS(),n=ms(e);return fa(await t.digest("SHA-512",n.buffer))},sha512:void 0},aa=8,ux=256,Vg=Math.ceil(ux/aa)+1,Fl=2**(aa-1),dx=()=>{let e=[],t=Ir,n=t;for(let r=0;r<Vg;r++){n=t,e.push(n);for(let s=1;s<Fl;s++)n=n.add(t),e.push(n);t=n.double()}return e},dg=void 0,fg=(e,t)=>{let n=t.negate();return e?n:t},fx=e=>{let t=dg||(dg=dx()),n=Cr,r=Ir,s=2**aa,o=s,i=ia(s-1),a=ia(aa);for(let c=0;c<Vg;c++){let l=Number(e&i);e>>=a,l>Fl&&(l-=o,e+=1n);let u=c*Fl,d=u,f=u+Math.abs(l)-1,m=c%2!==0,p=l<0;l===0?r=r.add(fg(m,t[d])):n=n.add(fg(p,t[f]))}return e!==0n&&Ae("invalid wnaf"),{p:n,f:r}};Gg=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});Wg=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=Ml(this.buffer)}update(e){mg(this),qg(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=Ml(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){mg(this),px(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,_o(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=Ml(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()}},Nn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ne=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Xi=BigInt(2**32-1),pg=BigInt(32);gg=(e,t,n)=>e>>>n,hg=(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,Zi=(e,t,n)=>e<<64-n|t>>>n-32,Qi=(e,t,n)=>e>>>n-32|t<<64-n;bx=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),vx=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,wx=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Sx=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,xx=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),Tx=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,kx=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]),Ln=new Uint32Array(64),Ax=class extends Wg{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)Ln[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let d=Ln[u-15],f=Ln[u-2],m=It(d,7)^It(d,18)^d>>>3,p=It(f,17)^It(f,19)^f>>>10;Ln[u]=p+Ln[u-7]+m+Ln[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=It(i,6)^It(i,11)^It(i,25),f=l+d+gx(i,a,c)+kx[u]+Ln[u]|0,p=(It(n,2)^It(n,13)^It(n,22))+hx(n,r,s)|0;l=c,c=a,a=i,i=o+f|0,o=s,s=r,r=n,n=f+p|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(){_o(Ln)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),_o(this.buffer)}},Ex=class extends Ax{A=Nn[0]|0;B=Nn[1]|0;C=Nn[2]|0;D=Nn[3]|0;E=Nn[4]|0;F=Nn[5]|0;G=Nn[6]|0;H=Nn[7]|0;constructor(){super(32)}},Yg=_x(["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))),Cx=Yg[0],Rx=Yg[1],Un=new Uint32Array(80),Dn=new Uint32Array(80),Ix=class extends Wg{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:f,Gl:m,Hh:p,Hl:g}=this;return[e,t,n,r,s,o,i,a,c,l,u,d,f,m,p,g]}set(e,t,n,r,s,o,i,a,c,l,u,d,f,m,p,g){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=f|0,this.Gl=m|0,this.Hh=p|0,this.Hl=g|0}process(e,t){for(let b=0;b<16;b++,t+=4)Un[b]=e.getUint32(t),Dn[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let w=Un[b-15]|0,S=Dn[b-15]|0,C=ls(w,S,1)^ls(w,S,8)^gg(w,S,7),I=us(w,S,1)^us(w,S,8)^hg(w,S,7),y=Un[b-2]|0,T=Dn[b-2]|0,z=ls(y,T,19)^Zi(y,T,61)^gg(y,T,6),Z=us(y,T,19)^Qi(y,T,61)^hg(y,T,6),H=wx(I,Z,Dn[b-7],Dn[b-16]),be=Sx(H,C,z,Un[b-7],Un[b-16]);Un[b]=be|0,Dn[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:f,Fl:m,Gh:p,Gl:g,Hh:v,Hl:k}=this;for(let b=0;b<80;b++){let w=ls(u,d,14)^ls(u,d,18)^Zi(u,d,41),S=us(u,d,14)^us(u,d,18)^Qi(u,d,41),C=u&f^~u&p,I=d&m^~d&g,y=xx(k,S,I,Rx[b],Dn[b]),T=Tx(y,v,w,C,Cx[b],Un[b]),z=y|0,Z=ls(n,r,28)^Zi(n,r,34)^Zi(n,r,39),H=us(n,r,28)^Qi(n,r,34)^Qi(n,r,39),be=n&s^n&i^s&i,se=r&o^r&a^o&a;v=p|0,k=g|0,p=f|0,g=m|0,f=u|0,m=d|0,{h:u,l:d}=en(c|0,l|0,T|0,z|0),c=i|0,l=a|0,i=s|0,a=o|0,s=n|0,o=r|0;let X=bx(z,H,se);n=vx(X,T,Z,be),r=X|0}({h:n,l:r}=en(this.Ah|0,this.Al|0,n|0,r|0)),{h:s,l:o}=en(this.Bh|0,this.Bl|0,s|0,o|0),{h:i,l:a}=en(this.Ch|0,this.Cl|0,i|0,a|0),{h:c,l}=en(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=en(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:m}=en(this.Fh|0,this.Fl|0,f|0,m|0),{h:p,l:g}=en(this.Gh|0,this.Gl|0,p|0,g|0),{h:v,l:k}=en(this.Hh|0,this.Hl|0,v|0,k|0),this.set(n,r,s,o,i,a,c,l,u,d,f,m,p,g,v,k)}roundClean(){_o(Un,Dn)}destroy(){this.destroyed=!0,_o(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},$x=class extends Ix{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)}},Px=Kg(()=>new Ex,Gg(1)),Ox=Kg(()=>new $x,Gg(3)),yg=Hg;yg.sha512||(yg.sha512=e=>Ox(e));Lx=zl.bytesToHex,zg=zl.hexToBytes;zl.concatBytes;Dx=new TextEncoder,jx={subwayAgentMsgV1:"message_id;sender_peer_id;sender_name;timestamp_ms;message_type;payload_hash;nonce"};zg("302e020100300506032b657004220420");zg("302a300506032b6570032100");Jg=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:ca,n:sa,Gx:_g,Gy:bg,a:Nl,d:Ll,h:Vx}=Jg,ps=32,qx=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},Ee=(e="")=>{let t=new Error(e);throw qx(t,Ee),t},Kx=e=>typeof e=="bigint",Gx=e=>typeof e=="string",Wx=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,Hn=(e,t,n="")=>{let r=Wx(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},ma=e=>new Uint8Array(e),Jl=e=>Uint8Array.from(e),Xg=(e,t)=>e.toString(16).padStart(t,"0"),Zg=e=>Array.from(Hn(e)).map(t=>Xg(t,2)).join(""),tn={_0:48,_9:57,A:65,F:70,a:97,f:102},vg=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)},Qg=e=>{let t="hex invalid";if(!Gx(e))return Ee(t);let n=e.length,r=n/2;if(n%2)return Ee(t);let s=ma(r);for(let o=0,i=0;o<r;o++,i+=2){let a=vg(e.charCodeAt(i)),c=vg(e.charCodeAt(i+1));if(a===void 0||c===void 0)return Ee(t);s[o]=a*16+c}return s},eh=()=>globalThis?.crypto,Yx=()=>eh()?.subtle??Ee("crypto.subtle must be defined, consider polyfill"),Xl=(...e)=>{let t=0;for(let s of e)t+=Hn(s).length;let n=ma(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},zx=(e=ps)=>eh().getRandomValues(ma(e)),la=BigInt,kr=(e,t,n,r="bad number: out of range")=>{if(!Kx(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},ae=(e,t=ca)=>{let n=e%t;return n>=0n?n:t+n},wg=(1n<<255n)-1n,P=e=>{e<0n&&Ee("negative coordinate");let t=(e>>255n)*19n+(e&wg);return t=(t>>255n)*19n+(t&wg),t%ca},Jx=e=>ae(e,sa),Xx=(e,t)=>{(e===0n||t<=0n)&&Ee("no inverse n="+e+" mod="+t);let n=ae(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?ae(s,t):Ee("no inverse")},th=e=>{let t=ih[e];return typeof t!="function"&&Ee("hashes."+e+" not set"),t},nh=e=>Hn(e,64,"digest"),Ul=e=>e instanceof vo?e:Ee("Point expected"),Hl=2n**256n,vo=class Ar{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=Hl;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 Jg}static fromAffine(t){return new Ar(t.x,t.y,1n,P(t.x*t.y))}static fromBytes(t,n=!1){let r=Ll,s=Jl(Hn(t,ps)),o=t[31];s[31]=o&-129;let i=rh(s);kr(i,0n,n?Hl:ca);let c=P(i*i),l=ae(c-1n),u=P(r*c+1n),{isValid:d,value:f}=eT(l,u);d||Ee("bad point: y not sqrt");let m=(f&1n)===1n,p=(o&128)!==0;return!n&&f===0n&&p&&Ee("bad point: x==0, isLastByteOdd"),p!==m&&(f=ae(-f)),new Ar(f,i,1n,P(f*i))}static fromHex(t,n){return Ar.fromBytes(Qg(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Nl,n=Ll,r=this;if(r.is0())return Ee("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),f=P(c*t),m=P(u*(f+l)),p=ae(d+P(n*P(c*l)));if(m!==p)return Ee("bad point: equation left != right (1)");let g=P(s*o),v=P(i*a);return g!==v?Ee("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=Ul(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(Rr)}negate(){return new Ar(ae(-this.X),this.Y,this.Z,ae(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=Nl,o=P(t*t),i=P(n*n),a=P(2n*r*r),c=P(s*o),l=ae(t+n),u=ae(P(l*l)-o-i),d=ae(c+i),f=ae(d-a),m=ae(c-i),p=P(u*f),g=P(d*m),v=P(u*m),k=P(f*d);return new Ar(p,g,k,v)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=Ul(t),u=Nl,d=Ll,f=P(n*i),m=P(r*a),p=P(P(o*d)*l),g=P(s*c),v=ae(P(ae(n+r)*ae(i+a))-f-m),k=ae(g-p),b=ae(g+p),w=ae(m-P(u*f)),S=P(v*k),C=P(b*w),I=P(v*w),y=P(k*b);return new Ar(S,C,y,I)}subtract(t){return this.add(Ul(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(kr(t,1n,sa),!n&&this.is0()))return Rr;if(t===1n)return this;if(this.equals(gs))return uT(t).p;let r=Rr,s=gs;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(Rr))return{x:0n,y:1n};let s=Xx(r,ca);P(r*s)!==1n&&Ee("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=Zx(n);return r[31]|=t&1n?128:0,r}toHex(){return Zg(this.toBytes())}clearCofactor(){return this.multiply(la(Vx),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(sa/2n,!1).double();return sa%2n&&(t=t.add(this)),t.is0()}},gs=new vo(_g,bg,1n,ae(_g*bg)),Rr=new vo(0n,1n,1n,0n);vo.BASE=gs;vo.ZERO=Rr;Zx=e=>Qg(Xg(kr(e,0n,Hl),64)).reverse(),rh=e=>la("0x"+Zg(Jl(Hn(e)).reverse())),$t=(e,t)=>{let n=e;for(;t-- >0n;)n=P(n*n);return n},Qx=e=>{let t=P(e*e),n=P(t*e),r=P($t(n,2n)*n),s=P($t(r,1n)*e),o=P($t(s,5n)*s),i=P($t(o,10n)*o),a=P($t(i,20n)*i),c=P($t(a,40n)*a),l=P($t(c,80n)*c),u=P($t(l,80n)*c),d=P($t(u,10n)*o);return{pow_p_5_8:P($t(d,2n)*e),b2:n}},Sg=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,eT=(e,t)=>{let n=P(t*P(t*t)),r=P(P(n*n)*t),s=Qx(P(e*r)).pow_p_5_8,o=P(e*P(n*s)),i=P(t*P(o*o)),a=o,c=P(o*Sg),l=i===e,u=i===ae(-e),d=i===ae(-e*Sg);return l&&(o=a),(u||d)&&(o=c),(ae(o)&1n)===1n&&(o=ae(-o)),{isValid:l||u,value:o}},tT=e=>Jx(rh(e)),nT=(...e)=>Promise.resolve(th("sha512Async")(Xl(...e))).then(nh),rT=(...e)=>nh(th("sha512")(Xl(...e))),sh=e=>{let t=Jl(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=tT(n),o=gs.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},sT=e=>nT(Hn(e,ps)).then(sh),oh=e=>sh(rT(Hn(e,ps))),oT=e=>oh(e).pointBytes,ih={sha512Async:async e=>{let t=Yx(),n=Xl(e);return ma(await t.digest("SHA-512",n.buffer))},sha512:void 0},iT=e=>(e=e===void 0?zx(ps):e,Hn(e,ps)),aT=Object.freeze({getExtendedPublicKeyAsync:sT,getExtendedPublicKey:oh,randomSecretKey:iT}),ua=8,cT=256,ah=Math.ceil(cT/ua)+1,Vl=2**(ua-1),lT=()=>{let e=[],t=gs,n=t;for(let r=0;r<ah;r++){n=t,e.push(n);for(let s=1;s<Vl;s++)n=n.add(t),e.push(n);t=n.double()}return e},xg=void 0,Tg=(e,t)=>{let n=t.negate();return e?n:t},uT=e=>{let t=xg||(xg=lT()),n=Rr,r=gs,s=2**ua,o=s,i=la(s-1),a=la(ua);for(let c=0;c<ah;c++){let l=Number(e&i);e>>=a,l>Vl&&(l-=o,e+=1n);let u=c*Vl,d=u,f=u+Math.abs(l)-1,m=c%2!==0,p=l<0;l===0?r=r.add(Tg(m,t[d])):n=n.add(Tg(p,t[f]))}return e!==0n&&Ee("invalid wnaf"),{p:n,f:r}};pT=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),gT=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=Dl(this.buffer)}update(e){kg(this),ch(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=Dl(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){kg(this),fT(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,ql(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=Dl(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()}},Le=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),ea=BigInt(2**32-1),Ag=BigInt(32);Eg=(e,t,n)=>e>>>n,Cg=(e,t,n)=>e<<32-n|t>>>n,ds=(e,t,n)=>e>>>n|t<<32-n,fs=(e,t,n)=>e<<32-n|t>>>n,ta=(e,t,n)=>e<<64-n|t>>>n-32,na=(e,t,n)=>e>>>n-32|t<<64-n;_T=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),bT=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,vT=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),wT=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,ST=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),xT=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,lh=yT(["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))),TT=lh[0],kT=lh[1],jn=new Uint32Array(80),Bn=new Uint32Array(80),AT=class extends gT{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:f,Gl:m,Hh:p,Hl:g}=this;return[e,t,n,r,s,o,i,a,c,l,u,d,f,m,p,g]}set(e,t,n,r,s,o,i,a,c,l,u,d,f,m,p,g){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=f|0,this.Gl=m|0,this.Hh=p|0,this.Hl=g|0}process(e,t){for(let b=0;b<16;b++,t+=4)jn[b]=e.getUint32(t),Bn[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let w=jn[b-15]|0,S=Bn[b-15]|0,C=ds(w,S,1)^ds(w,S,8)^Eg(w,S,7),I=fs(w,S,1)^fs(w,S,8)^Cg(w,S,7),y=jn[b-2]|0,T=Bn[b-2]|0,z=ds(y,T,19)^ta(y,T,61)^Eg(y,T,6),Z=fs(y,T,19)^na(y,T,61)^Cg(y,T,6),H=vT(I,Z,Bn[b-7],Bn[b-16]),be=wT(H,C,z,jn[b-7],jn[b-16]);jn[b]=be|0,Bn[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:f,Fl:m,Gh:p,Gl:g,Hh:v,Hl:k}=this;for(let b=0;b<80;b++){let w=ds(u,d,14)^ds(u,d,18)^ta(u,d,41),S=fs(u,d,14)^fs(u,d,18)^na(u,d,41),C=u&f^~u&p,I=d&m^~d&g,y=ST(k,S,I,kT[b],Bn[b]),T=xT(y,v,w,C,TT[b],jn[b]),z=y|0,Z=ds(n,r,28)^ta(n,r,34)^ta(n,r,39),H=fs(n,r,28)^na(n,r,34)^na(n,r,39),be=n&s^n&i^s&i,se=r&o^r&a^o&a;v=p|0,k=g|0,p=f|0,g=m|0,f=u|0,m=d|0,{h:u,l:d}=nn(c|0,l|0,T|0,z|0),c=i|0,l=a|0,i=s|0,a=o|0,s=n|0,o=r|0;let X=_T(z,H,se);n=bT(X,T,Z,be),r=X|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:f,l:m}=nn(this.Fh|0,this.Fl|0,f|0,m|0),{h:p,l:g}=nn(this.Gh|0,this.Gl|0,p|0,g|0),{h:v,l:k}=nn(this.Hh|0,this.Hl|0,v|0,k|0),this.set(n,r,s,o,i,a,c,l,u,d,f,m,p,g,v,k)}roundClean(){ql(jn,Bn)}destroy(){this.destroyed=!0,ql(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},ET=class extends AT{Ah=Le[0]|0;Al=Le[1]|0;Bh=Le[2]|0;Bl=Le[3]|0;Ch=Le[4]|0;Cl=Le[5]|0;Dh=Le[6]|0;Dl=Le[7]|0;Eh=Le[8]|0;El=Le[9]|0;Fh=Le[10]|0;Fl=Le[11]|0;Gh=Le[12]|0;Gl=Le[13]|0;Hh=Le[14]|0;Hl=Le[15]|0;constructor(){super(64)}},CT=mT(()=>new ET,pT(3)),Rg=ih;Rg.sha512||(Rg.sha512=e=>CT(e));MT="ws://localhost:9001/ws",NT=3e4,dh=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=Er(e.name),e.keyPath)try{this._keypair=PT(e.keyPath)}catch{}this.options={name:this._name,url:e.url??MT,relay:e.relay??"",autoReconnect:e.autoReconnect??!0,reconnectInterval:e.reconnectInterval??1e3,maxReconnectAttempts:e.maxReconnectAttempts??10,rpcTimeout:e.rpcTimeout??NT,pingInterval:e.pingInterval??3e4,binding:e.binding??""},this.transport=new WS({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=Hx(new Uint8Array(t));n&&(this._keypair={privateKey:n,publicKey:Mx(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=Ig(this._keypair.publicKey)),this.options.binding&&(n.binding=this.options.binding);try{this.transport.send(n)}catch(r){this.registerPromise=null,t(r instanceof Error?r:new Me(String(r)))}})}disconnect(){for(let[,e]of this.pendingCalls)clearTimeout(e.timer),e.reject(new Me("Client disconnected"));this.pendingCalls.clear();for(let[,e]of this.pendingSend)e.reject(new Me("Client disconnected"));this.pendingSend.clear();for(let[,e]of this.pendingResolve)e.reject(new Me("Client disconnected"));this.pendingResolve.clear(),this.registerPromise&&(this.registerPromise.reject(new Me("Client disconnected")),this.registerPromise=null),this.transport.disconnect(),this._peerId=null,this.hasConnectedOnce=!1}async send(e,t,n,r){let s=Er(e),o=Il();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 Me(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=Er(e),o=Il(),i=Date.now(),a=Math.floor(Math.random()*2**32),c=new TextEncoder().encode(n),{signature:l,signatureInput:u}=await OT(this._keypair.privateKey,o,this._peerId,this._name,i,t,c,a);return new Promise((d,f)=>{this.pendingSend.set(s,{resolve:d,reject:f});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(m){this.pendingSend.delete(s),f(m instanceof Error?m:new Me(String(m)))}setTimeout(()=>{this.pendingSend.has(s)&&(this.pendingSend.delete(s),d({messageId:o,to:s}))},5e3)})}async call(e,t,n,r){let s=Er(e),o=r?.correlationId??Il(),i=r?.timeout??this.options.rpcTimeout;return new Promise((a,c)=>{let l=setTimeout(()=>{this.pendingCalls.delete(o),c(new yo(`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 Me(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=Er(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 Me(String(s)))}setTimeout(()=>{this.pendingResolve.has(t)&&(this.pendingResolve.delete(t),r(new yo(`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=El(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=Ig(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 tk(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Uh(e,t,n=""){let r=tk(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 bh(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 nk(e,t){Uh(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 iu(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function nu(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function rk(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 ik(e,t=!1){return t?{h:Number(e&pa),l:Number(e>>vh&pa)}:{h:Number(e>>vh&pa)|0,l:Number(e&pa)|0}}function ak(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}=ik(e[o],t);[r[o],s[o]]=[i,a]}return[r,s]}function on(e,t,n,r){let s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}function bk(){return XT.randomSecretKey()}function Sa(e){return GT(e)}function jh(){let e=bk();return{secretKey:e,publicKey:Sa(e)}}function So(e,t){return zT(t,e)}function vk(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function wk(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 vs(e){return vk(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Sk(e){let t=e.length%4===0?0:4-e.length%4,n=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return wk(n)}function xk(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function Fh(e){let t=Sa(e);return{kty:"OKP",crv:"Ed25519",x:vs(t),d:vs(e)}}function Hh(e){return{kty:"OKP",crv:"Ed25519",x:vs(e)}}function xo(e){if(xk(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return Sk(e.d)}var Th,_a,ya,fh,mh,Ql,eu,LT,_s,UT,Ce,DT,jT,BT,Ot,wa,au,kh,cu,sn,ph,lu,Ah,FT,bs,Eh,ba,$r,ie,gh,O,Ch,Rh,Ih,$h,tu,ru,wo,Mr,Or,Ph,Oh,Pt,HT,hh,VT,su,qT,uu,Mh,KT,du,GT,WT,YT,zT,fu,Nh,JT,XT,va,ZT,Lh,ou,QT,yh,_h,ek,sk,ok,Ue,pa,vh,wh,Sh,hs,ys,ga,ha,ck,lk,uk,dk,fk,mk,Dh,pk,gk,Vn,qn,hk,yk,_k,xh,e$,Bh,t$,n$,r$,s$,xa=nt(()=>{"use strict";Th=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:_a,n:ya,Gx:fh,Gy:mh,a:Ql,d:eu,h:LT}=Th,_s=32,UT=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},Ce=(e="")=>{let t=new Error(e);throw UT(t,Ce),t},DT=e=>typeof e=="bigint",jT=e=>typeof e=="string",BT=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,Ot=(e,t,n="")=>{let r=BT(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},wa=e=>new Uint8Array(e),au=e=>Uint8Array.from(e),kh=(e,t)=>e.toString(16).padStart(t,"0"),cu=e=>Array.from(Ot(e)).map(t=>kh(t,2)).join(""),sn={_0:48,_9:57,A:65,F:70,a:97,f:102},ph=e=>{if(e>=sn._0&&e<=sn._9)return e-sn._0;if(e>=sn.A&&e<=sn.F)return e-(sn.A-10);if(e>=sn.a&&e<=sn.f)return e-(sn.a-10)},lu=e=>{let t="hex invalid";if(!jT(e))return Ce(t);let n=e.length,r=n/2;if(n%2)return Ce(t);let s=wa(r);for(let o=0,i=0;o<r;o++,i+=2){let a=ph(e.charCodeAt(i)),c=ph(e.charCodeAt(i+1));if(a===void 0||c===void 0)return Ce(t);s[o]=a*16+c}return s},Ah=()=>globalThis?.crypto,FT=()=>Ah()?.subtle??Ce("crypto.subtle must be defined, consider polyfill"),bs=(...e)=>{let t=0;for(let s of e)t+=Ot(s).length;let n=wa(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},Eh=(e=_s)=>Ah().getRandomValues(wa(e)),ba=BigInt,$r=(e,t,n,r="bad number: out of range")=>{if(!DT(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},ie=(e,t=_a)=>{let n=e%t;return n>=0n?n:t+n},gh=(1n<<255n)-1n,O=e=>{e<0n&&Ce("negative coordinate");let t=(e>>255n)*19n+(e&gh);return t=(t>>255n)*19n+(t&gh),t%_a},Ch=e=>ie(e,ya),Rh=(e,t)=>{(e===0n||t<=0n)&&Ce("no inverse n="+e+" mod="+t);let n=ie(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?ie(s,t):Ce("no inverse")},Ih=e=>{let t=Nh[e];return typeof t!="function"&&Ce("hashes."+e+" not set"),t},$h=e=>Ot(e,64,"digest"),tu=e=>e instanceof wo?e:Ce("Point expected"),ru=2n**256n,wo=class Pr{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=ru;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 Th}static fromAffine(t){return new Pr(t.x,t.y,1n,O(t.x*t.y))}static fromBytes(t,n=!1){let r=eu,s=au(Ot(t,_s)),o=t[31];s[31]=o&-129;let i=Oh(s);$r(i,0n,n?ru:_a);let c=O(i*i),l=ie(c-1n),u=O(r*c+1n),{isValid:d,value:f}=VT(l,u);d||Ce("bad point: y not sqrt");let m=(f&1n)===1n,p=(o&128)!==0;return!n&&f===0n&&p&&Ce("bad point: x==0, isLastByteOdd"),p!==m&&(f=ie(-f)),new Pr(f,i,1n,O(f*i))}static fromHex(t,n){return Pr.fromBytes(lu(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Ql,n=eu,r=this;if(r.is0())return Ce("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),f=O(c*t),m=O(u*(f+l)),p=ie(d+O(n*O(c*l)));if(m!==p)return Ce("bad point: equation left != right (1)");let g=O(s*o),v=O(i*a);return g!==v?Ce("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=tu(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(Or)}negate(){return new Pr(ie(-this.X),this.Y,this.Z,ie(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=Ql,o=O(t*t),i=O(n*n),a=O(2n*r*r),c=O(s*o),l=ie(t+n),u=ie(O(l*l)-o-i),d=ie(c+i),f=ie(d-a),m=ie(c-i),p=O(u*f),g=O(d*m),v=O(u*m),k=O(f*d);return new Pr(p,g,k,v)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=tu(t),u=Ql,d=eu,f=O(n*i),m=O(r*a),p=O(O(o*d)*l),g=O(s*c),v=ie(O(ie(n+r)*ie(i+a))-f-m),k=ie(g-p),b=ie(g+p),w=ie(m-O(u*f)),S=O(v*k),C=O(b*w),I=O(v*w),y=O(k*b);return new Pr(S,C,y,I)}subtract(t){return this.add(tu(t).negate())}multiply(t,n=!0){if(!n&&t===0n||($r(t,1n,ya),!n&&this.is0()))return Or;if(t===1n)return this;if(this.equals(Mr))return ek(t).p;let r=Or,s=Mr;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(Or))return{x:0n,y:1n};let s=Rh(r,_a);O(r*s)!==1n&&Ce("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=Ph(n);return r[31]|=t&1n?128:0,r}toHex(){return cu(this.toBytes())}clearCofactor(){return this.multiply(ba(LT),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(ya/2n,!1).double();return ya%2n&&(t=t.add(this)),t.is0()}},Mr=new wo(fh,mh,1n,ie(fh*mh)),Or=new wo(0n,1n,1n,0n);wo.BASE=Mr;wo.ZERO=Or;Ph=e=>lu(kh($r(e,0n,ru),64)).reverse(),Oh=e=>ba("0x"+cu(au(Ot(e)).reverse())),Pt=(e,t)=>{let n=e;for(;t-- >0n;)n=O(n*n);return n},HT=e=>{let t=O(e*e),n=O(t*e),r=O(Pt(n,2n)*n),s=O(Pt(r,1n)*e),o=O(Pt(s,5n)*s),i=O(Pt(o,10n)*o),a=O(Pt(i,20n)*i),c=O(Pt(a,40n)*a),l=O(Pt(c,80n)*c),u=O(Pt(l,80n)*c),d=O(Pt(u,10n)*o);return{pow_p_5_8:O(Pt(d,2n)*e),b2:n}},hh=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,VT=(e,t)=>{let n=O(t*O(t*t)),r=O(O(n*n)*t),s=HT(O(e*r)).pow_p_5_8,o=O(e*O(n*s)),i=O(t*O(o*o)),a=o,c=O(o*hh),l=i===e,u=i===ie(-e),d=i===ie(-e*hh);return l&&(o=a),(u||d)&&(o=c),(ie(o)&1n)===1n&&(o=ie(-o)),{isValid:l||u,value:o}},su=e=>Ch(Oh(e)),qT=(...e)=>Promise.resolve(Ih("sha512Async")(bs(...e))).then($h),uu=(...e)=>$h(Ih("sha512")(bs(...e))),Mh=e=>{let t=au(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=su(n),o=Mr.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},KT=e=>qT(Ot(e,_s)).then(Mh),du=e=>Mh(uu(Ot(e,_s))),GT=e=>du(e).pointBytes,WT=e=>e.finish(uu(e.hashable)),YT=(e,t,n)=>{let{pointBytes:r,scalar:s}=e,o=su(t),i=Mr.multiply(o).toBytes();return{hashable:bs(i,r,n),finish:l=>{let u=Ch(o+su(l)*s);return Ot(bs(i,Ph(u)),64)}}},zT=(e,t)=>{let n=Ot(e),r=du(t),s=uu(r.prefix,n);return WT(YT(r,s,n))},fu=Object.freeze({bytesToHex:cu,hexToBytes:lu,concatBytes:bs,mod:ie,invert:Rh,randomBytes:Eh}),Nh={sha512Async:async e=>{let t=FT(),n=bs(e);return wa(await t.digest("SHA-512",n.buffer))},sha512:void 0},JT=e=>(e=e===void 0?Eh(_s):e,Ot(e,_s)),XT=Object.freeze({getExtendedPublicKeyAsync:KT,getExtendedPublicKey:du,randomSecretKey:JT}),va=8,ZT=256,Lh=Math.ceil(ZT/va)+1,ou=2**(va-1),QT=()=>{let e=[],t=Mr,n=t;for(let r=0;r<Lh;r++){n=t,e.push(n);for(let s=1;s<ou;s++)n=n.add(t),e.push(n);t=n.double()}return e},yh=void 0,_h=(e,t)=>{let n=t.negate();return e?n:t},ek=e=>{let t=yh||(yh=QT()),n=Or,r=Mr,s=2**va,o=s,i=ba(s-1),a=ba(va);for(let c=0;c<Lh;c++){let l=Number(e&i);e>>=a,l>ou&&(l-=o,e+=1n);let u=c*ou,d=u,f=u+Math.abs(l)-1,m=c%2!==0,p=l<0;l===0?r=r.add(_h(m,t[d])):n=n.add(_h(p,t[f]))}return e!==0n&&Ce("invalid wnaf"),{p:n,f:r}};sk=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),ok=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=nu(this.buffer)}update(e){bh(this),Uh(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=nu(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){bh(this),nk(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,iu(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=nu(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()}},Ue=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),pa=BigInt(2**32-1),vh=BigInt(32);wh=(e,t,n)=>e>>>n,Sh=(e,t,n)=>e<<32-n|t>>>n,hs=(e,t,n)=>e>>>n|t<<32-n,ys=(e,t,n)=>e<<32-n|t>>>n,ga=(e,t,n)=>e<<64-n|t>>>n-32,ha=(e,t,n)=>e>>>n-32|t<<64-n;ck=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),lk=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,uk=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),dk=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,fk=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),mk=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,Dh=ak(["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))),pk=Dh[0],gk=Dh[1],Vn=new Uint32Array(80),qn=new Uint32Array(80),hk=class extends ok{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:f,Gl:m,Hh:p,Hl:g}=this;return[e,t,n,r,s,o,i,a,c,l,u,d,f,m,p,g]}set(e,t,n,r,s,o,i,a,c,l,u,d,f,m,p,g){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=f|0,this.Gl=m|0,this.Hh=p|0,this.Hl=g|0}process(e,t){for(let b=0;b<16;b++,t+=4)Vn[b]=e.getUint32(t),qn[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let w=Vn[b-15]|0,S=qn[b-15]|0,C=hs(w,S,1)^hs(w,S,8)^wh(w,S,7),I=ys(w,S,1)^ys(w,S,8)^Sh(w,S,7),y=Vn[b-2]|0,T=qn[b-2]|0,z=hs(y,T,19)^ga(y,T,61)^wh(y,T,6),Z=ys(y,T,19)^ha(y,T,61)^Sh(y,T,6),H=uk(I,Z,qn[b-7],qn[b-16]),be=dk(H,C,z,Vn[b-7],Vn[b-16]);Vn[b]=be|0,qn[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:f,Fl:m,Gh:p,Gl:g,Hh:v,Hl:k}=this;for(let b=0;b<80;b++){let w=hs(u,d,14)^hs(u,d,18)^ga(u,d,41),S=ys(u,d,14)^ys(u,d,18)^ha(u,d,41),C=u&f^~u&p,I=d&m^~d&g,y=fk(k,S,I,gk[b],qn[b]),T=mk(y,v,w,C,pk[b],Vn[b]),z=y|0,Z=hs(n,r,28)^ga(n,r,34)^ga(n,r,39),H=ys(n,r,28)^ha(n,r,34)^ha(n,r,39),be=n&s^n&i^s&i,se=r&o^r&a^o&a;v=p|0,k=g|0,p=f|0,g=m|0,f=u|0,m=d|0,{h:u,l:d}=on(c|0,l|0,T|0,z|0),c=i|0,l=a|0,i=s|0,a=o|0,s=n|0,o=r|0;let X=ck(z,H,se);n=lk(X,T,Z,be),r=X|0}({h:n,l:r}=on(this.Ah|0,this.Al|0,n|0,r|0)),{h:s,l:o}=on(this.Bh|0,this.Bl|0,s|0,o|0),{h:i,l:a}=on(this.Ch|0,this.Cl|0,i|0,a|0),{h:c,l}=on(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=on(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:m}=on(this.Fh|0,this.Fl|0,f|0,m|0),{h:p,l:g}=on(this.Gh|0,this.Gl|0,p|0,g|0),{h:v,l:k}=on(this.Hh|0,this.Hl|0,v|0,k|0),this.set(n,r,s,o,i,a,c,l,u,d,f,m,p,g,v,k)}roundClean(){iu(Vn,qn)}destroy(){this.destroyed=!0,iu(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},yk=class extends hk{Ah=Ue[0]|0;Al=Ue[1]|0;Bh=Ue[2]|0;Bl=Ue[3]|0;Ch=Ue[4]|0;Cl=Ue[5]|0;Dh=Ue[6]|0;Dl=Ue[7]|0;Eh=Ue[8]|0;El=Ue[9]|0;Fh=Ue[10]|0;Fl=Ue[11]|0;Gh=Ue[12]|0;Gl=Ue[13]|0;Hh=Ue[14]|0;Hl=Ue[15]|0;constructor(){super(64)}},_k=rk(()=>new yk,sk(3)),xh=Nh;xh.sha512||(xh.sha512=e=>_k(e));e$=fu.bytesToHex,Bh=fu.hexToBytes,t$=fu.concatBytes;n$=new TextEncoder;r$=Bh("302e020100300506032b657004220420"),s$=Bh("302a300506032b6570032100");});var Yh={};Br(Yh,{CardRequiredError:()=>an,buildIssuanceRequest:()=>Wh,enrollCardUrl:()=>Ta,jkt:()=>Kh,proofPayload:()=>Gh,readSeed:()=>ka,requestVisaBinding:()=>mu});function Kh(e){let t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return Vh.createHash("sha256").update(t,"utf8").digest("base64url")}function Gh(e,t,n){return`visa-agent-binding:v1:${e}:${t}:${n}`}function Wh(e,t,n="visa",r=Math.floor(Date.now()/1e3)){let s=Hh(Sa(e)),o=Buffer.from(Gh(t,Kh(s),r),"utf8"),i=Buffer.from(So(e,o)).toString("base64url");return{name:t,mesh:n,agent_pubkey:s,proof:{ts:r,sig:i}}}function Ta(e){try{return new URL("/enroll-card",e).toString()}catch{return"https://auth.visacli.sh/enroll-card"}}async function mu(e){let t=Wh(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="",i="";try{let a=await s.json();o=a?.error??"",i=a?.error_code??""}catch{}throw s.status===403&&(i==="ACCOUNT_NOT_APPROVED"||/no card/i.test(o))?new an("No card on file \u2014 enroll a card to register on the trusted .visa mesh.",Ta(e.authUrl),"no_card"):new Error(`Visa binding issuance failed (${s.status})${o?`: ${o}`:""}`)}return await s.json()}function ka(e){return new Uint8Array(qh.readFileSync(e))}var Vh,qh,an,Aa=nt(()=>{"use strict";Vh=R(require("crypto")),qh=R(require("fs"));xa();an=class extends Error{enrollUrl;reason;constructor(t,n,r){super(t),this.name="CardRequiredError",this.enrollUrl=n,this.reason=r}}});var vu={};Br(vu,{SUBWAY_PROTOCOL:()=>oy,registerDirect:()=>Lk,resolveDirect:()=>Uk});function hu(e,t){let n=typeof t=="bigint"?t:BigInt(t);for(;n>0x7fn;)e.push(Number(n&0x7fn|0x80n)),n>>=7n;e.push(Number(n))}function Ze(e,t){let n=0n,r=0n,s=t;for(;;){let o=e[s++];if(n|=BigInt(o&127)<<r,(o&128)===0)break;r+=7n}return[n,s]}function yu(e,t){return e<<3|t}function To(e,t,n){e.push(yu(t,2)),hu(e,n.length);for(let r of n)e.push(r)}function Tk(e,t){let n=[];return To(n,1,gu.encode(e)),t&&t.length>0&&To(n,2,gu.encode(t)),Uint8Array.from(n)}function kk(e,t,n){let r=[];return n!==0n&&(r.push(yu(1,0)),hu(r,n)),To(r,2,Tk(e,t)),Uint8Array.from(r)}function Ak(e){let t=[];return To(t,1,gu.encode(e)),Uint8Array.from(t)}function Ek(e,t){let n=[];return t!==0n&&(n.push(yu(1,0)),hu(n,t)),To(n,3,Ak(e)),Uint8Array.from(n)}function Ck(e){let t=0,n={success:!1,error:""};for(;t<e.length;){let[r,s]=Ze(e,t);t=s;let o=Number(r)>>3,i=Number(r)&7;if(o===1&&i===0){let[a,c]=Ze(e,t);t=c,n.success=a!==0n}else if(o===2&&i===2){let[a,c]=Ze(e,t),l=c,u=l+Number(a);n.error=ry.decode(e.subarray(l,u)),t=u}else t=_u(e,t,i)}return n}function Rk(e){let t=0,n={peerId:new Uint8Array(0),error:""};for(;t<e.length;){let[r,s]=Ze(e,t);t=s;let o=Number(r)>>3,i=Number(r)&7;if(o===1&&i===2){let[a,c]=Ze(e,t),l=c,u=l+Number(a);n.peerId=e.subarray(l,u),t=u}else if(o===2&&i===2){let[a,c]=Ze(e,t),l=c,u=l+Number(a);n.error=ry.decode(e.subarray(l,u)),t=u}else t=_u(e,t,i)}return n}function _u(e,t,n){if(n===0)return Ze(e,t)[1];if(n===2){let[r,s]=Ze(e,t);return s+Number(r)}if(n===5)return t+4;if(n===1)return t+8;throw new Error(`unsupported wire type ${n}`)}function sy(e){let t=0,n={requestId:0n};for(;t<e.length;){let[r,s]=Ze(e,t);t=s;let o=Number(r)>>3,i=Number(r)&7;if(o===1&&i===0){let[a,c]=Ze(e,t);t=c,n.requestId=a}else if(o===13&&i===2){let[a,c]=Ze(e,t),l=c,u=l+Number(a);n.registerNameResponse=Ck(e.subarray(l,u)),t=u}else if(o===14&&i===2){let[a,c]=Ze(e,t),l=c,u=l+Number(a);n.resolveNameResponse=Rk(e.subarray(l,u)),t=u}else t=_u(e,t,i)}return n}function Ik(e){let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t}function bu(e){return new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1)}function $k(e){if(e.length<4)return{success:!1,error:"short reply (no length prefix)"};let t=bu(e.subarray(0,4));return e.length<4+t?{success:!1,error:`truncated frame (have ${e.length-4}, need ${t})`}:sy(e.subarray(4,4+t)).registerNameResponse??{success:!1,error:"reply carried no register_name_response"}}function Pk(e){if(e.length<4)return{peerId:new Uint8Array(0),error:"short reply (no length prefix)"};let t=bu(e.subarray(0,4));return e.length<4+t?{peerId:new Uint8Array(0),error:`truncated frame (have ${e.length-4}, need ${t})`}:sy(e.subarray(4,4+t)).resolveNameResponse??{peerId:new Uint8Array(0),error:"reply carried no resolve_name_response"}}function pu(e){let t=e.reduce((s,o)=>s+o.length,0),n=new Uint8Array(t),r=0;for(let s of e)n.set(s,r),r+=s.length;return n}async function Nk(e){let t=[],n=0,r=-1;for await(let s of e){let o=s instanceof Uint8Array?s:s.subarray();if(t.push(o),n+=o.length,n>zh)throw new Error("subway: reply exceeded max size");if(r<0&&n>=4&&(r=4+bu(pu(t).subarray(0,4)),r>zh))throw new Error("subway: declared frame exceeds max size");if(r>=0&&n>=r)return pu(t).subarray(0,r)}return pu(t)}async function iy(e){return(0,Jh.createLibp2p)({...e?{privateKey:await(0,ey.generateKeyPairFromSeed)("Ed25519",e)}:{},transports:[(0,Xh.tcp)()],connectionEncrypters:[(0,Zh.noise)()],streamMuxers:[(0,Qh.yamux)()],connectionGater:{denyDialMultiaddr:async()=>!1}})}async function ay(e,t,n){let r=await e.dialProtocol((0,ty.multiaddr)(t),oy,{signal:AbortSignal.timeout(Ok)});r.send(Ik(n));let s;return Promise.race([Nk(r),new Promise((o,i)=>{s=setTimeout(()=>i(new Error("subway: request timed out")),Mk)})]).finally(()=>clearTimeout(s))}async function Lk(e){let t=await iy(e.seed);try{let n=await ay(t,e.relayMultiaddr,kk(e.name,e.binding,e.requestId??1n)),r=$k(n);return{success:r.success,error:r.error,peerId:t.peerId.toString()}}finally{await t.stop()}}async function Uk(e){let t=await iy(e.seed);try{let n=await ay(t,e.relayMultiaddr,Ek(e.name,e.requestId??1n)),r=Pk(n);return r.peerId.length===0?{found:!1,peerId:"",error:r.error||"name not found"}:{found:!0,peerId:(0,ny.toString)(r.peerId,"base58btc"),error:""}}finally{await t.stop()}}var Jh,Xh,Zh,Qh,ey,ty,ny,gu,ry,oy,Ok,Mk,zh,wu=nt(()=>{"use strict";Rl();Jh=require("libp2p"),Xh=require("@libp2p/tcp"),Zh=require("@chainsafe/libp2p-noise"),Qh=require("@chainsafe/libp2p-yamux"),ey=require("@libp2p/crypto/keys"),ty=require("@multiformats/multiaddr"),ny=require("uint8arrays/to-string"),gu=new TextEncoder,ry=new TextDecoder;oy="/subway/p2p/1.0.0",Ok=15e3,Mk=15e3,zh=1<<20});var Eo={};Br(Eo,{MESH:()=>Re,RELAY_URL:()=>Ao,connectOrThrow:()=>xs,ensureMailbox:()=>Mu,isSubwayEnabled:()=>Au,listRegistered:()=>Ou,loadBindingFor:()=>Ru,loadRegistry:()=>Nr,makeClient:()=>Ss,maybeMintVisaBinding:()=>uy,meshName:()=>dt,readInbox:()=>Bk,registerName:()=>Iu,resolveActingName:()=>Ra,resolveMeshName:()=>$u,seedSubwayKeyFromTapAgent:()=>ly,sendMessage:()=>Pu,sendVia:()=>Fk,subwayKeyPath:()=>Ca});function dt(e){return e.includes(".")?e:`${e}.${Re}`}function Au(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 Cu(){ve.mkdirSync(Eu,{recursive:!0,mode:448})}function Dk(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function Ca(e){return ws.join(Eu,`${Dk(e)}.key`)}function Nr(){if(!ve.existsSync(ku))return{};try{return JSON.parse(ve.readFileSync(ku,"utf8"))}catch{return{}}}function xu(e){Cu(),ve.writeFileSync(ku,JSON.stringify(e,null,2),{mode:384})}function Tu(){try{return ko.userInfo().username}catch{return"local"}}function ly(e){if(ve.existsSync(e)||!ve.existsSync(Su))return null;let t=ve.readdirSync(Su).filter(r=>r.endsWith(".json"));if(t.length===0)return null;let n=t.map(r=>ws.join(Su,r)).sort((r,s)=>ve.statSync(s).mtimeMs-ve.statSync(r).mtimeMs)[0];try{let r=JSON.parse(ve.readFileSync(n,"utf8"));if(!r.private_key_jwk)return null;let s=xo(r.private_key_jwk);return Cu(),ve.writeFileSync(e,Buffer.from(s),{mode:384}),r.agent_id??null}catch{return null}}function Ss(e,t={}){return new dh({name:dt(e),url:Ao,keyPath:Ca(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function Ru(e){if(Re!=="visa")return;let t=Nr()[e];if(t?.binding&&!(t.bindingExpiresAt&&Date.parse(t.bindingExpiresAt)<=Date.now()))return t.binding}async function xs(e,t=15e3){await Promise.race([e.connect(),new Promise((n,r)=>setTimeout(()=>r(new Error(`Subway relay connect timed out after ${t}ms (${Ao})`)),t))])}function Ra(e){if(e)return e;let t=Object.keys(Nr());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 uy(e){if(Re!=="visa")return null;let t=process.env.VISA_CLI_API_KEY?.trim();if(!t)throw new an("No Visa Key configured \u2014 set VISA_CLI_API_KEY (a Visa Key with a card on file) to register on the trusted .visa mesh.",Ta($e()),"no_key");try{return await mu({authUrl:$e(),apiKey:t,seed:ka(Ca(e)),name:dt(e)})}catch(n){if(n instanceof an)throw n;return console.warn(`[subway] Visa binding not minted: ${n instanceof Error?n.message:String(n)}`),null}}async function Iu(e){let t=Ca(e),n=ly(t),r=dt(e);Re==="visa"&&!ve.existsSync(t)&&(Cu(),ve.writeFileSync(t,(0,cy.randomBytes)(32),{mode:384}));let s=await uy(e),o=s?{binding:s.binding,bindingExpiresAt:new Date(Date.now()+s.expires_in*1e3).toISOString()}:{},i=process.env.SUBWAY_RELAY_MULTIADDR;if(Re==="visa"&&i){let{registerDirect:c}=await Promise.resolve().then(()=>(wu(),vu)),l=await c({relayMultiaddr:i,seed:ka(t),name:r,binding:s?.binding});if(!l.success)throw new Error(`.visa relay admission failed: ${l.error||"unknown"}`);let u=Nr();return u[e]={relayName:r,mesh:Re,peerId:l.peerId,owner:Tu(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},xu(u),{relayName:r,mesh:Re,peerId:l.peerId,tapAgentId:n,...s?{binding:s.binding}:{}}}if(Re==="visa"&&!process.env.SUBWAY_RELAY){let c=Nr();return c[e]={relayName:r,mesh:Re,peerId:null,owner:Tu(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},xu(c),{relayName:r,mesh:Re,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 a=Ss(e,{autoReconnect:!1,binding:s?.binding});try{await xs(a);let c=Nr();return c[e]={relayName:r,mesh:Re,peerId:a.peerId,owner:Tu(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},xu(c),{relayName:r,mesh:Re,peerId:a.peerId,tapAgentId:n,...s?{binding:s.binding}:{}}}finally{a.disconnect()}}async function $u(e){let t=dt(e),n=process.env.SUBWAY_RELAY_MULTIADDR;if(Re==="visa"&&n){let{resolveDirect:r}=await Promise.resolve().then(()=>(wu(),vu)),s=await r({relayMultiaddr:n,name:t});return{relayName:t,found:s.found,peerId:s.peerId,error:s.error}}throw new Error("subway find needs the .visa mesh with a dedicated relay \u2014 set SUBWAY_MESH=visa and SUBWAY_RELAY_MULTIADDR.")}async function Pu(e,t,n){let r=Ss(e,{autoReconnect:!1,binding:Ru(e)});try{await xs(r);let s=dt(t);return await r.sendSigned(s,"chat",n),{to:s,as:dt(e)}}finally{r.disconnect()}}function Ou(){let e=Nr();return Object.entries(e).map(([t,n])=>({name:t,...n}))}async function Mu(e){let t=Ea.get(e);if(t)return{relayName:dt(e),peerId:t.client.peerId};let n=Ss(e,{autoReconnect:!0,binding:Ru(e)}),r=[];return n.onMessage(s=>{r.push({from:s.fromName,text:s.payload,ts:s.timestampMs,verified:!!s.verified}),r.length>jk&&r.shift()}),Ea.set(e,{client:n,buffer:r}),await xs(n),{relayName:dt(e),peerId:n.peerId}}async function Bk(e,t=20,n=!1){await Mu(e);let r=Ea.get(e);if(!r)return[];let s=r.buffer.slice(-t);return n&&(r.buffer.length=0),s}async function Fk(e,t,n){await Mu(e);let r=Ea.get(e);if(!r)throw new Error(`mailbox for ${e} unavailable`);let s=dt(t);return await r.client.sendSigned(s,"chat",n),{to:s,as:dt(e)}}var ve,ko,ws,cy,Re,Ao,Eu,ku,Su,Ea,jk,Ts=nt(()=>{"use strict";Zl();xa();ve=R(require("fs")),ko=R(require("os")),ws=R(require("path")),cy=require("crypto");qt();Aa();Re=process.env.SUBWAY_MESH??"relay",Ao=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";Eu=ws.join(ko.homedir(),".visa-cli","subway"),ku=ws.join(Eu,"registry.json"),Su=ws.join(ko.homedir(),".visa-cli","agents");Ea=new Map,jk=200});var Fa={};Br(Fa,{initSentry:()=>bC,isSentryConfigured:()=>_C,reportFatal:()=>vC});function _C(){return!1}async function bC(){return null}async function vC(e,t){process.exit(t?.exitCode??1)}var Ha=nt(()=>{});var u1={};Br(u1,{printGroupHelpAndExit:()=>Lt});module.exports=H_(u1);var y_=require("commander"),Ga=R(require("crypto")),ce=R(require("fs")),re=R(require("os")),tt=R(require("path")),__=require("child_process"),pd=require("node:readline/promises"),b_=require("util");var Yo=require("child_process"),Ld=require("util"),mn=R(require("fs")),zo=R(require("os")),ic=R(require("path"));var Id=R(require("crypto"));var Dt="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";var $d="VISA_ALLOW_INSECURE_MOCKS",Ed,Cd,Rd;function tc(e){return`${e}-${Id.randomBytes(24).toString("base64url")}`}function Pd(e=process.env){return e.NODE_ENV==="test"||e[$d]==="true"}function dn(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&Pd(e)}function Fr(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&Pd(e)}function nc(){return`Set ${$d}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function Od(){return Ed??=tc("mock-session"),Ed}function Md(e=process.env){return e.NODE_ENV==="test"?Dt:(Cd??=tc("mock-rc"),Cd)}function Nd(){return Rd??=tc("mock-signature"),Rd}var yt=(0,Ld.promisify)(Yo.execFile),ac=ic.join(zo.homedir(),".visa-mcp"),Ls=ic.join(ac,"session-token"),Ye="visa-cli",fn="session-token",Go="rc-access",V_=5e3,Wo=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function q_(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
10
- `)}function Ud(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=q_(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function K_(){try{let{stdout:e}=await yt("security",["find-generic-password","-s",Ye,"-a",fn,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(Ud(e))throw new Wo("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 G_(e){try{try{await yt("security",["delete-generic-password","-s",Ye,"-a",fn],{timeout:5e3})}catch{}return await yt("security",["add-generic-password","-s",Ye,"-a",fn,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function W_(){try{await yt("security",["delete-generic-password","-s",Ye,"-a",fn],{timeout:5e3})}catch{}}async function Y_(){if(!cc())return null;try{let{stdout:e}=await yt("secret-tool",["lookup","service",Ye,"account",fn],{timeout:5e3});return e.trim()||null}catch{return null}}async function z_(e){if(!cc())return!1;try{let t=(0,Yo.execFile)("secret-tool",["store","--label",`${Ye} ${fn}`,"service",Ye,"account",fn]);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"))},V_))]),!0):!1}catch{return!1}}async function J_(){if(cc())try{await yt("secret-tool",["clear","service",Ye,"account",fn],{timeout:5e3})}catch{}}function cc(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function X_(){try{let{stdout:e}=await yt("security",["find-generic-password","-s",Ye,"-a",Go,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Z_(e){try{try{await yt("security",["delete-generic-password","-s",Ye,"-a",Go],{timeout:5e3})}catch{}await yt("security",["add-generic-password","-s",Ye,"-a",Go,"-w",e],{timeout:5e3})}catch{}}async function Q_(){try{await yt("security",["delete-generic-password","-s",Ye,"-a",Go],{timeout:5e3})}catch{}}function sc(){try{return mn.readFileSync(Ls,"utf-8").trim()||null}catch(e){if(Ud(e))throw new Wo(`Unable to read Visa CLI credentials from ${Ls}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function Dd(e){mn.mkdirSync(ac,{recursive:!0,mode:448}),mn.writeFileSync(Ls,e,{mode:384}),process.platform==="win32"&&eb(Ls)}function oc(){try{mn.unlinkSync(Ls)}catch{}}function eb(e){try{let t=zo.userInfo().username;(0,Yo.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 rc(){switch(process.platform){case"darwin":return{get:K_,store:G_,delete:W_};case"linux":return{get:Y_,store:z_,delete:J_};default:return{get:async()=>sc(),store:async e=>{try{return Dd(e),!0}catch{return!1}},delete:async()=>oc(),storesInSessionFile:!0}}}var G=class{static async getSessionToken(){if(dn())return Promise.resolve(Od());let t=rc(),n=await t.get();if(n)return n;let r=sc();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(dn())return;let n=rc();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||oc();return}await n.delete()}if(Dd(t),sc()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${ac} is writable.`))}static async getRcAccessToken(){return dn()?Md():X_()}static async saveRcAccessToken(t){dn()||await Z_(t)}static async deleteSessionToken(){if(dn())return;await rc().delete(),oc()}static async clearAll(){await this.deleteSessionToken(),await Q_()}};var Jo=R(require("crypto")),Xo=R(require("tty")),Zo=R(require("fs"));function nb(e){return/-rc\.|-beta\./.test(e)}function lc(e){return Jo.createHash("sha256").update(e.trim()).digest("hex")}function jd(e){return Dt==="SKIP"?!0:Jo.timingSafeEqual(Buffer.from(lc(e)),Buffer.from(Dt))}function rb(){try{let e=Zo.openSync("/dev/tty","r+"),t=new Xo.ReadStream(e),n=new Xo.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{Zo.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 sb(e){return new Promise((t,n)=>{let r;try{r=rb()}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===`
9
+ ${e.nonce}`;return jx.encode(n)}function Hx(e,t,n,r,s,o,i){return Fx({messageId:e,senderPeerId:t,senderName:n,timestampMs:r,messageType:s,payload:o,nonce:i})}function Vx(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 fT(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function lh(e,t,n=""){let r=fT(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 kg(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 mT(e,t){lh(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 Kl(...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 pT(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 yT(e,t=!1){return t?{h:Number(e&ta),l:Number(e>>Cg&ta)}:{h:Number(e>>Cg&ta)|0,l:Number(e&ta)|0}}function _T(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}=yT(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 IT(){return cT.randomSecretKey()}function dh(e){return iT(e)}function PT(){let e=IT();return{secretKey:e,publicKey:dh(e)}}function $T(e){if((0,Fn.existsSync)(e)){let n=(0,Fn.readFileSync)(e),r=new Uint8Array(n.buffer.slice(n.byteOffset,n.byteOffset+32));return{secretKey:r,publicKey:dh(r)}}let t=PT();return(0,Fn.mkdirSync)((0,$g.dirname)(e),{recursive:!0}),(0,Fn.writeFileSync)(e,new Uint8Array(t.secretKey)),t}function OT(e){let{secretKey:t,publicKey:n}=$T(e);return{privateKey:t,publicKey:n}}async function MT(e,t,n,r,s,o,i,a){let c=Hx(t,n,r,s,o,i,a);return{signature:await Lx(e,c),signatureInput:Bx.subwayAgentMsgV1}}function Pg(e){return Dx(e)}var Fn,$g,qS,KS,GS,WS,YS,Og,ia,sa,ag,cg,$l,Ol,zS,fa,JS,ke,XS,ZS,QS,rn,ma,Gl,Mg,Wl,Qt,lg,Yl,Ng,ex,ms,tx,aa,xr,oe,ug,P,Lg,Ug,Dg,jg,Ml,Bl,vo,Ir,Er,Bg,Fg,Rt,nx,dg,rx,Fl,zl,sx,Hg,ox,ix,ax,cx,lx,ux,Jl,Vg,ca,dx,qg,Hl,fx,fg,mg,mx,Wg,Yg,Nn,Ne,Zi,gg,hg,yg,ls,us,Qi,ea,vx,wx,Sx,xx,Tx,Ax,kx,Ln,Cx,Ex,zg,Rx,Ix,Un,Dn,Px,$x,Ox,Mx,_g,Ux,Jg,jx,Bx,Xg,la,oa,bg,vg,Ll,Ul,qx,ps,Kx,Ce,Gx,Wx,Yx,Hn,pa,Xl,Zg,Qg,tn,wg,eh,th,zx,Zl,Jx,ua,Ar,ae,Sg,$,Xx,Zx,nh,rh,Dl,Vl,wo,gs,Rr,Qx,sh,Pt,eT,xg,tT,nT,rT,sT,oh,oT,ih,iT,ah,aT,cT,da,lT,ch,ql,uT,Tg,Ag,dT,gT,hT,Le,ta,Cg,Eg,Rg,ds,fs,na,ra,bT,vT,wT,ST,xT,TT,uh,AT,kT,jn,Bn,CT,ET,RT,Ig,NT,LT,fh,Ql=nt(()=>{"use strict";Rl();Rl();Il();Fn=require("fs"),$g=require("path");qS=1e3,KS=10,GS=3e4,WS=3e4,YS=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??qS,this.maxReconnectAttempts=e.maxReconnectAttempts??KS,this.pingInterval=e.pingInterval??GS}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=HS();if(!n){t(new Me('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 Me(`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 Me("WebSocket closed before connection established")))},this.ws.onerror=()=>{r||(r=!0,t(new Me(`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 Me("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=VS(this.reconnectInterval*Math.pow(2,this.reconnectAttempt),this.reconnectInterval,WS);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)}}},Og=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:ia,n:sa,Gx:ag,Gy:cg,a:$l,d:Ol,h:zS}=Og,fa=32,JS=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},ke=(e="")=>{let t=new Error(e);throw JS(t,ke),t},XS=e=>typeof e=="bigint",ZS=e=>typeof e=="string",QS=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,rn=(e,t,n="")=>{let r=QS(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},ma=e=>new Uint8Array(e),Gl=e=>Uint8Array.from(e),Mg=(e,t)=>e.toString(16).padStart(t,"0"),Wl=e=>Array.from(rn(e)).map(t=>Mg(t,2)).join(""),Qt={_0:48,_9:57,A:65,F:70,a:97,f:102},lg=e=>{if(e>=Qt._0&&e<=Qt._9)return e-Qt._0;if(e>=Qt.A&&e<=Qt.F)return e-(Qt.A-10);if(e>=Qt.a&&e<=Qt.f)return e-(Qt.a-10)},Yl=e=>{let t="hex invalid";if(!ZS(e))return ke(t);let n=e.length,r=n/2;if(n%2)return ke(t);let s=ma(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 ke(t);s[o]=a*16+c}return s},Ng=()=>globalThis?.crypto,ex=()=>Ng()?.subtle??ke("crypto.subtle must be defined, consider polyfill"),ms=(...e)=>{let t=0;for(let s of e)t+=rn(s).length;let n=ma(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},tx=(e=fa)=>Ng().getRandomValues(ma(e)),aa=BigInt,xr=(e,t,n,r="bad number: out of range")=>{if(!XS(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},oe=(e,t=ia)=>{let n=e%t;return n>=0n?n:t+n},ug=(1n<<255n)-1n,P=e=>{e<0n&&ke("negative coordinate");let t=(e>>255n)*19n+(e&ug);return t=(t>>255n)*19n+(t&ug),t%ia},Lg=e=>oe(e,sa),Ug=(e,t)=>{(e===0n||t<=0n)&&ke("no inverse n="+e+" mod="+t);let n=oe(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?oe(s,t):ke("no inverse")},Dg=e=>{let t=Vg[e];return typeof t!="function"&&ke("hashes."+e+" not set"),t},jg=e=>rn(e,64,"digest"),Ml=e=>e instanceof vo?e:ke("Point expected"),Bl=2n**256n,vo=class Tr{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=Bl;this.X=xr(t,0n,o),this.Y=xr(n,0n,o),this.Z=xr(r,1n,o),this.T=xr(s,0n,o),Object.freeze(this)}static CURVE(){return Og}static fromAffine(t){return new Tr(t.x,t.y,1n,P(t.x*t.y))}static fromBytes(t,n=!1){let r=Ol,s=Gl(rn(t,fa)),o=t[31];s[31]=o&-129;let i=Fg(s);xr(i,0n,n?Bl:ia);let c=P(i*i),l=oe(c-1n),u=P(r*c+1n),{isValid:d,value:f}=rx(l,u);d||ke("bad point: y not sqrt");let m=(f&1n)===1n,p=(o&128)!==0;return!n&&f===0n&&p&&ke("bad point: x==0, isLastByteOdd"),p!==m&&(f=oe(-f)),new Tr(f,i,1n,P(f*i))}static fromHex(t,n){return Tr.fromBytes(Yl(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=$l,n=Ol,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),f=P(c*t),m=P(u*(f+l)),p=oe(d+P(n*P(c*l)));if(m!==p)return ke("bad point: equation left != right (1)");let g=P(s*o),v=P(i*a);return g!==v?ke("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=Ml(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(Er)}negate(){return new Tr(oe(-this.X),this.Y,this.Z,oe(-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=oe(t+n),u=oe(P(l*l)-o-i),d=oe(c+i),f=oe(d-a),m=oe(c-i),p=P(u*f),g=P(d*m),v=P(u*m),A=P(f*d);return new Tr(p,g,A,v)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=Ml(t),u=$l,d=Ol,f=P(n*i),m=P(r*a),p=P(P(o*d)*l),g=P(s*c),v=oe(P(oe(n+r)*oe(i+a))-f-m),A=oe(g-p),b=oe(g+p),w=oe(m-P(u*f)),S=P(v*A),E=P(b*w),I=P(v*w),y=P(A*b);return new Tr(S,E,y,I)}subtract(t){return this.add(Ml(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(xr(t,1n,sa),!n&&this.is0()))return Er;if(t===1n)return this;if(this.equals(Ir))return mx(t).p;let r=Er,s=Ir;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(Er))return{x:0n,y:1n};let s=Ug(r,ia);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=Bg(n);return r[31]|=t&1n?128:0,r}toHex(){return Wl(this.toBytes())}clearCofactor(){return this.multiply(aa(zS),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(sa/2n,!1).double();return sa%2n&&(t=t.add(this)),t.is0()}},Ir=new vo(ag,cg,1n,oe(ag*cg)),Er=new vo(0n,1n,1n,0n);vo.BASE=Ir;vo.ZERO=Er;Bg=e=>Yl(Mg(xr(e,0n,Bl),64)).reverse(),Fg=e=>aa("0x"+Wl(Gl(rn(e)).reverse())),Rt=(e,t)=>{let n=e;for(;t-- >0n;)n=P(n*n);return n},nx=e=>{let t=P(e*e),n=P(t*e),r=P(Rt(n,2n)*n),s=P(Rt(r,1n)*e),o=P(Rt(s,5n)*s),i=P(Rt(o,10n)*o),a=P(Rt(i,20n)*i),c=P(Rt(a,40n)*a),l=P(Rt(c,80n)*c),u=P(Rt(l,80n)*c),d=P(Rt(u,10n)*o);return{pow_p_5_8:P(Rt(d,2n)*e),b2:n}},dg=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,rx=(e,t)=>{let n=P(t*P(t*t)),r=P(P(n*n)*t),s=nx(P(e*r)).pow_p_5_8,o=P(e*P(n*s)),i=P(t*P(o*o)),a=o,c=P(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=>Lg(Fg(e)),zl=(...e)=>Promise.resolve(Dg("sha512Async")(ms(...e))).then(jg),sx=(...e)=>jg(Dg("sha512")(ms(...e))),Hg=e=>{let t=Gl(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=Ir.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},ox=e=>zl(rn(e,fa)).then(Hg),ix=e=>Hg(sx(rn(e,fa))),ax=e=>ix(e).pointBytes,cx=e=>zl(e.hashable).then(e.finish),lx=(e,t,n)=>{let{pointBytes:r,scalar:s}=e,o=Fl(t),i=Ir.multiply(o).toBytes();return{hashable:ms(i,r,n),finish:l=>{let u=Lg(o+Fl(l)*s);return rn(ms(i,Bg(u)),64)}}},ux=async(e,t)=>{let n=rn(e),r=await ox(t),s=await zl(r.prefix,n);return cx(lx(r,s,n))},Jl=Object.freeze({bytesToHex:Wl,hexToBytes:Yl,concatBytes:ms,mod:oe,invert:Ug,randomBytes:tx}),Vg={sha512Async:async e=>{let t=ex(),n=ms(e);return ma(await t.digest("SHA-512",n.buffer))},sha512:void 0},ca=8,dx=256,qg=Math.ceil(dx/ca)+1,Hl=2**(ca-1),fx=()=>{let e=[],t=Ir,n=t;for(let r=0;r<qg;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},fg=void 0,mg=(e,t)=>{let n=t.negate();return e?n:t},mx=e=>{let t=fg||(fg=fx()),n=Er,r=Ir,s=2**ca,o=s,i=aa(s-1),a=aa(ca);for(let c=0;c<qg;c++){let l=Number(e&i);e>>=a,l>Hl&&(l-=o,e+=1n);let u=c*Hl,d=u,f=u+Math.abs(l)-1,m=c%2!==0,p=l<0;l===0?r=r.add(mg(m,t[d])):n=n.add(mg(p,t[f]))}return e!==0n&&ke("invalid wnaf"),{p:n,f:r}};Wg=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});Yg=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=Nl(this.buffer)}update(e){pg(this),Kg(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=Nl(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){pg(this),gx(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,bo(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=Nl(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()}},Nn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ne=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Zi=BigInt(2**32-1),gg=BigInt(32);hg=(e,t,n)=>e>>>n,yg=(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,Qi=(e,t,n)=>e<<64-n|t>>>n-32,ea=(e,t,n)=>e>>>n-32|t<<64-n;vx=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),wx=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Sx=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),xx=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,Tx=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),Ax=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,kx=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]),Ln=new Uint32Array(64),Cx=class extends Yg{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)Ln[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let d=Ln[u-15],f=Ln[u-2],m=It(d,7)^It(d,18)^d>>>3,p=It(f,17)^It(f,19)^f>>>10;Ln[u]=p+Ln[u-7]+m+Ln[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=It(i,6)^It(i,11)^It(i,25),f=l+d+hx(i,a,c)+kx[u]+Ln[u]|0,p=(It(n,2)^It(n,13)^It(n,22))+yx(n,r,s)|0;l=c,c=a,a=i,i=o+f|0,o=s,s=r,r=n,n=f+p|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(){bo(Ln)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),bo(this.buffer)}},Ex=class extends Cx{A=Nn[0]|0;B=Nn[1]|0;C=Nn[2]|0;D=Nn[3]|0;E=Nn[4]|0;F=Nn[5]|0;G=Nn[6]|0;H=Nn[7]|0;constructor(){super(32)}},zg=bx(["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))),Rx=zg[0],Ix=zg[1],Un=new Uint32Array(80),Dn=new Uint32Array(80),Px=class extends Yg{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:f,Gl:m,Hh:p,Hl:g}=this;return[e,t,n,r,s,o,i,a,c,l,u,d,f,m,p,g]}set(e,t,n,r,s,o,i,a,c,l,u,d,f,m,p,g){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=f|0,this.Gl=m|0,this.Hh=p|0,this.Hl=g|0}process(e,t){for(let b=0;b<16;b++,t+=4)Un[b]=e.getUint32(t),Dn[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let w=Un[b-15]|0,S=Dn[b-15]|0,E=ls(w,S,1)^ls(w,S,8)^hg(w,S,7),I=us(w,S,1)^us(w,S,8)^yg(w,S,7),y=Un[b-2]|0,T=Dn[b-2]|0,z=ls(y,T,19)^Qi(y,T,61)^hg(y,T,6),Z=us(y,T,19)^ea(y,T,61)^yg(y,T,6),H=Sx(I,Z,Dn[b-7],Dn[b-16]),be=xx(H,E,z,Un[b-7],Un[b-16]);Un[b]=be|0,Dn[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:f,Fl:m,Gh:p,Gl:g,Hh:v,Hl:A}=this;for(let b=0;b<80;b++){let w=ls(u,d,14)^ls(u,d,18)^Qi(u,d,41),S=us(u,d,14)^us(u,d,18)^ea(u,d,41),E=u&f^~u&p,I=d&m^~d&g,y=Tx(A,S,I,Ix[b],Dn[b]),T=Ax(y,v,w,E,Rx[b],Un[b]),z=y|0,Z=ls(n,r,28)^Qi(n,r,34)^Qi(n,r,39),H=us(n,r,28)^ea(n,r,34)^ea(n,r,39),be=n&s^n&i^s&i,se=r&o^r&a^o&a;v=p|0,A=g|0,p=f|0,g=m|0,f=u|0,m=d|0,{h:u,l:d}=en(c|0,l|0,T|0,z|0),c=i|0,l=a|0,i=s|0,a=o|0,s=n|0,o=r|0;let X=vx(z,H,se);n=wx(X,T,Z,be),r=X|0}({h:n,l:r}=en(this.Ah|0,this.Al|0,n|0,r|0)),{h:s,l:o}=en(this.Bh|0,this.Bl|0,s|0,o|0),{h:i,l:a}=en(this.Ch|0,this.Cl|0,i|0,a|0),{h:c,l}=en(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=en(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:m}=en(this.Fh|0,this.Fl|0,f|0,m|0),{h:p,l:g}=en(this.Gh|0,this.Gl|0,p|0,g|0),{h:v,l:A}=en(this.Hh|0,this.Hl|0,v|0,A|0),this.set(n,r,s,o,i,a,c,l,u,d,f,m,p,g,v,A)}roundClean(){bo(Un,Dn)}destroy(){this.destroyed=!0,bo(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},$x=class extends Px{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)}},Ox=Gg(()=>new Ex,Wg(1)),Mx=Gg(()=>new $x,Wg(3)),_g=Vg;_g.sha512||(_g.sha512=e=>Mx(e));Ux=Jl.bytesToHex,Jg=Jl.hexToBytes;Jl.concatBytes;jx=new TextEncoder,Bx={subwayAgentMsgV1:"message_id;sender_peer_id;sender_name;timestamp_ms;message_type;payload_hash;nonce"};Jg("302e020100300506032b657004220420");Jg("302a300506032b6570032100");Xg=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:la,n:oa,Gx:bg,Gy:vg,a:Ll,d:Ul,h:qx}=Xg,ps=32,Kx=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},Ce=(e="")=>{let t=new Error(e);throw Kx(t,Ce),t},Gx=e=>typeof e=="bigint",Wx=e=>typeof e=="string",Yx=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,Hn=(e,t,n="")=>{let r=Yx(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},pa=e=>new Uint8Array(e),Xl=e=>Uint8Array.from(e),Zg=(e,t)=>e.toString(16).padStart(t,"0"),Qg=e=>Array.from(Hn(e)).map(t=>Zg(t,2)).join(""),tn={_0:48,_9:57,A:65,F:70,a:97,f:102},wg=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)},eh=e=>{let t="hex invalid";if(!Wx(e))return Ce(t);let n=e.length,r=n/2;if(n%2)return Ce(t);let s=pa(r);for(let o=0,i=0;o<r;o++,i+=2){let a=wg(e.charCodeAt(i)),c=wg(e.charCodeAt(i+1));if(a===void 0||c===void 0)return Ce(t);s[o]=a*16+c}return s},th=()=>globalThis?.crypto,zx=()=>th()?.subtle??Ce("crypto.subtle must be defined, consider polyfill"),Zl=(...e)=>{let t=0;for(let s of e)t+=Hn(s).length;let n=pa(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},Jx=(e=ps)=>th().getRandomValues(pa(e)),ua=BigInt,Ar=(e,t,n,r="bad number: out of range")=>{if(!Gx(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},ae=(e,t=la)=>{let n=e%t;return n>=0n?n:t+n},Sg=(1n<<255n)-1n,$=e=>{e<0n&&Ce("negative coordinate");let t=(e>>255n)*19n+(e&Sg);return t=(t>>255n)*19n+(t&Sg),t%la},Xx=e=>ae(e,oa),Zx=(e,t)=>{(e===0n||t<=0n)&&Ce("no inverse n="+e+" mod="+t);let n=ae(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?ae(s,t):Ce("no inverse")},nh=e=>{let t=ah[e];return typeof t!="function"&&Ce("hashes."+e+" not set"),t},rh=e=>Hn(e,64,"digest"),Dl=e=>e instanceof wo?e:Ce("Point expected"),Vl=2n**256n,wo=class kr{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=Vl;this.X=Ar(t,0n,o),this.Y=Ar(n,0n,o),this.Z=Ar(r,1n,o),this.T=Ar(s,0n,o),Object.freeze(this)}static CURVE(){return Xg}static fromAffine(t){return new kr(t.x,t.y,1n,$(t.x*t.y))}static fromBytes(t,n=!1){let r=Ul,s=Xl(Hn(t,ps)),o=t[31];s[31]=o&-129;let i=sh(s);Ar(i,0n,n?Vl:la);let c=$(i*i),l=ae(c-1n),u=$(r*c+1n),{isValid:d,value:f}=tT(l,u);d||Ce("bad point: y not sqrt");let m=(f&1n)===1n,p=(o&128)!==0;return!n&&f===0n&&p&&Ce("bad point: x==0, isLastByteOdd"),p!==m&&(f=ae(-f)),new kr(f,i,1n,$(f*i))}static fromHex(t,n){return kr.fromBytes(eh(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 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),f=$(c*t),m=$(u*(f+l)),p=ae(d+$(n*$(c*l)));if(m!==p)return Ce("bad point: equation left != right (1)");let g=$(s*o),v=$(i*a);return g!==v?Ce("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=$(n*a),l=$(o*s),u=$(r*a),d=$(i*s);return c===l&&u===d}is0(){return this.equals(Rr)}negate(){return new kr(ae(-this.X),this.Y,this.Z,ae(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=Ll,o=$(t*t),i=$(n*n),a=$(2n*r*r),c=$(s*o),l=ae(t+n),u=ae($(l*l)-o-i),d=ae(c+i),f=ae(d-a),m=ae(c-i),p=$(u*f),g=$(d*m),v=$(u*m),A=$(f*d);return new kr(p,g,A,v)}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,f=$(n*i),m=$(r*a),p=$($(o*d)*l),g=$(s*c),v=ae($(ae(n+r)*ae(i+a))-f-m),A=ae(g-p),b=ae(g+p),w=ae(m-$(u*f)),S=$(v*A),E=$(b*w),I=$(v*w),y=$(A*b);return new kr(S,E,y,I)}subtract(t){return this.add(Dl(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(Ar(t,1n,oa),!n&&this.is0()))return Rr;if(t===1n)return this;if(this.equals(gs))return dT(t).p;let r=Rr,s=gs;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(Rr))return{x:0n,y:1n};let s=Zx(r,la);$(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=Qx(n);return r[31]|=t&1n?128:0,r}toHex(){return Qg(this.toBytes())}clearCofactor(){return this.multiply(ua(qx),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(oa/2n,!1).double();return oa%2n&&(t=t.add(this)),t.is0()}},gs=new wo(bg,vg,1n,ae(bg*vg)),Rr=new wo(0n,1n,1n,0n);wo.BASE=gs;wo.ZERO=Rr;Qx=e=>eh(Zg(Ar(e,0n,Vl),64)).reverse(),sh=e=>ua("0x"+Qg(Xl(Hn(e)).reverse())),Pt=(e,t)=>{let n=e;for(;t-- >0n;)n=$(n*n);return n},eT=e=>{let t=$(e*e),n=$(t*e),r=$(Pt(n,2n)*n),s=$(Pt(r,1n)*e),o=$(Pt(s,5n)*s),i=$(Pt(o,10n)*o),a=$(Pt(i,20n)*i),c=$(Pt(a,40n)*a),l=$(Pt(c,80n)*c),u=$(Pt(l,80n)*c),d=$(Pt(u,10n)*o);return{pow_p_5_8:$(Pt(d,2n)*e),b2:n}},xg=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,tT=(e,t)=>{let n=$(t*$(t*t)),r=$($(n*n)*t),s=eT($(e*r)).pow_p_5_8,o=$(e*$(n*s)),i=$(t*$(o*o)),a=o,c=$(o*xg),l=i===e,u=i===ae(-e),d=i===ae(-e*xg);return l&&(o=a),(u||d)&&(o=c),(ae(o)&1n)===1n&&(o=ae(-o)),{isValid:l||u,value:o}},nT=e=>Xx(sh(e)),rT=(...e)=>Promise.resolve(nh("sha512Async")(Zl(...e))).then(rh),sT=(...e)=>rh(nh("sha512")(Zl(...e))),oh=e=>{let t=Xl(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=nT(n),o=gs.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},oT=e=>rT(Hn(e,ps)).then(oh),ih=e=>oh(sT(Hn(e,ps))),iT=e=>ih(e).pointBytes,ah={sha512Async:async e=>{let t=zx(),n=Zl(e);return pa(await t.digest("SHA-512",n.buffer))},sha512:void 0},aT=e=>(e=e===void 0?Jx(ps):e,Hn(e,ps)),cT=Object.freeze({getExtendedPublicKeyAsync:oT,getExtendedPublicKey:ih,randomSecretKey:aT}),da=8,lT=256,ch=Math.ceil(lT/da)+1,ql=2**(da-1),uT=()=>{let e=[],t=gs,n=t;for(let r=0;r<ch;r++){n=t,e.push(n);for(let s=1;s<ql;s++)n=n.add(t),e.push(n);t=n.double()}return e},Tg=void 0,Ag=(e,t)=>{let n=t.negate();return e?n:t},dT=e=>{let t=Tg||(Tg=uT()),n=Rr,r=gs,s=2**da,o=s,i=ua(s-1),a=ua(da);for(let c=0;c<ch;c++){let l=Number(e&i);e>>=a,l>ql&&(l-=o,e+=1n);let u=c*ql,d=u,f=u+Math.abs(l)-1,m=c%2!==0,p=l<0;l===0?r=r.add(Ag(m,t[d])):n=n.add(Ag(p,t[f]))}return e!==0n&&Ce("invalid wnaf"),{p:n,f:r}};gT=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),hT=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){kg(this),lh(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){kg(this),mT(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,Kl(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()}},Le=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),ta=BigInt(2**32-1),Cg=BigInt(32);Eg=(e,t,n)=>e>>>n,Rg=(e,t,n)=>e<<32-n|t>>>n,ds=(e,t,n)=>e>>>n|t<<32-n,fs=(e,t,n)=>e<<32-n|t>>>n,na=(e,t,n)=>e<<64-n|t>>>n-32,ra=(e,t,n)=>e>>>n-32|t<<64-n;bT=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),vT=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,wT=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),ST=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,xT=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),TT=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,uh=_T(["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))),AT=uh[0],kT=uh[1],jn=new Uint32Array(80),Bn=new Uint32Array(80),CT=class extends hT{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:f,Gl:m,Hh:p,Hl:g}=this;return[e,t,n,r,s,o,i,a,c,l,u,d,f,m,p,g]}set(e,t,n,r,s,o,i,a,c,l,u,d,f,m,p,g){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=f|0,this.Gl=m|0,this.Hh=p|0,this.Hl=g|0}process(e,t){for(let b=0;b<16;b++,t+=4)jn[b]=e.getUint32(t),Bn[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let w=jn[b-15]|0,S=Bn[b-15]|0,E=ds(w,S,1)^ds(w,S,8)^Eg(w,S,7),I=fs(w,S,1)^fs(w,S,8)^Rg(w,S,7),y=jn[b-2]|0,T=Bn[b-2]|0,z=ds(y,T,19)^na(y,T,61)^Eg(y,T,6),Z=fs(y,T,19)^ra(y,T,61)^Rg(y,T,6),H=wT(I,Z,Bn[b-7],Bn[b-16]),be=ST(H,E,z,jn[b-7],jn[b-16]);jn[b]=be|0,Bn[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:f,Fl:m,Gh:p,Gl:g,Hh:v,Hl:A}=this;for(let b=0;b<80;b++){let w=ds(u,d,14)^ds(u,d,18)^na(u,d,41),S=fs(u,d,14)^fs(u,d,18)^ra(u,d,41),E=u&f^~u&p,I=d&m^~d&g,y=xT(A,S,I,kT[b],Bn[b]),T=TT(y,v,w,E,AT[b],jn[b]),z=y|0,Z=ds(n,r,28)^na(n,r,34)^na(n,r,39),H=fs(n,r,28)^ra(n,r,34)^ra(n,r,39),be=n&s^n&i^s&i,se=r&o^r&a^o&a;v=p|0,A=g|0,p=f|0,g=m|0,f=u|0,m=d|0,{h:u,l:d}=nn(c|0,l|0,T|0,z|0),c=i|0,l=a|0,i=s|0,a=o|0,s=n|0,o=r|0;let X=bT(z,H,se);n=vT(X,T,Z,be),r=X|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:f,l:m}=nn(this.Fh|0,this.Fl|0,f|0,m|0),{h:p,l:g}=nn(this.Gh|0,this.Gl|0,p|0,g|0),{h:v,l:A}=nn(this.Hh|0,this.Hl|0,v|0,A|0),this.set(n,r,s,o,i,a,c,l,u,d,f,m,p,g,v,A)}roundClean(){Kl(jn,Bn)}destroy(){this.destroyed=!0,Kl(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},ET=class extends CT{Ah=Le[0]|0;Al=Le[1]|0;Bh=Le[2]|0;Bl=Le[3]|0;Ch=Le[4]|0;Cl=Le[5]|0;Dh=Le[6]|0;Dl=Le[7]|0;Eh=Le[8]|0;El=Le[9]|0;Fh=Le[10]|0;Fl=Le[11]|0;Gh=Le[12]|0;Gl=Le[13]|0;Hh=Le[14]|0;Hl=Le[15]|0;constructor(){super(64)}},RT=pT(()=>new ET,gT(3)),Ig=ah;Ig.sha512||(Ig.sha512=e=>RT(e));NT="ws://localhost:9001/ws",LT=3e4,fh=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=Cr(e.name),e.keyPath)try{this._keypair=OT(e.keyPath)}catch{}this.options={name:this._name,url:e.url??NT,relay:e.relay??"",autoReconnect:e.autoReconnect??!0,reconnectInterval:e.reconnectInterval??1e3,maxReconnectAttempts:e.maxReconnectAttempts??10,rpcTimeout:e.rpcTimeout??LT,pingInterval:e.pingInterval??3e4,binding:e.binding??""},this.transport=new YS({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=Vx(new Uint8Array(t));n&&(this._keypair={privateKey:n,publicKey:Nx(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=Pg(this._keypair.publicKey)),this.options.binding&&(n.binding=this.options.binding);try{this.transport.send(n)}catch(r){this.registerPromise=null,t(r instanceof Error?r:new Me(String(r)))}})}disconnect(){for(let[,e]of this.pendingCalls)clearTimeout(e.timer),e.reject(new Me("Client disconnected"));this.pendingCalls.clear();for(let[,e]of this.pendingSend)e.reject(new Me("Client disconnected"));this.pendingSend.clear();for(let[,e]of this.pendingResolve)e.reject(new Me("Client disconnected"));this.pendingResolve.clear(),this.registerPromise&&(this.registerPromise.reject(new Me("Client disconnected")),this.registerPromise=null),this.transport.disconnect(),this._peerId=null,this.hasConnectedOnce=!1}async send(e,t,n,r){let s=Cr(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 Me(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=Cr(e),o=Pl(),i=Date.now(),a=Math.floor(Math.random()*2**32),c=new TextEncoder().encode(n),{signature:l,signatureInput:u}=await MT(this._keypair.privateKey,o,this._peerId,this._name,i,t,c,a);return new Promise((d,f)=>{this.pendingSend.set(s,{resolve:d,reject:f});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(m){this.pendingSend.delete(s),f(m instanceof Error?m:new Me(String(m)))}setTimeout(()=>{this.pendingSend.has(s)&&(this.pendingSend.delete(s),d({messageId:o,to:s}))},5e3)})}async call(e,t,n,r){let s=Cr(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 _o(`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 Me(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=Cr(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 Me(String(s)))}setTimeout(()=>{this.pendingResolve.has(t)&&(this.pendingResolve.delete(t),r(new _o(`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=El(e.code,e.message);this.registerPromise&&e.code==="register_failed"&&(this.registerPromise.reject(new Xi(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=Pg(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 nA(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Dh(e,t,n=""){let r=nA(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 vh(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 rA(e,t){Dh(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 au(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ru(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function sA(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 aA(e,t=!1){return t?{h:Number(e&ga),l:Number(e>>wh&ga)}:{h:Number(e>>wh&ga)|0,l:Number(e&ga)|0}}function cA(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}=aA(e[o],t);[r[o],s[o]]=[i,a]}return[r,s]}function on(e,t,n,r){let s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}function vA(){return ZT.randomSecretKey()}function xa(e){return WT(e)}function Bh(){let e=vA();return{secretKey:e,publicKey:xa(e)}}function xo(e,t){return JT(t,e)}function wA(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function SA(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 vs(e){return wA(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function xA(e){let t=e.length%4===0?0:4-e.length%4,n=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return SA(n)}function TA(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function Hh(e){let t=xa(e);return{kty:"OKP",crv:"Ed25519",x:vs(t),d:vs(e)}}function Vh(e){return{kty:"OKP",crv:"Ed25519",x:vs(e)}}function To(e){if(TA(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return xA(e.d)}var Ah,ba,_a,mh,ph,eu,tu,UT,_s,DT,Ee,jT,BT,FT,Ot,Sa,cu,kh,lu,sn,gh,uu,Ch,HT,bs,Eh,va,Pr,ie,hh,O,Rh,Ih,Ph,$h,nu,su,So,Mr,Or,Oh,Mh,$t,VT,yh,qT,ou,KT,du,Nh,GT,fu,WT,YT,zT,JT,mu,Lh,XT,ZT,wa,QT,Uh,iu,eA,_h,bh,tA,oA,iA,Ue,ga,wh,Sh,xh,hs,ys,ha,ya,lA,uA,dA,fA,mA,pA,jh,gA,hA,Vn,qn,yA,_A,bA,Th,tP,Fh,nP,rP,sP,oP,Ta=nt(()=>{"use strict";Ah=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:ba,n:_a,Gx:mh,Gy:ph,a:eu,d:tu,h:UT}=Ah,_s=32,DT=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},Ee=(e="")=>{let t=new Error(e);throw DT(t,Ee),t},jT=e=>typeof e=="bigint",BT=e=>typeof e=="string",FT=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,Ot=(e,t,n="")=>{let r=FT(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},Sa=e=>new Uint8Array(e),cu=e=>Uint8Array.from(e),kh=(e,t)=>e.toString(16).padStart(t,"0"),lu=e=>Array.from(Ot(e)).map(t=>kh(t,2)).join(""),sn={_0:48,_9:57,A:65,F:70,a:97,f:102},gh=e=>{if(e>=sn._0&&e<=sn._9)return e-sn._0;if(e>=sn.A&&e<=sn.F)return e-(sn.A-10);if(e>=sn.a&&e<=sn.f)return e-(sn.a-10)},uu=e=>{let t="hex invalid";if(!BT(e))return Ee(t);let n=e.length,r=n/2;if(n%2)return Ee(t);let s=Sa(r);for(let o=0,i=0;o<r;o++,i+=2){let a=gh(e.charCodeAt(i)),c=gh(e.charCodeAt(i+1));if(a===void 0||c===void 0)return Ee(t);s[o]=a*16+c}return s},Ch=()=>globalThis?.crypto,HT=()=>Ch()?.subtle??Ee("crypto.subtle must be defined, consider polyfill"),bs=(...e)=>{let t=0;for(let s of e)t+=Ot(s).length;let n=Sa(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},Eh=(e=_s)=>Ch().getRandomValues(Sa(e)),va=BigInt,Pr=(e,t,n,r="bad number: out of range")=>{if(!jT(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},ie=(e,t=ba)=>{let n=e%t;return n>=0n?n:t+n},hh=(1n<<255n)-1n,O=e=>{e<0n&&Ee("negative coordinate");let t=(e>>255n)*19n+(e&hh);return t=(t>>255n)*19n+(t&hh),t%ba},Rh=e=>ie(e,_a),Ih=(e,t)=>{(e===0n||t<=0n)&&Ee("no inverse n="+e+" mod="+t);let n=ie(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?ie(s,t):Ee("no inverse")},Ph=e=>{let t=Lh[e];return typeof t!="function"&&Ee("hashes."+e+" not set"),t},$h=e=>Ot(e,64,"digest"),nu=e=>e instanceof So?e:Ee("Point expected"),su=2n**256n,So=class $r{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=su;this.X=Pr(t,0n,o),this.Y=Pr(n,0n,o),this.Z=Pr(r,1n,o),this.T=Pr(s,0n,o),Object.freeze(this)}static CURVE(){return Ah}static fromAffine(t){return new $r(t.x,t.y,1n,O(t.x*t.y))}static fromBytes(t,n=!1){let r=tu,s=cu(Ot(t,_s)),o=t[31];s[31]=o&-129;let i=Mh(s);Pr(i,0n,n?su:ba);let c=O(i*i),l=ie(c-1n),u=O(r*c+1n),{isValid:d,value:f}=qT(l,u);d||Ee("bad point: y not sqrt");let m=(f&1n)===1n,p=(o&128)!==0;return!n&&f===0n&&p&&Ee("bad point: x==0, isLastByteOdd"),p!==m&&(f=ie(-f)),new $r(f,i,1n,O(f*i))}static fromHex(t,n){return $r.fromBytes(uu(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=eu,n=tu,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),f=O(c*t),m=O(u*(f+l)),p=ie(d+O(n*O(c*l)));if(m!==p)return Ee("bad point: equation left != right (1)");let g=O(s*o),v=O(i*a);return g!==v?Ee("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=nu(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(Or)}negate(){return new $r(ie(-this.X),this.Y,this.Z,ie(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=eu,o=O(t*t),i=O(n*n),a=O(2n*r*r),c=O(s*o),l=ie(t+n),u=ie(O(l*l)-o-i),d=ie(c+i),f=ie(d-a),m=ie(c-i),p=O(u*f),g=O(d*m),v=O(u*m),A=O(f*d);return new $r(p,g,A,v)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=nu(t),u=eu,d=tu,f=O(n*i),m=O(r*a),p=O(O(o*d)*l),g=O(s*c),v=ie(O(ie(n+r)*ie(i+a))-f-m),A=ie(g-p),b=ie(g+p),w=ie(m-O(u*f)),S=O(v*A),E=O(b*w),I=O(v*w),y=O(A*b);return new $r(S,E,y,I)}subtract(t){return this.add(nu(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(Pr(t,1n,_a),!n&&this.is0()))return Or;if(t===1n)return this;if(this.equals(Mr))return tA(t).p;let r=Or,s=Mr;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(Or))return{x:0n,y:1n};let s=Ih(r,ba);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=Oh(n);return r[31]|=t&1n?128:0,r}toHex(){return lu(this.toBytes())}clearCofactor(){return this.multiply(va(UT),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(_a/2n,!1).double();return _a%2n&&(t=t.add(this)),t.is0()}},Mr=new So(mh,ph,1n,ie(mh*ph)),Or=new So(0n,1n,1n,0n);So.BASE=Mr;So.ZERO=Or;Oh=e=>uu(kh(Pr(e,0n,su),64)).reverse(),Mh=e=>va("0x"+lu(cu(Ot(e)).reverse())),$t=(e,t)=>{let n=e;for(;t-- >0n;)n=O(n*n);return n},VT=e=>{let t=O(e*e),n=O(t*e),r=O($t(n,2n)*n),s=O($t(r,1n)*e),o=O($t(s,5n)*s),i=O($t(o,10n)*o),a=O($t(i,20n)*i),c=O($t(a,40n)*a),l=O($t(c,80n)*c),u=O($t(l,80n)*c),d=O($t(u,10n)*o);return{pow_p_5_8:O($t(d,2n)*e),b2:n}},yh=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,qT=(e,t)=>{let n=O(t*O(t*t)),r=O(O(n*n)*t),s=VT(O(e*r)).pow_p_5_8,o=O(e*O(n*s)),i=O(t*O(o*o)),a=o,c=O(o*yh),l=i===e,u=i===ie(-e),d=i===ie(-e*yh);return l&&(o=a),(u||d)&&(o=c),(ie(o)&1n)===1n&&(o=ie(-o)),{isValid:l||u,value:o}},ou=e=>Rh(Mh(e)),KT=(...e)=>Promise.resolve(Ph("sha512Async")(bs(...e))).then($h),du=(...e)=>$h(Ph("sha512")(bs(...e))),Nh=e=>{let t=cu(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=ou(n),o=Mr.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},GT=e=>KT(Ot(e,_s)).then(Nh),fu=e=>Nh(du(Ot(e,_s))),WT=e=>fu(e).pointBytes,YT=e=>e.finish(du(e.hashable)),zT=(e,t,n)=>{let{pointBytes:r,scalar:s}=e,o=ou(t),i=Mr.multiply(o).toBytes();return{hashable:bs(i,r,n),finish:l=>{let u=Rh(o+ou(l)*s);return Ot(bs(i,Oh(u)),64)}}},JT=(e,t)=>{let n=Ot(e),r=fu(t),s=du(r.prefix,n);return YT(zT(r,s,n))},mu=Object.freeze({bytesToHex:lu,hexToBytes:uu,concatBytes:bs,mod:ie,invert:Ih,randomBytes:Eh}),Lh={sha512Async:async e=>{let t=HT(),n=bs(e);return Sa(await t.digest("SHA-512",n.buffer))},sha512:void 0},XT=e=>(e=e===void 0?Eh(_s):e,Ot(e,_s)),ZT=Object.freeze({getExtendedPublicKeyAsync:GT,getExtendedPublicKey:fu,randomSecretKey:XT}),wa=8,QT=256,Uh=Math.ceil(QT/wa)+1,iu=2**(wa-1),eA=()=>{let e=[],t=Mr,n=t;for(let r=0;r<Uh;r++){n=t,e.push(n);for(let s=1;s<iu;s++)n=n.add(t),e.push(n);t=n.double()}return e},_h=void 0,bh=(e,t)=>{let n=t.negate();return e?n:t},tA=e=>{let t=_h||(_h=eA()),n=Or,r=Mr,s=2**wa,o=s,i=va(s-1),a=va(wa);for(let c=0;c<Uh;c++){let l=Number(e&i);e>>=a,l>iu&&(l-=o,e+=1n);let u=c*iu,d=u,f=u+Math.abs(l)-1,m=c%2!==0,p=l<0;l===0?r=r.add(bh(m,t[d])):n=n.add(bh(p,t[f]))}return e!==0n&&Ee("invalid wnaf"),{p:n,f:r}};oA=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),iA=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=ru(this.buffer)}update(e){vh(this),Dh(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=ru(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){vh(this),rA(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,au(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=ru(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()}},Ue=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),ga=BigInt(2**32-1),wh=BigInt(32);Sh=(e,t,n)=>e>>>n,xh=(e,t,n)=>e<<32-n|t>>>n,hs=(e,t,n)=>e>>>n|t<<32-n,ys=(e,t,n)=>e<<32-n|t>>>n,ha=(e,t,n)=>e<<64-n|t>>>n-32,ya=(e,t,n)=>e>>>n-32|t<<64-n;lA=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),uA=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,dA=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),fA=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,mA=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),pA=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,jh=cA(["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))),gA=jh[0],hA=jh[1],Vn=new Uint32Array(80),qn=new Uint32Array(80),yA=class extends iA{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:f,Gl:m,Hh:p,Hl:g}=this;return[e,t,n,r,s,o,i,a,c,l,u,d,f,m,p,g]}set(e,t,n,r,s,o,i,a,c,l,u,d,f,m,p,g){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=f|0,this.Gl=m|0,this.Hh=p|0,this.Hl=g|0}process(e,t){for(let b=0;b<16;b++,t+=4)Vn[b]=e.getUint32(t),qn[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let w=Vn[b-15]|0,S=qn[b-15]|0,E=hs(w,S,1)^hs(w,S,8)^Sh(w,S,7),I=ys(w,S,1)^ys(w,S,8)^xh(w,S,7),y=Vn[b-2]|0,T=qn[b-2]|0,z=hs(y,T,19)^ha(y,T,61)^Sh(y,T,6),Z=ys(y,T,19)^ya(y,T,61)^xh(y,T,6),H=dA(I,Z,qn[b-7],qn[b-16]),be=fA(H,E,z,Vn[b-7],Vn[b-16]);Vn[b]=be|0,qn[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:f,Fl:m,Gh:p,Gl:g,Hh:v,Hl:A}=this;for(let b=0;b<80;b++){let w=hs(u,d,14)^hs(u,d,18)^ha(u,d,41),S=ys(u,d,14)^ys(u,d,18)^ya(u,d,41),E=u&f^~u&p,I=d&m^~d&g,y=mA(A,S,I,hA[b],qn[b]),T=pA(y,v,w,E,gA[b],Vn[b]),z=y|0,Z=hs(n,r,28)^ha(n,r,34)^ha(n,r,39),H=ys(n,r,28)^ya(n,r,34)^ya(n,r,39),be=n&s^n&i^s&i,se=r&o^r&a^o&a;v=p|0,A=g|0,p=f|0,g=m|0,f=u|0,m=d|0,{h:u,l:d}=on(c|0,l|0,T|0,z|0),c=i|0,l=a|0,i=s|0,a=o|0,s=n|0,o=r|0;let X=lA(z,H,se);n=uA(X,T,Z,be),r=X|0}({h:n,l:r}=on(this.Ah|0,this.Al|0,n|0,r|0)),{h:s,l:o}=on(this.Bh|0,this.Bl|0,s|0,o|0),{h:i,l:a}=on(this.Ch|0,this.Cl|0,i|0,a|0),{h:c,l}=on(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=on(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:m}=on(this.Fh|0,this.Fl|0,f|0,m|0),{h:p,l:g}=on(this.Gh|0,this.Gl|0,p|0,g|0),{h:v,l:A}=on(this.Hh|0,this.Hl|0,v|0,A|0),this.set(n,r,s,o,i,a,c,l,u,d,f,m,p,g,v,A)}roundClean(){au(Vn,qn)}destroy(){this.destroyed=!0,au(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},_A=class extends yA{Ah=Ue[0]|0;Al=Ue[1]|0;Bh=Ue[2]|0;Bl=Ue[3]|0;Ch=Ue[4]|0;Cl=Ue[5]|0;Dh=Ue[6]|0;Dl=Ue[7]|0;Eh=Ue[8]|0;El=Ue[9]|0;Fh=Ue[10]|0;Fl=Ue[11]|0;Gh=Ue[12]|0;Gl=Ue[13]|0;Hh=Ue[14]|0;Hl=Ue[15]|0;constructor(){super(64)}},bA=sA(()=>new _A,oA(3)),Th=Lh;Th.sha512||(Th.sha512=e=>bA(e));tP=mu.bytesToHex,Fh=mu.hexToBytes,nP=mu.concatBytes;rP=new TextEncoder;sP=Fh("302e020100300506032b657004220420"),oP=Fh("302a300506032b6570032100");});var zh={};Br(zh,{CardRequiredError:()=>an,buildIssuanceRequest:()=>Yh,enrollCardUrl:()=>Aa,jkt:()=>Gh,proofPayload:()=>Wh,readSeed:()=>ka,requestVisaBinding:()=>pu});function Gh(e){let t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return qh.createHash("sha256").update(t,"utf8").digest("base64url")}function Wh(e,t,n){return`visa-agent-binding:v1:${e}:${t}:${n}`}function Yh(e,t,n="visa",r=Math.floor(Date.now()/1e3)){let s=Vh(xa(e)),o=Buffer.from(Wh(t,Gh(s),r),"utf8"),i=Buffer.from(xo(e,o)).toString("base64url");return{name:t,mesh:n,agent_pubkey:s,proof:{ts:r,sig:i}}}function Aa(e){try{return new URL("/enroll-card",e).toString()}catch{return"https://auth.visacli.sh/enroll-card"}}async function pu(e){let t=Yh(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="",i="";try{let a=await s.json();o=a?.error??"",i=a?.error_code??""}catch{}throw s.status===403&&(i==="ACCOUNT_NOT_APPROVED"||/no card/i.test(o))?new an("No card on file \u2014 enroll a card to register on the trusted .visa mesh.",Aa(e.authUrl),"no_card"):new Error(`Visa binding issuance failed (${s.status})${o?`: ${o}`:""}`)}return await s.json()}function ka(e){return new Uint8Array(Kh.readFileSync(e))}var qh,Kh,an,Ca=nt(()=>{"use strict";qh=R(require("crypto")),Kh=R(require("fs"));Ta();an=class extends Error{enrollUrl;reason;constructor(t,n,r){super(t),this.name="CardRequiredError",this.enrollUrl=n,this.reason=r}}});var wu={};Br(wu,{SUBWAY_PROTOCOL:()=>iy,registerDirect:()=>UA,resolveDirect:()=>DA});function yu(e,t){let n=typeof t=="bigint"?t:BigInt(t);for(;n>0x7fn;)e.push(Number(n&0x7fn|0x80n)),n>>=7n;e.push(Number(n))}function Ze(e,t){let n=0n,r=0n,s=t;for(;;){let o=e[s++];if(n|=BigInt(o&127)<<r,(o&128)===0)break;r+=7n}return[n,s]}function _u(e,t){return e<<3|t}function Ao(e,t,n){e.push(_u(t,2)),yu(e,n.length);for(let r of n)e.push(r)}function AA(e,t){let n=[];return Ao(n,1,hu.encode(e)),t&&t.length>0&&Ao(n,2,hu.encode(t)),Uint8Array.from(n)}function kA(e,t,n){let r=[];return n!==0n&&(r.push(_u(1,0)),yu(r,n)),Ao(r,2,AA(e,t)),Uint8Array.from(r)}function CA(e){let t=[];return Ao(t,1,hu.encode(e)),Uint8Array.from(t)}function EA(e,t){let n=[];return t!==0n&&(n.push(_u(1,0)),yu(n,t)),Ao(n,3,CA(e)),Uint8Array.from(n)}function RA(e){let t=0,n={success:!1,error:""};for(;t<e.length;){let[r,s]=Ze(e,t);t=s;let o=Number(r)>>3,i=Number(r)&7;if(o===1&&i===0){let[a,c]=Ze(e,t);t=c,n.success=a!==0n}else if(o===2&&i===2){let[a,c]=Ze(e,t),l=c,u=l+Number(a);n.error=sy.decode(e.subarray(l,u)),t=u}else t=bu(e,t,i)}return n}function IA(e){let t=0,n={peerId:new Uint8Array(0),error:""};for(;t<e.length;){let[r,s]=Ze(e,t);t=s;let o=Number(r)>>3,i=Number(r)&7;if(o===1&&i===2){let[a,c]=Ze(e,t),l=c,u=l+Number(a);n.peerId=e.subarray(l,u),t=u}else if(o===2&&i===2){let[a,c]=Ze(e,t),l=c,u=l+Number(a);n.error=sy.decode(e.subarray(l,u)),t=u}else t=bu(e,t,i)}return n}function bu(e,t,n){if(n===0)return Ze(e,t)[1];if(n===2){let[r,s]=Ze(e,t);return s+Number(r)}if(n===5)return t+4;if(n===1)return t+8;throw new Error(`unsupported wire type ${n}`)}function oy(e){let t=0,n={requestId:0n};for(;t<e.length;){let[r,s]=Ze(e,t);t=s;let o=Number(r)>>3,i=Number(r)&7;if(o===1&&i===0){let[a,c]=Ze(e,t);t=c,n.requestId=a}else if(o===13&&i===2){let[a,c]=Ze(e,t),l=c,u=l+Number(a);n.registerNameResponse=RA(e.subarray(l,u)),t=u}else if(o===14&&i===2){let[a,c]=Ze(e,t),l=c,u=l+Number(a);n.resolveNameResponse=IA(e.subarray(l,u)),t=u}else t=bu(e,t,i)}return n}function PA(e){let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t}function vu(e){return new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1)}function $A(e){if(e.length<4)return{success:!1,error:"short reply (no length prefix)"};let t=vu(e.subarray(0,4));return e.length<4+t?{success:!1,error:`truncated frame (have ${e.length-4}, need ${t})`}:oy(e.subarray(4,4+t)).registerNameResponse??{success:!1,error:"reply carried no register_name_response"}}function OA(e){if(e.length<4)return{peerId:new Uint8Array(0),error:"short reply (no length prefix)"};let t=vu(e.subarray(0,4));return e.length<4+t?{peerId:new Uint8Array(0),error:`truncated frame (have ${e.length-4}, need ${t})`}:oy(e.subarray(4,4+t)).resolveNameResponse??{peerId:new Uint8Array(0),error:"reply carried no resolve_name_response"}}function gu(e){let t=e.reduce((s,o)=>s+o.length,0),n=new Uint8Array(t),r=0;for(let s of e)n.set(s,r),r+=s.length;return n}async function LA(e){let t=[],n=0,r=-1;for await(let s of e){let o=s instanceof Uint8Array?s:s.subarray();if(t.push(o),n+=o.length,n>Jh)throw new Error("subway: reply exceeded max size");if(r<0&&n>=4&&(r=4+vu(gu(t).subarray(0,4)),r>Jh))throw new Error("subway: declared frame exceeds max size");if(r>=0&&n>=r)return gu(t).subarray(0,r)}return gu(t)}async function ay(e){return(0,Xh.createLibp2p)({...e?{privateKey:await(0,ty.generateKeyPairFromSeed)("Ed25519",e)}:{},transports:[(0,Zh.tcp)()],connectionEncrypters:[(0,Qh.noise)()],streamMuxers:[(0,ey.yamux)()],connectionGater:{denyDialMultiaddr:async()=>!1}})}async function cy(e,t,n){let r=await e.dialProtocol((0,ny.multiaddr)(t),iy,{signal:AbortSignal.timeout(MA)});r.send(PA(n));let s;return Promise.race([LA(r),new Promise((o,i)=>{s=setTimeout(()=>i(new Error("subway: request timed out")),NA)})]).finally(()=>clearTimeout(s))}async function UA(e){let t=await ay(e.seed);try{let n=await cy(t,e.relayMultiaddr,kA(e.name,e.binding,e.requestId??1n)),r=$A(n);return{success:r.success,error:r.error,peerId:t.peerId.toString()}}finally{await t.stop()}}async function DA(e){let t=await ay(e.seed);try{let n=await cy(t,e.relayMultiaddr,EA(e.name,e.requestId??1n)),r=OA(n);return r.peerId.length===0?{found:!1,peerId:"",error:r.error||"name not found"}:{found:!0,peerId:(0,ry.toString)(r.peerId,"base58btc"),error:""}}finally{await t.stop()}}var Xh,Zh,Qh,ey,ty,ny,ry,hu,sy,iy,MA,NA,Jh,Su=nt(()=>{"use strict";Il();Xh=require("libp2p"),Zh=require("@libp2p/tcp"),Qh=require("@chainsafe/libp2p-noise"),ey=require("@chainsafe/libp2p-yamux"),ty=require("@libp2p/crypto/keys"),ny=require("@multiformats/multiaddr"),ry=require("uint8arrays/to-string"),hu=new TextEncoder,sy=new TextDecoder;iy="/subway/p2p/1.0.0",MA=15e3,NA=15e3,Jh=1<<20});var Eo={};Br(Eo,{MESH:()=>Re,RELAY_URL:()=>Co,connectOrThrow:()=>xs,ensureMailbox:()=>Nu,isSubwayEnabled:()=>Cu,listRegistered:()=>Mu,loadBindingFor:()=>Iu,loadRegistry:()=>Nr,makeClient:()=>Ss,maybeMintVisaBinding:()=>dy,meshName:()=>dt,readInbox:()=>FA,registerName:()=>Pu,resolveActingName:()=>Ia,resolveMeshName:()=>$u,seedSubwayKeyFromTapAgent:()=>uy,sendMessage:()=>Ou,sendVia:()=>HA,subwayKeyPath:()=>Ra});function dt(e){return e.includes(".")?e:`${e}.${Re}`}function Cu(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 Ru(){ve.mkdirSync(Eu,{recursive:!0,mode:448})}function jA(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function Ra(e){return ws.join(Eu,`${jA(e)}.key`)}function Nr(){if(!ve.existsSync(ku))return{};try{return JSON.parse(ve.readFileSync(ku,"utf8"))}catch{return{}}}function Tu(e){Ru(),ve.writeFileSync(ku,JSON.stringify(e,null,2),{mode:384})}function Au(){try{return ko.userInfo().username}catch{return"local"}}function uy(e){if(ve.existsSync(e)||!ve.existsSync(xu))return null;let t=ve.readdirSync(xu).filter(r=>r.endsWith(".json"));if(t.length===0)return null;let n=t.map(r=>ws.join(xu,r)).sort((r,s)=>ve.statSync(s).mtimeMs-ve.statSync(r).mtimeMs)[0];try{let r=JSON.parse(ve.readFileSync(n,"utf8"));if(!r.private_key_jwk)return null;let s=To(r.private_key_jwk);return Ru(),ve.writeFileSync(e,Buffer.from(s),{mode:384}),r.agent_id??null}catch{return null}}function Ss(e,t={}){return new fh({name:dt(e),url:Co,keyPath:Ra(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function Iu(e){if(Re!=="visa")return;let t=Nr()[e];if(t?.binding&&!(t.bindingExpiresAt&&Date.parse(t.bindingExpiresAt)<=Date.now()))return t.binding}async function xs(e,t=15e3){await Promise.race([e.connect(),new Promise((n,r)=>setTimeout(()=>r(new Error(`Subway relay connect timed out after ${t}ms (${Co})`)),t))])}function Ia(e){if(e)return e;let t=Object.keys(Nr());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 dy(e){if(Re!=="visa")return null;let t=process.env.VISA_CLI_API_KEY?.trim();if(!t)throw new an("No Visa Key configured \u2014 set VISA_CLI_API_KEY (a Visa Key with a card on file) to register on the trusted .visa mesh.",Aa(Pe()),"no_key");try{return await pu({authUrl:Pe(),apiKey:t,seed:ka(Ra(e)),name:dt(e)})}catch(n){if(n instanceof an)throw n;return console.warn(`[subway] Visa binding not minted: ${n instanceof Error?n.message:String(n)}`),null}}async function Pu(e){let t=Ra(e),n=uy(t),r=dt(e);Re==="visa"&&!ve.existsSync(t)&&(Ru(),ve.writeFileSync(t,(0,ly.randomBytes)(32),{mode:384}));let s=await dy(e),o=s?{binding:s.binding,bindingExpiresAt:new Date(Date.now()+s.expires_in*1e3).toISOString()}:{},i=process.env.SUBWAY_RELAY_MULTIADDR;if(Re==="visa"&&i){let{registerDirect:c}=await Promise.resolve().then(()=>(Su(),wu)),l=await c({relayMultiaddr:i,seed:ka(t),name:r,binding:s?.binding});if(!l.success)throw new Error(`.visa relay admission failed: ${l.error||"unknown"}`);let u=Nr();return u[e]={relayName:r,mesh:Re,peerId:l.peerId,owner:Au(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},Tu(u),{relayName:r,mesh:Re,peerId:l.peerId,tapAgentId:n,...s?{binding:s.binding}:{}}}if(Re==="visa"&&!process.env.SUBWAY_RELAY){let c=Nr();return c[e]={relayName:r,mesh:Re,peerId:null,owner:Au(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},Tu(c),{relayName:r,mesh:Re,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 a=Ss(e,{autoReconnect:!1,binding:s?.binding});try{await xs(a);let c=Nr();return c[e]={relayName:r,mesh:Re,peerId:a.peerId,owner:Au(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},Tu(c),{relayName:r,mesh:Re,peerId:a.peerId,tapAgentId:n,...s?{binding:s.binding}:{}}}finally{a.disconnect()}}async function $u(e){let t=dt(e),n=process.env.SUBWAY_RELAY_MULTIADDR;if(Re==="visa"&&n){let{resolveDirect:r}=await Promise.resolve().then(()=>(Su(),wu)),s=await r({relayMultiaddr:n,name:t});return{relayName:t,found:s.found,peerId:s.peerId,error:s.error}}throw new Error("subway find needs the .visa mesh with a dedicated relay \u2014 set SUBWAY_MESH=visa and SUBWAY_RELAY_MULTIADDR.")}async function Ou(e,t,n){let r=Ss(e,{autoReconnect:!1,binding:Iu(e)});try{await xs(r);let s=dt(t);return await r.sendSigned(s,"chat",n),{to:s,as:dt(e)}}finally{r.disconnect()}}function Mu(){let e=Nr();return Object.entries(e).map(([t,n])=>({name:t,...n}))}async function Nu(e){let t=Ea.get(e);if(t)return{relayName:dt(e),peerId:t.client.peerId};let n=Ss(e,{autoReconnect:!0,binding:Iu(e)}),r=[];return n.onMessage(s=>{r.push({from:s.fromName,text:s.payload,ts:s.timestampMs,verified:!!s.verified}),r.length>BA&&r.shift()}),Ea.set(e,{client:n,buffer:r}),await xs(n),{relayName:dt(e),peerId:n.peerId}}async function FA(e,t=20,n=!1){await Nu(e);let r=Ea.get(e);if(!r)return[];let s=r.buffer.slice(-t);return n&&(r.buffer.length=0),s}async function HA(e,t,n){await Nu(e);let r=Ea.get(e);if(!r)throw new Error(`mailbox for ${e} unavailable`);let s=dt(t);return await r.client.sendSigned(s,"chat",n),{to:s,as:dt(e)}}var ve,ko,ws,ly,Re,Co,Eu,ku,xu,Ea,BA,Ts=nt(()=>{"use strict";Ql();Ta();ve=R(require("fs")),ko=R(require("os")),ws=R(require("path")),ly=require("crypto");qt();Ca();Re=process.env.SUBWAY_MESH??"relay",Co=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";Eu=ws.join(ko.homedir(),".visa-cli","subway"),ku=ws.join(Eu,"registry.json"),xu=ws.join(ko.homedir(),".visa-cli","agents");Ea=new Map,BA=200});var Ha={};Br(Ha,{initSentry:()=>vE,isSentryConfigured:()=>bE,reportFatal:()=>wE});function bE(){return!1}async function vE(){return null}async function wE(e,t){process.exit(t?.exitCode??1)}var Va=nt(()=>{});var d1={};Br(d1,{printGroupHelpAndExit:()=>Lt});module.exports=V_(d1);var __=require("commander"),Wa=R(require("crypto")),ce=R(require("fs")),re=R(require("os")),tt=R(require("path")),b_=require("child_process"),gd=require("node:readline/promises"),v_=require("util");var zo=require("child_process"),Ud=require("util"),mn=R(require("fs")),Jo=R(require("os")),ac=R(require("path"));var Pd=R(require("crypto"));var Dt="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";var $d="VISA_ALLOW_INSECURE_MOCKS",Ed,Rd,Id;function nc(e){return`${e}-${Pd.randomBytes(24).toString("base64url")}`}function Od(e=process.env){return e.NODE_ENV==="test"||e[$d]==="true"}function dn(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&Od(e)}function Fr(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&Od(e)}function rc(){return`Set ${$d}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function Md(){return Ed??=nc("mock-session"),Ed}function Nd(e=process.env){return e.NODE_ENV==="test"?Dt:(Rd??=nc("mock-rc"),Rd)}function Ld(){return Id??=nc("mock-signature"),Id}var yt=(0,Ud.promisify)(zo.execFile),cc=ac.join(Jo.homedir(),".visa-mcp"),Ls=ac.join(cc,"session-token"),Ye="visa-cli",fn="session-token",Wo="rc-access",q_=5e3,Yo=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function K_(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
10
+ `)}function Dd(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=K_(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function G_(){try{let{stdout:e}=await yt("security",["find-generic-password","-s",Ye,"-a",fn,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(Dd(e))throw new Yo("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 W_(e){try{try{await yt("security",["delete-generic-password","-s",Ye,"-a",fn],{timeout:5e3})}catch{}return await yt("security",["add-generic-password","-s",Ye,"-a",fn,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function Y_(){try{await yt("security",["delete-generic-password","-s",Ye,"-a",fn],{timeout:5e3})}catch{}}async function z_(){if(!lc())return null;try{let{stdout:e}=await yt("secret-tool",["lookup","service",Ye,"account",fn],{timeout:5e3});return e.trim()||null}catch{return null}}async function J_(e){if(!lc())return!1;try{let t=(0,zo.execFile)("secret-tool",["store","--label",`${Ye} ${fn}`,"service",Ye,"account",fn]);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"))},q_))]),!0):!1}catch{return!1}}async function X_(){if(lc())try{await yt("secret-tool",["clear","service",Ye,"account",fn],{timeout:5e3})}catch{}}function lc(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function Z_(){try{let{stdout:e}=await yt("security",["find-generic-password","-s",Ye,"-a",Wo,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Q_(e){try{try{await yt("security",["delete-generic-password","-s",Ye,"-a",Wo],{timeout:5e3})}catch{}await yt("security",["add-generic-password","-s",Ye,"-a",Wo,"-w",e],{timeout:5e3})}catch{}}async function eb(){try{await yt("security",["delete-generic-password","-s",Ye,"-a",Wo],{timeout:5e3})}catch{}}function oc(){try{return mn.readFileSync(Ls,"utf-8").trim()||null}catch(e){if(Dd(e))throw new Yo(`Unable to read Visa CLI credentials from ${Ls}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function jd(e){mn.mkdirSync(cc,{recursive:!0,mode:448}),mn.writeFileSync(Ls,e,{mode:384}),process.platform==="win32"&&tb(Ls)}function ic(){try{mn.unlinkSync(Ls)}catch{}}function tb(e){try{let t=Jo.userInfo().username;(0,zo.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 sc(){switch(process.platform){case"darwin":return{get:G_,store:W_,delete:Y_};case"linux":return{get:z_,store:J_,delete:X_};default:return{get:async()=>oc(),store:async e=>{try{return jd(e),!0}catch{return!1}},delete:async()=>ic(),storesInSessionFile:!0}}}var G=class{static async getSessionToken(){if(dn())return Promise.resolve(Md());let t=sc(),n=await t.get();if(n)return n;let r=oc();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(dn())return;let n=sc();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||ic();return}await n.delete()}if(jd(t),oc()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${cc} is writable.`))}static async getRcAccessToken(){return dn()?Nd():Z_()}static async saveRcAccessToken(t){dn()||await Q_(t)}static async deleteSessionToken(){if(dn())return;await sc().delete(),ic()}static async clearAll(){await this.deleteSessionToken(),await eb()}};var Xo=R(require("crypto")),Zo=R(require("tty")),Qo=R(require("fs"));function rb(e){return/-rc\.|-beta\./.test(e)}function uc(e){return Xo.createHash("sha256").update(e.trim()).digest("hex")}function Bd(e){return Dt==="SKIP"?!0:Xo.timingSafeEqual(Buffer.from(uc(e)),Buffer.from(Dt))}function sb(){try{let e=Qo.openSync("/dev/tty","r+"),t=new Zo.ReadStream(e),n=new Zo.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{Qo.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 ob(e){return new Promise((t,n)=>{let r;try{r=sb()}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(`
13
- `),a(),n(new Error("Cancelled"))):u==="\x7F"||u==="\b"?c.length>0&&(c=c.slice(0,-1),o.write("\b \b")):(c+=u,o.write("\u2022"))};s.on("data",l)})}var ob=`
13
+ `),a(),n(new Error("Cancelled"))):u==="\x7F"||u==="\b"?c.length>0&&(c=c.slice(0,-1),o.write("\b \b")):(c+=u,o.write("\u2022"))};s.on("data",l)})}var ib=`
14
14
  \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
15
15
  \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557
16
16
  \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551
@@ -19,25 +19,25 @@ ${e.nonce}`;return Dx.encode(n)}function Fx(e,t,n,r,s,o,i){return Bx({messageId:
19
19
  \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D
20
20
 
21
21
  This is a Release Candidate build. Access is restricted to Visa employees.
22
- `;async function Bd(e={}){let t=e.version??Us().version;if(!nb(t))return;let n=process.env.VISA_RC_CODE;if(n&&jd(n)){await G.saveRcAccessToken(lc(n));return}if(e.isMcp??!1){let i=await G.getRcAccessToken();if(i&&(Dt==="SKIP"||i===Dt))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
23
- `),process.exit(1)}let s=await G.getRcAccessToken();if(s&&(Dt==="SKIP"||s===Dt))return;console.log(ob);let o=3;for(let i=1;i<=o;i++){let a;try{a=await sb(" Enter RC access code: ")}catch{process.exit(1)}if(jd(a)){await G.saveRcAccessToken(lc(a)),console.log(`
22
+ `;async function Fd(e={}){let t=e.version??Us().version;if(!rb(t))return;let n=process.env.VISA_RC_CODE;if(n&&Bd(n)){await G.saveRcAccessToken(uc(n));return}if(e.isMcp??!1){let i=await G.getRcAccessToken();if(i&&(Dt==="SKIP"||i===Dt))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
23
+ `),process.exit(1)}let s=await G.getRcAccessToken();if(s&&(Dt==="SKIP"||s===Dt))return;console.log(ib);let o=3;for(let i=1;i<=o;i++){let a;try{a=await ob(" Enter RC access code: ")}catch{process.exit(1)}if(Bd(a)){await G.saveRcAccessToken(uc(a)),console.log(`
24
24
  Access granted. Welcome.
25
25
  `);return}i<o&&console.log(`
26
26
  Invalid code. ${o-i} attempt(s) remaining.
27
27
  `)}console.log(`
28
28
  Invalid code. Contact your team lead.
29
- `),process.exit(1)}var Qo=R(require("fs")),Fd=R(require("os")),uc=R(require("path")),ib=[{prefix:"iVBORw0KGgo",sig:{mime:"image/png",ext:"png"}},{prefix:"/9j/",sig:{mime:"image/jpeg",ext:"jpg"}},{prefix:"R0lGOD",sig:{mime:"image/gif",ext:"gif"}},{prefix:"UklGR",sig:{mime:"image/webp",ext:"webp"}}],ab=/^data:(image\/(png|jpeg|jpg|gif|webp));base64,([A-Za-z0-9+/=]+)$/;function Hr(e){if(typeof e!="string"||e.length===0)return null;let t=e.trim(),n=ab.exec(t);if(n){let s=n[2]==="jpg"?"jpeg":n[2],o=s==="png"?{mime:"image/png",ext:"png"}:s==="jpeg"?{mime:"image/jpeg",ext:"jpg"}:s==="gif"?{mime:"image/gif",ext:"gif"}:{mime:"image/webp",ext:"webp"};return{base64:n[3],sig:o}}if(!/^[A-Za-z0-9+/=\s]+$/.test(t)||t.length<64)return null;let r=t.replace(/\s+/g,"");for(let{prefix:s,sig:o}of ib)if(r.startsWith(s))return{base64:r,sig:o};return null}function Ds(e,t={}){let n=t.outputDir??uc.join(Fd.tmpdir(),"visa-cli");Qo.mkdirSync(n,{recursive:!0});let r=(t.tag??"media").toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"media",s=new Date().toISOString().replace(/[:.]/g,"-"),o=uc.join(n,`${r}-${s}.${e.sig.ext}`),i=Buffer.from(e.base64,"base64");return Qo.writeFileSync(o,i,{mode:384}),{filePath:o,bytes:i.length,mime:e.sig.mime}}function Hd(e){return typeof e?.status=="string"&&(e.status==="IN_QUEUE"||e.status==="PENDING")}function dc(e,t=console.log){typeof e?.merchantName=="string"&&t(`Merchant: ${e.merchantName}`),typeof e?.amount=="number"&&t(`Cost: $${e.amount.toFixed(2)}`),typeof e?.transactionId=="string"&&t(`Transaction: ${e.transactionId}`)}function cb(e,t={}){let n={success:!0,command:e,ts:new Date().toISOString()};for(let[r,s]of Object.entries(t))s!==void 0&&(n[r]=s);return n}function js(e,t,n={}){let r={success:!1,command:e,ts:new Date().toISOString(),error:t};for(let[s,o]of Object.entries(n))o!==void 0&&(r[s]=o);return r}function fc(e,t){if(!t||typeof t!="object")return js(e,"No result payload from tool");let n=t;if(n.success===!1)return js(e,typeof n.error=="string"?n.error:"Tool execution failed",{error_code:typeof n.error_code=="string"?n.error_code:typeof n.code=="string"?n.code:void 0,transactionId:typeof n.transactionId=="string"?n.transactionId:null});let r=Array.isArray(n.urls)?n.urls.filter(u=>typeof u=="string"):Array.isArray(n.receipt?.urls)?n.receipt.urls.filter(u=>typeof u=="string"):void 0,s=n.data&&typeof n.data=="object"?n.data:void 0,o=n.result&&typeof n.result=="object"?n.result:void 0,i=o&&Array.isArray(o.choices)?o.choices:void 0,a=i&&i[0]&&typeof i[0]=="object"?i[0]:void 0,c=a&&a.message&&typeof a.message=="object"?a.message:void 0,l;if(s&&typeof s.content=="string")l=s.content;else if(s&&typeof s.text=="string")l=s.text;else if(typeof n.content=="string")l=n.content;else if(typeof n.text=="string")l=n.text;else if(c&&typeof c.content=="string")l=c.content;else if(a&&typeof a.text=="string")l=a.text;else if(Array.isArray(n.content)&&n.content[0]&&typeof n.content[0]=="object"){let u=n.content[0].text;typeof u=="string"&&(l=u)}return cb(e,{transactionId:typeof n.transactionId=="string"?n.transactionId:void 0,amount:typeof n.amount=="number"?n.amount:void 0,currency:typeof n.currency=="string"?n.currency:void 0,merchantName:typeof n.merchantName=="string"?n.merchantName:void 0,toolId:typeof n.toolId=="string"?n.toolId:typeof n.tool_id=="string"?n.tool_id:void 0,urls:r,text:l})}var mc=require("process");async function pc(){let e="";mc.stdin.setEncoding("utf8");for await(let t of mc.stdin)e+=t;return e.endsWith(`
30
- `)?e.slice(0,-1):e}async function Yn(e,t){if(e==="-"||t.stdin===!0&&!e){let s=(await pc()).trim();if(!s)throw new Error("stdin was empty \u2014 pipe a prompt or pass it as the positional argument");return s}if(e&&e.length>0)return e;throw new Error("prompt required (positional arg, `-`, or --stdin)")}function Bs(e,t){if(!(t?.isTty??!!process.stdout.isTTY)&&!e.yes)throw new Error("Non-TTY shell detected on a paid command. Pass --yes to confirm you intend to charge the card from a pipe/script.")}var Gd=R(require("fs")),ei=R(require("path"));var pn=class extends Error{constructor(t){super(t),this.name="FromStdinFieldError"}},Vd=new Set;function lb(e){Vd.add(e)}function qd(e){return Vd.has(e)}function Kd(e,t){if(!t.startsWith("."))throw new pn(`--from-stdin path must start with "." (got: "${t}")`);let n=ub(t),r=e;for(let o of n){if(r==null)throw new pn(`--from-stdin path "${t}" failed: hit ${r===null?"null":"undefined"} at segment "${o}"`);if(typeof r!="object")throw new pn(`--from-stdin path "${t}" failed: cannot descend into primitive at segment "${o}"`);if(typeof o=="number"){if(!Array.isArray(r))throw new pn(`--from-stdin path "${t}" failed: expected array at segment [${o}], got object`);r=r[o]}else r=r[o]}if(r==null)throw new pn(`--from-stdin path "${t}" resolved to ${r===null?"null":"undefined"}`);if(typeof r=="object")throw new pn(`--from-stdin path "${t}" resolved to ${Array.isArray(r)?"an array":"an object"} \u2014 refusing to coerce non-primitive to flag value`);let s=String(r);return lb(s),s}function ub(e){let t=e.slice(1),n=[];for(let r of t.split(".")){if(!r)continue;let s=/^([^[\]]+)|\[(\d+)\]/g,o;for(;(o=s.exec(r))!==null;)o[1]!==void 0?/^\d+$/.test(o[1])?n.push(Number(o[1])):n.push(o[1]):o[2]!==void 0&&n.push(Number(o[2]))}return n}var gc=class extends Error{constructor(t){super(t),this.name="FileShorthandStdinSourceError"}};async function Wd(e){if(e===void 0)return;if(!e.startsWith("@"))return e;if(qd(e))throw new gc("Refusing to expand @file from a --from-stdin-sourced value: upstream JSON cannot be allowed to read arbitrary local files. If the file path is legitimate, pass it as an argv flag instead of routing it through --from-stdin.");let t=e.slice(1),n=t.startsWith("~")?ei.join(process.env.HOME??"",t.slice(1)):ei.resolve(process.cwd(),t),r=await Gd.promises.readFile(n,"utf8");return r.endsWith(`
31
- `)?r.slice(0,-1):r}var Fs=require("process"),gn=["json","yaml","tsv","table"];function ti(e){return gn.includes(e)}function Hs(e,t){switch(t){case"json":Fs.stdout.write(JSON.stringify(e)+`
32
- `);return;case"yaml":Fs.stdout.write(db(e)+`
33
- `);return;case"tsv":Fs.stdout.write(fb(e)+`
34
- `);return;case"table":Fs.stdout.write(mb(e)+`
35
- `);return}}function db(e){let t=[];for(let[n,r]of Object.entries(e))if(r!==void 0)if(Array.isArray(r)){t.push(`${n}:`);for(let s of r)t.push(` - ${Yd(s)}`)}else r!==null&&typeof r=="object"?t.push(`${n}: ${JSON.stringify(r)}`):t.push(`${n}: ${Yd(r)}`);return t.join(`
36
- `)}function Yd(e){if(e===null)return"null";if(typeof e=="boolean"||typeof e=="number")return String(e);let t=String(e);return t===""?'""':/^[-?:,\[\]{}#&*!|>'"%@`]/.test(t)||/:\s|\s#/.test(t)||/^\s|\s$/.test(t)?JSON.stringify(t):t}function fb(e){let t=[];for(let[n,r]of Object.entries(e)){if(r===void 0)continue;let s=Array.isArray(r)||r!==null&&typeof r=="object"?JSON.stringify(r):String(r);t.push(`${n} ${s}`)}return t.join(`
37
- `)}function mb(e){let t=[];for(let[r,s]of Object.entries(e)){if(s===void 0)continue;let o=Array.isArray(s)||s!==null&&typeof s=="object"?JSON.stringify(s):String(s);t.push([r,o])}let n=Math.max(...t.map(([r])=>r.length),1);return t.map(([r,s])=>`${r.padEnd(n)} ${s}`).join(`
38
- `)}var Jd=require("child_process");function hc(e=process.env,t=process.platform){return e.VISA_CLI_NO_BROWSER==="1"||e.VISA_CLI_NO_BROWSER==="true"?{headless:!0,reason:"VISA_CLI_NO_BROWSER is set"}:e.CI==="true"||e.CI==="1"?{headless:!0,reason:"CI environment detected"}:e.SSH_CONNECTION||e.SSH_TTY?{headless:!0,reason:"SSH session detected"}:t==="linux"&&!e.DISPLAY&&!e.WAYLAND_DISPLAY?{headless:!0,reason:"Linux with no $DISPLAY or $WAYLAND_DISPLAY"}:{headless:!1}}function pb(e){let n=e.length+4;return[`\u250C${"\u2500".repeat(n)}\u2510`,`\u2502${" ".repeat(2)}${e}${" ".repeat(2)}\u2502`,`\u2514${"\u2500".repeat(n)}\u2518`].join(`
39
- `)}function Vs(e){if(typeof e!="string"||e.length===0)return null;let t;try{t=new URL(e)}catch{return null}return t.protocol!=="https:"&&t.protocol!=="http:"?null:t.toString()}function Xd(e,t){let n=Vs(e);if(!n)return null;let r,s;try{r=new URL(n),s=new URL(t)}catch{return null}return r.origin===s.origin?n:null}function Zd(e,t){return t==="darwin"?{cmd:"open",args:[e]}:t==="win32"?{cmd:"rundll32.exe",args:["url.dll,FileProtocolHandler",e]}:t==="linux"?{cmd:"xdg-open",args:[e]}:null}function Qd(e,t=process.platform){let n=Vs(e);return n?Zd(n,t):null}function zd(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function yc(e,t={}){let n=t.log??(l=>console.log(l)),r=t.env??process.env,s=t.platform??process.platform,o=Vs(e),i=t.spawn??((l,u,d)=>{(0,Jd.execFile)(l,u,f=>d(f))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let l of pb(o??e).split(`
40
- `))n(` ${l}`);if(n(""),!o){n(" (Auth URL is not a valid absolute http(s) URL \u2014 skipping browser auto-open.)"),n(" Open the URL above manually to continue."),n("");return}let a=hc(r,s);if(a.headless){n(` (${a.reason} \u2014 skipping browser auto-open.)`),n(" Open the URL above on any device with a browser. The CLI will"),n(" continue waiting for you to complete sign-in."),n("");return}let c=Zd(o,s);if(!c){n(` No known browser-open command for platform "${s}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(l=>{let u=d=>{d?zd(n,d):(n(" Opened browser. Waiting for you to sign in..."),n("")),l()};try{i(c.cmd,c.args,u)}catch(d){zd(n,d instanceof Error?d:new Error(String(d))),l()}})}function gb(e){return new Promise(t=>setTimeout(t,e))}function ef(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e*1e3;if(typeof e!="string"||e.trim()==="")return null;let t=Number(e);if(Number.isFinite(t)&&t>0)return t*1e3;let n=Date.parse(e);return Number.isFinite(n)?Math.max(n-Date.now(),0):null}function tf(e){return!Number.isFinite(e)||e===null||e<=0?1e3:Math.min(Math.max(Math.ceil(e),1e3),3e4)}async function hb(e,t=Math.random()*250){let n=s=>Math.min(s+Math.max(0,Math.ceil(t)),3e4);if(!e||e.status!==429)return n(1e3);let r=ef(e.headers?.get("Retry-After"));if(r!==null)return n(tf(r));if(typeof e.json=="function")try{let s=await e.json();return n(tf(ef(s?.retryAfter)))}catch{return n(1e3)}return n(1e3)}async function hn(e,t){let n=await hb(e);return t?.(n),await gb(n),n}var wf=R(require("crypto")),Sf=require("child_process"),we=R(require("fs")),xf=R(require("os")),De=R(require("path"));var Y=R(require("fs")),Xn=R(require("os")),Q=R(require("path")),lf=require("child_process"),vc=require("crypto");var qr=R(require("fs")),ni=R(require("tty"));function rf(e=process.env){let t=(e.COLORTERM??"").toLowerCase();if(t==="truecolor"||t==="24bit")return!0;let n=(e.TERM??"").toLowerCase();return n.includes("truecolor")||n.includes("24bit")}function sf(e,t){let n=(s,o,i)=>`\x1B[38;2;${s};${o};${i}m`,r=s=>`\x1B[38;5;${s}m`;return e==="light"?{reset:"\x1B[0m",visaBlue:t?n(20,52,203):r(26),visaBlueSoft:t?n(11,78,162):r(25),visaGold:t?n(122,82,0):r(94),green:t?n(15,107,47):r(22),muted:t?n(92,100,112):r(241),chrome:t?n(138,138,138):r(245)}:{reset:"\x1B[0m",visaBlue:t?n(168,184,255):r(153),visaBlueSoft:t?n(127,149,242):r(111),visaGold:t?n(255,210,74):r(221),green:t?n(86,211,100):r(77),muted:t?n(199,205,215):r(251),chrome:t?n(110,118,129):r(243)}}function of(e){if(!e)return null;let t=e.split(";");if(t.length<2)return null;let n=t[t.length-1].trim();if(n==="0")return"dark";if(n==="7"||n==="15")return"light";let r=Number(n);return Number.isInteger(r)&&r>=0&&r<=255?r<=6||r>=232&&r<=243?"dark":"light":null}function nf(e){let t=/rgb:([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})/.exec(e);if(!t)return null;let n=i=>{let a=parseInt(i,16),c=(1<<i.length*4)-1;return c>0?a/c:0},r=n(t[1]),s=n(t[2]),o=n(t[3]);return[r,s,o].some(i=>!Number.isFinite(i))?null:.299*r+.587*s+.114*o}var yb=80,_b="/dev/tty";function bb(e=_b){if(process.platform==="win32")return null;let t,n;try{t=qr.openSync(e,"r"),n=qr.openSync(e,"w");let r=new ni.ReadStream(t),s=new ni.WriteStream(n);return{stdin:r,stdout:s,close:()=>{try{r.destroy?.()}catch{}try{s.destroy?.()}catch{}}}}catch{try{t!==void 0&&qr.closeSync(t)}catch{}try{n!==void 0&&qr.closeSync(n)}catch{}return null}}function vb(e){let t={stdin:e.stdin??process.stdin,stdout:e.stdout??process.stdout};if(t.stdout.isTTY&&t.stdin.isTTY&&typeof t.stdin.setRawMode=="function")return t;let n=e.stdin!==void 0||e.stdout!==void 0;if(!(e.allowControllingTerminal??!n))return null;let o=(e.openControllingTerminal??bb)(e.ttyPath);return o?.stdout.isTTY&&o.stdin.isTTY&&typeof o.stdin.setRawMode=="function"?o:(o?.close?.(),null)}async function wb(e={}){let t=vb(e);if(!t)return null;let{stdin:n,stdout:r}=t,s=e.timeoutMs??yb,o=e.setTimeoutFn??((a,c)=>setTimeout(a,c)),i=e.clearTimeoutFn??(a=>clearTimeout(a));return new Promise(a=>{let c=!1,l="",u=n.isRaw===!0,d=g=>{l+=typeof g=="string"?g:g.toString("utf-8");let v=nf(l),k=l.includes("\x07")||l.includes("\x1B\\");v!==null&&k&&m(v>.5?"light":"dark")},f=()=>{try{n.removeListener("data",d)}catch{}try{i(p)}catch{}try{!u&&typeof n.setRawMode=="function"&&n.setRawMode(!1)}catch{}try{n.pause?.()}catch{}try{n.unref?.()}catch{}try{t.close?.()}catch{}},m=g=>{c||(c=!0,f(),a(g))},p=o(()=>{let g=nf(l);m(g!==null?g>.5?"light":"dark":null)},s);try{u||n.setRawMode?.(!0),n.resume?.(),n.on("data",d),r.write("\x1B]11;?\x1B\\")}catch{m(null)}})}var zn,qs;function Sb(e){if((e.NO_COLOR??"")!=="")return"no-color";let t=(e.VISA_CLI_HUD_THEME??"").toLowerCase().trim();if(t==="light")return"light";if(t==="dark")return"dark";let n=of(e.COLORFGBG);return n||"dark"}function ri(e=process.env){return zn!==void 0||(zn=Sb(e)),zn}function Ie(e=process.env){if(qs!==void 0)return qs;let t=ri(e),n=rf(e);return qs=sf(t==="light"?"light":"dark",n),qs}function si(e=process.env){return ri(e)==="no-color"}async function _c(e={}){if(zn!==void 0)return zn;let t=e.env??process.env;if((t.NO_COLOR??"")!=="")return Vr("no-color",t);let n=(t.VISA_CLI_HUD_THEME??"").toLowerCase().trim();if(n==="light")return Vr("light",t);if(n==="dark")return Vr("dark",t);let r=of(t.COLORFGBG);if(r)return Vr(r,t);let s=await wb(e);return Vr(s||"dark",t)}function Vr(e,t){zn=e;let n=rf(t);return qs=sf(e==="light"?"light":"dark",n),e}var xb=2,oi="# >>> visa-cli shell hud v2 >>>",ii="# <<< visa-cli shell hud v2 <<<",Tb="# >>> visa-cli shell hud >>>",kb="# <<< visa-cli shell hud <<<",uf=3e4,Ab=6e4,Eb="VISA | HUD not ready \u2014 run: visa-cli config hud doctor",Cb={currentVersion:"0.0.0"},Rb=15e3;function wc(){try{return Q.join(Tc(),".visa-cli")}catch{return Q.join(Xn.tmpdir(),".visa-cli")}}function yn(){return Q.join(wc(),"shell-hud.json")}function Ks(){return Q.join(wc(),"shell-hud.line")}function df(){return Q.join(wc(),"shell-hud.lock")}function Wr(e){let t=e??process.env.SHELL;if(!t)return null;let n=Q.basename(t.replace(/\\/g,"/")).toLowerCase();return n==="zsh"?"zsh":n==="bash"?"bash":n==="pwsh"||n==="pwsh.exe"||n==="powershell"||n==="powershell.exe"?"powershell":null}function Gs(e){let t=Tc();if(e==="zsh")return Q.join(t,".zshrc");if(e==="bash")return Q.join(t,".bashrc");let n=(process.platform==="win32","PowerShell");return Q.join(t,"Documents",n,"Microsoft.PowerShell_profile.ps1")}function ff(e,t){let n=t??Tc(),r=[{shell:"zsh",rcPath:Q.join(n,".zshrc")},{shell:"bash",rcPath:Q.join(n,".bashrc")},{shell:"bash",rcPath:Q.join(n,".bash_profile")},{shell:"powershell",rcPath:Q.join(n,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:Q.join(n,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:Q.join(n,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:Q.join(n,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:Q.join(n,".config","powershell","Microsoft.PowerShell_profile.ps1")}];if(!e)return r;let s=r.filter(i=>i.shell===e),o=r.filter(i=>i.shell!==e);return[...s,...o]}function Ib(e){let t="$HOME/.visa-cli/shell-hud.line",n=Yb(e),r=zb(e);if(e==="zsh")return`${oi}
29
+ `),process.exit(1)}var ei=R(require("fs")),Hd=R(require("os")),dc=R(require("path")),ab=[{prefix:"iVBORw0KGgo",sig:{mime:"image/png",ext:"png"}},{prefix:"/9j/",sig:{mime:"image/jpeg",ext:"jpg"}},{prefix:"R0lGOD",sig:{mime:"image/gif",ext:"gif"}},{prefix:"UklGR",sig:{mime:"image/webp",ext:"webp"}}],cb=/^data:(image\/(png|jpeg|jpg|gif|webp));base64,([A-Za-z0-9+/=]+)$/;function Hr(e){if(typeof e!="string"||e.length===0)return null;let t=e.trim(),n=cb.exec(t);if(n){let s=n[2]==="jpg"?"jpeg":n[2],o=s==="png"?{mime:"image/png",ext:"png"}:s==="jpeg"?{mime:"image/jpeg",ext:"jpg"}:s==="gif"?{mime:"image/gif",ext:"gif"}:{mime:"image/webp",ext:"webp"};return{base64:n[3],sig:o}}if(!/^[A-Za-z0-9+/=\s]+$/.test(t)||t.length<64)return null;let r=t.replace(/\s+/g,"");for(let{prefix:s,sig:o}of ab)if(r.startsWith(s))return{base64:r,sig:o};return null}function Ds(e,t={}){let n=t.outputDir??dc.join(Hd.tmpdir(),"visa-cli");ei.mkdirSync(n,{recursive:!0});let r=(t.tag??"media").toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"media",s=new Date().toISOString().replace(/[:.]/g,"-"),o=dc.join(n,`${r}-${s}.${e.sig.ext}`),i=Buffer.from(e.base64,"base64");return ei.writeFileSync(o,i,{mode:384}),{filePath:o,bytes:i.length,mime:e.sig.mime}}function Vd(e){return typeof e?.status=="string"&&(e.status==="IN_QUEUE"||e.status==="PENDING")}function fc(e,t=console.log){typeof e?.merchantName=="string"&&t(`Merchant: ${e.merchantName}`),typeof e?.amount=="number"&&t(`Cost: $${e.amount.toFixed(2)}`),typeof e?.transactionId=="string"&&t(`Transaction: ${e.transactionId}`)}function lb(e,t={}){let n={success:!0,command:e,ts:new Date().toISOString()};for(let[r,s]of Object.entries(t))s!==void 0&&(n[r]=s);return n}function js(e,t,n={}){let r={success:!1,command:e,ts:new Date().toISOString(),error:t};for(let[s,o]of Object.entries(n))o!==void 0&&(r[s]=o);return r}function mc(e,t){if(!t||typeof t!="object")return js(e,"No result payload from tool");let n=t;if(n.success===!1)return js(e,typeof n.error=="string"?n.error:"Tool execution failed",{error_code:typeof n.error_code=="string"?n.error_code:typeof n.code=="string"?n.code:void 0,transactionId:typeof n.transactionId=="string"?n.transactionId:null});let r=Array.isArray(n.urls)?n.urls.filter(u=>typeof u=="string"):Array.isArray(n.receipt?.urls)?n.receipt.urls.filter(u=>typeof u=="string"):void 0,s=n.data&&typeof n.data=="object"?n.data:void 0,o=n.result&&typeof n.result=="object"?n.result:void 0,i=o&&Array.isArray(o.choices)?o.choices:void 0,a=i&&i[0]&&typeof i[0]=="object"?i[0]:void 0,c=a&&a.message&&typeof a.message=="object"?a.message:void 0,l;if(s&&typeof s.content=="string")l=s.content;else if(s&&typeof s.text=="string")l=s.text;else if(typeof n.content=="string")l=n.content;else if(typeof n.text=="string")l=n.text;else if(c&&typeof c.content=="string")l=c.content;else if(a&&typeof a.text=="string")l=a.text;else if(Array.isArray(n.content)&&n.content[0]&&typeof n.content[0]=="object"){let u=n.content[0].text;typeof u=="string"&&(l=u)}return lb(e,{transactionId:typeof n.transactionId=="string"?n.transactionId:void 0,amount:typeof n.amount=="number"?n.amount:void 0,currency:typeof n.currency=="string"?n.currency:void 0,merchantName:typeof n.merchantName=="string"?n.merchantName:void 0,toolId:typeof n.toolId=="string"?n.toolId:typeof n.tool_id=="string"?n.tool_id:void 0,urls:r,text:l})}var pc=require("process");async function gc(){let e="";pc.stdin.setEncoding("utf8");for await(let t of pc.stdin)e+=t;return e.endsWith(`
30
+ `)?e.slice(0,-1):e}async function Yn(e,t){if(e==="-"||t.stdin===!0&&!e){let s=(await gc()).trim();if(!s)throw new Error("stdin was empty \u2014 pipe a prompt or pass it as the positional argument");return s}if(e&&e.length>0)return e;throw new Error("prompt required (positional arg, `-`, or --stdin)")}function Bs(e,t){if(!(t?.isTty??!!process.stdout.isTTY)&&!e.yes)throw new Error("Non-TTY shell detected on a paid command. Pass --yes to confirm you intend to charge the card from a pipe/script.")}var Wd=R(require("fs")),ti=R(require("path"));var pn=class extends Error{constructor(t){super(t),this.name="FromStdinFieldError"}},qd=new Set;function ub(e){qd.add(e)}function Kd(e){return qd.has(e)}function Gd(e,t){if(!t.startsWith("."))throw new pn(`--from-stdin path must start with "." (got: "${t}")`);let n=db(t),r=e;for(let o of n){if(r==null)throw new pn(`--from-stdin path "${t}" failed: hit ${r===null?"null":"undefined"} at segment "${o}"`);if(typeof r!="object")throw new pn(`--from-stdin path "${t}" failed: cannot descend into primitive at segment "${o}"`);if(typeof o=="number"){if(!Array.isArray(r))throw new pn(`--from-stdin path "${t}" failed: expected array at segment [${o}], got object`);r=r[o]}else r=r[o]}if(r==null)throw new pn(`--from-stdin path "${t}" resolved to ${r===null?"null":"undefined"}`);if(typeof r=="object")throw new pn(`--from-stdin path "${t}" resolved to ${Array.isArray(r)?"an array":"an object"} \u2014 refusing to coerce non-primitive to flag value`);let s=String(r);return ub(s),s}function db(e){let t=e.slice(1),n=[];for(let r of t.split(".")){if(!r)continue;let s=/^([^[\]]+)|\[(\d+)\]/g,o;for(;(o=s.exec(r))!==null;)o[1]!==void 0?/^\d+$/.test(o[1])?n.push(Number(o[1])):n.push(o[1]):o[2]!==void 0&&n.push(Number(o[2]))}return n}var hc=class extends Error{constructor(t){super(t),this.name="FileShorthandStdinSourceError"}};async function Yd(e){if(e===void 0)return;if(!e.startsWith("@"))return e;if(Kd(e))throw new hc("Refusing to expand @file from a --from-stdin-sourced value: upstream JSON cannot be allowed to read arbitrary local files. If the file path is legitimate, pass it as an argv flag instead of routing it through --from-stdin.");let t=e.slice(1),n=t.startsWith("~")?ti.join(process.env.HOME??"",t.slice(1)):ti.resolve(process.cwd(),t),r=await Wd.promises.readFile(n,"utf8");return r.endsWith(`
31
+ `)?r.slice(0,-1):r}var Fs=require("process"),gn=["json","yaml","tsv","table"];function ni(e){return gn.includes(e)}function Hs(e,t){switch(t){case"json":Fs.stdout.write(JSON.stringify(e)+`
32
+ `);return;case"yaml":Fs.stdout.write(fb(e)+`
33
+ `);return;case"tsv":Fs.stdout.write(mb(e)+`
34
+ `);return;case"table":Fs.stdout.write(pb(e)+`
35
+ `);return}}function fb(e){let t=[];for(let[n,r]of Object.entries(e))if(r!==void 0)if(Array.isArray(r)){t.push(`${n}:`);for(let s of r)t.push(` - ${zd(s)}`)}else r!==null&&typeof r=="object"?t.push(`${n}: ${JSON.stringify(r)}`):t.push(`${n}: ${zd(r)}`);return t.join(`
36
+ `)}function zd(e){if(e===null)return"null";if(typeof e=="boolean"||typeof e=="number")return String(e);let t=String(e);return t===""?'""':/^[-?:,\[\]{}#&*!|>'"%@`]/.test(t)||/:\s|\s#/.test(t)||/^\s|\s$/.test(t)?JSON.stringify(t):t}function mb(e){let t=[];for(let[n,r]of Object.entries(e)){if(r===void 0)continue;let s=Array.isArray(r)||r!==null&&typeof r=="object"?JSON.stringify(r):String(r);t.push(`${n} ${s}`)}return t.join(`
37
+ `)}function pb(e){let t=[];for(let[r,s]of Object.entries(e)){if(s===void 0)continue;let o=Array.isArray(s)||s!==null&&typeof s=="object"?JSON.stringify(s):String(s);t.push([r,o])}let n=Math.max(...t.map(([r])=>r.length),1);return t.map(([r,s])=>`${r.padEnd(n)} ${s}`).join(`
38
+ `)}var Xd=require("child_process");function yc(e=process.env,t=process.platform){return e.VISA_CLI_NO_BROWSER==="1"||e.VISA_CLI_NO_BROWSER==="true"?{headless:!0,reason:"VISA_CLI_NO_BROWSER is set"}:e.CI==="true"||e.CI==="1"?{headless:!0,reason:"CI environment detected"}:e.SSH_CONNECTION||e.SSH_TTY?{headless:!0,reason:"SSH session detected"}:t==="linux"&&!e.DISPLAY&&!e.WAYLAND_DISPLAY?{headless:!0,reason:"Linux with no $DISPLAY or $WAYLAND_DISPLAY"}:{headless:!1}}function gb(e){let n=e.length+4;return[`\u250C${"\u2500".repeat(n)}\u2510`,`\u2502${" ".repeat(2)}${e}${" ".repeat(2)}\u2502`,`\u2514${"\u2500".repeat(n)}\u2518`].join(`
39
+ `)}function Vs(e){if(typeof e!="string"||e.length===0)return null;let t;try{t=new URL(e)}catch{return null}return t.protocol!=="https:"&&t.protocol!=="http:"?null:t.toString()}function Zd(e,t){let n=Vs(e);if(!n)return null;let r,s;try{r=new URL(n),s=new URL(t)}catch{return null}return r.origin===s.origin?n:null}function Qd(e,t){return t==="darwin"?{cmd:"open",args:[e]}:t==="win32"?{cmd:"rundll32.exe",args:["url.dll,FileProtocolHandler",e]}:t==="linux"?{cmd:"xdg-open",args:[e]}:null}function ef(e,t=process.platform){let n=Vs(e);return n?Qd(n,t):null}function Jd(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function _c(e,t={}){let n=t.log??(l=>console.log(l)),r=t.env??process.env,s=t.platform??process.platform,o=Vs(e),i=t.spawn??((l,u,d)=>{(0,Xd.execFile)(l,u,f=>d(f))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let l of gb(o??e).split(`
40
+ `))n(` ${l}`);if(n(""),!o){n(" (Auth URL is not a valid absolute http(s) URL \u2014 skipping browser auto-open.)"),n(" Open the URL above manually to continue."),n("");return}let a=yc(r,s);if(a.headless){n(` (${a.reason} \u2014 skipping browser auto-open.)`),n(" Open the URL above on any device with a browser. The CLI will"),n(" continue waiting for you to complete sign-in."),n("");return}let c=Qd(o,s);if(!c){n(` No known browser-open command for platform "${s}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(l=>{let u=d=>{d?Jd(n,d):(n(" Opened browser. Waiting for you to sign in..."),n("")),l()};try{i(c.cmd,c.args,u)}catch(d){Jd(n,d instanceof Error?d:new Error(String(d))),l()}})}function hb(e){return new Promise(t=>setTimeout(t,e))}function tf(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e*1e3;if(typeof e!="string"||e.trim()==="")return null;let t=Number(e);if(Number.isFinite(t)&&t>0)return t*1e3;let n=Date.parse(e);return Number.isFinite(n)?Math.max(n-Date.now(),0):null}function nf(e){return!Number.isFinite(e)||e===null||e<=0?1e3:Math.min(Math.max(Math.ceil(e),1e3),3e4)}async function yb(e,t=Math.random()*250){let n=s=>Math.min(s+Math.max(0,Math.ceil(t)),3e4);if(!e||e.status!==429)return n(1e3);let r=tf(e.headers?.get("Retry-After"));if(r!==null)return n(nf(r));if(typeof e.json=="function")try{let s=await e.json();return n(nf(tf(s?.retryAfter)))}catch{return n(1e3)}return n(1e3)}async function hn(e,t){let n=await yb(e);return t?.(n),await hb(n),n}var Sf=R(require("crypto")),xf=require("child_process"),we=R(require("fs")),Tf=R(require("os")),De=R(require("path"));var Y=R(require("fs")),Xn=R(require("os")),Q=R(require("path")),uf=require("child_process"),wc=require("crypto");var qr=R(require("fs")),ri=R(require("tty"));function sf(e=process.env){let t=(e.COLORTERM??"").toLowerCase();if(t==="truecolor"||t==="24bit")return!0;let n=(e.TERM??"").toLowerCase();return n.includes("truecolor")||n.includes("24bit")}function of(e,t){let n=(s,o,i)=>`\x1B[38;2;${s};${o};${i}m`,r=s=>`\x1B[38;5;${s}m`;return e==="light"?{reset:"\x1B[0m",visaBlue:t?n(20,52,203):r(26),visaBlueSoft:t?n(11,78,162):r(25),visaGold:t?n(122,82,0):r(94),green:t?n(15,107,47):r(22),muted:t?n(92,100,112):r(241),chrome:t?n(138,138,138):r(245)}:{reset:"\x1B[0m",visaBlue:t?n(168,184,255):r(153),visaBlueSoft:t?n(127,149,242):r(111),visaGold:t?n(255,210,74):r(221),green:t?n(86,211,100):r(77),muted:t?n(199,205,215):r(251),chrome:t?n(110,118,129):r(243)}}function af(e){if(!e)return null;let t=e.split(";");if(t.length<2)return null;let n=t[t.length-1].trim();if(n==="0")return"dark";if(n==="7"||n==="15")return"light";let r=Number(n);return Number.isInteger(r)&&r>=0&&r<=255?r<=6||r>=232&&r<=243?"dark":"light":null}function rf(e){let t=/rgb:([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})/.exec(e);if(!t)return null;let n=i=>{let a=parseInt(i,16),c=(1<<i.length*4)-1;return c>0?a/c:0},r=n(t[1]),s=n(t[2]),o=n(t[3]);return[r,s,o].some(i=>!Number.isFinite(i))?null:.299*r+.587*s+.114*o}var _b=80,bb="/dev/tty";function vb(e=bb){if(process.platform==="win32")return null;let t,n;try{t=qr.openSync(e,"r"),n=qr.openSync(e,"w");let r=new ri.ReadStream(t),s=new ri.WriteStream(n);return{stdin:r,stdout:s,close:()=>{try{r.destroy?.()}catch{}try{s.destroy?.()}catch{}}}}catch{try{t!==void 0&&qr.closeSync(t)}catch{}try{n!==void 0&&qr.closeSync(n)}catch{}return null}}function wb(e){let t={stdin:e.stdin??process.stdin,stdout:e.stdout??process.stdout};if(t.stdout.isTTY&&t.stdin.isTTY&&typeof t.stdin.setRawMode=="function")return t;let n=e.stdin!==void 0||e.stdout!==void 0;if(!(e.allowControllingTerminal??!n))return null;let o=(e.openControllingTerminal??vb)(e.ttyPath);return o?.stdout.isTTY&&o.stdin.isTTY&&typeof o.stdin.setRawMode=="function"?o:(o?.close?.(),null)}async function Sb(e={}){let t=wb(e);if(!t)return null;let{stdin:n,stdout:r}=t,s=e.timeoutMs??_b,o=e.setTimeoutFn??((a,c)=>setTimeout(a,c)),i=e.clearTimeoutFn??(a=>clearTimeout(a));return new Promise(a=>{let c=!1,l="",u=n.isRaw===!0,d=g=>{l+=typeof g=="string"?g:g.toString("utf-8");let v=rf(l),A=l.includes("\x07")||l.includes("\x1B\\");v!==null&&A&&m(v>.5?"light":"dark")},f=()=>{try{n.removeListener("data",d)}catch{}try{i(p)}catch{}try{!u&&typeof n.setRawMode=="function"&&n.setRawMode(!1)}catch{}try{n.pause?.()}catch{}try{n.unref?.()}catch{}try{t.close?.()}catch{}},m=g=>{c||(c=!0,f(),a(g))},p=o(()=>{let g=rf(l);m(g!==null?g>.5?"light":"dark":null)},s);try{u||n.setRawMode?.(!0),n.resume?.(),n.on("data",d),r.write("\x1B]11;?\x1B\\")}catch{m(null)}})}var zn,qs;function xb(e){if((e.NO_COLOR??"")!=="")return"no-color";let t=(e.VISA_CLI_HUD_THEME??"").toLowerCase().trim();if(t==="light")return"light";if(t==="dark")return"dark";let n=af(e.COLORFGBG);return n||"dark"}function si(e=process.env){return zn!==void 0||(zn=xb(e)),zn}function Ie(e=process.env){if(qs!==void 0)return qs;let t=si(e),n=sf(e);return qs=of(t==="light"?"light":"dark",n),qs}function oi(e=process.env){return si(e)==="no-color"}async function bc(e={}){if(zn!==void 0)return zn;let t=e.env??process.env;if((t.NO_COLOR??"")!=="")return Vr("no-color",t);let n=(t.VISA_CLI_HUD_THEME??"").toLowerCase().trim();if(n==="light")return Vr("light",t);if(n==="dark")return Vr("dark",t);let r=af(t.COLORFGBG);if(r)return Vr(r,t);let s=await Sb(e);return Vr(s||"dark",t)}function Vr(e,t){zn=e;let n=sf(t);return qs=of(e==="light"?"light":"dark",n),e}var Tb=2,ii="# >>> visa-cli shell hud v2 >>>",ai="# <<< visa-cli shell hud v2 <<<",Ab="# >>> visa-cli shell hud >>>",kb="# <<< visa-cli shell hud <<<",df=3e4,Cb=6e4,Eb="VISA | HUD not ready \u2014 run: visa-cli config hud doctor",Rb={currentVersion:"0.0.0"},Ib=15e3;function Sc(){try{return Q.join(Ac(),".visa-cli")}catch{return Q.join(Xn.tmpdir(),".visa-cli")}}function yn(){return Q.join(Sc(),"shell-hud.json")}function Ks(){return Q.join(Sc(),"shell-hud.line")}function ff(){return Q.join(Sc(),"shell-hud.lock")}function Wr(e){let t=e??process.env.SHELL;if(!t)return null;let n=Q.basename(t.replace(/\\/g,"/")).toLowerCase();return n==="zsh"?"zsh":n==="bash"?"bash":n==="pwsh"||n==="pwsh.exe"||n==="powershell"||n==="powershell.exe"?"powershell":null}function Gs(e){let t=Ac();if(e==="zsh")return Q.join(t,".zshrc");if(e==="bash")return Q.join(t,".bashrc");let n=(process.platform==="win32","PowerShell");return Q.join(t,"Documents",n,"Microsoft.PowerShell_profile.ps1")}function mf(e,t){let n=t??Ac(),r=[{shell:"zsh",rcPath:Q.join(n,".zshrc")},{shell:"bash",rcPath:Q.join(n,".bashrc")},{shell:"bash",rcPath:Q.join(n,".bash_profile")},{shell:"powershell",rcPath:Q.join(n,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:Q.join(n,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:Q.join(n,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:Q.join(n,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:Q.join(n,".config","powershell","Microsoft.PowerShell_profile.ps1")}];if(!e)return r;let s=r.filter(i=>i.shell===e),o=r.filter(i=>i.shell!==e);return[...s,...o]}function Pb(e){let t="$HOME/.visa-cli/shell-hud.line",n=zb(e),r=Jb(e);if(e==="zsh")return`${ii}
41
41
  _visa_cli_shell_hud_precmd() {
42
42
  setopt localoptions no_bg_nice
43
43
  if [[ -f "${t}" ]]; then
@@ -54,7 +54,7 @@ autoload -Uz add-zsh-hook
54
54
  if [[ -z "\${precmd_functions[(r)_visa_cli_shell_hud_precmd]}" ]]; then
55
55
  add-zsh-hook precmd _visa_cli_shell_hud_precmd
56
56
  fi
57
- ${ii}`;if(e==="powershell"){let s="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${oi}
57
+ ${ai}`;if(e==="powershell"){let s="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${ii}
58
58
  if (-not (Test-Path Function:\\global:__visa_cli_original_prompt)) {
59
59
  $function:global:__visa_cli_original_prompt = if (Test-Path Function:\\prompt) { $function:prompt } else { { '' } }
60
60
  }
@@ -73,7 +73,7 @@ function global:prompt {
73
73
  }
74
74
  & $function:global:__visa_cli_original_prompt
75
75
  }
76
- ${ii}`}return`${oi}
76
+ ${ai}`}return`${ii}
77
77
  __visa_cli_shell_hud_precmd() {
78
78
  if [ -f "${t}" ]; then
79
79
  cat "${t}"
@@ -90,62 +90,62 @@ case ";$PROMPT_COMMAND;" in
90
90
  *";__visa_cli_shell_hud_precmd;"*) ;;
91
91
  *) PROMPT_COMMAND="__visa_cli_shell_hud_precmd\${PROMPT_COMMAND:+;$PROMPT_COMMAND}" ;;
92
92
  esac
93
- ${ii}`}function $b(e){return e.includes("_visa_cli_shell_hud_precmd")||e.includes("visa-cli config shell-hud refresh")||e.includes("shell-hud.line")||e.includes("__visa_cli_original_prompt")||e.includes("function global:prompt")}function Pb(e,t,n){let r=new RegExp(`(^|\\n)([ \\t]*${cf(t)}[ \\t]*\\r?\\n)([\\s\\S]*?)(\\r?\\n[ \\t]*${cf(n)}[ \\t]*)(?=\\r?\\n|$)(\\r?\\n)?`,"g");return e.replace(r,(s,o,i,a,c,l,u)=>{if(!$b(a))return s;let d=u>0?e[u-1]:"";return o===`
93
+ ${ai}`}function $b(e){return e.includes("_visa_cli_shell_hud_precmd")||e.includes("visa-cli config shell-hud refresh")||e.includes("shell-hud.line")||e.includes("__visa_cli_original_prompt")||e.includes("function global:prompt")}function Ob(e,t,n){let r=new RegExp(`(^|\\n)([ \\t]*${lf(t)}[ \\t]*\\r?\\n)([\\s\\S]*?)(\\r?\\n[ \\t]*${lf(n)}[ \\t]*)(?=\\r?\\n|$)(\\r?\\n)?`,"g");return e.replace(r,(s,o,i,a,c,l,u)=>{if(!$b(a))return s;let d=u>0?e[u-1]:"";return o===`
94
94
  `&&d!==`
95
95
  `?`
96
- `:""})}function Ws(e){let t=e;for(let[n,r]of[[oi,ii],[Tb,kb]])t=Pb(t,n,r);return t.trimEnd()}function mf(e){return Ws(e)!==e.trimEnd()}function Ob(e,t){let n=Ws(e).trimEnd(),r=Ib(t);return n.length>0?`${n}
96
+ `:""})}function Ws(e){let t=e;for(let[n,r]of[[ii,ai],[Ab,kb]])t=Ob(t,n,r);return t.trimEnd()}function pf(e){return Ws(e)!==e.trimEnd()}function Mb(e,t){let n=Ws(e).trimEnd(),r=Pb(t);return n.length>0?`${n}
97
97
 
98
98
  ${r}
99
99
  `:`${r}
100
- `}function ai(e=Wr()){if(!e)return!1;try{let t=Gs(e),n=Y.readFileSync(t,"utf-8");return mf(n)}catch{return!1}}function Zn(e=Xn.homedir()){let t=[],n=Mb(e);for(let r of n)try{if(!Y.existsSync(r))continue;let s=Y.readFileSync(r,"utf-8");mf(s)&&t.push(r)}catch{}return t}function Mb(e){return ff(null,e).map(t=>t.rcPath)}function ci(e=Wr()){if(!e)return{installed:!1,changed:!1,shell:null,message:"Shell HUD auto-install skipped: supported shells are zsh, bash, and PowerShell."};let t;try{t=Gs(e);let n=Y.existsSync(t)?Y.readFileSync(t,"utf-8"):"",r=Ob(n,e),s=r!==n;return s&&Gr(t,r),{installed:!0,changed:s,shell:e,rcPath:t,message:s?`Persistent shell HUD installed in ${t}. Open a new terminal to start seeing it. Disable it any time with: visa-cli config shell-hud disable`:`Persistent shell HUD already installed in ${t}. Disable it any time with: visa-cli config shell-hud disable`}}catch(n){return{installed:!1,changed:!1,shell:e,rcPath:t,message:`Failed to install persistent shell HUD in ${t}: ${bc(n)}`}}}function jt(e=Wr(),t){let n=[],r=[],s=[];try{for(let o of ff(e,t))if(r.push(o.rcPath),!!Y.existsSync(o.rcPath))try{let i=Y.readFileSync(o.rcPath,"utf-8"),a=Ws(i);if(a===i.trimEnd())continue;Gr(o.rcPath,a.length>0?`${a}
101
- `:""),n.push(o.rcPath)}catch(i){s.push(`${o.rcPath}: ${bc(i)}`)}return n.length>0?{removed:!0,shell:e,rcPath:n[0],rcPaths:n,message:s.length>0?`Removed persistent shell HUD from ${n.join(", ")}. Some rc files could not be updated: ${s.join("; ")}.`:`Removed persistent shell HUD from ${n.join(", ")}.`}:s.length>0?{removed:!1,shell:e,rcPath:r[0],rcPaths:r,message:`Failed to remove persistent shell HUD: ${s.join("; ")}`}:{removed:!0,shell:e,rcPath:r[0],rcPaths:r,message:"Persistent shell HUD was not installed in any supported shell rc file."}}catch(o){return{removed:!1,shell:e,message:`Failed to remove persistent shell HUD: ${bc(o)}`}}}function Sc(e,t){let n=t??Cb,r=n.currentVersion==="0.0.0"&&e.version?e.version:n.currentVersion,s=_n(r),o=` ${te("\u2502",ee.chrome)} `,i=pf(n),a=jb(n,i),c=n.updateCheckDisabled?"":i,l=Db(s,c);if(!e.enrolled)return[l,te("setup needed",ee.visaGold),a].filter(Boolean).join(o);let u=Wb(e),d=Ub(e),f=_n(Xn.hostname().split(".")[0]),m=[l,f?te(f,ee.muted):"",te(u,ee.visaGold),a].filter(Boolean).join(o),p=[d,Nb(e)].filter(Boolean),g=p.length>0?p.join(o):"";return g?`${m}
102
- ${g}`:m}function Nb(e){let t=` ${te("\u2502",ee.chrome)} `,n=[];if(typeof e.spentToday=="number"&&Number.isFinite(e.spentToday)&&n.push(te(`spent today ${Kr(Math.max(0,e.spentToday))}`,ee.muted)),e.lastService&&typeof e.lastService.toolName=="string"&&e.lastService.toolName.length>0){let r=Gb(_n(e.lastService.toolName)),s=Lb(e.lastService.createdAt),o=te(s?`last ${r} ${s}`:`last ${r}`,ee.muted);n.push(o)}if(typeof e.apiKeyCount=="number"&&Number.isFinite(e.apiKeyCount)){let r=Math.max(0,Math.floor(e.apiKeyCount)),s=r===1?"VISA Key":"VISA Keys";n.push(te(`${r} ${s}`,ee.muted))}else e.apiKeyStatus==="rollout_locked"&&n.push(te("VISA Key \u{1F51C}",ee.muted));return n.join(t)}function Lb(e){if(!e)return"";let t=Date.parse(e);if(!Number.isFinite(t))return"";let n=Date.now()-t;if(n<0)return"";let r=Math.floor(n/1e3);if(r<60)return`${r}s`;let s=Math.floor(r/60);if(s<60)return`${s}m`;let o=Math.floor(s/60);return o<24?`${o}h`:`${Math.floor(o/24)}d`}function Ub(e){let t=typeof e.balanceCents=="number"?e.balanceCents:typeof e.prepaidBalance?.cents=="number"?e.prepaidBalance.cents:null,n=e.activeSession;if(t===null)return te("balance unknown",ee.muted);let r=t/100;if(n){let i=Math.max(0,n.capCents),a=Math.max(0,n.estimatedRemainingCents),c=Math.max(0,i-a),l=i>0?Math.max(0,Math.min(1,c/i)):0;return`${Kb(l)} ${te(`${Kr(a/100)} in session`,ee.green)} ${te(`(${Kr(c/100)}/${Kr(i/100)} cap)`,ee.muted)} ${te("\xB7",ee.chrome)} ${te(`${Kr(r)} balance`,ee.muted)}`}let s=10,o=`balance ${Kr(r)}`;return t>=s?te(o,ee.green):te(`${o} \u2014 top up via buy_credits`,ee.visaGold)}function Db(e,t){let n=e,r=`${te("VISA CLI",ee.visaBlue)} ${te(`v${n}`,ee.visaBlueSoft)}`;if(!t)return r;let s=t;return`${r} ${te("\u2B06 update",ee.visaGold)} ${te(`v${s}`,ee.visaGold)}`}function jb(e,t){return t&&!e.updateCheckDisabled?te("run: visa-cli update",ee.visaGold):t?null:Bb(e)}function pf(e){return e.latestVersion?_n(e.latestVersion):""}function Bb(e){let t=pf(e);return t?te(`update ready v${t}`,ee.visaGold):null}function gf(){let e=Ys();return!(!e||Date.now()-e.renderedAt>uf||e.cwd&&e.cwd!==process.cwd())}function li(){let e=Ys(),t=Date.now();if(e&&t-e.renderedAt<=uf||(Hb(),e?.line))return af(e.line,e,t);try{let n=Ks();if(Y.existsSync(n)){let r=Y.readFileSync(n,"utf-8").trimEnd();if(r&&!ui(r))return r}}catch{}return Eb}function af(e,t,n){let r=n-t.renderedAt,s=typeof t.refreshFailedAt=="number"&&t.refreshFailedAt>t.renderedAt,o=[];if(r>=Ab&&o.push(`stale ${Fb(r)}`),s&&o.push("\u26A0 refresh failed"),o.length===0)return e;let i=` ${te("\xB7",ee.chrome)} ${te(o.join(" \xB7 "),ee.visaGold)}`,a=e.split(`
100
+ `}function ci(e=Wr()){if(!e)return!1;try{let t=Gs(e),n=Y.readFileSync(t,"utf-8");return pf(n)}catch{return!1}}function Zn(e=Xn.homedir()){let t=[],n=Nb(e);for(let r of n)try{if(!Y.existsSync(r))continue;let s=Y.readFileSync(r,"utf-8");pf(s)&&t.push(r)}catch{}return t}function Nb(e){return mf(null,e).map(t=>t.rcPath)}function li(e=Wr()){if(!e)return{installed:!1,changed:!1,shell:null,message:"Shell HUD auto-install skipped: supported shells are zsh, bash, and PowerShell."};let t;try{t=Gs(e);let n=Y.existsSync(t)?Y.readFileSync(t,"utf-8"):"",r=Mb(n,e),s=r!==n;return s&&Gr(t,r),{installed:!0,changed:s,shell:e,rcPath:t,message:s?`Persistent shell HUD installed in ${t}. Open a new terminal to start seeing it. Disable it any time with: visa-cli config shell-hud disable`:`Persistent shell HUD already installed in ${t}. Disable it any time with: visa-cli config shell-hud disable`}}catch(n){return{installed:!1,changed:!1,shell:e,rcPath:t,message:`Failed to install persistent shell HUD in ${t}: ${vc(n)}`}}}function jt(e=Wr(),t){let n=[],r=[],s=[];try{for(let o of mf(e,t))if(r.push(o.rcPath),!!Y.existsSync(o.rcPath))try{let i=Y.readFileSync(o.rcPath,"utf-8"),a=Ws(i);if(a===i.trimEnd())continue;Gr(o.rcPath,a.length>0?`${a}
101
+ `:""),n.push(o.rcPath)}catch(i){s.push(`${o.rcPath}: ${vc(i)}`)}return n.length>0?{removed:!0,shell:e,rcPath:n[0],rcPaths:n,message:s.length>0?`Removed persistent shell HUD from ${n.join(", ")}. Some rc files could not be updated: ${s.join("; ")}.`:`Removed persistent shell HUD from ${n.join(", ")}.`}:s.length>0?{removed:!1,shell:e,rcPath:r[0],rcPaths:r,message:`Failed to remove persistent shell HUD: ${s.join("; ")}`}:{removed:!0,shell:e,rcPath:r[0],rcPaths:r,message:"Persistent shell HUD was not installed in any supported shell rc file."}}catch(o){return{removed:!1,shell:e,message:`Failed to remove persistent shell HUD: ${vc(o)}`}}}function xc(e,t){let n=t??Rb,r=n.currentVersion==="0.0.0"&&e.version?e.version:n.currentVersion,s=_n(r),o=` ${te("\u2502",ee.chrome)} `,i=gf(n),a=Bb(n,i),c=n.updateCheckDisabled?"":i,l=jb(s,c);if(!e.enrolled)return[l,te("setup needed",ee.visaGold),a].filter(Boolean).join(o);let u=Yb(e),d=Db(e),f=_n(Xn.hostname().split(".")[0]),m=[l,f?te(f,ee.muted):"",te(u,ee.visaGold),a].filter(Boolean).join(o),p=[d,Lb(e)].filter(Boolean),g=p.length>0?p.join(o):"";return g?`${m}
102
+ ${g}`:m}function Lb(e){let t=` ${te("\u2502",ee.chrome)} `,n=[];if(typeof e.spentToday=="number"&&Number.isFinite(e.spentToday)&&n.push(te(`spent today ${Kr(Math.max(0,e.spentToday))}`,ee.muted)),e.lastService&&typeof e.lastService.toolName=="string"&&e.lastService.toolName.length>0){let r=Wb(_n(e.lastService.toolName)),s=Ub(e.lastService.createdAt),o=te(s?`last ${r} ${s}`:`last ${r}`,ee.muted);n.push(o)}if(typeof e.apiKeyCount=="number"&&Number.isFinite(e.apiKeyCount)){let r=Math.max(0,Math.floor(e.apiKeyCount)),s=r===1?"VISA Key":"VISA Keys";n.push(te(`${r} ${s}`,ee.muted))}else e.apiKeyStatus==="rollout_locked"&&n.push(te("VISA Key \u{1F51C}",ee.muted));return n.join(t)}function Ub(e){if(!e)return"";let t=Date.parse(e);if(!Number.isFinite(t))return"";let n=Date.now()-t;if(n<0)return"";let r=Math.floor(n/1e3);if(r<60)return`${r}s`;let s=Math.floor(r/60);if(s<60)return`${s}m`;let o=Math.floor(s/60);return o<24?`${o}h`:`${Math.floor(o/24)}d`}function Db(e){let t=typeof e.balanceCents=="number"?e.balanceCents:typeof e.prepaidBalance?.cents=="number"?e.prepaidBalance.cents:null,n=e.activeSession;if(t===null)return te("balance unknown",ee.muted);let r=t/100;if(n){let i=Math.max(0,n.capCents),a=Math.max(0,n.estimatedRemainingCents),c=Math.max(0,i-a),l=i>0?Math.max(0,Math.min(1,c/i)):0;return`${Gb(l)} ${te(`${Kr(a/100)} in session`,ee.green)} ${te(`(${Kr(c/100)}/${Kr(i/100)} cap)`,ee.muted)} ${te("\xB7",ee.chrome)} ${te(`${Kr(r)} balance`,ee.muted)}`}let s=10,o=`balance ${Kr(r)}`;return t>=s?te(o,ee.green):te(`${o} \u2014 top up via buy_credits`,ee.visaGold)}function jb(e,t){let n=e,r=`${te("VISA CLI",ee.visaBlue)} ${te(`v${n}`,ee.visaBlueSoft)}`;if(!t)return r;let s=t;return`${r} ${te("\u2B06 update",ee.visaGold)} ${te(`v${s}`,ee.visaGold)}`}function Bb(e,t){return t&&!e.updateCheckDisabled?te("run: visa-cli update",ee.visaGold):t?null:Fb(e)}function gf(e){return e.latestVersion?_n(e.latestVersion):""}function Fb(e){let t=gf(e);return t?te(`update ready v${t}`,ee.visaGold):null}function hf(){let e=Ys();return!(!e||Date.now()-e.renderedAt>df||e.cwd&&e.cwd!==process.cwd())}function ui(){let e=Ys(),t=Date.now();if(e&&t-e.renderedAt<=df||(Vb(),e?.line))return cf(e.line,e,t);try{let n=Ks();if(Y.existsSync(n)){let r=Y.readFileSync(n,"utf-8").trimEnd();if(r&&!di(r))return r}}catch{}return Eb}function cf(e,t,n){let r=n-t.renderedAt,s=typeof t.refreshFailedAt=="number"&&t.refreshFailedAt>t.renderedAt,o=[];if(r>=Cb&&o.push(`stale ${Hb(r)}`),s&&o.push("\u26A0 refresh failed"),o.length===0)return e;let i=` ${te("\xB7",ee.chrome)} ${te(o.join(" \xB7 "),ee.visaGold)}`,a=e.split(`
103
103
  `);for(let c=a.length-1;c>=0;c--)if(a[c].length>0)return a[c]=`${a[c]}${i}`,a.join(`
104
- `);return`${e}${i}`}function Fb(e){if(e<0)return"0s";let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60);if(n<60)return`${n}m`;let r=Math.floor(n/60);return r<24?`${r}h`:`${Math.floor(r/24)}d`}function xc(e,t){try{let n=Q.dirname(yn());Y.mkdirSync(n,{recursive:!0});let r=e.split(`
105
- `).map(o=>qb(o)).filter(o=>o.length>0).join(`
106
- `),s={hudVersion:xb,renderedAt:Date.now(),line:r,cwd:process.cwd(),status:t};Gr(yn(),JSON.stringify(s)+`
104
+ `);return`${e}${i}`}function Hb(e){if(e<0)return"0s";let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60);if(n<60)return`${n}m`;let r=Math.floor(n/60);return r<24?`${r}h`:`${Math.floor(r/24)}d`}function Tc(e,t){try{let n=Q.dirname(yn());Y.mkdirSync(n,{recursive:!0});let r=e.split(`
105
+ `).map(o=>Kb(o)).filter(o=>o.length>0).join(`
106
+ `),s={hudVersion:Tb,renderedAt:Date.now(),line:r,cwd:process.cwd(),status:t};Gr(yn(),JSON.stringify(s)+`
107
107
  `),Gr(Ks(),r+`
108
- `)}catch{}}function hf(e){try{let t=Ys();if(!t)return;let n=Math.max(Date.now(),t.renderedAt+1),r={...t,refreshFailedAt:n,refreshErrorReason:_n(e).slice(0,200)};Gr(yn(),JSON.stringify(r)+`
109
- `)}catch{}}function yf(){try{let e=Ys();if(!e)return;let t={...e,renderedAt:0};Gr(yn(),JSON.stringify(t)+`
110
- `)}catch{}}function Jn(){try{Y.unlinkSync(df())}catch{}}function Ys(){let e=yn();if(!Y.existsSync(e))return null;try{let t=JSON.parse(Y.readFileSync(e,"utf-8"));return typeof t?.line=="string"&&ui(t.line)?null:t}catch{return null}}function ui(e){for(let t of e.split(`
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 _f(){return Ys()?.status??null}function Hb(){if(process.env.JEST_WORKER_ID)return;let e=df();try{if(Y.mkdirSync(Q.dirname(e),{recursive:!0}),!Jb(e))return;let t=process.argv[1]?Q.resolve(process.argv[1]):"";if(!t){Jn();return}let n=ri(),r=(process.env.VISA_CLI_HUD_THEME??"").toLowerCase().trim(),s=n==="no-color"||r==="light"||r==="dark"?{}:{VISA_CLI_HUD_THEME:n},o=(0,lf.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,...s,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});o.once("error",Jn),o.unref()}catch{Jn()}}function _n(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 Vb=/^\u001B\[(?:0|38;2;\d{1,3};\d{1,3};\d{1,3}|38;5;\d{1,3})m$/;function qb(e){let t=[],n=`__VISA_CLI_HUD_SGR_${(0,vc.randomBytes)(8).toString("hex")}_`,r=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,o=>{if(!Vb.test(o))return"";let i=`${n}${t.length}__`;return t.push(o),i}),s=new RegExp(`${n}(\\d+)__`,"g");return _n(r).replace(s,(o,i)=>t[Number(i)]??"")}function Kb(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${te(r||"",ee.green)}${te(s||"",ee.chrome)}`}function Kr(e){return`$${e.toFixed(2)}`}function Gb(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 Wb(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=_n(n.toUpperCase()),o=_n(r);return`${t.isDefault?"default":"active"} ${s} ****${o}`}var ee={get reset(){return Ie().reset},get visaBlue(){return Ie().visaBlue},get visaBlueSoft(){return Ie().visaBlueSoft},get visaGold(){return Ie().visaGold},get green(){return Ie().green},get muted(){return Ie().muted},get chrome(){return Ie().chrome}};function te(e,t){return e.length===0||process.env.NO_COLOR||si()?e:`${t}${e}${ee.reset}`}function cf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Tc(){let e=Xn.homedir();if(!e||!Q.isAbsolute(e))throw new Error("unable to determine a valid home directory");return Q.resolve(e)}function Yb(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function zb(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function Jb(e){for(let t=0;t<2;t+=1){let n;try{return n=Y.openSync(e,"wx"),Y.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=Y.statSync(e);if(Date.now()-s.mtimeMs<=Rb)return!1;Y.unlinkSync(e)}catch{}}finally{n!==void 0&&Y.closeSync(n)}}return!1}function bc(e){return e instanceof Error?e.message:"unknown file system error"}function Gr(e,t){Y.mkdirSync(Q.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${(0,vc.randomBytes)(8).toString("hex")}.tmp`;try{Y.writeFileSync(n,t),Y.renameSync(n,e)}catch(r){try{Y.unlinkSync(n)}catch{}throw r}}var Xb=1440*60*1e3;function fi(e,t){we.mkdirSync(De.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${wf.randomBytes(8).toString("hex")}.tmp`;try{we.writeFileSync(n,JSON.stringify(t,null,2)+`
112
- `),we.renameSync(n,e)}catch(r){try{we.unlinkSync(n)}catch{}throw r}}function bf(e){return`'${e.replace(/'/g,"'\\''")}'`}var Ac="# visa-cli-hud-v1";function mi(e,t){if(!e&&!t&&Zb())return`visa-cli config statusline ${Ac}`;let n=e??process.execPath,r=t??process.argv[1]??"",s=r?De.resolve(r):"";return`${s?`${bf(n)} ${bf(s)} config statusline`:"visa-cli config statusline"} ${Ac}`}function Zb(){try{return(0,Sf.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function bn(e){return typeof e!="string"?!1:e.includes(Ac)?!0:e.includes("visa-cli")&&e.includes("statusline")}function Qb(){return"3.4.7-rc.1"}function pi(e){let t=De.dirname(De.resolve(e));return De.basename(t)===".claude"?De.dirname(t):xf.homedir()}function di(e,t){let n=De.relative(t,e);return!n.startsWith("..")&&!De.isAbsolute(n)?`~/${n}`:e}function e0(e){return De.join(pi(e),".visa-cli","hud-self-heal.json")}function t0(e,t,n,r){try{if(!we.existsSync(e))return!1;let s=JSON.parse(we.readFileSync(e,"utf-8"));return s.version===t&&typeof s.checkedAt=="number"&&n-s.checkedAt<r}catch{return!1}}function kc(e,t,n){try{fi(e,{version:t,checkedAt:n})}catch{}}function n0(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function Ec(e,t={}){let n=t.now??Date.now(),r=t.version??Qb(),s=t.stampPath??e0(e),o=t.minIntervalMs??Xb,i=[],a=!1,c=!1;if(!t.force&&t0(s,r,n,o))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:i,skippedReason:"recently checked"};try{if(!we.existsSync(e))return kc(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let l=JSON.parse(we.readFileSync(e,"utf-8")),u=l.statusLine,d=u&&typeof u=="object"&&!Array.isArray(u)?u.command:"";if(!bn(d))return kc(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let f=(t.getCommand??mi)();if(d!==f&&(l.statusLine=n0(u,f),fi(e,l),a=!0,i.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!gi()){let m=pi(e);if(Zn(m).length>0){let g=jt(null,m);if(g.removed&&g.rcPaths&&g.rcPaths.length>0){let v=g.rcPaths.map(k=>di(k,m)).join(", ");c=!0,i.push(`Cleaned legacy shell-prompt HUD block from ${v}.`)}}}return kc(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
- `)}catch{}}return{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i}}}function r0(e,t){let n=pi(t),r=Zn(n);if(r.length===0)return e;let s=r.map(o=>di(o,n)).join(", ");return`${e}
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 gi(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 vf(e,t){let n=pi(t),r=Zn(n);if(r.length===0)return e;let s=r.map(i=>di(i,n)).join(", ");if(gi())return`${e}
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=jt(null,n);if(o.removed&&o.rcPaths&&o.rcPaths.length>0){let i=o.rcPaths.map(a=>di(a,n)).join(", ");return`${e}
108
+ `)}catch{}}function yf(e){try{let t=Ys();if(!t)return;let n=Math.max(Date.now(),t.renderedAt+1),r={...t,refreshFailedAt:n,refreshErrorReason:_n(e).slice(0,200)};Gr(yn(),JSON.stringify(r)+`
109
+ `)}catch{}}function _f(){try{let e=Ys();if(!e)return;let t={...e,renderedAt:0};Gr(yn(),JSON.stringify(t)+`
110
+ `)}catch{}}function Jn(){try{Y.unlinkSync(ff())}catch{}}function Ys(){let e=yn();if(!Y.existsSync(e))return null;try{let t=JSON.parse(Y.readFileSync(e,"utf-8"));return typeof t?.line=="string"&&di(t.line)?null:t}catch{return null}}function di(e){for(let t of e.split(`
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 bf(){return Ys()?.status??null}function Vb(){if(process.env.JEST_WORKER_ID)return;let e=ff();try{if(Y.mkdirSync(Q.dirname(e),{recursive:!0}),!Xb(e))return;let t=process.argv[1]?Q.resolve(process.argv[1]):"";if(!t){Jn();return}let n=si(),r=(process.env.VISA_CLI_HUD_THEME??"").toLowerCase().trim(),s=n==="no-color"||r==="light"||r==="dark"?{}:{VISA_CLI_HUD_THEME:n},o=(0,uf.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,...s,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});o.once("error",Jn),o.unref()}catch{Jn()}}function _n(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 qb=/^\u001B\[(?:0|38;2;\d{1,3};\d{1,3};\d{1,3}|38;5;\d{1,3})m$/;function Kb(e){let t=[],n=`__VISA_CLI_HUD_SGR_${(0,wc.randomBytes)(8).toString("hex")}_`,r=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,o=>{if(!qb.test(o))return"";let i=`${n}${t.length}__`;return t.push(o),i}),s=new RegExp(`${n}(\\d+)__`,"g");return _n(r).replace(s,(o,i)=>t[Number(i)]??"")}function Gb(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${te(r||"",ee.green)}${te(s||"",ee.chrome)}`}function Kr(e){return`$${e.toFixed(2)}`}function Wb(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 Yb(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=_n(n.toUpperCase()),o=_n(r);return`${t.isDefault?"default":"active"} ${s} ****${o}`}var ee={get reset(){return Ie().reset},get visaBlue(){return Ie().visaBlue},get visaBlueSoft(){return Ie().visaBlueSoft},get visaGold(){return Ie().visaGold},get green(){return Ie().green},get muted(){return Ie().muted},get chrome(){return Ie().chrome}};function te(e,t){return e.length===0||process.env.NO_COLOR||oi()?e:`${t}${e}${ee.reset}`}function lf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ac(){let e=Xn.homedir();if(!e||!Q.isAbsolute(e))throw new Error("unable to determine a valid home directory");return Q.resolve(e)}function zb(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function Jb(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function Xb(e){for(let t=0;t<2;t+=1){let n;try{return n=Y.openSync(e,"wx"),Y.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=Y.statSync(e);if(Date.now()-s.mtimeMs<=Ib)return!1;Y.unlinkSync(e)}catch{}}finally{n!==void 0&&Y.closeSync(n)}}return!1}function vc(e){return e instanceof Error?e.message:"unknown file system error"}function Gr(e,t){Y.mkdirSync(Q.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${(0,wc.randomBytes)(8).toString("hex")}.tmp`;try{Y.writeFileSync(n,t),Y.renameSync(n,e)}catch(r){try{Y.unlinkSync(n)}catch{}throw r}}var Zb=1440*60*1e3;function mi(e,t){we.mkdirSync(De.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Sf.randomBytes(8).toString("hex")}.tmp`;try{we.writeFileSync(n,JSON.stringify(t,null,2)+`
112
+ `),we.renameSync(n,e)}catch(r){try{we.unlinkSync(n)}catch{}throw r}}function vf(e){return`'${e.replace(/'/g,"'\\''")}'`}var Cc="# visa-cli-hud-v1";function pi(e,t){if(!e&&!t&&Qb())return`visa-cli config statusline ${Cc}`;let n=e??process.execPath,r=t??process.argv[1]??"",s=r?De.resolve(r):"";return`${s?`${vf(n)} ${vf(s)} config statusline`:"visa-cli config statusline"} ${Cc}`}function Qb(){try{return(0,xf.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function bn(e){return typeof e!="string"?!1:e.includes(Cc)?!0:e.includes("visa-cli")&&e.includes("statusline")}function e0(){return"3.4.8-rc.0"}function gi(e){let t=De.dirname(De.resolve(e));return De.basename(t)===".claude"?De.dirname(t):Tf.homedir()}function fi(e,t){let n=De.relative(t,e);return!n.startsWith("..")&&!De.isAbsolute(n)?`~/${n}`:e}function t0(e){return De.join(gi(e),".visa-cli","hud-self-heal.json")}function n0(e,t,n,r){try{if(!we.existsSync(e))return!1;let s=JSON.parse(we.readFileSync(e,"utf-8"));return s.version===t&&typeof s.checkedAt=="number"&&n-s.checkedAt<r}catch{return!1}}function kc(e,t,n){try{mi(e,{version:t,checkedAt:n})}catch{}}function r0(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function Ec(e,t={}){let n=t.now??Date.now(),r=t.version??e0(),s=t.stampPath??t0(e),o=t.minIntervalMs??Zb,i=[],a=!1,c=!1;if(!t.force&&n0(s,r,n,o))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:i,skippedReason:"recently checked"};try{if(!we.existsSync(e))return kc(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let l=JSON.parse(we.readFileSync(e,"utf-8")),u=l.statusLine,d=u&&typeof u=="object"&&!Array.isArray(u)?u.command:"";if(!bn(d))return kc(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let f=(t.getCommand??pi)();if(d!==f&&(l.statusLine=r0(u,f),mi(e,l),a=!0,i.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!hi()){let m=gi(e);if(Zn(m).length>0){let g=jt(null,m);if(g.removed&&g.rcPaths&&g.rcPaths.length>0){let v=g.rcPaths.map(A=>fi(A,m)).join(", ");c=!0,i.push(`Cleaned legacy shell-prompt HUD block from ${v}.`)}}}return kc(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
+ `)}catch{}}return{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i}}}function s0(e,t){let n=gi(t),r=Zn(n);if(r.length===0)return e;let s=r.map(o=>fi(o,n)).join(", ");return`${e}
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 hi(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 wf(e,t){let n=gi(t),r=Zn(n);if(r.length===0)return e;let s=r.map(i=>fi(i,n)).join(", ");if(hi())return`${e}
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=jt(null,n);if(o.removed&&o.rcPaths&&o.rcPaths.length>0){let i=o.rcPaths.map(a=>fi(a,n)).join(", ");return`${e}
116
116
  Cleaned legacy shell-prompt HUD block from ${i} (was leaking output above every shell prompt). Set VISA_HUD_KEEP_SHELL=true to keep both surfaces (also accepts 1, yes, on).`}return`${e}
117
- Note: a legacy shell-prompt HUD block was detected in ${s} but could not be auto-removed (${o.message}). Remove it manually with: visa-cli config hud disable shell`}function zs(e,t=mi){let n={},r=!1;if(we.existsSync(e)){r=!0;try{n=JSON.parse(we.readFileSync(e,"utf-8"))}catch(s){return{installed:"malformed-json",message:`~/.claude/settings.json is not valid JSON (${s.message}). Fix the file manually, then run: visa-cli config hud enable claude`}}}if(n.statusLine){let s=typeof n.statusLine=="object"?n.statusLine.command:"";return bn(s)?{installed:"already-visa",message:vf("Visa HUD already registered in ~/.claude/settings.json.",e)}:{installed:"other-hud-present",message:r0("Another HUD is already configured (keeping it). To switch to Visa HUD, edit ~/.claude/settings.json \u2192 statusLine.command",e)}}try{return n.statusLine={type:"command",command:t()},fi(e,n),{installed:"new",message:vf(`Visa HUD registered in ~/.claude/settings.json${r?"":" (new file)"}. Restart Claude Code to see it pinned below the input.`,e)}}catch(s){return{installed:"error",message:`Failed to write settings: ${s.message}. Enable manually later with: visa-cli config hud enable claude`}}}function Cc(e){if(!we.existsSync(e))return{removed:!1,status:"missing-settings",message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(we.readFileSync(e,"utf-8"))}catch(r){return{removed:!1,status:"malformed-json",message:`~/.claude/settings.json is not valid JSON: ${r.message}`}}if(!t.statusLine)return{removed:!1,status:"missing-statusline",message:"No statusLine configured."};let n=typeof t.statusLine=="object"?t.statusLine.command:"";if(!bn(n))return{removed:!1,status:"foreign-statusline",message:"statusLine is owned by another tool \u2014 leaving it alone."};delete t.statusLine;try{fi(e,t)}catch(r){return{removed:!1,status:"error",message:`Failed to write ~/.claude/settings.json: ${r.message}`}}return{removed:!0,status:"removed",message:"Visa HUD removed from ~/.claude/settings.json. Restart Claude Code to take effect."}}var Tf=R(require("os")),kf=R(require("path"));function Bt(e=Tf.homedir()){return kf.join(e,".claude","settings.json")}var Ft=R(require("fs")),_t=R(require("path"));var s0=1,Qn={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},o0=["terminal","claude","claude-code","all"];function yi(e){let t=e.toLowerCase();return o0.includes(t)?t:null}var i0=50,a0=64*1024,Af=10,Rc=80,N={get reset(){return Ie().reset},get visaBlue(){return Ie().visaBlue},get visaBlueSoft(){return Ie().visaBlueSoft},get visaGold(){return Ie().visaGold},get green(){return Ie().green},get muted(){return Ie().muted},get chrome(){return Ie().chrome}};function L(e,t){return e.length===0||process.env.NO_COLOR||si()?e:`${t}${e}${N.reset}`}function Ef(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function $f(e=process.stdin){return e.isTTY?null:new Promise(t=>{let n=[],r=!1,s=()=>{e.removeListener("data",i),e.removeListener("end",a),e.removeListener("error",c),clearTimeout(l)},o=u=>{r||(r=!0,s(),t(u))},i=u=>{n.push(typeof u=="string"?Buffer.from(u):u)},a=()=>{let u=Buffer.concat(n).toString("utf-8").trim();if(!u)return o(null);try{let d=JSON.parse(u);o(d&&typeof d=="object"?d:null)}catch{o(null)}},c=()=>o(null),l=setTimeout(()=>{n.length>0?a():o(null)},i0);e.on("data",i),e.on("end",a),e.on("error",c)})}function Js(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${L(r||"",N.visaBlueSoft)}${L(s||"",N.chrome)}`}function Xs(e){return!Number.isFinite(e)||e<0?"0":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:String(Math.round(e))}function c0(e){if(Ff(e))return u0(e);let t=` ${L("\u2502",N.chrome)} `,n=hi(e)||"claude",r=e.cwd?ge(_t.basename(e.cwd)):"",s=_i(e.workspace),o=r||s,i=s&&s!==o?` ${L(`@${s}`,N.visaBlueSoft)}`:"",a=[L(`[${n}]`,N.visaBlueSoft)];o&&a.push(`${L(o,N.visaGold)}${i}`);let c=ge(e.git_branch??e.branch??"");c&&a.push(`${L("git:(",N.muted)}${L(c,N.visaBlueSoft)}${L(")",N.muted)}`);let l=a.join(t),u=Number(e.context_window?.context_window_size??0),d=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,f=e.context_window?.current_usage,m=[f?.input_tokens,f?.output_tokens,f?.cache_creation_input_tokens,f?.cache_read_input_tokens].filter(I=>typeof I=="number"&&Number.isFinite(I)),p=m.length>0?m.reduce((I,y)=>I+y,0):null,g=Number(e.context_window?.total_input_tokens??p??f?.input_tokens??0),v=d!==null?Math.max(0,Math.min(1,d/100)):u>0?Math.max(0,Math.min(1,g/u)):0,k=d!==null&&u>0?Math.round(v*u):g,b;if(u>0||d!==null){let I=`${String(Math.round(v*100)).padStart(2," ")}%`,y=u>0?` ${L(`(${Xs(k)}/${Xs(u)})`,N.muted)}`:"";b=`${L("Context",N.muted)} ${Js(v)} ${L(I,N.green)}${y}`}else b=`${L("Context",N.muted)} ${L("-",N.muted)}`;let w=Pf(e.rate_limits),S=[b];w&&S.push(w);let C=S.join(t);return`${l}
118
- ${C}`}function l0(e){if(Ff(e))return null;let t=` ${L("\u2502",N.chrome)} `,n=hi(e)||"claude",r=e.cwd?ge(_t.basename(e.cwd)):"",s=_i(e.workspace),o=r||s,i=s&&s!==o?` ${L(`@${s}`,N.visaBlueSoft)}`:"",a=[L(`[${n}]`,N.visaBlueSoft)];o&&a.push(`${L(o,N.visaGold)}${i}`);let c=ge(e.git_branch??e.branch??"");c&&a.push(`${L("git:(",N.muted)}${L(c,N.visaBlueSoft)}${L(")",N.muted)}`);let l=Number(e.context_window?.context_window_size??0),u=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,d=e.context_window?.current_usage,f=[d?.input_tokens,d?.output_tokens,d?.cache_creation_input_tokens,d?.cache_read_input_tokens].filter(S=>typeof S=="number"&&Number.isFinite(S)),m=f.length>0?f.reduce((S,C)=>S+C,0):null,p=Number(e.context_window?.total_input_tokens??m??d?.input_tokens??0),g=u!==null?Math.max(0,Math.min(1,u/100)):l>0?Math.max(0,Math.min(1,p/l)):0,v=u!==null&&l>0?Math.round(g*l):p,k;if(l>0||u!==null){let S=`${String(Math.round(g*100)).padStart(2," ")}%`,C=l>0?` ${L(`(${Xs(v)}/${Xs(l)})`,N.muted)}`:"";k=`${L("Context",N.muted)} ${Js(g)} ${L(S,N.green)}${C}`}else k=`${L("Context",N.muted)} ${L("-",N.muted)}`;let b=Pf(e.rate_limits),w=[k];return b&&w.push(b),{identity:a.join(t),metrics:w.join(t)}}function u0(e){let t=` ${L("\u2502",N.chrome)} `,n=Hf(e),r=n.model||"codex",s=[L(`[${r}]`,N.visaBlueSoft)];n.project&&s.push(L(n.project,N.visaGold)),n.gitBranch&&s.push(`${L("git",N.muted)} ${L(n.gitBranch,N.visaGold)}`);let o=s.join(t),i=[];if(typeof n.contextUsedPercent=="number"){let c=Math.max(0,Math.min(1,n.contextUsedPercent/100));i.push(`${L("Context",N.muted)} ${Js(c)} ${L(`${Math.round(n.contextUsedPercent)}%`,N.green)}`)}else if(typeof n.contextRemainingPercent=="number"){let c=100-n.contextRemainingPercent,l=Math.max(0,Math.min(1,c/100));i.push(`${L("Context",N.muted)} ${Js(l)} ${L(`${Math.round(c)}%`,N.green)}`)}typeof n.usedTokens=="number"&&i.push(`${L("Tokens",N.muted)} ${Xs(n.usedTokens)}`),n.status&&i.push(`${L("Status",N.muted)} ${L(n.status,N.visaBlueSoft)}`),n.threadTitle&&i.push(`${L("Thread",N.muted)} ${L(n.threadTitle,N.visaBlueSoft)}`);let a=i.length>0?i.join(t):`${L("Context",N.muted)} ${L("-",N.muted)}`;return`${o}
119
- ${a}`}function d0(e){if(typeof e!="number"||e<=0)return"";let n=(e>1e12?e:e*1e3)-Date.now();if(n<=0||n>=10080*60*1e3)return"";let r=Math.floor(n/6e4),s=Math.floor(r/60),o=r%60;return s>0?`${s}h ${o}m`:`${o}m`}function Cf(e,t){if(!e||typeof e.used_percentage!="number")return null;let n=Math.max(0,Math.min(100,e.used_percentage)),r=n/100,s=Js(r),o=n>=90?"\x1B[38;5;196m":n>=70?N.visaGold:N.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=d0(e.resets_at),c=a?` ${L(`(${a} / ${t})`,N.muted)}`:` ${L(`(${t})`,N.muted)}`;return`${s} ${L(i,o)}${c}`}function Pf(e){if(!e)return null;let t=Cf(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?Cf(e.seven_day,"7d"):null;if(!t&&!r)return null;let s=` ${L("\u2502",N.chrome)} `,o=[t,r].filter(Boolean);return`${L("Usage",N.muted)} ${o.join(s)}`}function Of(e){let t;try{let n=Ft.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let s=Math.min(r,a0),o=r-s;t=Ft.openSync(e,"r");let i=Buffer.alloc(s);Ft.readSync(t,i,0,s,o);let a=i.toString("utf-8");if(o>0){let c=Buffer.alloc(1);if(Ft.readSync(t,c,0,1,o-1),c[0]!==10){let l=a.indexOf(`
120
- `);l>=0&&(a=a.slice(l+1))}}return a}catch{return null}finally{if(t!==void 0)try{Ft.closeSync(t)}catch{}}}function f0(e){if(!e||typeof e!="object")return;let t=e,n=["file_path","path","notebook_path","pattern","command","url"];for(let r of n){let s=t[r];if(typeof s=="string"&&s.length>0){if(r.endsWith("_path")||r==="path"){let o=_t.basename(_t.dirname(s)),i=_t.basename(s);return o&&o!=="."&&o!=="/"?`${o}/${i}`:i}return s}}}function m0(e){let t=e.split(`
121
- `),n=[],r=new Set;for(let s=t.length-1;s>=0&&n.length<Af*3;s-=1){let o=t[s].trim();if(!o)continue;let i;try{i=JSON.parse(o)}catch{continue}if(!i||typeof i!="object")continue;let c=i.message;if(!c||typeof c!="object")continue;let l=c.content;if(Array.isArray(l))for(let u of l){if(!u||typeof u!="object")continue;let d=u;if(d.type==="tool_result"&&typeof d.tool_use_id=="string")r.add(d.tool_use_id);else if(d.type==="tool_use"&&typeof d.name=="string"){let f=typeof d.id=="string"?d.id:"",m=f.length>0?!r.has(f):!1;n.push({name:d.name,target:f0(d.input),running:m})}}}return n.reverse(),n.slice(Math.max(0,n.length-Af))}function p0(e){let t=[];for(let n of e){let r=t[t.length-1];r&&!r.running&&!n.running&&r.name===n.name&&r.target===void 0&&n.target===void 0?r.count+=1:t.push({...n,count:1})}return t}function g0(e){let t=e.running?L("\u25D0",N.visaGold):L("\u2713",N.green),n=e.running?N.visaGold:N.visaBlueSoft,r=L(ge(e.name),n),s=e.target?ge(e.target):"",o=s?`${L(":",N.chrome)} ${L(s,N.muted)}`:"",i=e.count>1?` ${L(`\xD7${e.count}`,N.muted)}`:"";return o?`${t} ${r}${o}${i}`:`${t} ${r}${i}`}function h0(e){let t=` ${L("\u2502",N.chrome)} `,n=Ef(t),r=e.slice();for(;r.length>0;){let c=r.join(t);if(Ef(c)<=Rc)return c;r=r.slice(1)}if(e.length===0)return"";let s="\u2026",i=e[e.length-1].replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,""),a=i.length>Rc-n-1?i.slice(0,Rc-n-1)+s:i;return`${L(s,N.muted)}${t}${a}`}async function Rf(e){if(!e||typeof e!="string")return null;let t=Of(e);if(!t)return null;let n;try{n=m0(t)}catch{return null}if(n.length===0)return null;let s=p0(n).map(g0);return h0(s)||null}async function Mf(e,t,n){return(await Lf(e,t,n)).join(`
122
- `)}function Nf(e,t,n){let r=!!t?.activeSession||e.includes("in session"),s=n?_0(n):!1;return{isActive:r||s,hasSession:r,hasToolActivity:s}}async function Lf(e,t,n){let{isActive:r}=Nf(e,n,t?.transcript_path),s=e.split(`
123
- `).filter(a=>a.length>0),i=t&&!r?s.map(a=>L(Ic(a),N.muted)):[...s];if(t){let a=l0(t);if(a){if(i.push(a.identity),t.transcript_path){let c=await Rf(t.transcript_path);c&&i.push(...c.split(`
124
- `))}i.push(a.metrics)}else{let c=c0(t);if(c&&i.push(...c.split(`
125
- `)),t.transcript_path){let l=await Rf(t.transcript_path);l&&i.push(...l.split(`
126
- `))}}}return i}var y0=["generate_image","generate_video","generate_music","generate_audio","generate_3d","upscale_image","run_llm","transcribe_audio","pay","get_status","buy_credits","get_cards","add_card","set_session_mode","query_onchain_prices","allium_explorer"];function _0(e){let t=Of(e);if(!t)return!1;let n=t.slice(-16384).toLowerCase();return y0.some(r=>n.includes(`"${r}"`))}async function Uf(e,t,n){let r=await Lf(e,t,n),s=r.join(`
127
- `),{isActive:o}=Nf(e,n,t?.transcript_path);return{schemaVersion:s0,client:t?Bf(t):Qn.UNKNOWN,rendered:s,lines:r.map(Ic),visa:{spendLine:Ic(e),balanceCents:n?.balanceCents,balanceMicros:n?.balanceMicros,balanceUsd:n?.amountUsd,sessionMode:n?.sessionMode,activeSession:n?.activeSession,isVisaActive:o},context:t?Hf(t):{}}}function ge(e){return e?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():""}function _i(e){if(typeof e=="string")return ge(_t.basename(e));if(!e||typeof e!="object")return"";let t=typeof e.current_dir=="string"?e.current_dir:typeof e.path=="string"?e.path:"";return ge(t?_t.basename(t):e.name)}function Df(e){return ge(e.app_name??e.appName??e.app??e.client)}function hi(e){return ge(e.model?.display_name??e.model?.id??e.model_name??e.modelName)}function jf(e){return ge(e.cwd??e.current_dir??e.project_root)}function If(e){let t=ge(e.project);if(t)return t;let n=jf(e);if(n)return ge(_t.basename(n));let r=_i(e.workspace);return r||""}function rt(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function Bf(e){let t=Df(e).toLowerCase();return t.includes("codex")?Qn.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?Qn.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||rt(e.context_used)!==void 0?Qn.CODEX:Qn.UNKNOWN}function Ff(e){return Bf(e)===Qn.CODEX}function Hf(e){let t=Df(e),n=jf(e),r=_i(e.workspace),s=rt(e.context_used)??rt(e.context_window?.used_percentage??void 0),o=rt(e.context_remaining)??rt(e.context_window?.remaining_percentage??void 0);return{...t?{app:t}:{},...hi(e)?{model:hi(e)}:{},...If(e)?{project:If(e)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...ge(e.git_branch??e.branch)?{gitBranch:ge(e.git_branch??e.branch)}:{},...ge(e.status??e.run_state??e.runState)?{status:ge(e.status??e.run_state??e.runState)}:{},...ge(e.thread_title??e.threadTitle)?{threadTitle:ge(e.thread_title??e.threadTitle)}:{},...s!==void 0?{contextUsedPercent:s}:{},...o!==void 0?{contextRemainingPercent:o}:{},...rt(e.used_tokens)!==void 0?{usedTokens:rt(e.used_tokens)}:{},...rt(e.total_input_tokens)!==void 0?{totalInputTokens:rt(e.total_input_tokens)}:{},...rt(e.total_output_tokens)!==void 0?{totalOutputTokens:rt(e.total_output_tokens)}:{}}}function Ic(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}var qf=R(require("path"));function Vf(e){return e instanceof Error?e.message:String(e)}function $c(e,t){let n=[],r=[],s=e??"claude",o=yi(s);if(s==="shell"||s==="prompt")try{let a=t.installShellHud();return a.installed?{ok:!0,messages:[a.message],errors:r}:{ok:!1,messages:n,errors:[a.message]}}catch(a){return{ok:!1,messages:n,errors:[`Failed to install shell HUD: ${Vf(a)}`]}}if(!o)return{ok:!1,messages:n,errors:[`Unknown HUD surface: ${s}`,"Supported: claude (default), shell, all"]};let i=!0;if(o==="claude"||o==="claude-code"||o==="all"){let a=qf.join(t.homeDir,".claude","settings.json");try{let c=t.installVisaStatusLine(a);n.push(c.message),(c.installed==="error"||c.installed==="malformed-json")&&(i=!1)}catch(c){i=!1,r.push(`Failed to install Claude HUD: ${Vf(c)}`)}}return{ok:i,messages:n,errors:r}}function Kf(e){if(!e||typeof e!="object")return"";let t=e;return Array.isArray(t.enum)&&t.enum.length>0?"enum":typeof t.type=="string"?t.type:Array.isArray(t.type)?t.type.filter(n=>typeof n=="string").join("|"):""}var Gf=R(require("os")),Wf=require("node:readline/promises"),Zs={card:"default VISA ****7242",balance:"balance $6.38",spentToday:"spent today $0.62",lastActivity:"last Visa tool 38m",model:"Opus 4.6"};async function Pc(e,t=!1){if(!process.stdin.isTTY)return t;let n=t?"[Y/n]":"[y/N]",r,s;try{r=(0,Wf.createInterface)({input:process.stdin,output:process.stdout});let o=new AbortController;s=()=>o.abort(),r.once("close",s);let i=(await r.question(`${e} ${n} `,{signal:o.signal})).trim();return i?/^y(es)?$/i.test(i):t}catch{return t}finally{r&&s&&r.off("close",s),r?.close()}}function b0(e,t){return e.replace(/[\x00-\x1F\x7F\u202A-\u202E\u2066-\u2069]/g,"").trim()||t}function Yf(e=Gf.hostname()){let t=Us().version,n=b0(e,"this-machine");return[" Preview if installed (sample):",` VISA CLI v${t} | ${n} | ${Zs.card}`,` ${Zs.balance} | ${Zs.spentToday} | ${Zs.lastActivity}`,` [${Zs.model}] | you`," Activity live"].join(`
128
- `)}function zf(e="CLI"){return[" \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557"," \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551"," \u255A\u2588\u2588\u2557 \u2588\u2588\u2554\u255D\u2588\u2588\u2551\u255A\u2550\u2550\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551"," \u255A\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551",e?` \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u2588 ${e}`:" \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D"]}function Oc(e){return`$${(e/100).toFixed(2)}`}function Jf(e){return typeof e=="number"?Oc(e):"no cap"}function Xf(e){return e.length>0?e.join(", "):"all tools"}var v0=[" \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557"," \u2588\u2588\u2551 \u2588\u2588\u2554\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u255A\u2588\u2588\u2557 \u2588\u2588\u2554\u255D"," \u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2588\u2588\u2588\u2557 \u255A\u2588\u2588\u2588\u2588\u2554\u255D "," \u2588\u2588\u2554\u2550\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u255D \u255A\u2588\u2588\u2554\u255D "," \u2588\u2588\u2551 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 "," \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D "];function w0(){return[...zf(null),...v0].join(`
129
- `)}var Zf="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 S0(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 Qf(e,t={}){let n=t.authUrl??"https://auth.visacli.sh",r=[...w0().split(`
130
- `),"","Visa Key active","Scoped agent spend credential ready for apps and agents","",...S0([["Key",e.key],["Label",e.label],["Owner",e.owner],["Daily cap",`${Oc(e.daily_cap_cents)}/day`],["Total cap",Jf(e.total_cap_cents)],["Allowed tools",Xf(e.allowed_tools)]]),"","Guardrails",`- Spend: ${Oc(e.daily_cap_cents)}/day, ${Jf(e.total_cap_cents)} total`,`- Tools: ${Xf(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("",Zf,`Server warning: ${e.biometric_warning}`):e.biometric_enabled&&r.push("",Zf),`${r.join(`
117
+ Note: a legacy shell-prompt HUD block was detected in ${s} but could not be auto-removed (${o.message}). Remove it manually with: visa-cli config hud disable shell`}function zs(e,t=pi){let n={},r=!1;if(we.existsSync(e)){r=!0;try{n=JSON.parse(we.readFileSync(e,"utf-8"))}catch(s){return{installed:"malformed-json",message:`~/.claude/settings.json is not valid JSON (${s.message}). Fix the file manually, then run: visa-cli config hud enable claude`}}}if(n.statusLine){let s=typeof n.statusLine=="object"?n.statusLine.command:"";return bn(s)?{installed:"already-visa",message:wf("Visa HUD already registered in ~/.claude/settings.json.",e)}:{installed:"other-hud-present",message:s0("Another HUD is already configured (keeping it). To switch to Visa HUD, edit ~/.claude/settings.json \u2192 statusLine.command",e)}}try{return n.statusLine={type:"command",command:t()},mi(e,n),{installed:"new",message:wf(`Visa HUD registered in ~/.claude/settings.json${r?"":" (new file)"}. Restart Claude Code to see it pinned below the input.`,e)}}catch(s){return{installed:"error",message:`Failed to write settings: ${s.message}. Enable manually later with: visa-cli config hud enable claude`}}}function Rc(e){if(!we.existsSync(e))return{removed:!1,status:"missing-settings",message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(we.readFileSync(e,"utf-8"))}catch(r){return{removed:!1,status:"malformed-json",message:`~/.claude/settings.json is not valid JSON: ${r.message}`}}if(!t.statusLine)return{removed:!1,status:"missing-statusline",message:"No statusLine configured."};let n=typeof t.statusLine=="object"?t.statusLine.command:"";if(!bn(n))return{removed:!1,status:"foreign-statusline",message:"statusLine is owned by another tool \u2014 leaving it alone."};delete t.statusLine;try{mi(e,t)}catch(r){return{removed:!1,status:"error",message:`Failed to write ~/.claude/settings.json: ${r.message}`}}return{removed:!0,status:"removed",message:"Visa HUD removed from ~/.claude/settings.json. Restart Claude Code to take effect."}}var Af=R(require("os")),kf=R(require("path"));function Bt(e=Af.homedir()){return kf.join(e,".claude","settings.json")}var Ft=R(require("fs")),_t=R(require("path"));var o0=1,Qn={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},i0=["terminal","claude","claude-code","all"];function _i(e){let t=e.toLowerCase();return i0.includes(t)?t:null}var a0=50,c0=64*1024,Cf=10,Ic=80,N={get reset(){return Ie().reset},get visaBlue(){return Ie().visaBlue},get visaBlueSoft(){return Ie().visaBlueSoft},get visaGold(){return Ie().visaGold},get green(){return Ie().green},get muted(){return Ie().muted},get chrome(){return Ie().chrome}};function L(e,t){return e.length===0||process.env.NO_COLOR||oi()?e:`${t}${e}${N.reset}`}function Ef(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function $f(e=process.stdin){return e.isTTY?null:new Promise(t=>{let n=[],r=!1,s=()=>{e.removeListener("data",i),e.removeListener("end",a),e.removeListener("error",c),clearTimeout(l)},o=u=>{r||(r=!0,s(),t(u))},i=u=>{n.push(typeof u=="string"?Buffer.from(u):u)},a=()=>{let u=Buffer.concat(n).toString("utf-8").trim();if(!u)return o(null);try{let d=JSON.parse(u);o(d&&typeof d=="object"?d:null)}catch{o(null)}},c=()=>o(null),l=setTimeout(()=>{n.length>0?a():o(null)},a0);e.on("data",i),e.on("end",a),e.on("error",c)})}function Js(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${L(r||"",N.visaBlueSoft)}${L(s||"",N.chrome)}`}function Xs(e){return!Number.isFinite(e)||e<0?"0":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:String(Math.round(e))}function l0(e){if(Hf(e))return d0(e);let t=` ${L("\u2502",N.chrome)} `,n=yi(e)||"claude",r=e.cwd?ge(_t.basename(e.cwd)):"",s=bi(e.workspace),o=r||s,i=s&&s!==o?` ${L(`@${s}`,N.visaBlueSoft)}`:"",a=[L(`[${n}]`,N.visaBlueSoft)];o&&a.push(`${L(o,N.visaGold)}${i}`);let c=ge(e.git_branch??e.branch??"");c&&a.push(`${L("git:(",N.muted)}${L(c,N.visaBlueSoft)}${L(")",N.muted)}`);let l=a.join(t),u=Number(e.context_window?.context_window_size??0),d=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,f=e.context_window?.current_usage,m=[f?.input_tokens,f?.output_tokens,f?.cache_creation_input_tokens,f?.cache_read_input_tokens].filter(I=>typeof I=="number"&&Number.isFinite(I)),p=m.length>0?m.reduce((I,y)=>I+y,0):null,g=Number(e.context_window?.total_input_tokens??p??f?.input_tokens??0),v=d!==null?Math.max(0,Math.min(1,d/100)):u>0?Math.max(0,Math.min(1,g/u)):0,A=d!==null&&u>0?Math.round(v*u):g,b;if(u>0||d!==null){let I=`${String(Math.round(v*100)).padStart(2," ")}%`,y=u>0?` ${L(`(${Xs(A)}/${Xs(u)})`,N.muted)}`:"";b=`${L("Context",N.muted)} ${Js(v)} ${L(I,N.green)}${y}`}else b=`${L("Context",N.muted)} ${L("-",N.muted)}`;let w=Of(e.rate_limits),S=[b];w&&S.push(w);let E=S.join(t);return`${l}
118
+ ${E}`}function u0(e){if(Hf(e))return null;let t=` ${L("\u2502",N.chrome)} `,n=yi(e)||"claude",r=e.cwd?ge(_t.basename(e.cwd)):"",s=bi(e.workspace),o=r||s,i=s&&s!==o?` ${L(`@${s}`,N.visaBlueSoft)}`:"",a=[L(`[${n}]`,N.visaBlueSoft)];o&&a.push(`${L(o,N.visaGold)}${i}`);let c=ge(e.git_branch??e.branch??"");c&&a.push(`${L("git:(",N.muted)}${L(c,N.visaBlueSoft)}${L(")",N.muted)}`);let l=Number(e.context_window?.context_window_size??0),u=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,d=e.context_window?.current_usage,f=[d?.input_tokens,d?.output_tokens,d?.cache_creation_input_tokens,d?.cache_read_input_tokens].filter(S=>typeof S=="number"&&Number.isFinite(S)),m=f.length>0?f.reduce((S,E)=>S+E,0):null,p=Number(e.context_window?.total_input_tokens??m??d?.input_tokens??0),g=u!==null?Math.max(0,Math.min(1,u/100)):l>0?Math.max(0,Math.min(1,p/l)):0,v=u!==null&&l>0?Math.round(g*l):p,A;if(l>0||u!==null){let S=`${String(Math.round(g*100)).padStart(2," ")}%`,E=l>0?` ${L(`(${Xs(v)}/${Xs(l)})`,N.muted)}`:"";A=`${L("Context",N.muted)} ${Js(g)} ${L(S,N.green)}${E}`}else A=`${L("Context",N.muted)} ${L("-",N.muted)}`;let b=Of(e.rate_limits),w=[A];return b&&w.push(b),{identity:a.join(t),metrics:w.join(t)}}function d0(e){let t=` ${L("\u2502",N.chrome)} `,n=Vf(e),r=n.model||"codex",s=[L(`[${r}]`,N.visaBlueSoft)];n.project&&s.push(L(n.project,N.visaGold)),n.gitBranch&&s.push(`${L("git",N.muted)} ${L(n.gitBranch,N.visaGold)}`);let o=s.join(t),i=[];if(typeof n.contextUsedPercent=="number"){let c=Math.max(0,Math.min(1,n.contextUsedPercent/100));i.push(`${L("Context",N.muted)} ${Js(c)} ${L(`${Math.round(n.contextUsedPercent)}%`,N.green)}`)}else if(typeof n.contextRemainingPercent=="number"){let c=100-n.contextRemainingPercent,l=Math.max(0,Math.min(1,c/100));i.push(`${L("Context",N.muted)} ${Js(l)} ${L(`${Math.round(c)}%`,N.green)}`)}typeof n.usedTokens=="number"&&i.push(`${L("Tokens",N.muted)} ${Xs(n.usedTokens)}`),n.status&&i.push(`${L("Status",N.muted)} ${L(n.status,N.visaBlueSoft)}`),n.threadTitle&&i.push(`${L("Thread",N.muted)} ${L(n.threadTitle,N.visaBlueSoft)}`);let a=i.length>0?i.join(t):`${L("Context",N.muted)} ${L("-",N.muted)}`;return`${o}
119
+ ${a}`}function f0(e){if(typeof e!="number"||e<=0)return"";let n=(e>1e12?e:e*1e3)-Date.now();if(n<=0||n>=10080*60*1e3)return"";let r=Math.floor(n/6e4),s=Math.floor(r/60),o=r%60;return s>0?`${s}h ${o}m`:`${o}m`}function Rf(e,t){if(!e||typeof e.used_percentage!="number")return null;let n=Math.max(0,Math.min(100,e.used_percentage)),r=n/100,s=Js(r),o=n>=90?"\x1B[38;5;196m":n>=70?N.visaGold:N.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=f0(e.resets_at),c=a?` ${L(`(${a} / ${t})`,N.muted)}`:` ${L(`(${t})`,N.muted)}`;return`${s} ${L(i,o)}${c}`}function Of(e){if(!e)return null;let t=Rf(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?Rf(e.seven_day,"7d"):null;if(!t&&!r)return null;let s=` ${L("\u2502",N.chrome)} `,o=[t,r].filter(Boolean);return`${L("Usage",N.muted)} ${o.join(s)}`}function Mf(e){let t;try{let n=Ft.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let s=Math.min(r,c0),o=r-s;t=Ft.openSync(e,"r");let i=Buffer.alloc(s);Ft.readSync(t,i,0,s,o);let a=i.toString("utf-8");if(o>0){let c=Buffer.alloc(1);if(Ft.readSync(t,c,0,1,o-1),c[0]!==10){let l=a.indexOf(`
120
+ `);l>=0&&(a=a.slice(l+1))}}return a}catch{return null}finally{if(t!==void 0)try{Ft.closeSync(t)}catch{}}}function m0(e){if(!e||typeof e!="object")return;let t=e,n=["file_path","path","notebook_path","pattern","command","url"];for(let r of n){let s=t[r];if(typeof s=="string"&&s.length>0){if(r.endsWith("_path")||r==="path"){let o=_t.basename(_t.dirname(s)),i=_t.basename(s);return o&&o!=="."&&o!=="/"?`${o}/${i}`:i}return s}}}function p0(e){let t=e.split(`
121
+ `),n=[],r=new Set;for(let s=t.length-1;s>=0&&n.length<Cf*3;s-=1){let o=t[s].trim();if(!o)continue;let i;try{i=JSON.parse(o)}catch{continue}if(!i||typeof i!="object")continue;let c=i.message;if(!c||typeof c!="object")continue;let l=c.content;if(Array.isArray(l))for(let u of l){if(!u||typeof u!="object")continue;let d=u;if(d.type==="tool_result"&&typeof d.tool_use_id=="string")r.add(d.tool_use_id);else if(d.type==="tool_use"&&typeof d.name=="string"){let f=typeof d.id=="string"?d.id:"",m=f.length>0?!r.has(f):!1;n.push({name:d.name,target:m0(d.input),running:m})}}}return n.reverse(),n.slice(Math.max(0,n.length-Cf))}function g0(e){let t=[];for(let n of e){let r=t[t.length-1];r&&!r.running&&!n.running&&r.name===n.name&&r.target===void 0&&n.target===void 0?r.count+=1:t.push({...n,count:1})}return t}function h0(e){let t=e.running?L("\u25D0",N.visaGold):L("\u2713",N.green),n=e.running?N.visaGold:N.visaBlueSoft,r=L(ge(e.name),n),s=e.target?ge(e.target):"",o=s?`${L(":",N.chrome)} ${L(s,N.muted)}`:"",i=e.count>1?` ${L(`\xD7${e.count}`,N.muted)}`:"";return o?`${t} ${r}${o}${i}`:`${t} ${r}${i}`}function y0(e){let t=` ${L("\u2502",N.chrome)} `,n=Ef(t),r=e.slice();for(;r.length>0;){let c=r.join(t);if(Ef(c)<=Ic)return c;r=r.slice(1)}if(e.length===0)return"";let s="\u2026",i=e[e.length-1].replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,""),a=i.length>Ic-n-1?i.slice(0,Ic-n-1)+s:i;return`${L(s,N.muted)}${t}${a}`}async function If(e){if(!e||typeof e!="string")return null;let t=Mf(e);if(!t)return null;let n;try{n=p0(t)}catch{return null}if(n.length===0)return null;let s=g0(n).map(h0);return y0(s)||null}async function Nf(e,t,n){return(await Uf(e,t,n)).join(`
122
+ `)}function Lf(e,t,n){let r=!!t?.activeSession||e.includes("in session"),s=n?b0(n):!1;return{isActive:r||s,hasSession:r,hasToolActivity:s}}async function Uf(e,t,n){let{isActive:r}=Lf(e,n,t?.transcript_path),s=e.split(`
123
+ `).filter(a=>a.length>0),i=t&&!r?s.map(a=>L(Pc(a),N.muted)):[...s];if(t){let a=u0(t);if(a){if(i.push(a.identity),t.transcript_path){let c=await If(t.transcript_path);c&&i.push(...c.split(`
124
+ `))}i.push(a.metrics)}else{let c=l0(t);if(c&&i.push(...c.split(`
125
+ `)),t.transcript_path){let l=await If(t.transcript_path);l&&i.push(...l.split(`
126
+ `))}}}return i}var _0=["generate_image","generate_video","generate_music","generate_audio","generate_3d","upscale_image","run_llm","transcribe_audio","pay","get_status","buy_credits","get_cards","add_card","set_session_mode","query_onchain_prices","allium_explorer"];function b0(e){let t=Mf(e);if(!t)return!1;let n=t.slice(-16384).toLowerCase();return _0.some(r=>n.includes(`"${r}"`))}async function Df(e,t,n){let r=await Uf(e,t,n),s=r.join(`
127
+ `),{isActive:o}=Lf(e,n,t?.transcript_path);return{schemaVersion:o0,client:t?Ff(t):Qn.UNKNOWN,rendered:s,lines:r.map(Pc),visa:{spendLine:Pc(e),balanceCents:n?.balanceCents,balanceMicros:n?.balanceMicros,balanceUsd:n?.amountUsd,sessionMode:n?.sessionMode,activeSession:n?.activeSession,isVisaActive:o},context:t?Vf(t):{}}}function ge(e){return e?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():""}function bi(e){if(typeof e=="string")return ge(_t.basename(e));if(!e||typeof e!="object")return"";let t=typeof e.current_dir=="string"?e.current_dir:typeof e.path=="string"?e.path:"";return ge(t?_t.basename(t):e.name)}function jf(e){return ge(e.app_name??e.appName??e.app??e.client)}function yi(e){return ge(e.model?.display_name??e.model?.id??e.model_name??e.modelName)}function Bf(e){return ge(e.cwd??e.current_dir??e.project_root)}function Pf(e){let t=ge(e.project);if(t)return t;let n=Bf(e);if(n)return ge(_t.basename(n));let r=bi(e.workspace);return r||""}function rt(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function Ff(e){let t=jf(e).toLowerCase();return t.includes("codex")?Qn.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?Qn.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||rt(e.context_used)!==void 0?Qn.CODEX:Qn.UNKNOWN}function Hf(e){return Ff(e)===Qn.CODEX}function Vf(e){let t=jf(e),n=Bf(e),r=bi(e.workspace),s=rt(e.context_used)??rt(e.context_window?.used_percentage??void 0),o=rt(e.context_remaining)??rt(e.context_window?.remaining_percentage??void 0);return{...t?{app:t}:{},...yi(e)?{model:yi(e)}:{},...Pf(e)?{project:Pf(e)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...ge(e.git_branch??e.branch)?{gitBranch:ge(e.git_branch??e.branch)}:{},...ge(e.status??e.run_state??e.runState)?{status:ge(e.status??e.run_state??e.runState)}:{},...ge(e.thread_title??e.threadTitle)?{threadTitle:ge(e.thread_title??e.threadTitle)}:{},...s!==void 0?{contextUsedPercent:s}:{},...o!==void 0?{contextRemainingPercent:o}:{},...rt(e.used_tokens)!==void 0?{usedTokens:rt(e.used_tokens)}:{},...rt(e.total_input_tokens)!==void 0?{totalInputTokens:rt(e.total_input_tokens)}:{},...rt(e.total_output_tokens)!==void 0?{totalOutputTokens:rt(e.total_output_tokens)}:{}}}function Pc(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}var Kf=R(require("path"));function qf(e){return e instanceof Error?e.message:String(e)}function $c(e,t){let n=[],r=[],s=e??"claude",o=_i(s);if(s==="shell"||s==="prompt")try{let a=t.installShellHud();return a.installed?{ok:!0,messages:[a.message],errors:r}:{ok:!1,messages:n,errors:[a.message]}}catch(a){return{ok:!1,messages:n,errors:[`Failed to install shell HUD: ${qf(a)}`]}}if(!o)return{ok:!1,messages:n,errors:[`Unknown HUD surface: ${s}`,"Supported: claude (default), shell, all"]};let i=!0;if(o==="claude"||o==="claude-code"||o==="all"){let a=Kf.join(t.homeDir,".claude","settings.json");try{let c=t.installVisaStatusLine(a);n.push(c.message),(c.installed==="error"||c.installed==="malformed-json")&&(i=!1)}catch(c){i=!1,r.push(`Failed to install Claude HUD: ${qf(c)}`)}}return{ok:i,messages:n,errors:r}}function Gf(e){if(!e||typeof e!="object")return"";let t=e;return Array.isArray(t.enum)&&t.enum.length>0?"enum":typeof t.type=="string"?t.type:Array.isArray(t.type)?t.type.filter(n=>typeof n=="string").join("|"):""}var Wf=R(require("os")),Yf=require("node:readline/promises"),Zs={card:"default VISA ****7242",balance:"balance $6.38",spentToday:"spent today $0.62",lastActivity:"last Visa tool 38m",model:"Opus 4.6"};async function Oc(e,t=!1){if(!process.stdin.isTTY)return t;let n=t?"[Y/n]":"[y/N]",r,s;try{r=(0,Yf.createInterface)({input:process.stdin,output:process.stdout});let o=new AbortController;s=()=>o.abort(),r.once("close",s);let i=(await r.question(`${e} ${n} `,{signal:o.signal})).trim();return i?/^y(es)?$/i.test(i):t}catch{return t}finally{r&&s&&r.off("close",s),r?.close()}}function v0(e,t){return e.replace(/[\x00-\x1F\x7F\u202A-\u202E\u2066-\u2069]/g,"").trim()||t}function zf(e=Wf.hostname()){let t=Us().version,n=v0(e,"this-machine");return[" Preview if installed (sample):",` VISA CLI v${t} | ${n} | ${Zs.card}`,` ${Zs.balance} | ${Zs.spentToday} | ${Zs.lastActivity}`,` [${Zs.model}] | you`," Activity live"].join(`
128
+ `)}function Jf(e="CLI"){return[" \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557"," \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551"," \u255A\u2588\u2588\u2557 \u2588\u2588\u2554\u255D\u2588\u2588\u2551\u255A\u2550\u2550\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551"," \u255A\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551",e?` \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u2588 ${e}`:" \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D"]}function Mc(e){return`$${(e/100).toFixed(2)}`}function Xf(e){return typeof e=="number"?Mc(e):"no cap"}function Zf(e){return e.length>0?e.join(", "):"all tools"}var w0=[" \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557"," \u2588\u2588\u2551 \u2588\u2588\u2554\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u255A\u2588\u2588\u2557 \u2588\u2588\u2554\u255D"," \u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2588\u2588\u2588\u2557 \u255A\u2588\u2588\u2588\u2588\u2554\u255D "," \u2588\u2588\u2554\u2550\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u255D \u255A\u2588\u2588\u2554\u255D "," \u2588\u2588\u2551 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 "," \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D "];function S0(){return[...Jf(null),...w0].join(`
129
+ `)}var Qf="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 x0(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 em(e,t={}){let n=t.authUrl??"https://auth.visacli.sh",r=[...S0().split(`
130
+ `),"","Visa Key active","Scoped agent spend credential ready for apps and agents","",...x0([["Key",e.key],["Label",e.label],["Owner",e.owner],["Daily cap",`${Mc(e.daily_cap_cents)}/day`],["Total cap",Xf(e.total_cap_cents)],["Allowed tools",Zf(e.allowed_tools)]]),"","Guardrails",`- Spend: ${Mc(e.daily_cap_cents)}/day, ${Xf(e.total_cap_cents)} total`,`- Tools: ${Zf(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("",Qf,`Server warning: ${e.biometric_warning}`):e.biometric_enabled&&r.push("",Qf),`${r.join(`
131
131
  `)}
132
- `}function em(e){return e.json===!0||e.isTTY!==!0}function Mc(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 Nc(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 tm(e,t){let n=Mc(e);if(n!==void 0)return n;if(em(t))return 500}function nm(e,t){let n=Nc(e);if(n!==void 0)return n;if(em(t)||t.recommendedCapsAccepted===!0)return 2500}async function bt(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 er=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},Yr=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}},Ht=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}},vt=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}},he=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}},st=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 rm={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 zr(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&&rm[n]?rm[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.`}wt();var E0=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function im(e,t){let n=om(e),r=om(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:C0(n.pre,r.pre)>0}function om(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(E0);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function C0(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 St(){return!!(am(process.env.VISA_CLI_NO_UPDATE_CHECK)||am(process.env.CI)||process.env.NODE_ENV==="test")}function am(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}qt();var D0="CARD_REENROLLMENT_REQUIRED",j0="https://auth.visacli.sh/enroll-card";function B0(){try{return new URL("/enroll-card",$e()).toString()}catch{return j0}}function F0(e){let t=B0();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 h.warn("card-reenroll:reenroll_url_rejected_fallback",{reason:"untrusted_or_malformed_reenroll_url",fallbackPath:"/enroll-card"}),t}var Sn="3.4.7-rc.1",H0=/^(?:VisaKey_[A-Za-z0-9_-]{16,128}|visakey_[A-Za-z0-9_-]{16,128}|vk_[A-Za-z0-9_-]{32,128})$/;function V0(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 Gc(e){return e==="TOPUP_CHARGE_AMBIGUOUS"||e==="TOPUP_RECONCILIATION_REQUIRED"?e:null}var q0="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function Jr(e){return typeof e=="string"?e.trim():""}function no(e){let t=e&&typeof e=="object"?e:{},n=Jr(t.error)||Jr(t.message);if(!n)return q0;let r=Jr(t.error_code),s=[["surface",Jr(t.disabled_surface)],["flag",Jr(t.flag)],["correlation_id",Jr(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 ro(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?H0.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
- `)}var qe=class{constructor(t){this.getSessionToken=t;this.baseUrl=$e()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!St()){let r=t.headers.get("X-Latest-Version");r&&im(r,Sn)&&(this.lastSignals.updateAvailable={currentVersion:Sn,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return Sn}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new er(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(no(n))}async request(t,n,r,s,o,i){let a=await this.getSessionToken();if(!a)throw new Error(ro());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 bt(`${this.baseUrl}${n}`,{method:t,headers:{...c,"X-Visa-CLI-Version":Sn,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:s})}catch(d){throw new Error(zr(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===D0){let f=typeof u?.last4=="string"?u.last4:"",m=typeof u?.brand=="string"?u.brand:"card",p=F0(u?.reenroll_url),g=f?`${m} ending in ${f}`:"your card";throw new Error(`Please re-add ${g} to keep payments running. Open: ${p}`)}let d=Gc(u?.error_code);if(d)throw new st(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 f=Number(u.retryAfter??l.headers.get("Retry-After"));throw new he(u.error||"Your card was declined.",!!u.retryable,u.code,u.reason,u.payment_error_class,u.correlation_id,u.transactionId,Number.isFinite(f)&&f>0?f:void 0)}if(l.status===402){let f=u?.error||"Gateway returned 402",m=typeof u?.error_code=="string"?u.error_code:"";throw m==="SPENDING_LIMIT_EXCEEDED"||m==="DAILY_LIMIT_EXCEEDED"||m==="PER_TXN_LIMIT_EXCEEDED"?new Error(`${f}. Check your limits with get_status or run: visa-cli update-spending-controls`):new Error(f)}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(ro());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":Sn,"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 bt(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(p){throw new Error(zr(p))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let p=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${p}s. Tip: use the batch tool to combine multiple requests into one.`)}let f=d.headers.get("X-Voucher-Receipt"),m;try{m=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(m),d.status===503){if(m?.error_code==="SESSION_LOCK_CONTENDED"){let v=Number(d.headers.get("Retry-After"))||1;throw new Ht(m?.message||m?.error||"Session budget is being modified by another request. Retry shortly.",v,d.status)}throw new Error(no(m))}let p=V0(m?.error_code);if(p||d.status===410){let v=p??"BUDGET_CLOSED";throw new Yr(m?.message||m?.error||"Your session was invalidated by the server.",v,{budgetId:n.session_budget_id,status:d.status})}if(m?.declined){let v=Number(m.retryAfter??d.headers.get("Retry-After"));throw new he(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite(v)&&v>0?v:void 0)}let g=Gc(m?.error_code);throw g?new st(m?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",g,{transactionId:typeof m?.transactionId=="string"?m.transactionId:void 0,retryable:!!m?.retryable,reconciliationRequired:m?.reconciliation_required!==!1}):new Error(m?.error||`Request failed (${d.status}). Try again.`)}return{data:m,voucherReceiptHeader:f}}async shortcutParentless(t,n,r,s,o,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error(ro());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":Sn,"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 bt(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(p){throw new Error(zr(p))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let p=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${p}s. Tip: use the batch tool to combine multiple requests into one.`)}let f=d.headers.get("X-Voucher-Receipt"),m;try{m=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 vt("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(m);let p=typeof m?.error_code=="string"?m.error_code:void 0;if(d.status===410&&p==="DIRECT_SHORTCUT_CARD_SURFACE_RETIRED")throw new vt(m?.error||"Parentless single-call is not enabled on this server.",{status:d.status,serverErrorCode:p});if(d.status===503){if(m?.error_code==="SESSION_LOCK_CONTENDED"){let v=Number(d.headers.get("Retry-After"))||1;throw new Ht(m?.message||m?.error||"Session budget is being modified by another request. Retry shortly.",v,d.status)}throw new Error(no(m))}if(m?.declined){let v=Number(m.retryAfter??d.headers.get("Retry-After"));throw new he(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite(v)&&v>0?v:void 0)}let g=Gc(m?.error_code);throw g?new st(m?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",g,{transactionId:typeof m?.transactionId=="string"?m.transactionId:void 0,retryable:!!m?.retryable,reconciliationRequired:m?.reconciliation_required!==!1}):new Error(m?.error||`Request failed (${d.status}). Try again.`)}return{data:m,voucherReceiptHeader:f}}async batchOpen(t){let n="/v1/batch/open",r=await this.getSessionToken();if(!r)throw new Error(ro());let s={Authorization:`Bearer ${r}`,"X-Visa-CLI-Version":Sn,"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 bt(`${this.baseUrl}${n}`,{method:"POST",headers:s,body:JSON.stringify(o),timeoutMs:void 0})}catch(u){throw new Error(zr(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 vt("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 vt(a?.error||"Parentless batch is not enabled on this server.",{status:i.status,serverErrorCode:u});if(i.status===503)throw new Error(no(a));if(a?.declined){let d=Number(a.retryAfter??i.headers.get("Retry-After"));throw new he(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(ro());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":Sn,"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 bt(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(p){throw new Error(zr(p))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let p=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${p}s. Tip: use the batch tool to combine multiple requests into one.`)}let f=d.headers.get("X-Voucher-Receipt"),m;try{m=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(m),d.status===503){if(m?.error_code==="SESSION_LOCK_CONTENDED"){let p=Number(d.headers.get("Retry-After"))||1;throw new Ht(m?.message||m?.error||"Batch parent is being modified by another request. Retry shortly.",p,d.status)}throw new Error(no(m))}if(m?.declined){let p=Number(m.retryAfter??d.headers.get("Retry-After"));throw new he(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite(p)&&p>0?p:void 0)}throw new Error(m?.error||`Request failed (${d.status}). Try again.`)}return{data:m,voucherReceiptHeader:f}}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 bt(`${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 bt(`${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 so(e,t){return t||(typeof e!="number"||!Number.isFinite(e)?"price unknown":`$${(e/100).toFixed(2)}`)}function wm(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 vm(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function K0(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 G0(e){return Math.max(4,e.reduce((t,n)=>Math.max(t,n.id.length),0))}function W0(e){return Math.max(8,Math.min(14,e.reduce((t,n)=>Math.max(t,(n.category||"").length),0)))}function Y0(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 Sm(e){let t=G0(e),n=7,r=W0(e),s=Y0(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)} ${so(o.priceCents,o.priceDisplay).padEnd(n)} ${vm(o.category||"other",r).padEnd(r)} ${vm(wm(o),s)}`)}function xm(e){console.log(`
132
+ `}function tm(e){return e.json===!0||e.isTTY!==!0}function Nc(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 Lc(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 nm(e,t){let n=Nc(e);if(n!==void 0)return n;if(tm(t))return 500}function rm(e,t){let n=Lc(e);if(n!==void 0)return n;if(tm(t)||t.recommendedCapsAccepted===!0)return 2500}async function bt(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 er=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},Yr=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}},Ht=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}},vt=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}},he=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}},st=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 sm={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 zr(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&&sm[n]?sm[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.`}wt();var E0=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function am(e,t){let n=im(e),r=im(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:R0(n.pre,r.pre)>0}function im(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(E0);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function R0(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 St(){return!!(cm(process.env.VISA_CLI_NO_UPDATE_CHECK)||cm(process.env.CI)||process.env.NODE_ENV==="test")}function cm(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}qt();var j0="CARD_REENROLLMENT_REQUIRED",B0="https://auth.visacli.sh/enroll-card";function F0(){try{return new URL("/enroll-card",Pe()).toString()}catch{return B0}}function H0(e){let t=F0();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 h.warn("card-reenroll:reenroll_url_rejected_fallback",{reason:"untrusted_or_malformed_reenroll_url",fallbackPath:"/enroll-card"}),t}var Sn="3.4.8-rc.0",V0=/^(?:VisaKey_[A-Za-z0-9_-]{16,128}|visakey_[A-Za-z0-9_-]{16,128}|vk_[A-Za-z0-9_-]{32,128})$/;async function no(e){let t=null;try{t=await e.json()}catch{}return t&&(t.error_code==="TOOL_UPSTREAM_AUTH_FAILED"||typeof t.upstream_status=="number")?new Error(typeof t.error=="string"&&t.error?t.error:"The tool upstream rejected the request credentials."):new Error("Your session has expired. Run: visa-cli setup")}function q0(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 Wc(e){return e==="TOPUP_CHARGE_AMBIGUOUS"||e==="TOPUP_RECONCILIATION_REQUIRED"?e:null}var K0="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function Jr(e){return typeof e=="string"?e.trim():""}function ro(e){let t=e&&typeof e=="object"?e:{},n=Jr(t.error)||Jr(t.message);if(!n)return K0;let r=Jr(t.error_code),s=[["surface",Jr(t.disabled_surface)],["flag",Jr(t.flag)],["correlation_id",Jr(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 so(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?V0.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
+ `)}var qe=class{constructor(t){this.getSessionToken=t;this.baseUrl=Pe()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!St()){let r=t.headers.get("X-Latest-Version");r&&am(r,Sn)&&(this.lastSignals.updateAvailable={currentVersion:Sn,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return Sn}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new er(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(ro(n))}async request(t,n,r,s,o,i){let a=await this.getSessionToken();if(!a)throw new Error(so());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 bt(`${this.baseUrl}${n}`,{method:t,headers:{...c,"X-Visa-CLI-Version":Sn,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:s})}catch(d){throw new Error(zr(d))}if(this.parseServerSignals(l),l.status===401)throw await no(l);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===j0){let f=typeof u?.last4=="string"?u.last4:"",m=typeof u?.brand=="string"?u.brand:"card",p=H0(u?.reenroll_url),g=f?`${m} ending in ${f}`:"your card";throw new Error(`Please re-add ${g} to keep payments running. Open: ${p}`)}let d=Wc(u?.error_code);if(d)throw new st(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 f=Number(u.retryAfter??l.headers.get("Retry-After"));throw new he(u.error||"Your card was declined.",!!u.retryable,u.code,u.reason,u.payment_error_class,u.correlation_id,u.transactionId,Number.isFinite(f)&&f>0?f:void 0)}if(l.status===402){let f=u?.error||"Gateway returned 402",m=typeof u?.error_code=="string"?u.error_code:"";throw m==="SPENDING_LIMIT_EXCEEDED"||m==="DAILY_LIMIT_EXCEEDED"||m==="PER_TXN_LIMIT_EXCEEDED"?new Error(`${f}. Check your limits with get_status or run: visa-cli update-spending-controls`):new Error(f)}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(so());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":Sn,"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 bt(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(p){throw new Error(zr(p))}if(this.parseServerSignals(d),d.status===401)throw await no(d);if(d.status===429){let p=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${p}s. Tip: use the batch tool to combine multiple requests into one.`)}let f=d.headers.get("X-Voucher-Receipt"),m;try{m=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(m),d.status===503){if(m?.error_code==="SESSION_LOCK_CONTENDED"){let v=Number(d.headers.get("Retry-After"))||1;throw new Ht(m?.message||m?.error||"Session budget is being modified by another request. Retry shortly.",v,d.status)}throw new Error(ro(m))}let p=q0(m?.error_code);if(p||d.status===410){let v=p??"BUDGET_CLOSED";throw new Yr(m?.message||m?.error||"Your session was invalidated by the server.",v,{budgetId:n.session_budget_id,status:d.status})}if(m?.declined){let v=Number(m.retryAfter??d.headers.get("Retry-After"));throw new he(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite(v)&&v>0?v:void 0)}let g=Wc(m?.error_code);throw g?new st(m?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",g,{transactionId:typeof m?.transactionId=="string"?m.transactionId:void 0,retryable:!!m?.retryable,reconciliationRequired:m?.reconciliation_required!==!1}):new Error(m?.error||`Request failed (${d.status}). Try again.`)}return{data:m,voucherReceiptHeader:f}}async shortcutParentless(t,n,r,s,o,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error(so());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":Sn,"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 bt(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(p){throw new Error(zr(p))}if(this.parseServerSignals(d),d.status===401)throw await no(d);if(d.status===429){let p=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${p}s. Tip: use the batch tool to combine multiple requests into one.`)}let f=d.headers.get("X-Voucher-Receipt"),m;try{m=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 vt("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(m);let p=typeof m?.error_code=="string"?m.error_code:void 0;if(d.status===410&&p==="DIRECT_SHORTCUT_CARD_SURFACE_RETIRED")throw new vt(m?.error||"Parentless single-call is not enabled on this server.",{status:d.status,serverErrorCode:p});if(d.status===503){if(m?.error_code==="SESSION_LOCK_CONTENDED"){let v=Number(d.headers.get("Retry-After"))||1;throw new Ht(m?.message||m?.error||"Session budget is being modified by another request. Retry shortly.",v,d.status)}throw new Error(ro(m))}if(m?.declined){let v=Number(m.retryAfter??d.headers.get("Retry-After"));throw new he(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite(v)&&v>0?v:void 0)}let g=Wc(m?.error_code);throw g?new st(m?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",g,{transactionId:typeof m?.transactionId=="string"?m.transactionId:void 0,retryable:!!m?.retryable,reconciliationRequired:m?.reconciliation_required!==!1}):new Error(m?.error||`Request failed (${d.status}). Try again.`)}return{data:m,voucherReceiptHeader:f}}async batchOpen(t){let n="/v1/batch/open",r=await this.getSessionToken();if(!r)throw new Error(so());let s={Authorization:`Bearer ${r}`,"X-Visa-CLI-Version":Sn,"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 bt(`${this.baseUrl}${n}`,{method:"POST",headers:s,body:JSON.stringify(o),timeoutMs:void 0})}catch(u){throw new Error(zr(u))}if(this.parseServerSignals(i),i.status===401)throw await no(i);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 vt("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 vt(a?.error||"Parentless batch is not enabled on this server.",{status:i.status,serverErrorCode:u});if(i.status===503)throw new Error(ro(a));if(a?.declined){let d=Number(a.retryAfter??i.headers.get("Retry-After"));throw new he(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(so());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":Sn,"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 bt(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(p){throw new Error(zr(p))}if(this.parseServerSignals(d),d.status===401)throw await no(d);if(d.status===429){let p=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${p}s. Tip: use the batch tool to combine multiple requests into one.`)}let f=d.headers.get("X-Voucher-Receipt"),m;try{m=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(m),d.status===503){if(m?.error_code==="SESSION_LOCK_CONTENDED"){let p=Number(d.headers.get("Retry-After"))||1;throw new Ht(m?.message||m?.error||"Batch parent is being modified by another request. Retry shortly.",p,d.status)}throw new Error(ro(m))}if(m?.declined){let p=Number(m.retryAfter??d.headers.get("Retry-After"));throw new he(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite(p)&&p>0?p:void 0)}throw new Error(m?.error||`Request failed (${d.status}). Try again.`)}return{data:m,voucherReceiptHeader:f}}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 bt(`${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 bt(`${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 oo(e,t){return t||(typeof e!="number"||!Number.isFinite(e)?"price unknown":`$${(e/100).toFixed(2)}`)}function Sm(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 wm(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function G0(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 W0(e){return Math.max(4,e.reduce((t,n)=>Math.max(t,n.id.length),0))}function Y0(e){return Math.max(8,Math.min(14,e.reduce((t,n)=>Math.max(t,(n.category||"").length),0)))}function z0(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 xm(e){let t=W0(e),n=7,r=Y0(e),s=z0(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)} ${oo(o.priceCents,o.priceDisplay).padEnd(n)} ${wm(o.category||"other",r).padEnd(r)} ${wm(Sm(o),s)}`)}function Tm(e){console.log(`
134
134
  Merchant tools
135
- `),Sm(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 Wc(e){console.log(`
135
+ `),xm(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 Yc(e){console.log(`
136
136
  Merchant tools
137
- `);for(let[t,n]of K0(e)){console.log(t[0]?.toUpperCase()+t.slice(1));for(let r of n)console.log(` ${r.id.padEnd(28)} ${so(r.priceCents,r.priceDisplay).padEnd(8)} ${r.description}`),console.log(` Params: ${wm(r)}`);console.log()}console.log(`Run one with: visa-cli merchants run <tool> --json '{"prompt":"a lobster"}'`),console.log("Details: visa-cli describe <tool>"),console.log(`Shortcut: visa-cli generate image "a lobster"
138
- `)}function Tm(e,t){console.log(`
137
+ `);for(let[t,n]of G0(e)){console.log(t[0]?.toUpperCase()+t.slice(1));for(let r of n)console.log(` ${r.id.padEnd(28)} ${oo(r.priceCents,r.priceDisplay).padEnd(8)} ${r.description}`),console.log(` Params: ${Sm(r)}`);console.log()}console.log(`Run one with: visa-cli merchants run <tool> --json '{"prompt":"a lobster"}'`),console.log("Details: visa-cli describe <tool>"),console.log(`Shortcut: visa-cli generate image "a lobster"
138
+ `)}function Am(e,t){console.log(`
139
139
  ${e} tools
140
- `),Sm(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
- `)}function Yc(e){if(e.count<=0)return;let t=[],n=e.byReason.kill_switch??0,r=e.byReason.flag_state_unknown??0;n>0&&t.push(`${n} suppressed by kill switch`),r>0&&t.push(`${r} suppressed while feature-flag store is unreachable`);let s=e.count-n-r;s>0&&t.push(`${s} unavailable`);let o=t.length>0?t.join(", "):`${e.count} hidden`;console.log(`
142
- Hidden: ${o}.`),n>0&&console.log("Inspect: `visa-cli tools --json` with query params `?available=all`, or check the admin Tool Hub flag list.")}var _={};Br(_,{BRAND:()=>vv,DIRTY:()=>rr,EMPTY_PATH:()=>Z0,INVALID:()=>D,NEVER:()=>sw,OK:()=>Pe,ParseStatus:()=>ke,Schema:()=>V,ZodAny:()=>kn,ZodArray:()=>Yt,ZodBigInt:()=>or,ZodBoolean:()=>ir,ZodBranded:()=>io,ZodCatch:()=>yr,ZodDate:()=>ar,ZodDefault:()=>hr,ZodDiscriminatedUnion:()=>Ei,ZodEffects:()=>Xe,ZodEnum:()=>pr,ZodError:()=>Fe,ZodFirstPartyTypeKind:()=>j,ZodFunction:()=>Ri,ZodIntersection:()=>dr,ZodIssueCode:()=>x,ZodLazy:()=>fr,ZodLiteral:()=>mr,ZodMap:()=>ns,ZodNaN:()=>ss,ZodNativeEnum:()=>gr,ZodNever:()=>it,ZodNull:()=>lr,ZodNullable:()=>kt,ZodNumber:()=>sr,ZodObject:()=>He,ZodOptional:()=>ze,ZodParsedType:()=>E,ZodPipeline:()=>ao,ZodPromise:()=>An,ZodReadonly:()=>_r,ZodRecord:()=>Ci,ZodSchema:()=>V,ZodSet:()=>rs,ZodString:()=>Tn,ZodSymbol:()=>es,ZodTransformer:()=>Xe,ZodTuple:()=>Tt,ZodType:()=>V,ZodUndefined:()=>cr,ZodUnion:()=>ur,ZodUnknown:()=>Wt,ZodVoid:()=>ts,addIssueToContext:()=>A,any:()=>Rv,array:()=>Ov,bigint:()=>Tv,boolean:()=>Nm,coerce:()=>rw,custom:()=>Pm,date:()=>kv,datetimeRegex:()=>Im,defaultErrorMap:()=>Kt,discriminatedUnion:()=>Uv,effect:()=>zv,enum:()=>Gv,function:()=>Vv,getErrorMap:()=>Xr,getParsedType:()=>xt,instanceof:()=>Sv,intersection:()=>Dv,isAborted:()=>ki,isAsync:()=>Zr,isDirty:()=>Ai,isValid:()=>xn,late:()=>wv,lazy:()=>qv,literal:()=>Kv,makeIssue:()=>oo,map:()=>Fv,nan:()=>xv,nativeEnum:()=>Wv,never:()=>$v,null:()=>Cv,nullable:()=>Xv,number:()=>Mm,object:()=>Mv,objectUtil:()=>zc,oboolean:()=>nw,onumber:()=>tw,optional:()=>Jv,ostring:()=>ew,pipeline:()=>Qv,preprocess:()=>Zv,promise:()=>Yv,quotelessJson:()=>z0,record:()=>Bv,set:()=>Hv,setErrorMap:()=>X0,strictObject:()=>Nv,string:()=>Om,symbol:()=>Av,transformer:()=>zv,tuple:()=>jv,undefined:()=>Ev,union:()=>Lv,unknown:()=>Iv,util:()=>q,void:()=>Pv});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 zc;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(zc||(zc={}));var E=q.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),xt=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"]),z0=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),Fe=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()}};Fe.create=e=>new Fe(e);var J0=(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}},Kt=J0;var km=Kt;function X0(e){km=e}function Xr(){return km}var oo=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}},Z0=[];function A(e,t){let n=Xr(),r=oo({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Kt?void 0:Kt].filter(s=>!!s)});e.common.issues.push(r)}var ke=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"}),rr=e=>({status:"dirty",value:e}),Pe=e=>({status:"valid",value:e}),ki=e=>e.status==="aborted",Ai=e=>e.status==="dirty",xn=e=>e.status==="valid",Zr=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 Je=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}},Am=(e,t)=>{if(xn(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 Fe(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 xt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:xt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ke,ctx:{common:t.parent.common,data:t.data,parsedType:xt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Zr(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:xt(t)},s=this._parseSync({data:t,path:r.path,parent:r});return Am(r,s)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:xt(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return xn(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=>xn(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:xt(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(Zr(s)?s:Promise.resolve(s));return Am(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 Xe({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 ze.create(this,this._def)}nullable(){return kt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yt.create(this)}promise(){return An.create(this,this._def)}or(t){return ur.create([this,t],this._def)}and(t){return dr.create(this,t,this._def)}transform(t){return new Xe({...B(this._def),schema:this,typeName:j.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new hr({...B(this._def),innerType:this,defaultValue:n,typeName:j.ZodDefault})}brand(){return new io({typeName:j.ZodBranded,type:this,...B(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new yr({...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 ao.create(this,t)}readonly(){return _r.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Q0=/^c[^\s-]{8,}$/i,ev=/^[0-9a-z]+$/,tv=/^[0-9A-HJKMNP-TV-Z]{26}$/i,nv=/^[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,rv=/^[a-z0-9_-]{21}$/i,sv=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ov=/^[-+]?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)?)??$/,iv=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,av="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Jc,cv=/^(?:(?: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])$/,lv=/^(?:(?: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])$/,uv=/^(([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]))$/,dv=/^(([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])$/,fv=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,mv=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Cm="((\\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])))",pv=new RegExp(`^${Cm}$`);function Rm(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 gv(e){return new RegExp(`^${Rm(e)}$`)}function Im(e){let t=`${Cm}T${Rm(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 hv(e,t){return!!((t==="v4"||!t)&&cv.test(e)||(t==="v6"||!t)&&uv.test(e))}function yv(e,t){if(!sv.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 _v(e,t){return!!((t==="v4"||!t)&&lv.test(e)||(t==="v6"||!t)&&dv.test(e))}var Tn=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 A(o,{code:x.invalid_type,expected:E.string,received:o.parsedType}),D}let r=new ke,s;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(s=this._getOrReturnCtx(t,s),A(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),A(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?A(s,{code:x.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&A(s,{code:x.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")iv.test(t.data)||(s=this._getOrReturnCtx(t,s),A(s,{validation:"email",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")Jc||(Jc=new RegExp(av,"u")),Jc.test(t.data)||(s=this._getOrReturnCtx(t,s),A(s,{validation:"emoji",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")nv.test(t.data)||(s=this._getOrReturnCtx(t,s),A(s,{validation:"uuid",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")rv.test(t.data)||(s=this._getOrReturnCtx(t,s),A(s,{validation:"nanoid",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")Q0.test(t.data)||(s=this._getOrReturnCtx(t,s),A(s,{validation:"cuid",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")ev.test(t.data)||(s=this._getOrReturnCtx(t,s),A(s,{validation:"cuid2",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")tv.test(t.data)||(s=this._getOrReturnCtx(t,s),A(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),A(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),A(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),A(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),A(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),A(s,{code:x.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?Im(o).test(t.data)||(s=this._getOrReturnCtx(t,s),A(s,{code:x.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?pv.test(t.data)||(s=this._getOrReturnCtx(t,s),A(s,{code:x.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?gv(o).test(t.data)||(s=this._getOrReturnCtx(t,s),A(s,{code:x.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?ov.test(t.data)||(s=this._getOrReturnCtx(t,s),A(s,{validation:"duration",code:x.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?hv(t.data,o.version)||(s=this._getOrReturnCtx(t,s),A(s,{validation:"ip",code:x.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?yv(t.data,o.alg)||(s=this._getOrReturnCtx(t,s),A(s,{validation:"jwt",code:x.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?_v(t.data,o.version)||(s=this._getOrReturnCtx(t,s),A(s,{validation:"cidr",code:x.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?fv.test(t.data)||(s=this._getOrReturnCtx(t,s),A(s,{validation:"base64",code:x.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?mv.test(t.data)||(s=this._getOrReturnCtx(t,s),A(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}};Tn.create=e=>new Tn({checks:[],typeName:j.ZodString,coerce:e?.coerce??!1,...B(e)});function bv(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 sr=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 A(o,{code:x.invalid_type,expected:E.number,received:o.parsedType}),D}let r,s=new ke;for(let o of this._def.checks)o.kind==="int"?q.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),A(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),A(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),A(r,{code:x.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?bv(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),A(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),A(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)}};sr.create=e=>new sr({checks:[],typeName:j.ZodNumber,coerce:e?.coerce||!1,...B(e)});var or=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 ke;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),A(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),A(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),A(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 A(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}};or.create=e=>new or({checks:[],typeName:j.ZodBigInt,coerce:e?.coerce??!1,...B(e)});var ir=class extends V{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==E.boolean){let r=this._getOrReturnCtx(t);return A(r,{code:x.invalid_type,expected:E.boolean,received:r.parsedType}),D}return Pe(t.data)}};ir.create=e=>new ir({typeName:j.ZodBoolean,coerce:e?.coerce||!1,...B(e)});var ar=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 A(o,{code:x.invalid_type,expected:E.date,received:o.parsedType}),D}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return A(o,{code:x.invalid_date}),D}let r=new ke,s;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(s=this._getOrReturnCtx(t,s),A(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),A(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}};ar.create=e=>new ar({checks:[],coerce:e?.coerce||!1,typeName:j.ZodDate,...B(e)});var es=class extends V{_parse(t){if(this._getType(t)!==E.symbol){let r=this._getOrReturnCtx(t);return A(r,{code:x.invalid_type,expected:E.symbol,received:r.parsedType}),D}return Pe(t.data)}};es.create=e=>new es({typeName:j.ZodSymbol,...B(e)});var cr=class extends V{_parse(t){if(this._getType(t)!==E.undefined){let r=this._getOrReturnCtx(t);return A(r,{code:x.invalid_type,expected:E.undefined,received:r.parsedType}),D}return Pe(t.data)}};cr.create=e=>new cr({typeName:j.ZodUndefined,...B(e)});var lr=class extends V{_parse(t){if(this._getType(t)!==E.null){let r=this._getOrReturnCtx(t);return A(r,{code:x.invalid_type,expected:E.null,received:r.parsedType}),D}return Pe(t.data)}};lr.create=e=>new lr({typeName:j.ZodNull,...B(e)});var kn=class extends V{constructor(){super(...arguments),this._any=!0}_parse(t){return Pe(t.data)}};kn.create=e=>new kn({typeName:j.ZodAny,...B(e)});var Wt=class extends V{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Pe(t.data)}};Wt.create=e=>new Wt({typeName:j.ZodUnknown,...B(e)});var it=class extends V{_parse(t){let n=this._getOrReturnCtx(t);return A(n,{code:x.invalid_type,expected:E.never,received:n.parsedType}),D}};it.create=e=>new it({typeName:j.ZodNever,...B(e)});var ts=class extends V{_parse(t){if(this._getType(t)!==E.undefined){let r=this._getOrReturnCtx(t);return A(r,{code:x.invalid_type,expected:E.void,received:r.parsedType}),D}return Pe(t.data)}};ts.create=e=>new ts({typeName:j.ZodVoid,...B(e)});var Yt=class e extends V{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==E.array)return A(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)&&(A(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&&(A(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&&(A(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 Je(n,i,n.path,a)))).then(i=>ke.mergeArray(r,i));let o=[...n.data].map((i,a)=>s.type._parseSync(new Je(n,i,n.path,a)));return ke.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)}};Yt.create=(e,t)=>new Yt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:j.ZodArray,...B(t)});function Qr(e){if(e instanceof He){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=ze.create(Qr(r))}return new He({...e._def,shape:()=>t})}else return e instanceof Yt?new Yt({...e._def,type:Qr(e.element)}):e instanceof ze?ze.create(Qr(e.unwrap())):e instanceof kt?kt.create(Qr(e.unwrap())):e instanceof Tt?Tt.create(e.items.map(t=>Qr(t))):e}var He=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 A(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 it&&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 Je(s,d,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof it){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&&(A(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 Je(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,f=await u.value;l.push({key:d,value:f,alwaysSet:u.alwaysSet})}return l}).then(l=>ke.mergeObjectSync(r,l)):ke.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 Qr(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 ze;)o=o._def.innerType;n[r]=o}return new e({...this._def,shape:()=>n})}keyof(){return $m(q.objectKeys(this.shape))}};He.create=(e,t)=>new He({shape:()=>e,unknownKeys:"strip",catchall:it.create(),typeName:j.ZodObject,...B(t)});He.strictCreate=(e,t)=>new He({shape:()=>e,unknownKeys:"strict",catchall:it.create(),typeName:j.ZodObject,...B(t)});He.lazycreate=(e,t)=>new He({shape:e,unknownKeys:"strip",catchall:it.create(),typeName:j.ZodObject,...B(t)});var ur=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 Fe(a.ctx.common.issues));return A(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 Fe(c));return A(n,{code:x.invalid_union,unionErrors:a}),D}}get options(){return this._def.options}};ur.create=(e,t)=>new ur({options:e,typeName:j.ZodUnion,...B(t)});var Gt=e=>e instanceof fr?Gt(e.schema):e instanceof Xe?Gt(e.innerType()):e instanceof mr?[e.value]:e instanceof pr?e.options:e instanceof gr?q.objectValues(e.enum):e instanceof hr?Gt(e._def.innerType):e instanceof cr?[void 0]:e instanceof lr?[null]:e instanceof ze?[void 0,...Gt(e.unwrap())]:e instanceof kt?[null,...Gt(e.unwrap())]:e instanceof io||e instanceof _r?Gt(e.unwrap()):e instanceof yr?Gt(e._def.innerType):[],Ei=class e extends V{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==E.object)return A(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}):(A(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=Gt(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 Xc(e,t){let n=xt(e),r=xt(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=Xc(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=Xc(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 dr=class extends V{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=(o,i)=>{if(ki(o)||ki(i))return D;let a=Xc(o.value,i.value);return a.valid?((Ai(o)||Ai(i))&&n.dirty(),{status:n.value,value:a.data}):(A(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}))}};dr.create=(e,t,n)=>new dr({left:e,right:t,typeName:j.ZodIntersection,...B(n)});var Tt=class e extends V{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==E.array)return A(r,{code:x.invalid_type,expected:E.array,received:r.parsedType}),D;if(r.data.length<this._def.items.length)return A(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&&(A(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 Je(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>ke.mergeArray(n,i)):ke.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Tt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Tt({items:e,typeName:j.ZodTuple,rest:null,...B(t)})};var Ci=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 A(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 Je(r,a,r.path,a)),value:i._parse(new Je(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?ke.mergeObjectAsync(n,s):ke.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:Tn.create(),valueType:t,typeName:j.ZodRecord,...B(n)})}},ns=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 A(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 Je(r,a,r.path,[l,"key"])),value:o._parse(new Je(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}}}};ns.create=(e,t,n)=>new ns({valueType:t,keyType:e,typeName:j.ZodMap,...B(n)});var rs=class e extends V{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==E.set)return A(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&&(A(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&&(A(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 Je(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)}};rs.create=(e,t)=>new rs({valueType:e,minSize:null,maxSize:null,typeName:j.ZodSet,...B(t)});var Ri=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 A(n,{code:x.invalid_type,expected:E.function,received:n.parsedType}),D;function r(a,c){return oo({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Xr(),Kt].filter(l=>!!l),issueData:{code:x.invalid_arguments,argumentsError:c}})}function s(a,c){return oo({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Xr(),Kt].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 An){let a=this;return Pe(async function(...c){let l=new Fe([]),u=await a._def.args.parseAsync(c,o).catch(m=>{throw l.addIssue(r(c,m)),l}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,o).catch(m=>{throw l.addIssue(s(d,m)),l})})}else{let a=this;return Pe(function(...c){let l=a._def.args.safeParse(c,o);if(!l.success)throw new Fe([r(c,l.error)]);let u=Reflect.apply(i,this,l.data),d=a._def.returns.safeParse(u,o);if(!d.success)throw new Fe([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:Tt.create(t).rest(Wt.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||Tt.create([]).rest(Wt.create()),returns:n||Wt.create(),typeName:j.ZodFunction,...B(r)})}},fr=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})}};fr.create=(e,t)=>new fr({getter:e,typeName:j.ZodLazy,...B(t)});var mr=class extends V{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return A(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}};mr.create=(e,t)=>new mr({value:e,typeName:j.ZodLiteral,...B(t)});function $m(e,t){return new pr({values:e,typeName:j.ZodEnum,...B(t)})}var pr=class e extends V{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return A(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 A(n,{received:n.data,code:x.invalid_enum_value,options:r}),D}return Pe(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})}};pr.create=$m;var gr=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 A(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 A(r,{received:r.data,code:x.invalid_enum_value,options:s}),D}return Pe(t.data)}get enum(){return this._def.values}};gr.create=(e,t)=>new gr({values:e,typeName:j.ZodNativeEnum,...B(t)});var An=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 A(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 Pe(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};An.create=(e,t)=>new An({type:e,typeName:j.ZodPromise,...B(t)});var Xe=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=>{A(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"?rr(c.value):n.value==="dirty"?rr(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"?rr(a.value):n.value==="dirty"?rr(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(!xn(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=>xn(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:n.value,value:a})):D);q.assertNever(s)}};Xe.create=(e,t,n)=>new Xe({schema:e,typeName:j.ZodEffects,effect:t,...B(n)});Xe.createWithPreprocess=(e,t,n)=>new Xe({schema:t,effect:{type:"preprocess",transform:e},typeName:j.ZodEffects,...B(n)});var ze=class extends V{_parse(t){return this._getType(t)===E.undefined?Pe(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};ze.create=(e,t)=>new ze({innerType:e,typeName:j.ZodOptional,...B(t)});var kt=class extends V{_parse(t){return this._getType(t)===E.null?Pe(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};kt.create=(e,t)=>new kt({innerType:e,typeName:j.ZodNullable,...B(t)});var hr=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}};hr.create=(e,t)=>new hr({innerType:e,typeName:j.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...B(t)});var yr=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 Zr(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Fe(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Fe(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};yr.create=(e,t)=>new yr({innerType:e,typeName:j.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...B(t)});var ss=class extends V{_parse(t){if(this._getType(t)!==E.nan){let r=this._getOrReturnCtx(t);return A(r,{code:x.invalid_type,expected:E.nan,received:r.parsedType}),D}return{status:"valid",value:t.data}}};ss.create=e=>new ss({typeName:j.ZodNaN,...B(e)});var vv=Symbol("zod_brand"),io=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}},ao=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(),rr(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})}},_r=class extends V{_parse(t){let n=this._def.innerType._parse(t),r=s=>(xn(s)&&(s.value=Object.freeze(s.value)),s);return Zr(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};_r.create=(e,t)=>new _r({innerType:e,typeName:j.ZodReadonly,...B(t)});function Em(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Pm(e,t={},n){return e?kn.create().superRefine((r,s)=>{let o=e(r);if(o instanceof Promise)return o.then(i=>{if(!i){let a=Em(t,r),c=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=Em(t,r),a=i.fatal??n??!0;s.addIssue({code:"custom",...i,fatal:a})}}):kn.create()}var wv={object:He.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 Sv=(e,t={message:`Input not instance of ${e.name}`})=>Pm(n=>n instanceof e,t),Om=Tn.create,Mm=sr.create,xv=ss.create,Tv=or.create,Nm=ir.create,kv=ar.create,Av=es.create,Ev=cr.create,Cv=lr.create,Rv=kn.create,Iv=Wt.create,$v=it.create,Pv=ts.create,Ov=Yt.create,Mv=He.create,Nv=He.strictCreate,Lv=ur.create,Uv=Ei.create,Dv=dr.create,jv=Tt.create,Bv=Ci.create,Fv=ns.create,Hv=rs.create,Vv=Ri.create,qv=fr.create,Kv=mr.create,Gv=pr.create,Wv=gr.create,Yv=An.create,zv=Xe.create,Jv=ze.create,Xv=kt.create,Zv=Xe.createWithPreprocess,Qv=ao.create,ew=()=>Om().optional(),tw=()=>Mm().optional(),nw=()=>Nm().optional(),rw={string:(e=>Tn.create({...e,coerce:!0})),number:(e=>sr.create({...e,coerce:!0})),boolean:(e=>ir.create({...e,coerce:!0})),bigint:(e=>or.create({...e,coerce:!0})),date:(e=>ar.create({...e,coerce:!0}))};var sw=D;var ow=/^[A-Za-z0-9._-]+$/,iw=/^[A-Za-z0-9._-]+(\|[A-Za-z0-9._-]+)*$/,Lm=new Set([".",".."]),je=class extends Error{pattern;constructor(t,n){super(`Invalid freeReadPathPattern ${JSON.stringify(n)}: ${t}`),this.pattern=n,this.name="FreePathPatternError"}};function aw(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 je(`malformed alternation segment ${JSON.stringify(e)}`,t);let s=n?e.slice(1,-2):e.slice(1,-1);if(!iw.test(s))throw new je(`malformed alternation segment ${JSON.stringify(e)}`,t);let o=s.split("|");if(o.some(i=>Lm.has(i)))throw new je(`alternation segment ${JSON.stringify(e)} may not contain '.' or '..'`,t);return{raw:e,kind:n?"alt-optional":"alt",alternatives:o}}if(ow.test(e)){if(Lm.has(e))throw new je(`literal segment ${JSON.stringify(e)} is not permitted`,t);return{raw:e,kind:"literal"}}throw new je(`segment ${JSON.stringify(e)} must be '*', '**', a [A-Za-z0-9._-]+ literal, or (a|b) alternation`,t)}function cw(e){if(typeof e!="string"||e.length===0)throw new je("must be a non-empty string",String(e));if(!e.startsWith("/"))throw new je("must start with '/'",e);if(e.slice(1).includes("//"))throw new je("empty segments ('//') are not permitted",e);if(e.length>1&&e.endsWith("/"))throw new je("must not end with '/'",e);let n=e.slice(1).split("/").map(o=>aw(o,e));if(n.filter(o=>o.kind==="multi").length>1)throw new je("at most one '**' is permitted per pattern",e);if(n[0]?.kind==="multi")throw new je("'**' 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 je("optional alternation '(...)?' is only allowed as the final segment",e);return n}function Zc(e){cw(e)}var Um=["tempo","mpp_self","merchant_self"],Dm=["catalog_static","fal_direct","fal_queue","openrouter_chat","openrouter_image","platform_proxy","tempo_gateway","x402_gateway"],jm=["image","audio","queued_audio","video","queued_video","model_3d","llm","transcription","utility"],Bm=["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 el=_.object({inputPerMillion:_.number().positive(),outputPerMillion:_.number().positive(),contextWindow:_.number().int().positive().optional(),maxOutput:_.number().int().positive().optional(),perRequestFeeCents:_.number().nonnegative().optional()}),lw=_.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:el.optional()}).passthrough(),tl=_.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")})]),nl=_.object({amount:_.number().nonnegative(),currency:_.string().length(3).optional(),display:_.string().optional(),free:_.boolean().optional(),batchDiscount:_.number().min(0).max(100).optional()}),Fm=_.object({attestation:_.boolean().optional(),rateLimitMs:_.number().positive().optional()}),Hm=_.object({displayName:_.string().optional(),feedbackEligible:_.boolean().optional(),suggestionEligible:_.boolean().optional(),batchable:_.boolean().optional()}),Vm=_.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(),uw=_.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),dw=120,fw=120,mw=1200,pw=/^[^\u0000-\u001F\u007F]+$/;function Qc(e,t){return _.string().min(1).max(e).regex(pw,`${t} must not contain control characters`)}var rl={id:_.string().min(1),name:Qc(dw,"name"),description:Qc(mw,"description"),provider:_.string().min(1),model:_.string().min(1),category:uw,priceCents:_.number().nonnegative(),inputSchema:_.record(_.unknown()),gatewayUrl:_.string().min(1),merchantName:Qc(fw,"merchantName"),isAsync:_.boolean().optional(),pollUrl:_.string().optional(),pollInterval:_.number().positive().optional(),pollTimeout:_.number().positive().optional(),tags:_.array(_.string()).optional(),tokenPricing:el.optional(),priceDisplay:_.string().optional(),pricingModel:_.enum(["per-call","per-token","band"]).optional(),pricingInfo:lw.optional(),status:_.enum(["available","unavailable"]).optional(),handler:tl.optional(),pricing:nl.optional(),security:Fm.optional(),engagement:Hm.optional(),gatewayConfig:Vm.optional(),freeReadPathPattern:_.string().optional().superRefine((e,t)=>{if(e!==void 0)try{Zc(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(Um).optional(),executionKind:_.enum(Dm).optional(),resultKind:_.enum(jm).optional(),extractionMode:_.enum(Bm).optional(),pricingStrategy:_.enum(["flat","token","band"]).optional()},qm=_.object({...rl,dispatch:_.literal("routed"),routedPath:_.string().min(1).startsWith("/")}).strict(),Km=_.object({...rl,dispatch:_.literal("enveloped")}).strict(),Gm=_.object({...rl,handler:tl,pricing:nl}).strict(),Wm=_.union([_.discriminatedUnion("dispatch",[qm,Km]),Gm]);var sl=/^[a-z0-9][a-z0-9_-]*$/;var yw="https://fal.run",Xm="https://openrouter.mpp.tempo.xyz",il=1024,$i=8192,_w=4096,bw=10;function vw(e){return e>=bw?_w:$i}function Zm(e,t){let n=typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):il;return Math.min(n,t)}var ww=["num_images","num_outputs","num_samples","num_videos","batch_size","n"];function Qm(e){for(let t of ww)delete e[t];return e}function Sw(e){let{attestation:t,tool_id:n,...r}=e;return Qm(r)}var Ym={"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 Ii(e){let{attestation:t,tool_id:n,aspect_ratio:r,image_size:s,...o}=e,i=Qm({...o});return typeof s=="string"&&s.length>0?(i.image_size=s,i):(typeof r=="string"&&Ym[r]&&(i.image_size=Ym[r]),i)}function xw(e){let{attestation:t,tool_id:n,...r}=e;return r}function zm(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 Tw(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 kw(e,t,n,r,s,o,i,a){return Tw(e,t,n,"suno-ai",r,s,o,i,{merchantName:"Suno AI",...a})}function ye(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:`${yw}/${r}`,merchantName:"fal.ai",buildBody:Sw,tags:[],...a}}function ep(e,t=$i){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:f,...m}=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:f??.7,...m,model:e,max_tokens:Zm(c??l,t)}}}function tp(e,t=$i){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:f,image_config:m,temperature:p,...g}=n,v=[{type:"text",text:o}];return typeof i=="string"&&i.length>0&&v.push({type:"image_url",image_url:{url:i}}),{messages:Array.isArray(f)?f:[{role:"user",content:v}],temperature:p??.7,...g,model:e,...typeof a=="string"&&a.length>0?{image_config:{aspect_ratio:a}}:{},max_tokens:Zm(c??l,t)}}}function ue(e,t,n,r,s,o,i){let a=i?.maxOutputTokens??vw(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:f,maxOutputTokens:m,...p}=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: ${il}); 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:`${Xm}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:ep(r,a),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:s,outputPerMillion:o,...c>0?{perRequestFeeCents:c}:{}},...p}}function ol(e,t,n,r,s,o){let i=o?.maxOutputTokens??$i,{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: ${il}); 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:`${Xm}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:tp(r,i),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...c}}var al=[ye("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"]}),ye("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:Ii}),ye("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:Ii}),ye("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:Ii}),ye("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"]}),ol("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),ol("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}}),ol("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}}),ye("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"]}),ye("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"]}),ye("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"]}),ye("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"]}),ye("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"]}),ye("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"]}),ye("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"]}),ye("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"]}),ye("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"]}),kw("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}}}),ye("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"]}),ye("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"]}),ye("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"]}),ye("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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:zm,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:xw,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=>Ii({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"]},ye("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"}),ye("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:zm,tags:["onchain","prices","allium","crypto","legacy"]}];function os(e){return al.find(t=>t.id===e)}var np=1,rp=["pick_one","fan_out"],sp=["concat","dedupe_by_url","top_k_by_score"],Cw=8,Rw=_.object({type:_.string().min(1),description:_.string().min(1),enum:_.array(_.string()).optional(),default:_.unknown().optional(),minimum:_.number().optional(),maximum:_.number().optional()}),Iw=_.object({toolId:_.string().min(1),notes:_.string().min(1)}),$w=_.string().regex(/^[a-z0-9_-]{1,32}$/,"tier key must be 1-32 chars [a-z0-9_-]"),Pw=_.object({providers:_.array(_.string().min(1)).min(1).max(Cw),merge:_.enum(sp),maxResults:_.number().int().positive().optional()}),op=_.object({mode:_.enum(rp).default("pick_one"),intro:_.string().min(1),defaultTier:_.string().min(1),tiers:_.record($w,Iw).refine(e=>Object.keys(e).length>0,{message:"must have at least one tier"}),fanOut:Pw.optional(),guidance:_.string().min(1),inputProperties:_.record(_.string(),Rw),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"]}),Ow=_.object({version:_.literal(np),generatedAt:_.string().datetime(),tools:_.record(_.string().regex(sl,"tool name must match MCP naming rules"),op).refine(e=>Object.keys(e).length>0,{message:"manifest must have at least one tool"})});var Mw=[{type:"integer",matches:e=>typeof e=="number"&&Number.isInteger(e),phrase:"an integer"},{type:"number",matches:e=>typeof e=="number"&&Number.isFinite(e),phrase:"a number"},{type:"string",matches:e=>typeof e=="string",phrase:"a string"},{type:"boolean",matches:e=>typeof e=="boolean",phrase:"a boolean"},{type:"array",matches:e=>Array.isArray(e),phrase:"an array"},{type:"object",matches:e=>typeof e=="object"&&e!==null&&!Array.isArray(e),phrase:"an object"}];function Nw(e,t){let r=(Array.isArray(t.type)?t.type:t.type!==void 0?[t.type]:[]).flatMap(o=>Mw.filter(i=>i.type===o)),s=new Set(r.filter(o=>o.matches(e)).map(o=>o.type));return{declared:r,matched:s}}function cl(e,t,n){if(n.enum&&!n.enum.includes(t))return`${e} must be one of: ${n.enum.map(String).join(", ")}.`;let{declared:r,matched:s}=Nw(t,n);if(r.length>0&&s.size===0)return`${e} must be ${r.map(o=>o.phrase).join(" or ")}.`;if(s.has("string")&&typeof t=="string"){if(t.trim()==="")return`${e} cannot be empty.`;if(n.minLength!==void 0&&t.length<n.minLength)return`${e} is too short.`;if(n.maxLength!==void 0&&t.length>n.maxLength)return`${e} is too long.`}if(typeof t=="number"){if(n.minimum!==void 0&&t<n.minimum)return`${e} must be at least ${n.minimum}.`;if(n.maximum!==void 0&&t>n.maximum)return`${e} must be at most ${n.maximum}.`}return null}var Oa=R(as());var Li=require("child_process"),bp=require("util"),vp=R(require("crypto")),ne=R(require("fs")),wp=R(require("os")),Oe=R(require("path"));wt();var ct=(0,bp.promisify)(Li.execFile),lS=6e4,uS=()=>process.platform==="darwin",En=()=>process.platform==="win32",Cn=Oe.join(wp.homedir(),".visa-mcp","bin"),br=Oe.join(Cn,"Visa CLI"),Xt=Oe.join(Cn,"visa-keychain-win.exe"),Sp=Oe.join(__dirname,"..","native"),up="6",dp=Oe.join(Cn,"visa-keychain.version"),fp=Oe.join(Cn,"visa-keychain.sha256"),mp="1",pp=Oe.join(Cn,"visa-keychain-win.version"),gp=Oe.join(Cn,"visa-keychain-win.sha256"),xp=[Oe.join(Sp,"bin","win32-x64","visa-keychain-win.exe"),Oe.resolve(__dirname,"..","..","native","bin","win32-x64","visa-keychain-win.exe"),Oe.resolve(__dirname,"..","native","bin","win32-x64","visa-keychain-win.exe")];function Oi(e){let t=ne.readFileSync(e);return vp.createHash("sha256").update(t).digest("hex")}function dS(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 hp(e){let t=typeof e?.message=="string"?e.message:"";return e?.code==="ETIMEDOUT"||e?.killed===!0||/timed out|timeout/i.test(t)}function yp(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 ll(){try{if(ne.readFileSync(dp,"utf-8").trim()===up&&ne.existsSync(br)){let r=ne.readFileSync(fp,"utf-8").trim();if(Oi(br)!==r)h.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),ne.unlinkSync(br);else return br}}catch{}let e=Oe.join(Sp,"visa-keychain.m");if(ne.existsSync(e)||(e=Oe.resolve(__dirname,"..","..","native","visa-keychain.m")),ne.existsSync(e)||(e=Oe.resolve(__dirname,"..","native","visa-keychain.m")),!ne.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");ne.mkdirSync(Cn,{recursive:!0,mode:448});try{await ct("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",br,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=Oi(br);return ne.writeFileSync(fp,t,{mode:384}),ne.writeFileSync(dp,up,{mode:384}),br}function Tp(){for(let e of xp)if(ne.existsSync(e))return e;return null}async function cs(){try{if(ne.readFileSync(pp,"utf-8").trim()===mp&&ne.existsSync(Xt)){let r=ne.readFileSync(gp,"utf-8").trim();if(Oi(Xt)!==r)h.warn("binary:hash-mismatch:win32",{message:"Windows binary hash mismatch. Redeploying."}),ne.unlinkSync(Xt);else return Xt}}catch{}let e=Tp();if(!e)throw new Error(`visa-keychain-win.exe not found in package. Reinstall @visa/cli.
143
- If building from source, run native/build-win.bat first.`);ne.mkdirSync(Cn,{recursive:!0}),ne.copyFileSync(e,Xt);let t=Oi(Xt);return ne.writeFileSync(gp,t,{mode:384}),ne.writeFileSync(pp,mp,{mode:384}),Xt}async function fS(){return En()?cs():ll()}var Mi="visa-cli",Ni="attestation-key";async function mS(e){try{await ct("security",["delete-generic-password","-s",Mi,"-a",Ni],{timeout:5e3})}catch{}await ct("security",["add-generic-password","-s",Mi,"-a",Ni,"-w",e],{timeout:5e3})}function pS(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 gS(){try{let{stdout:e}=await ct("security",["find-generic-password","-s",Mi,"-a",Ni,"-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:pS(e)}}}async function ul(){let e=await gS();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 kp(e){let t=await fS(),n;try{n=(await ct(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 dS(n)}var _p=!1;function hS(){if(!En())return!1;try{return ne.existsSync(Xt)||Tp()!==null?!0:(_p||(_p=!0,h.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:Xt,searchedPrebuiltPaths:xp})),!1)}catch{return!1}}function de(){return Fr()||uS()?!0:En()?hS():!1}async function Ui(){if(En()){let s=await cs(),{stdout:o}=await ct(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 kp(["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 mS(n),r}async function Di(){if(En())try{let e=await cs(),{stdout:t}=await ct(e,["public-key"],{timeout:1e4});return t.trim().startsWith("OK:")}catch{return!1}return await ul()!==null}async function Ap(){if(Fr())return"mock-public-key-spki";if(En()){let n=await cs(),{stdout:r}=await ct(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 ul();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await ll();return new Promise((n,r)=>{let s=(0,Li.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 Rn(e,t,n={}){if(Fr())return Promise.resolve(Nd());let r=n.timeoutMs??lS;if(En()){let a=await cs(),c=["sign",e];t&&c.push(t);let l;try{l=(await ct(a,c,{timeout:r})).stdout}catch(d){throw hp(d)?yp(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 ul();if(!s)throw new Error("Attestation key not found. Run setup to generate a new key.");let o=await ll(),i=["sign",e];return t&&i.push(t),new Promise((a,c)=>{let l=(0,Li.execFile)(o,i,{timeout:r},(u,d)=>{let f=(d||"").trim();if(u){f.startsWith("ERROR:")?c(new Error(f.slice(6))):hp(u)?c(yp(r)):c(new Error(u.stderr?.trim()||u.message||"Unknown error"));return}f.startsWith("OK:")?a(f.slice(3)):c(new Error(f.startsWith("ERROR:")?f.slice(6):"Unknown error"))});l.stdin.write(s),l.stdin.end()})}async function ji(){if(En()){try{let e=await cs();await ct(e,["delete-key"],{timeout:1e4})}catch{}return}try{await ct("security",["delete-generic-password","-s",Mi,"-a",Ni],{timeout:5e3})}catch{}try{await kp(["delete-key"])}catch{}}wt();var yS=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],_S=[...yS.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 fl(e,t=_S){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=dl(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(dl(r.match.provider)))&&r.match.keywords.every(s=>n.includes(dl(s))))return r.targetToolId;return null}function dl(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}wt();qt();var lo={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_anthropic:{toolId:"or-claude-opus",notes:"Claude Opus 4.7. Anthropic frontier model for complex tasks."},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_anthropic (Claude Opus, highest quality Anthropic tier; warn user it is 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 In(e,t,n){if(!Cp(e))return SS(e,n);let r=Ep[e];if(!r)return e;let s=Object.keys(r.tiers),o=t||s[0],i=xS(e,o,n);return i||TS(e,r,o,s)}function SS(e,t){return fl({requestedTool:e,intentText:t})??e}function xS(e,t,n){return fl({requestedTool:e,metaTool:e,tier:t,intentText:n})}function TS(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 Ep=lo;function Cp(e){return e in Ep}var uo=Object.keys(lo);function ml(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function Rp(e=process.env){return ml(e)!==null}var kS=new Set(["false","0","no","off","disable","disabled"]),AS=new Set(["true","1","yes","on","enable","enabled"]);function Ip(e){let t=(e??"").trim().toLowerCase();return t?kS.has(t)?!1:!!AS.has(t):!0}function $p(e=process.env){return Ip(e.VISA_CLI_PARENTLESS_SINGLE_CALL)}function Pp(e=process.env){return Ip(e.VISA_CLI_PARENTLESS_BATCH)}var Ty=require("child_process"),xe=R(require("crypto")),mt=R(require("fs")),$o=R(require("os")),Ma=R(require("path"));function At(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"?Hr(s):null,i=Array.isArray(n.urls)?n.urls[0]:void 0,c=typeof i=="string"&&i.startsWith("data:")?Hr(i):null;if(!o&&!c)return e;let l=o??c,u=o?"content":"urls",d;try{d=Ds(l,{tag:ES(r,n)})}catch(m){return{...n,_inline_media_warning:`Failed to persist inline media to disk: ${m instanceof Error?m.message:String(m)}`}}let f={...n,filePath:d.filePath,mime:d.mime,bytes:d.bytes};return u==="urls"?f.urls=void 0:(f.content=Array.isArray(n.content)?[...n.content]:[{}],f.content[0]={...f.content[0]??{},text:`[inline media saved to ${d.filePath}]`}),f}function ES(e,t){let n=typeof t.transactionId=="string"?t.transactionId:typeof t.transaction_id=="string"?t.transaction_id:null;return n?`${e}-${n}`:e}wt();var pl=!1;async function vr(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")||!de())throw r;if(h.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(pl)throw h.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;pl=!0,h.info("attestation:starting-browser-recovery");try{let o=await n();if(!o.success)throw h.error("attestation:browser-recovery-failed",{message:o.message}),r;let i=await Ui();await e.registerAttestationKey(i),await e.setBiometricPreference({required:!0}),h.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),h.info("attestation:key-reregistered-after-recovery");let a=await t();return pl=!1,a}catch(o){throw h.error("attestation:recovery-failure",{error:o.message}),r}}throw r}}function Et(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}async function Bi(e,t){if(!de())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 Di())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 Et(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."}}qt();var Op="3.4.7-rc.1";function gl(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function Fi(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=Si(t);return s!==void 0?{value:s,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function Ke(e){return e==null?"\u2014":e?"yes":"no"}function Hi(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function CS(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function RS(){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=Kc("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:Vc,source:{kind:"default"}}}async function fo(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=qc("auth.serverUrl"),i=$e(),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:Ke(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:Ke(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:Ke(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:de(),formatted:Ke(de()),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:Hi(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:Hi(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:Hi(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:Hi(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 f=t?.cards?.find(y=>y.isDefault)??t?.cards?.[0];f&&r.push({key:"cards.default",value:{brand:f.brand??null,last4:f.last4},formatted:`${f.brand||"card"} \u2022\u2022\u2022\u2022 ${f.last4}`,source:{kind:"server"}});let m=RS();r.push({key:"credit.sessionCapCents",value:m.value,formatted:CS(m.value),source:m.source});let p=hm();p.length>0&&r.push({key:"settings.retired",value:p.map(y=>y.key),formatted:p.map(y=>y.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${p.map(y=>`visa-cli config unset ${y.key}`).join(" && ")}`});let g=Fi("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:g.value,formatted:Ke(g.value),source:g.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let v=Fi("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:v.value,formatted:Ke(v.value),source:v.source});let k=St(),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:!k,formatted:Ke(!k),source:b});let w=Fi("VISA_META_TOOLS","tools.meta","opt-in");r.push({key:"tools.meta",value:w.value,formatted:Ke(w.value),source:w.source,hint:"Meta-tools are deprecated and off by default. Re-enable with `visa-cli config set tools.meta true`. Restart Claude Code for changes to take effect."});let S=Fi("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:S.value,formatted:Ke(S.value),source:S.source});let C=process.env.VISA_DRY_RUN,I=Rp();if(r.push({key:"tools.dryRun",value:I,formatted:Ke(I),source:C===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:Op,formatted:Op,source:{kind:"default"}}),e.includeDev){let y=process.env.VISA_MOCK_KEYCHAIN,T=dn();r.push({key:"dev.mockKeychain",value:T,formatted:Ke(T),source:gl("VISA_MOCK_KEYCHAIN",!!y),hint:nc()});let z=process.env.VISA_MOCK_TOUCHID,Z=Fr();r.push({key:"dev.mockTouchid",value:Z,formatted:Ke(Z),source:gl("VISA_MOCK_TOUCHID",!!z),hint:nc()});let H=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!H,formatted:Ke(!!H),source:gl("VISA_CLI_DEBUG",!!H)})}return{entries:r,statusError:n}}function IS(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 Mp(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}(${IS(o.source)})`),t.verbose&&o.hint&&s.push(` ${"\u21B3".padStart(n)} ${o.hint}`)}return s.join(`
144
- `)}function Np(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 Lp(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"}]}}}qt();wt();var $n=require("fs"),Dp=require("os"),hl=require("path"),$S=(0,hl.join)((0,Dp.homedir)(),".visa-mcp"),Up=(0,hl.join)($S,"mcp-session-budget.json");function Vi(){try{(0,$n.existsSync)(Up)&&(0,$n.unlinkSync)(Up)}catch{}}var _l=require("crypto"),ut=R(as()),Sr=null,Ge=0,On=0,Ve=0,Pn=null,bl=null,vl=null,wr=Promise.resolve();function PS(e){return Number((0,ut.fromCents)(e))}function Bp(e){return(0,ut.toCents)((0,ut.micros)(BigInt(e)))}function jp(e){return(0,ut.toWire)((0,ut.fromCents)(e))}function yl(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function qi(e){return typeof e=="string"&&/^\d+$/.test(e)}var OS=43,MS=new RegExp(`^[A-Za-z0-9_-]{${OS}}$`);function NS(e){return typeof e=="string"&&MS.test(e)}function LS(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||Sr&&e.session_id!==Sr||typeof e.nonce!="string"||e.nonce.length===0||!NS(e.server_signature)||!yl(e.cumulative)||!yl(e.remaining)||!yl(e.delta)||e.cumulative<Ge||Ve>0&&e.cumulative>Ve||Ve>0&&e.remaining>Ve||e.cumulative_micros!==void 0&&!qi(e.cumulative_micros)||e.remaining_micros!==void 0&&!qi(e.remaining_micros)||e.delta_micros!==void 0&&!qi(e.delta_micros)||e.reserved_micros!==void 0&&!qi(e.reserved_micros))}function Zt(e){Sr=e,Ge=0,On=0,Ve=0,Pn=null,bl=null,vl=null,wr=Promise.resolve()}function mo(e){Ve=Math.max(0,Math.floor(e))}function wl(){return Sr}function Sl(e){if(!Sr)return null;let t=Ge+On;return Ve>0&&t>Ve&&(t=Ve),{session_budget_id:Sr,cumulative_micros:PS(t),nonce:(0,_l.randomUUID)(),idempotency_key:e||(0,_l.randomUUID)()}}function po(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 LS(r)?(Ge=Math.max(Ge,r.cumulative),On=0,Pn=r,r):null}function Fp(){return Pn}function xl(e){let t=Bp(e.cumulative_micros);Ge=Math.max(Ge,t),On=0;let n={status:"accepted",session_id:e.session_budget_id,cumulative:Ge,remaining:Math.max(0,Ve-Ge),delta:0,cumulative_micros:jp(Ge),remaining_micros:jp(Math.max(0,Ve-Ge)),delta_micros:"0",nonce:e.nonce};return Pn=n,n}function go(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,ut.toCents)((0,ut.micros)(n));if(!Number.isFinite(r)||r<0)return;bl=t;let s=e,o=typeof s.session_id=="string"?s.session_id:Sr??"";Pn?(typeof s.remaining_micros=="string"&&/^\d+$/.test(s.remaining_micros)&&(Pn.remaining_micros=s.remaining_micros),typeof s.charged_micros=="string"&&/^\d+$/.test(s.charged_micros)&&(Pn.delta_micros=s.charged_micros)):Pn={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 Hp(e){let t=e.receipt??null;vl={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:Bp(e.voucher.cumulative_micros),estimatedCumulativeCents:Ki(),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 Vp(){return vl}function qp(){return Ge}function Kp(){return bl}function Ki(){let e=Ge+On;return Ve>0&&e>Ve&&(e=Ve),e}function Tl(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return wr=wr.then(()=>{On+=t}),wr}function ho(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return wr=wr.then(()=>{On=Math.max(0,On-t)}),wr}var US=10,DS=1,fe=null,Gp=Promise.resolve();function kl(e){let t=Gp.catch(()=>{}).then(e);return Gp=t.then(()=>{},()=>{}),t}var Se=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 Al(e,t,n){return kl(()=>Wp(e,t,n))}async function Wp(e,t,n){if(Vi(),fe&&new Date(fe.expiresAt).getTime()>Date.now())return wl()!==fe.budgetId&&(Zt(fe.budgetId),mo(fe.totalCents)),h.info("mcp-session:active-hit",{budgetId:fe.budgetId,tool:n.toolName,remainingEstimatedCents:fe.totalCents-Ki()}),{budgetId:fe.budgetId,isFresh:!1,totalCents:fe.totalCents,requestedCapCents:fe.totalCents,appliedCapCents:fe.totalCents,clampedReason:null};fe&&(fe=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"?DS:US,i=Math.max(o,Math.ceil(n.minRequiredCents??o));if(r.balanceCents<i)throw new Se(r.balanceCents,i);let a=n.capCentsOverride??bm(),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 m=d.error||"unknown error";throw new Error(`Failed to open credit session: ${m}`)}let f={budgetId:d.budget.id,expiresAt:d.budget.expiresAt,totalCents:d.budget.totalCents,createdAt:d.budget.createdAt};return fe=f,Zt(f.budgetId),mo(f.totalCents),h.info("mcp-session:opened",{budgetId:f.budgetId,capCents:f.totalCents,requestedCapCents:a,clampedReason:l,sessionKind:s,expiresAt:f.expiresAt,tool:n.toolName}),{budgetId:f.budgetId,isFresh:!0,totalCents:f.totalCents,requestedCapCents:a,appliedCapCents:f.totalCents,clampedReason:l}}async function Yp(e,t,n){return kl(async()=>{let s=Mn()?await zp(e):null,o=await Wp(e,t,n);return{budgetId:o.budgetId,totalCents:o.totalCents,closedPrevious:s,requestedCapCents:o.requestedCapCents,appliedCapCents:o.appliedCapCents,clampedReason:o.clampedReason}})}async function zp(e){let n=Mn()?.budgetId??wl(),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){h.warn("mcp-session:close-server-failed",{budgetId:n,error:i?.message||String(i)})}return Vi(),fe=null,Zt(null),{closedServerSide:r,budgetId:n,finalCumulativeCents:s,finalCumulativeMicros:o}}async function Gi(e){return kl(()=>zp(e))}function Mn(){return Vi(),fe?new Date(fe.expiresAt).getTime()<=Date.now()?(fe=null,Zt(null),null):{budgetId:fe.budgetId,totalCents:fe.totalCents,lastReceiptCumulative:qp(),lastReceiptCumulativeMicros:Fp()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:Kp(),estimatedCumulative:Ki(),lastToolSpend:Vp(),expiresAt:fe.expiresAt}:null}var Xp=R(as()),Jp=10000n;function jS(e){return e<=0n?0:Number((e+Jp-1n)/Jp)}function Zp(e){return jS((0,Xp.fromUsd)(e))}var Wi=R(as()),BS=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;function Yi(e){if(typeof e!="string"||!BS.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,Wi.toDisplay)((0,Wi.fromCents)(s),{symbol:""})}}var zi="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.",Qp="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.";qt();var dy=Promise.resolve();function Hk(e,t){if(e)try{let n=(0,Oa.fromWire)(e),r=n%10000n===0n?2:6;return(0,Oa.toDisplay)(n,{decimals:r})}catch{}return`$${(t/100).toFixed(2)}`}var fy=!1,my=!1,py=!1;function Na(e){let t=dy.catch(()=>{}).then(e);return dy=t.then(()=>{},()=>{}),t}async function ky(e){let t=await Te(()=>Al(U,et,{toolName:e.toolId,userContext:e.userContext}));await Tl(e.estimatedAmountCents);let n=Sl(e.idempotencyKey);if(!n)throw await ho(e.estimatedAmountCents),new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await Jk(),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 Ht){let d=Math.min(Math.max(u.retryAfterSecs,0),5)*1e3;h.warn("mcp-session:lock-contended-retrying",{tool:e.toolId,retryAfterSecs:u.retryAfterSecs}),await new Promise(f=>setTimeout(f,d)),{data:s,voucherReceiptHeader:o}=await i()}else throw u}}catch(u){if(await ho(e.estimatedAmountCents),u instanceof Yr){if(h.warn("mcp-session:server-invalidated-budget",{code:u.code,budgetId:u.budgetId??t.budgetId,tool:e.toolId}),await Gi(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 py||(py=!0,console.error(`[visa-cli] Your session was closed by another process; reopened automatically as pay-as-you-go.
145
- To require an explicit session approval instead, set VISA_REQUIRE_EXPLICIT_SESSION=true.`)),h.info("mcp-session:falling-back-to-payg",{code:u.code,tool:e.toolId}),Ay(e)}throw u instanceof Ht?(h.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=po(o)??(n?xl(n):null);if(go(s?.receipt_v2),Hp({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),Bu(s))return At(s);let c=await ju();if(e.idempotencyKey&&Fu(s,c,e.idempotencyKey))return At(s);let l=c?Ro(c):null;return At(Hu(s,r,l))}function Qe(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function Ia(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(Ia).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${Ia(r)}`).join(",")}}`}function Du(e,t,n,r){let s=xe.createHash("sha256").update(`${n}:${Ia(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${s}`}function Vk(e,t){return`${e}:${t}`}function qk(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 $a(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,s=ft(r),o=s!==null?s.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=qk(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),c=i!=null?String(i):a;return{batch_id:e,item_id:Vk(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 Ay(e){return Te(()=>Gk(e))}async function Ey(e,t,n){if(Bu(e))return At(e);let r=await ju();if(n&&Fu(e,r,n))return At(e);let s=r?Ro(r):null;return At(Hu(e,t,s))}async function Kk(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 et("shortcut_call",t,e.toolId,n,e.userContext);h.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 po(i),go(o?.receipt_v2),h.info("parentless-single-call:completed",{tool:e.toolId}),Ey(o,e.beforeBalanceMicros,e.idempotencyKey)}async function Gk(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 Se(n.balanceCents,t);let r=t,s=Ro(n);if($p()&&!fy){let u=e.idempotencyKey??xe.randomUUID();try{return await Kk({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 vt)fy=!0,h.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 et("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),mo(a.budget.totalCents),h.info("on-demand-session:opened",{budgetId:c,capCents:a.budget.totalCents,tool:e.toolId});let l=!1;try{await Tl(e.estimatedAmountCents);let u=Sl(e.idempotencyKey);if(!u)throw await ho(e.estimatedAmountCents),new Error(`Internal: mintVoucher returned null after on-demand session-open ${c}`);let{data:d,voucherReceiptHeader:f}=await U.shortcutWithSession(e.toolId,u,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(po(f)||xl(u),l=!0,go(d?.receipt_v2),Bu(d))return At(d);let m=await ju();if(e.idempotencyKey&&Fu(d,m,e.idempotencyKey))return At(d);let p=m?Ro(m):null;return At(Hu(d,s,p))}catch(u){throw l||await ho(e.estimatedAmountCents),u}finally{try{await U.closeSession(c)}catch(u){h.warn("on-demand-session:close-failed",{budgetId:c,error:u?.message||String(u)})}Zt(null),h.info("on-demand-session:closed",{budgetId:c,tool:e.toolId})}}async function Gn(e){return Na(async()=>Mn()?ky(e):Ay(e))}function La(){return $e()}var U=new qe(()=>G.getSessionToken());function ft(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function Ro(e){return ft(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function Wk(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 Yk(e){let t=ft(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=ft(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=ft(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function Co(e,t="INVALID_TOOL_PARAMS",n){return{success:!1,error_code:t,code:t,error:e,message:e,...n??{}}}function zk(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 Jk(){try{let e=await U.getBalance();return e.success?Ro(e):null}catch{return null}}async function ju(){try{let e=await U.getBalance();return e.success?e:null}catch{return null}}function Bu(e){if(!e||e.success===!1)return!1;let t=ft(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=ft(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 Fu(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=ft(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 Hu(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 Xk="3.4.7-rc.1",B$=["","","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',"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Generate an image of a sunset over Tokyo" \u2192 discover_tools \u2192 execute_tool','\u2022 "Make a 4-second video of a penguin juggling" \u2192 discover_tools \u2192 execute_tool','\u2022 "Make a song about coding late at night" \u2192 discover_tools \u2192 execute_tool','\u2022 "Run a reasoning model on this prompt" \u2192 discover_tools \u2192 execute_tool','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
146
- `);function pt(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=Vs(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(ym())return{opened:!1,url:t,blockedReason:"suppressed"};let n=hc();if(n.headless)return h.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let r=Xd(t,La());if(!r)return h.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let s=Qd(r);return s?((0,Ty.execFile)(s.cmd,s.args,o=>{o&&h.warn(`Browser open failed: ${o.message}. URL: ${r}`)}),{opened:!0,url:r}):(h.info(`No browser command for platform "${$o.platform()}". URL: ${r}`),{opened:!1,url:r,blockedReason:"unsupported_platform"})}async function Te(e){return vr(U,e,Ly)}var Cy="get_cards",Ry="set_default_card";function Zk(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 '${Cy}' to see enrolled cards and '${Ry}' to switch, then retry the original request.`}function Qk(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 '${Cy}' to see enrolled cards and '${Ry}' to switch. Do not retry automatically.`}function gt(e,t){let n=e.retryable?Zk(e.code,e.retryAfter):Qk(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 eA(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 As=null,tA=3e4;function Iy(){As=null}var Kn=class extends Error{constructor(n){super(`${Pa()} attestation is required for this action, but it is not available in this MCP process. `+Vu());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function Ua(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. `+Vu()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function nA(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:zi,agent_guidance:Qp}}function Pa(){return process.platform==="darwin"?"Touch ID":"local biometric"}function Vu(){return process.platform==="darwin"?"Run the action from an interactive terminal with Touch ID access, or call auth_recovery to re-sync a drifted local attestation key, 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. Call auth_recovery to re-sync a drifted local attestation key, or use reset with confirm:true to clear stale server biometric state through GitHub re-authentication."}async function rA(e){let t=Date.now();if(As&&As.expiresAt>t)return{required:As.required,hasRegisteredKey:As.hasRegisteredKey};try{let n=await U.getStatus(e),r=Et(n),s=n.attestationRequired!==!1;return As={required:s,hasRegisteredKey:r,expiresAt:t+tA},{required:s,hasRegisteredKey:r}}catch{return{required:!0,hasRegisteredKey:!0}}}async function et(e,t,n,r,s,o){if(!o?.forceRequired){let i=await rA(s);if(!i.required){h.info("attestation:skipped-by-server-policy",{context:e});return}if(!i.hasRegisteredKey){h.info("attestation:skipped-no-registered-key",{context:e});return}}if(!de())throw h.warn("attestation:unavailable",{context:e}),new Kn(e);h.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");h.info("touchid:prompt",{context:e,amount:t,merchant:n});let c=await Rn(a,r);return h.info("attestation:success",{context:e,amount:t,merchant:n}),{signature:c,nonce:i,amount:t,merchant:n}}catch(i){throw/cancel|dismiss/i.test(i.message??"")?(h.warn("attestation:cancelled",{context:e,merchant:n}),new Error("Touch ID was cancelled or dismissed. For automated environments (CI, scripts, MCP hooks without user present), run `visa-cli config biometric off` to enable paid calls without Touch ID.")):(h.error("attestation:failure",{context:e,amount:t,merchant:n,error:i.message}),i)}}var gy="[dry-run] https://placeholder.visa-cli.dev/image.png",sA=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"]),oA=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 iA(e,t){return t==="run_llm"||e.startsWith("or-")?"llm":t==="generate_image"||sA.has(e)?"image":t==="generate_video"||oA.has(e)?"video":aA(e)?"media":null}function aA(e){let t=os(e);return t?!Da(t):!1}function cA(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function lA(e){return e==="llm"?"OpenRouter":"fal.ai"}function Es(e,t,n,r){let s={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:lA(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${cA(n)}`;return{...s,content:i,data:{content:i,model:t,dry_run:!0}}}return{...s,urls:[gy],data:{[e==="video"?"videoUrl":e==="image"?"imageUrl":"url"]:gy,metadata:{dry_run:!0}}}}async function Nu(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:xe.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){h.warn("dry_run:telemetry_failed",{tool:e.toolName,error:s?.message||String(s),mode:t})}}var uA="https://openrouter.ai/api/v1/chat/completions",dA="openrouter/free",fA=50,mA=15e3;function pA(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 gA(e,t,n){let r=process.env.OPENROUTER_API_KEY;if(!r)return h.warn("preflight:no_openrouter_key_falling_back_to_mock",{tool:e}),{result:Es("llm",e,t,n),degraded:!0,resolvedModel:null};let s=pA(t),o;try{o=await bt(uA,{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:dA,messages:[{role:"user",content:s}],max_tokens:fA}),timeoutMs:mA})}catch(u){return h.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:Es("llm",e,t,n),degraded:!0,resolvedModel:null}}if(!o.ok){let u=await o.text().catch(()=>"");return h.warn("preflight:openrouter_http_error_falling_back_to_mock",{tool:e,status:o.status,bodyExcerpt:u.slice(0,200)}),{result:Es("llm",e,t,n),degraded:!0,resolvedModel:null}}let i;try{i=await o.json()}catch(u){return h.warn("preflight:openrouter_invalid_json_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:Es("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 Po(e,t,n,r){let s=ml();if(!s)return null;let o=iA(e,r);if(!o)return null;let i=Date.now();if(s==="mock"){let l=Es(o,e,t,r);return await Nu({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:l,userContext:n,startedAt:i,mode:"mock"}),h.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:o,mode:s}),l}if(o!=="llm"){h.warn("preflight:not_supported_for_kind_falling_back_to_mock",{tool:e,kind:o});let l=Es(o,e,t,r);return await Nu({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 gA(e,t,r);return await Nu({toolName:r??e,resolvedModel:c??(r&&r!==e?e:null),toolParams:t,result:a,userContext:n,startedAt:i,mode:"preflight"}),h.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:o,mode:s}),a}async function cn(e,t,n,r){let s=await U.paymentPreview({tool:e,url:t,...r&&Object.keys(r).length>0?{params:r}:{}},n);if(!s||!s.merchantName||s.amount===void 0||s.amount===null||s.amount<0)throw new Error("Could not determine payment amount and merchant. Try again.");if(!Number.isFinite(s.amount)||s.amount<0||s.amount>999999)throw new Error(`Invalid payment amount: ${s.amount}. Payment rejected for safety.`);return s}function ln(e){return Zp(e.amount)}function hA(e,t,n){return n.has(e.resolvedTool)?0:Math.max(1,ln(t[e.resolvedTool]))}function yA(){return Ma.join($o.homedir(),".visa-mcp","allium-results")}var F$=16*1024,H$=50*1024*1024;function _A(){let e=yA();try{if(!mt.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=mt.readdirSync(e),n=0,r=0;for(let s of t)try{let o=mt.statSync(Ma.join(e,s));o.isFile()&&(n+=o.size,r++)}catch{}return{file_count:r,size_bytes:n,path:e}}catch(t){return h.warn("allium:disk_usage_error",{error:t.message}),{file_count:0,size_bytes:0,path:e}}}var hy=3600*1e3,Lu=0;function bA(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function Oo(e){if(!_m()&&!(Date.now()<Lu))try{if(!await G.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}}),h.info("feed:submitted",{tool:e.tool,mediaType:e.mediaType,transactionId:e.transactionId})}catch(t){if(bA(t)){let n=Lu===0;Lu=Date.now()+hy,n&&h.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:hy});return}h.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function vA(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})`;h.info("payment:attempt",{tool:"get_visa_smi",amount:a,merchant:i});try{return await Te(async()=>{let l=await et("get_visa_smi",a,i,c),u=await U.getVisaSmi({state:n,county:r,start_date:s,end_date:o,attestation:l,idempotencyKey:xe.randomUUID()},t);return u.success?h.info("payment:success",{tool:"get_visa_smi",merchant:i,charged_cents:u.charged_cents}):h.warn("payment:declined",{tool:"get_visa_smi",merchant:i,message:u.error}),u})}catch(l){if(l instanceof he)return h.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:l.code,retryable:l.retryable}),gt(l,{amount:a,merchantName:i,description:"Visa SMI data"});throw h.error("payment:failure",{tool:"get_visa_smi",merchant:i,error:l.message}),l}}async function wA(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 Po("generate_image_card",e,t);if(n)return n;let r=await cn("generate_image_card",void 0,t),s=xe.randomUUID();h.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await Te(async()=>{let o;try{o=await Gn({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:ln(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof Se)return Qe(i);throw i}return h.info("payment:success",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>pt(i)),Oo({prompt:e.prompt,tool:"generate_image_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):h.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof he)return h.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),gt(o,r);throw un(o,{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName}),o}}async function SA(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 Po("generate_image_fast_card",e,t);if(n)return n;let r=await cn("generate_image_fast_card",void 0,t),s=xe.randomUUID();h.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await Te(async()=>{let o;try{o=await Gn({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:ln(r),userContext:t,timeoutMs:6e4,idempotencyKey:s})}catch(i){if(i instanceof Se)return Qe(i);throw i}return h.info("payment:success",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>pt(i)),Oo({prompt:e.prompt,tool:"generate_image_fast_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):h.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof he)return h.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),gt(o,r);throw un(o,{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName}),o}}async function xA(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 Po("generate_video_tempo_card",e,t);if(n)return n;let r=await cn("generate_video_tempo_card",void 0,t),s=xe.randomUUID();h.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await Te(async()=>{let o;try{o=await Gn({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:ln(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof Se)return Qe(i);throw i}return h.info("payment:success",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>pt(i)),Oo({prompt:e.prompt,tool:"generate_video_tempo_card",mediaUrl:o.urls[0],mediaType:"video",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):h.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof he)return h.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),gt(o,r);throw un(o,{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName}),o}}async function TA(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 cn("generate_music_tempo_card",void 0,t),r=xe.randomUUID();h.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await Te(async()=>{let s;try{s=await Gn({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:ln(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(o){if(o instanceof Se)return Qe(o);throw o}return h.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=>pt(o)),Oo({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,h.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):h.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof he)return h.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),gt(s,n);throw un(s,{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName}),s}}async function kA(e,t){let n=await cn("check_music_status_tempo_card",void 0,t),r=xe.randomUUID();h.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await Te(async()=>{let s;try{s=await Gn({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:ln(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof Se)return Qe(o);throw o}return h.info("payment:success",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),s.urls?.length&&s.urls.forEach(o=>pt(o)),s})}catch(s){if(s instanceof he)return h.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),gt(s,n);throw un(s,{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName}),s}}async function AA(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 cn("query_onchain_prices",void 0,t),r=xe.randomUUID();h.info("payment:attempt",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName});try{return await Te(async()=>{let s;try{s=await Gn({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:ln(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof Se)return Qe(o);throw o}if(h.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 he)return h.warn("payment:declined",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),gt(s,n);throw un(s,{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName}),s}}var EA=["generate_music_tempo_card"],ks=10,yy=5,_y=new Map;function by(e){let t=_y.get(e);if(t!==void 0)return t;let r=os(e)?.isAsync===!0||EA.includes(e);return _y.set(e,r),r}var CA=36e4,RA=18e4,IA=15e3,$A=12e4,PA=2e3;function Uu(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}function OA(e,t){return xe.createHash("sha256").update(`${e}:${Ia(t)}`).digest("hex")}function MA(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,...$a(n,r,o)});let l=0,u=0n;if(o?.success!==!1){let d=ft(o?.amountMicros??o?.amount_micros),f=typeof o?.amount=="number"?o.amount:i?.amount??0;d!==null&&d>0n?u+=d:u+=BigInt(Math.round(f*1e6)),l+=f}return o?.urls&&o.urls.forEach(d=>pt(d)),{deltaCharged:l,deltaMicros:u}}function NA(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,f=t.filter(k=>k?.success===!1).length,m=t.length-f,p=t.flatMap(k=>Array.isArray(k?.urls)?k.urls:[]),g=l>0n?Number(l)/1e6:Math.round((c+Number.EPSILON)*100)/100,v=m===0?"failure":f===0?"success":"partial";return h.info("payment:success",{tool:"batch",batchTool:o,count:n.length,totalAmount:a,totalCharged:g,merchant:i,successCount:m,failedCount:f,outcome:v,mode:d,batchId:u}),{success:m>0,outcome:v,batch_id:u,tool:s?r[0]:o,count:n.length,successCount:m,failedCount:f,totalCharged:g,...l>0n?{totalChargedMicros:l.toString(),amountMicros:l.toString(),amount_micros:l.toString()}:{},merchantName:i,results:t,...p.length?{urls:p}:{}}}async function LA(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:f,batchId:m,userContext:p}=e,g=i,v=await U.getBalance();if(!v.success)throw new Error(`Could not read balance: ${v.error||"unknown error"}`);if(v.balanceCents<g)throw new Se(v.balanceCents,g);let k=`batch-${m}`,b=`spend up to $${(g/100).toFixed(2)} across a batch of ${t.length}`,{batchParentId:w}=await Te(async()=>{let y=await et("batch_open",g,k,b,p,{forceRequired:!0}),T=y?.nonce??(await U.getAttestationChallenge()).nonce;h.info("parentless-batch:open-attempt",{batchTool:l,count:t.length,approvedTotalCents:g,attested:!!y});let{batch_parent_id:z}=await U.batchOpen({...y?{attestation:y}:{},nonce:T,approved_total_cents:g,batch_id:m});return{batchParentId:z}});h.info("parentless-batch:opened",{batchTool:l,count:t.length,batchParentId:w});let S=[],C=0,I=0n;try{for(let y=0;y<t.length;y+=1){let T=t[y],z=n[T.resolvedTool],Z=r.has(T.resolvedTool);try{let H;if(Z)H=await U.shortcut(T.resolvedTool,T.params,f,p,"batch");else{let{data:X,voucherReceiptHeader:Ms}=await U.shortcutParentlessBatchItem(T.resolvedTool,{batch_parent_id:w,batch_id:m,batch_index:y,batch_request_hash:OA(T.resolvedTool,T.params),item_ceiling_cents:o[y],idempotency_key:Du(m,y,T.resolvedTool,T.params)},T.params,f,p,"batch");po(Ms),go(X?.receipt_v2),H=await Ey(X,null,Du(m,y,T.resolvedTool,T.params))}let{deltaCharged:be,deltaMicros:se}=MA({results:S,batchId:m,index:y,item:T,itemResult:H,preview:z,isFree:Z,catalogName:s[T.resolvedTool]?.name});C+=be,I+=se}catch(H){if(H instanceof Se&&S.length===0)return Qe(H);h.warn("payment:batch-item-failed",{tool:T.resolvedTool,index:y,error:H?.message||String(H)}),S.push({success:!1,tool:T.resolvedTool,...$a(m,y),error:H?.message||String(H)})}}return NA({results:S,resolvedItems:t,uniqueTools:a,isHomogeneous:c,primaryTool:l,merchantNames:u,totalAmount:d,totalCharged:C,totalChargedMicros:I,batchId:m,mode:"parentless"})}catch(y){if(y instanceof he)return h.warn("payment:declined",{tool:"batch",batchTool:l,count:t.length,totalAmount:d,merchant:u,code:y.code,retryable:y.retryable}),gt(y,{amount:d,merchantName:u});throw un(y,{tool:"batch",batchTool:l,count:t.length,totalAmount:d,merchant:u}),y}}async function UA(e,t){let n;if(Array.isArray(e.requests)&&e.requests.length>ks)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${ks} 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 z=In(T,y.tier||e.tier,y.prompt??t),{tool:Z,tool_id:H,tier:be,params:se,...X}=y,Ms=se&&typeof se=="object"?{...se,...X}:X;return{resolvedTool:z,params:Ms}});else if(e.tool){let y=In(e.tool,e.tier,e.params?.prompt??t);if(e.count!==void 0){if(!Number.isSafeInteger(e.count)||e.count<1)return Uu("BATCH_INVALID_COUNT","Batch count must be a positive integer.");if(e.count>ks)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${ks} items. Please split into smaller batches.`}}n=(e.requests||(e.count!==void 0&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(z=>({resolvedTool:y,params:z}))}else return Uu("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return Uu("BATCH_EMPTY","Batch requires at least one item.");if(n.length>ks)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${ks} items. Please split into smaller batches.`};if([...new Set(n.map(y=>y.resolvedTool))].some(by)&&n.length>yy)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${yy} 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 Uy(y);let l=new Set(i.filter(y=>c[y]&&Da(c[y]))),u={};for(let y of i)l.has(y)||(u[y]=await cn(y,void 0,t));let d=0;for(let y of n)d+=u[y.resolvedTool]?.amount??0;let f=n.map(y=>hA(y,u,l)),m=f.reduce((y,T)=>y+T,0),p=[...new Set([...Object.values(u).map(y=>y.merchantName),...i.filter(y=>l.has(y)).map(y=>c[y]?.name??y)])].join(", "),g=a?i[0]:"mixed";h.info("payment:attempt",{tool:"batch",batchTool:g,count:n.length,totalAmount:d,merchant:p,heterogeneous:!a});let v=n.some(y=>by(y.resolvedTool)),k=n.some(y=>y.resolvedTool.startsWith("or-")||y.resolvedTool==="run_llm"||y.resolvedTool==="execute_tool"),b=v?CA:k?RA+n.length*IA:$A+n.length*PA,w=xe.randomUUID(),S=[],C=0,I=0n;return Na(async()=>{let y=!Mn();if(Pp()&&!my&&y&&m>0)try{return await LA({resolvedItems:n,previews:u,freeTools:l,catalogEntries:c,itemCeilingCents:f,batchCeilingCents:m,uniqueTools:i,isHomogeneous:a,primaryTool:g,merchantNames:p,totalAmount:d,timeoutMs:b,batchId:w,userContext:t})}catch(T){if(T instanceof vt)my=!0,h.info("parentless-batch:falling-back-to-session",{batchTool:g,count:n.length,status:T.status,serverErrorCode:T.serverErrorCode});else{if(T instanceof Se)return Qe(T);throw T}}if(y&&m>0)try{let T=m;await Te(()=>Al(U,et,{toolName:"batch",userContext:t,sessionKind:"one_shot",minRequiredCents:T,capCentsOverride:T}))}catch(T){return T instanceof Se?Qe(T):(h.warn("payment:batch-prewarm-failed",{batchTool:g,count:n.length,error:T?.message||String(T)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:T?.message||"Failed to authenticate batch session",tool:g,count:n.length,failedCount:n.length,results:[]})}try{for(let se=0;se<n.length;se+=1){let X=n[se],Ms=u[X.resolvedTool];try{let le=l.has(X.resolvedTool)?await U.shortcut(X.resolvedTool,X.params,b,t,"batch"):await ky({toolId:X.resolvedTool,toolParams:X.params,estimatedAmountCents:f[se],userContext:t,metaTool:"batch",timeoutMs:b,idempotencyKey:Du(w,se,X.resolvedTool,X.params)});if(l.has(X.resolvedTool)&&le&&typeof le=="object"&&!Array.isArray(le)&&le.merchantName==null&&(le.merchantName=c[X.resolvedTool]?.name??X.resolvedTool),S.push({success:le?.success!==!1,tool:X.resolvedTool,...le,...$a(w,se,le)}),le?.success!==!1){let Ns=ft(le?.amountMicros??le?.amount_micros),kd=typeof le?.amount=="number"?le.amount:Ms?.amount??0;Ns!==null&&Ns>0n?I+=Ns:I+=BigInt(Math.round(kd*1e6)),C+=kd}le?.urls&&le.urls.forEach(Ns=>pt(Ns))}catch(le){if(le instanceof Se&&S.length===0)return Qe(le);h.warn("payment:batch-item-failed",{tool:X.resolvedTool,index:se,error:le?.message||String(le)}),S.push({success:!1,tool:X.resolvedTool,...$a(w,se),error:le?.message||String(le)})}}let T=S.filter(se=>se?.success===!1).length,z=S.length-T,Z=S.flatMap(se=>Array.isArray(se?.urls)?se.urls:[]),H=I>0n?Number(I)/1e6:Math.round((C+Number.EPSILON)*100)/100,be=z===0?"failure":T===0?"success":"partial";return h.info("payment:success",{tool:"batch",batchTool:g,count:n.length,totalAmount:d,totalCharged:H,merchant:p,successCount:z,failedCount:T,outcome:be,mode:"session",batchId:w}),{success:z>0,outcome:be,batch_id:w,tool:a?i[0]:g,count:n.length,successCount:z,failedCount:T,totalCharged:H,...I>0n?{totalChargedMicros:I.toString(),amountMicros:I.toString(),amount_micros:I.toString()}:{},merchantName:p,results:S,...Z.length?{urls:Z}:{}}}catch(T){if(T instanceof he)return h.warn("payment:declined",{tool:"batch",batchTool:g,count:n.length,totalAmount:d,merchant:p,code:T.code,retryable:T.retryable}),gt(T,{amount:d,merchantName:p});throw un(T,{tool:"batch",batchTool:g,count:n.length,totalAmount:d,merchant:p}),T}finally{if(y){let T=await Gi(U);h.info("batch-session:closed",{budgetId:T.budgetId,closedServerSide:T.closedServerSide})}}})}function DA(){let e=!1,t;try{let r=Ma.join($o.homedir(),".claude","settings.json");if(mt.existsSync(r)){let s=JSON.parse(mt.readFileSync(r,"utf-8")),o=typeof s.statusLine=="object"?s.statusLine.command:"";e=bn(o)}}catch{}let n=ai();return n||(t="visa-cli config hud enable"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function jA(e){let[t,n]=await Promise.all([U.getStatus(e),U.getBalance().catch(o=>(h.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=_A();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=DA(),!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=Xk,Array.isArray(t.cards)&&(t.cards=t.cards.map(o=>({...o,displayName:qu(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=Mn();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 qu(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 $y(e,t){try{let r=((await U.getStatus(t)).cards||[]).find(s=>s?.id===e);if(r)return qu(r)}catch(n){h.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function BA(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:qu(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 FA(e,t){return await U.getTransactions({limit:e.limit,offset:e.offset},t)}async function HA(e,t){return await U.feedback(e.message,e.transaction_id,t)}async function VA(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Lr("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=Yi(String(e.amount));if(n.ok===!1)return{success:!1,error:n.error};let r=n.cents,s=r/100,o=xe.randomUUID();h.info("buy_credits:attempt",{amountCents:r});try{return await Te(async()=>{let i=await et("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){h.info("buy_credits:success",{amountCents:r,balanceCents:a.balanceCents,balanceMicros:a.balanceMicros});let c=Hk(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 h.warn("buy_credits:failed",{amountCents:r,error:a.error}),a})}catch(i){if(i instanceof Kn)return nA();if(i instanceof st)return h.warn("buy_credits:ambiguous",{amountCents:r,code:i.code,transactionId:i.transactionId}),eA(i);throw h.error("buy_credits:failure",{amountCents:r,error:i.message}),i}}function Lr(e,t){return{success:!1,error:t,code:e,message:t}}async function qA(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Lr("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 Lr("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 Lr("INVALID_VALUE","dailyLimit must be at least $1");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return Lr("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");h.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await Te(async()=>{let n=await et("spending-controls",0,"","update spending controls"),r=await U.updateSpendingControls({maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit,confirm:!0,attestation:n},t);return h.info("spending_controls:success",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit}),r})}catch(n){if(h.error("spending_controls:failure",{error:n.message}),n instanceof Kn)return Ua(n,"update_spending_controls");if(String(n?.message||n).includes("Attestation required"))return Lr("ATTESTATION_REQUIRED","Changing spending controls requires local attestation, even when payment biometric prompts are disabled.");throw n}}async function KA(e){let t=await fo({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 Ku=new Set(["auth.serverUrl"]);function Io(){return Object.keys(nr).filter(e=>!Ku.has(e)).sort()}function Py(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:Io()}}async function GA(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(Ku.has(e.key))return h.warn("config:set:rejected:mcp-forbidden",{key:e.key}),Py(e.key,"set");h.info("config:set",{key:e.key});try{let t=xi(e.key,e.value);return h.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 ot?"UNKNOWN_KEY":t instanceof Vt?"SERVER_CONTROLLED":t instanceof vn?"RETIRED_KEY":"INVALID_VALUE",r=t instanceof ot?`Unknown setting "${e.key}". MCP-settable keys: ${Io().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return h.warn("config:set:rejected",{key:e.key,code:n,error:r}),{success:!1,error:r,code:n,settableKeys:Io()}}}async function WA(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(Ku.has(e.key))return h.warn("config:unset:rejected:mcp-forbidden",{key:e.key}),Py(e.key,"unset");h.info("config:unset",{key:e.key});try{let t=Ti(e.key);return h.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 ot?"UNKNOWN_KEY":t instanceof Vt?"SERVER_CONTROLLED":t instanceof vn?"RETIRED_KEY":"INVALID_VALUE",r=t instanceof ot?`Unknown setting "${e.key}". MCP-settable keys: ${Io().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return h.warn("config:unset:rejected",{key:e.key,code:n,error:r}),{success:!1,error:r,code:n,settableKeys:Io()}}}async function YA(e){let t=await U.getStatus(e),n=t.attestationRequired!==!1,r=Et(t),s=de(),o=n?r?s?`${Pa()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${Pa()} is not available in this process. ${Vu()}`:"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 zA(e){h.info("biometric:on");let t=await Bi(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?(Iy(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:n.error||"unknown error"}}async function JA(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Lr("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.");h.info("biometric:off");try{return await Te(async()=>{let n=await U.getStatus(t),r;if(Et(n)&&(r=await et("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${Pa()} 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 Iy(),{success:!0,required:!1,message:"Touch ID is no longer required for payments."}})}catch(n){if(h.error("biometric:off:failure",{error:n.message}),n instanceof Kn)return Ua(n,"biometric_off");throw n}}var vy=3e4,XA=3e5;async function Oy(e,t,n="login"){let r=xe.randomUUID(),s=`${e}${e.includes("?")?"&":"?"}state=${r}`,o=pt(s);return!o.opened&&o.blockedReason!=="non_internal_host"&&o.blockedReason!=="invalid_url"?My(s,o,n):o.opened?{...await Ny(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 My(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 Ny(e,t,n="login"){let r=Date.now()+XA;for(;Date.now()<r;)try{let o=await fetch(`${La()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:vy,...t&&{user_context:t}}),signal:AbortSignal.timeout(vy+5e3)});if(!o.ok){await hn(o,a=>{h.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 h.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=Lp(a);if(n!=="enrollment"&&i.sessionToken){await G.saveSessionToken(i.sessionToken);let u=i.user||"",d=i.last4||"****";return h.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 h.info("auth:card_added",{last4:l,bonusCents:a}),{success:!0,message:`Card ending in ${l} enrolled and ready for payments.`,...c||{}}}}catch{await hn(void 0,o=>{h.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 Ly(e){let t=xe.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=pt(n.recoveryUrl);return!r.opened&&r.blockedReason!=="non_internal_host"&&r.blockedReason!=="invalid_url"?My(n.recoveryUrl,r,"attestation-recovery"):r.opened?{...await Ny(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 ZA(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."};h.info("cards:remove_attempt",{cardId:n});let r=`remove-card:${n}`,s=`remove ${await $y(n,t)}`;try{return await Te(async()=>{let o=await et(r,0,"",s,t,{forceRequired:!0}),i=await U.removeCard(n,{attestation:o},t);return h.info("cards:remove_success",{cardId:n,promotedId:i?.promotedId??null}),i})}catch(o){if(h.error("cards:remove_failure",{cardId:n,error:o.message}),o instanceof Kn)return Ua(o,"remove_card");throw o}}async function QA(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."};h.info("cards:set_default_attempt",{cardId:n});let r=`set-default-card:${n}`,s=`set ${await $y(n,t)} as default`;try{return await Te(async()=>{let o=await et(r,0,"",s,t,{forceRequired:!0}),i=await U.setDefaultCard(n,{attestation:o},t);return h.info("cards:set_default_success",{cardId:n}),i})}catch(o){if(h.error("cards:set_default_failure",{cardId:n,error:o.message}),o instanceof Kn)return Ua(o,"set_default_card");throw o}}async function eE(e){return h.info("auth:login_attempt"),Oy(`${La()}/login`,e)}function tE(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 nE(e={},t){let n;try{n=tE(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return Na(async()=>{let r=await Te(()=>Yp(U,et,{toolName:"start_session",userContext:t,capCentsOverride:n}));h.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 rE(){let e=Mn();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 sE(){return Na(async()=>{let e=Mn();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 Gi(U);h.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=Yk(e),r=ft(t.finalCumulativeMicros),s=r??(typeof t.finalCumulativeCents=="number"?BigInt(Math.max(0,t.finalCumulativeCents))*10000n:n.micros),o=Number(s/10000n);return h.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 ${Wk(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 oE(e){if(h.info("auth:add_card_attempt"),!await G.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 Oy(`${La()}/enroll-card?code=${encodeURIComponent(n)}`,e,"enrollment")}async function wy(){if(await G.clearAll(),de())try{await ji()}catch{}}async function iE(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};if(h.info("reset:attempt"),e.localOnly)return await wy(),h.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&&Et(r)){let s=await Ly(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}`};h.warn("reset:server_attestation_status_unavailable",{error:s})}try{await U.logout(void 0,t)}catch{}return await wy(),h.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 aE(e){let t=e.query?.trim()||void 0,n=e.category?.trim()||void 0,r=!t&&!n;h.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((f,m)=>`${m+1}. **${f.name}** (${f.id})
140
+ `),xm(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
+ `)}function zc(e){if(e.count<=0)return;let t=[],n=e.byReason.kill_switch??0,r=e.byReason.flag_state_unknown??0;n>0&&t.push(`${n} suppressed by kill switch`),r>0&&t.push(`${r} suppressed while feature-flag store is unreachable`);let s=e.count-n-r;s>0&&t.push(`${s} unavailable`);let o=t.length>0?t.join(", "):`${e.count} hidden`;console.log(`
142
+ Hidden: ${o}.`),n>0&&console.log("Inspect: `visa-cli tools --json` with query params `?available=all`, or check the admin Tool Hub flag list.")}var _={};Br(_,{BRAND:()=>wv,DIRTY:()=>rr,EMPTY_PATH:()=>Q0,INVALID:()=>D,NEVER:()=>ow,OK:()=>$e,ParseStatus:()=>Ae,Schema:()=>V,ZodAny:()=>An,ZodArray:()=>Yt,ZodBigInt:()=>or,ZodBoolean:()=>ir,ZodBranded:()=>ao,ZodCatch:()=>yr,ZodDate:()=>ar,ZodDefault:()=>hr,ZodDiscriminatedUnion:()=>Ei,ZodEffects:()=>Xe,ZodEnum:()=>pr,ZodError:()=>Fe,ZodFirstPartyTypeKind:()=>j,ZodFunction:()=>Ii,ZodIntersection:()=>dr,ZodIssueCode:()=>x,ZodLazy:()=>fr,ZodLiteral:()=>mr,ZodMap:()=>ns,ZodNaN:()=>ss,ZodNativeEnum:()=>gr,ZodNever:()=>it,ZodNull:()=>lr,ZodNullable:()=>At,ZodNumber:()=>sr,ZodObject:()=>He,ZodOptional:()=>ze,ZodParsedType:()=>C,ZodPipeline:()=>co,ZodPromise:()=>kn,ZodReadonly:()=>_r,ZodRecord:()=>Ri,ZodSchema:()=>V,ZodSet:()=>rs,ZodString:()=>Tn,ZodSymbol:()=>es,ZodTransformer:()=>Xe,ZodTuple:()=>Tt,ZodType:()=>V,ZodUndefined:()=>cr,ZodUnion:()=>ur,ZodUnknown:()=>Wt,ZodVoid:()=>ts,addIssueToContext:()=>k,any:()=>Iv,array:()=>Mv,bigint:()=>Av,boolean:()=>Lm,coerce:()=>sw,custom:()=>Om,date:()=>kv,datetimeRegex:()=>Pm,defaultErrorMap:()=>Kt,discriminatedUnion:()=>Dv,effect:()=>Jv,enum:()=>Wv,function:()=>qv,getErrorMap:()=>Xr,getParsedType:()=>xt,instanceof:()=>xv,intersection:()=>jv,isAborted:()=>ki,isAsync:()=>Zr,isDirty:()=>Ci,isValid:()=>xn,late:()=>Sv,lazy:()=>Kv,literal:()=>Gv,makeIssue:()=>io,map:()=>Hv,nan:()=>Tv,nativeEnum:()=>Yv,never:()=>$v,null:()=>Rv,nullable:()=>Zv,number:()=>Nm,object:()=>Nv,objectUtil:()=>Jc,oboolean:()=>rw,onumber:()=>nw,optional:()=>Xv,ostring:()=>tw,pipeline:()=>ew,preprocess:()=>Qv,promise:()=>zv,quotelessJson:()=>J0,record:()=>Fv,set:()=>Vv,setErrorMap:()=>Z0,strictObject:()=>Lv,string:()=>Mm,symbol:()=>Cv,transformer:()=>Jv,tuple:()=>Bv,undefined:()=>Ev,union:()=>Uv,unknown:()=>Pv,util:()=>q,void:()=>Ov});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 Jc;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Jc||(Jc={}));var C=q.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),xt=e=>{switch(typeof e){case"undefined":return C.undefined;case"string":return C.string;case"number":return Number.isNaN(e)?C.nan:C.number;case"boolean":return C.boolean;case"function":return C.function;case"bigint":return C.bigint;case"symbol":return C.symbol;case"object":return Array.isArray(e)?C.array:e===null?C.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?C.promise:typeof Map<"u"&&e instanceof Map?C.map:typeof Set<"u"&&e instanceof Set?C.set:typeof Date<"u"&&e instanceof Date?C.date:C.object;default:return C.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"]),J0=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),Fe=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()}};Fe.create=e=>new Fe(e);var X0=(e,t)=>{let n;switch(e.code){case x.invalid_type:e.received===C.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}},Kt=X0;var km=Kt;function Z0(e){km=e}function Xr(){return km}var io=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}},Q0=[];function k(e,t){let n=Xr(),r=io({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Kt?void 0:Kt].filter(s=>!!s)});e.common.issues.push(r)}var Ae=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"}),rr=e=>({status:"dirty",value:e}),$e=e=>({status:"valid",value:e}),ki=e=>e.status==="aborted",Ci=e=>e.status==="dirty",xn=e=>e.status==="valid",Zr=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 Je=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}},Cm=(e,t)=>{if(xn(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 Fe(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 xt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:xt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Ae,ctx:{common:t.parent.common,data:t.data,parsedType:xt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Zr(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:xt(t)},s=this._parseSync({data:t,path:r.path,parent:r});return Cm(r,s)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:xt(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return xn(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=>xn(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:xt(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(Zr(s)?s:Promise.resolve(s));return Cm(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 Xe({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 ze.create(this,this._def)}nullable(){return At.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yt.create(this)}promise(){return kn.create(this,this._def)}or(t){return ur.create([this,t],this._def)}and(t){return dr.create(this,t,this._def)}transform(t){return new Xe({...B(this._def),schema:this,typeName:j.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new hr({...B(this._def),innerType:this,defaultValue:n,typeName:j.ZodDefault})}brand(){return new ao({typeName:j.ZodBranded,type:this,...B(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new yr({...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 co.create(this,t)}readonly(){return _r.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},ev=/^c[^\s-]{8,}$/i,tv=/^[0-9a-z]+$/,nv=/^[0-9A-HJKMNP-TV-Z]{26}$/i,rv=/^[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,sv=/^[a-z0-9_-]{21}$/i,ov=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,iv=/^[-+]?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)?)??$/,av=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,cv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Xc,lv=/^(?:(?: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])$/,uv=/^(?:(?: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])$/,dv=/^(([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]))$/,fv=/^(([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])$/,mv=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,pv=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Rm="((\\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])))",gv=new RegExp(`^${Rm}$`);function Im(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 hv(e){return new RegExp(`^${Im(e)}$`)}function Pm(e){let t=`${Rm}T${Im(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 yv(e,t){return!!((t==="v4"||!t)&&lv.test(e)||(t==="v6"||!t)&&dv.test(e))}function _v(e,t){if(!ov.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 bv(e,t){return!!((t==="v4"||!t)&&uv.test(e)||(t==="v6"||!t)&&fv.test(e))}var Tn=class e extends V{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==C.string){let o=this._getOrReturnCtx(t);return k(o,{code:x.invalid_type,expected:C.string,received:o.parsedType}),D}let r=new Ae,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")av.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")Xc||(Xc=new RegExp(cv,"u")),Xc.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")rv.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")sv.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")ev.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")tv.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")nv.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"?Pm(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"?gv.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{code:x.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?hv(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"?iv.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"duration",code:x.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?yv(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"?_v(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"?bv(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"?mv.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"base64",code:x.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?pv.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}};Tn.create=e=>new Tn({checks:[],typeName:j.ZodString,coerce:e?.coerce??!1,...B(e)});function vv(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 sr=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)!==C.number){let o=this._getOrReturnCtx(t);return k(o,{code:x.invalid_type,expected:C.number,received:o.parsedType}),D}let r,s=new Ae;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"?vv(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)}};sr.create=e=>new sr({checks:[],typeName:j.ZodNumber,coerce:e?.coerce||!1,...B(e)});var or=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)!==C.bigint)return this._getInvalidInput(t);let r,s=new Ae;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:C.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}};or.create=e=>new or({checks:[],typeName:j.ZodBigInt,coerce:e?.coerce??!1,...B(e)});var ir=class extends V{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==C.boolean){let r=this._getOrReturnCtx(t);return k(r,{code:x.invalid_type,expected:C.boolean,received:r.parsedType}),D}return $e(t.data)}};ir.create=e=>new ir({typeName:j.ZodBoolean,coerce:e?.coerce||!1,...B(e)});var ar=class e extends V{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==C.date){let o=this._getOrReturnCtx(t);return k(o,{code:x.invalid_type,expected:C.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 Ae,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}};ar.create=e=>new ar({checks:[],coerce:e?.coerce||!1,typeName:j.ZodDate,...B(e)});var es=class extends V{_parse(t){if(this._getType(t)!==C.symbol){let r=this._getOrReturnCtx(t);return k(r,{code:x.invalid_type,expected:C.symbol,received:r.parsedType}),D}return $e(t.data)}};es.create=e=>new es({typeName:j.ZodSymbol,...B(e)});var cr=class extends V{_parse(t){if(this._getType(t)!==C.undefined){let r=this._getOrReturnCtx(t);return k(r,{code:x.invalid_type,expected:C.undefined,received:r.parsedType}),D}return $e(t.data)}};cr.create=e=>new cr({typeName:j.ZodUndefined,...B(e)});var lr=class extends V{_parse(t){if(this._getType(t)!==C.null){let r=this._getOrReturnCtx(t);return k(r,{code:x.invalid_type,expected:C.null,received:r.parsedType}),D}return $e(t.data)}};lr.create=e=>new lr({typeName:j.ZodNull,...B(e)});var An=class extends V{constructor(){super(...arguments),this._any=!0}_parse(t){return $e(t.data)}};An.create=e=>new An({typeName:j.ZodAny,...B(e)});var Wt=class extends V{constructor(){super(...arguments),this._unknown=!0}_parse(t){return $e(t.data)}};Wt.create=e=>new Wt({typeName:j.ZodUnknown,...B(e)});var it=class extends V{_parse(t){let n=this._getOrReturnCtx(t);return k(n,{code:x.invalid_type,expected:C.never,received:n.parsedType}),D}};it.create=e=>new it({typeName:j.ZodNever,...B(e)});var ts=class extends V{_parse(t){if(this._getType(t)!==C.undefined){let r=this._getOrReturnCtx(t);return k(r,{code:x.invalid_type,expected:C.void,received:r.parsedType}),D}return $e(t.data)}};ts.create=e=>new ts({typeName:j.ZodVoid,...B(e)});var Yt=class e extends V{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==C.array)return k(n,{code:x.invalid_type,expected:C.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 Je(n,i,n.path,a)))).then(i=>Ae.mergeArray(r,i));let o=[...n.data].map((i,a)=>s.type._parseSync(new Je(n,i,n.path,a)));return Ae.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)}};Yt.create=(e,t)=>new Yt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:j.ZodArray,...B(t)});function Qr(e){if(e instanceof He){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=ze.create(Qr(r))}return new He({...e._def,shape:()=>t})}else return e instanceof Yt?new Yt({...e._def,type:Qr(e.element)}):e instanceof ze?ze.create(Qr(e.unwrap())):e instanceof At?At.create(Qr(e.unwrap())):e instanceof Tt?Tt.create(e.items.map(t=>Qr(t))):e}var He=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)!==C.object){let l=this._getOrReturnCtx(t);return k(l,{code:x.invalid_type,expected:C.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 it&&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 Je(s,d,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof it){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 Je(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,f=await u.value;l.push({key:d,value:f,alwaysSet:u.alwaysSet})}return l}).then(l=>Ae.mergeObjectSync(r,l)):Ae.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 Qr(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 ze;)o=o._def.innerType;n[r]=o}return new e({...this._def,shape:()=>n})}keyof(){return $m(q.objectKeys(this.shape))}};He.create=(e,t)=>new He({shape:()=>e,unknownKeys:"strip",catchall:it.create(),typeName:j.ZodObject,...B(t)});He.strictCreate=(e,t)=>new He({shape:()=>e,unknownKeys:"strict",catchall:it.create(),typeName:j.ZodObject,...B(t)});He.lazycreate=(e,t)=>new He({shape:e,unknownKeys:"strip",catchall:it.create(),typeName:j.ZodObject,...B(t)});var ur=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 Fe(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 Fe(c));return k(n,{code:x.invalid_union,unionErrors:a}),D}}get options(){return this._def.options}};ur.create=(e,t)=>new ur({options:e,typeName:j.ZodUnion,...B(t)});var Gt=e=>e instanceof fr?Gt(e.schema):e instanceof Xe?Gt(e.innerType()):e instanceof mr?[e.value]:e instanceof pr?e.options:e instanceof gr?q.objectValues(e.enum):e instanceof hr?Gt(e._def.innerType):e instanceof cr?[void 0]:e instanceof lr?[null]:e instanceof ze?[void 0,...Gt(e.unwrap())]:e instanceof At?[null,...Gt(e.unwrap())]:e instanceof ao||e instanceof _r?Gt(e.unwrap()):e instanceof yr?Gt(e._def.innerType):[],Ei=class e extends V{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==C.object)return k(n,{code:x.invalid_type,expected:C.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=Gt(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 Zc(e,t){let n=xt(e),r=xt(t);if(e===t)return{valid:!0,data:e};if(n===C.object&&r===C.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=Zc(e[a],t[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===C.array&&r===C.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=Zc(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===C.date&&r===C.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var dr=class extends V{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=(o,i)=>{if(ki(o)||ki(i))return D;let a=Zc(o.value,i.value);return a.valid?((Ci(o)||Ci(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}))}};dr.create=(e,t,n)=>new dr({left:e,right:t,typeName:j.ZodIntersection,...B(n)});var Tt=class e extends V{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==C.array)return k(r,{code:x.invalid_type,expected:C.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 Je(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>Ae.mergeArray(n,i)):Ae.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Tt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Tt({items:e,typeName:j.ZodTuple,rest:null,...B(t)})};var Ri=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!==C.object)return k(r,{code:x.invalid_type,expected:C.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 Je(r,a,r.path,a)),value:i._parse(new Je(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?Ae.mergeObjectAsync(n,s):Ae.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:Tn.create(),valueType:t,typeName:j.ZodRecord,...B(n)})}},ns=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!==C.map)return k(r,{code:x.invalid_type,expected:C.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 Je(r,a,r.path,[l,"key"])),value:o._parse(new Je(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}}}};ns.create=(e,t,n)=>new ns({valueType:t,keyType:e,typeName:j.ZodMap,...B(n)});var rs=class e extends V{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==C.set)return k(r,{code:x.invalid_type,expected:C.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 Je(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)}};rs.create=(e,t)=>new rs({valueType:e,minSize:null,maxSize:null,typeName:j.ZodSet,...B(t)});var Ii=class e extends V{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==C.function)return k(n,{code:x.invalid_type,expected:C.function,received:n.parsedType}),D;function r(a,c){return io({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Xr(),Kt].filter(l=>!!l),issueData:{code:x.invalid_arguments,argumentsError:c}})}function s(a,c){return io({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Xr(),Kt].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 kn){let a=this;return $e(async function(...c){let l=new Fe([]),u=await a._def.args.parseAsync(c,o).catch(m=>{throw l.addIssue(r(c,m)),l}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,o).catch(m=>{throw l.addIssue(s(d,m)),l})})}else{let a=this;return $e(function(...c){let l=a._def.args.safeParse(c,o);if(!l.success)throw new Fe([r(c,l.error)]);let u=Reflect.apply(i,this,l.data),d=a._def.returns.safeParse(u,o);if(!d.success)throw new Fe([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:Tt.create(t).rest(Wt.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||Tt.create([]).rest(Wt.create()),returns:n||Wt.create(),typeName:j.ZodFunction,...B(r)})}},fr=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})}};fr.create=(e,t)=>new fr({getter:e,typeName:j.ZodLazy,...B(t)});var mr=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}};mr.create=(e,t)=>new mr({value:e,typeName:j.ZodLiteral,...B(t)});function $m(e,t){return new pr({values:e,typeName:j.ZodEnum,...B(t)})}var pr=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 $e(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})}};pr.create=$m;var gr=class extends V{_parse(t){let n=q.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==C.string&&r.parsedType!==C.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 $e(t.data)}get enum(){return this._def.values}};gr.create=(e,t)=>new gr({values:e,typeName:j.ZodNativeEnum,...B(t)});var kn=class extends V{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==C.promise&&n.common.async===!1)return k(n,{code:x.invalid_type,expected:C.promise,received:n.parsedType}),D;let r=n.parsedType===C.promise?n.data:Promise.resolve(n.data);return $e(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};kn.create=(e,t)=>new kn({type:e,typeName:j.ZodPromise,...B(t)});var Xe=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"?rr(c.value):n.value==="dirty"?rr(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"?rr(a.value):n.value==="dirty"?rr(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(!xn(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=>xn(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:n.value,value:a})):D);q.assertNever(s)}};Xe.create=(e,t,n)=>new Xe({schema:e,typeName:j.ZodEffects,effect:t,...B(n)});Xe.createWithPreprocess=(e,t,n)=>new Xe({schema:t,effect:{type:"preprocess",transform:e},typeName:j.ZodEffects,...B(n)});var ze=class extends V{_parse(t){return this._getType(t)===C.undefined?$e(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};ze.create=(e,t)=>new ze({innerType:e,typeName:j.ZodOptional,...B(t)});var At=class extends V{_parse(t){return this._getType(t)===C.null?$e(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};At.create=(e,t)=>new At({innerType:e,typeName:j.ZodNullable,...B(t)});var hr=class extends V{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===C.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};hr.create=(e,t)=>new hr({innerType:e,typeName:j.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...B(t)});var yr=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 Zr(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Fe(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Fe(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};yr.create=(e,t)=>new yr({innerType:e,typeName:j.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...B(t)});var ss=class extends V{_parse(t){if(this._getType(t)!==C.nan){let r=this._getOrReturnCtx(t);return k(r,{code:x.invalid_type,expected:C.nan,received:r.parsedType}),D}return{status:"valid",value:t.data}}};ss.create=e=>new ss({typeName:j.ZodNaN,...B(e)});var wv=Symbol("zod_brand"),ao=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}},co=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(),rr(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})}},_r=class extends V{_parse(t){let n=this._def.innerType._parse(t),r=s=>(xn(s)&&(s.value=Object.freeze(s.value)),s);return Zr(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};_r.create=(e,t)=>new _r({innerType:e,typeName:j.ZodReadonly,...B(t)});function Em(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Om(e,t={},n){return e?An.create().superRefine((r,s)=>{let o=e(r);if(o instanceof Promise)return o.then(i=>{if(!i){let a=Em(t,r),c=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=Em(t,r),a=i.fatal??n??!0;s.addIssue({code:"custom",...i,fatal:a})}}):An.create()}var Sv={object:He.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 xv=(e,t={message:`Input not instance of ${e.name}`})=>Om(n=>n instanceof e,t),Mm=Tn.create,Nm=sr.create,Tv=ss.create,Av=or.create,Lm=ir.create,kv=ar.create,Cv=es.create,Ev=cr.create,Rv=lr.create,Iv=An.create,Pv=Wt.create,$v=it.create,Ov=ts.create,Mv=Yt.create,Nv=He.create,Lv=He.strictCreate,Uv=ur.create,Dv=Ei.create,jv=dr.create,Bv=Tt.create,Fv=Ri.create,Hv=ns.create,Vv=rs.create,qv=Ii.create,Kv=fr.create,Gv=mr.create,Wv=pr.create,Yv=gr.create,zv=kn.create,Jv=Xe.create,Xv=ze.create,Zv=At.create,Qv=Xe.createWithPreprocess,ew=co.create,tw=()=>Mm().optional(),nw=()=>Nm().optional(),rw=()=>Lm().optional(),sw={string:(e=>Tn.create({...e,coerce:!0})),number:(e=>sr.create({...e,coerce:!0})),boolean:(e=>ir.create({...e,coerce:!0})),bigint:(e=>or.create({...e,coerce:!0})),date:(e=>ar.create({...e,coerce:!0}))};var ow=D;var iw=/^[A-Za-z0-9._-]+$/,aw=/^[A-Za-z0-9._-]+(\|[A-Za-z0-9._-]+)*$/,Um=new Set([".",".."]),je=class extends Error{pattern;constructor(t,n){super(`Invalid freeReadPathPattern ${JSON.stringify(n)}: ${t}`),this.pattern=n,this.name="FreePathPatternError"}};function cw(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 je(`malformed alternation segment ${JSON.stringify(e)}`,t);let s=n?e.slice(1,-2):e.slice(1,-1);if(!aw.test(s))throw new je(`malformed alternation segment ${JSON.stringify(e)}`,t);let o=s.split("|");if(o.some(i=>Um.has(i)))throw new je(`alternation segment ${JSON.stringify(e)} may not contain '.' or '..'`,t);return{raw:e,kind:n?"alt-optional":"alt",alternatives:o}}if(iw.test(e)){if(Um.has(e))throw new je(`literal segment ${JSON.stringify(e)} is not permitted`,t);return{raw:e,kind:"literal"}}throw new je(`segment ${JSON.stringify(e)} must be '*', '**', a [A-Za-z0-9._-]+ literal, or (a|b) alternation`,t)}function lw(e){if(typeof e!="string"||e.length===0)throw new je("must be a non-empty string",String(e));if(!e.startsWith("/"))throw new je("must start with '/'",e);if(e.slice(1).includes("//"))throw new je("empty segments ('//') are not permitted",e);if(e.length>1&&e.endsWith("/"))throw new je("must not end with '/'",e);let n=e.slice(1).split("/").map(o=>cw(o,e));if(n.filter(o=>o.kind==="multi").length>1)throw new je("at most one '**' is permitted per pattern",e);if(n[0]?.kind==="multi")throw new je("'**' 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 je("optional alternation '(...)?' is only allowed as the final segment",e);return n}function Qc(e){lw(e)}var Dm=["tempo","mpp_self","merchant_self"],jm=["catalog_static","fal_direct","fal_queue","openrouter_chat","openrouter_image","platform_proxy","tempo_gateway","x402_gateway"],Bm=["image","audio","queued_audio","video","queued_video","model_3d","llm","transcription","utility"],Fm=["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 tl=_.object({inputPerMillion:_.number().positive(),outputPerMillion:_.number().positive(),contextWindow:_.number().int().positive().optional(),maxOutput:_.number().int().positive().optional(),perRequestFeeCents:_.number().nonnegative().optional()}),uw=_.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:tl.optional()}).passthrough(),nl=_.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")})]),rl=_.object({amount:_.number().nonnegative(),currency:_.string().length(3).optional(),display:_.string().optional(),free:_.boolean().optional(),batchDiscount:_.number().min(0).max(100).optional()}),Hm=_.object({attestation:_.boolean().optional(),rateLimitMs:_.number().positive().optional()}),Vm=_.object({displayName:_.string().optional(),feedbackEligible:_.boolean().optional(),suggestionEligible:_.boolean().optional(),batchable:_.boolean().optional()}),qm=_.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(),dw=_.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),fw=120,mw=120,pw=1200,gw=/^[^\u0000-\u001F\u007F]+$/;function el(e,t){return _.string().min(1).max(e).regex(gw,`${t} must not contain control characters`)}var sl={id:_.string().min(1),name:el(fw,"name"),description:el(pw,"description"),provider:_.string().min(1),model:_.string().min(1),category:dw,priceCents:_.number().nonnegative(),inputSchema:_.record(_.unknown()),gatewayUrl:_.string().min(1),merchantName:el(mw,"merchantName"),isAsync:_.boolean().optional(),pollUrl:_.string().optional(),pollInterval:_.number().positive().optional(),pollTimeout:_.number().positive().optional(),tags:_.array(_.string()).optional(),tokenPricing:tl.optional(),priceDisplay:_.string().optional(),pricingModel:_.enum(["per-call","per-token","band"]).optional(),pricingInfo:uw.optional(),status:_.enum(["available","unavailable"]).optional(),handler:nl.optional(),pricing:rl.optional(),security:Hm.optional(),engagement:Vm.optional(),gatewayConfig:qm.optional(),freeReadPathPattern:_.string().optional().superRefine((e,t)=>{if(e!==void 0)try{Qc(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(Dm).optional(),executionKind:_.enum(jm).optional(),resultKind:_.enum(Bm).optional(),extractionMode:_.enum(Fm).optional(),pricingStrategy:_.enum(["flat","token","band"]).optional()},Km=_.object({...sl,dispatch:_.literal("routed"),routedPath:_.string().min(1).startsWith("/")}).strict(),Gm=_.object({...sl,dispatch:_.literal("enveloped")}).strict(),Wm=_.object({...sl,handler:nl,pricing:rl}).strict(),Ym=_.union([_.discriminatedUnion("dispatch",[Km,Gm]),Wm]);var ol=/^[a-z0-9][a-z0-9_-]*$/;var _w="https://fal.run",Zm="https://openrouter.mpp.tempo.xyz",al=1024,$i=8192,bw=4096,vw=10;function ww(e){return e>=vw?bw:$i}function Qm(e,t){let n=typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):al;return Math.min(n,t)}var Sw=["num_images","num_outputs","num_samples","num_videos","batch_size","n"];function ep(e){for(let t of Sw)delete e[t];return e}function xw(e){let{attestation:t,tool_id:n,...r}=e;return ep(r)}var zm={"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 Pi(e){let{attestation:t,tool_id:n,aspect_ratio:r,image_size:s,...o}=e,i=ep({...o});return typeof s=="string"&&s.length>0?(i.image_size=s,i):(typeof r=="string"&&zm[r]&&(i.image_size=zm[r]),i)}function Tw(e){let{attestation:t,tool_id:n,...r}=e;return r}function Jm(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 Aw(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 kw(e,t,n,r,s,o,i,a){return Aw(e,t,n,"suno-ai",r,s,o,i,{merchantName:"Suno AI",...a})}function ye(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:`${_w}/${r}`,merchantName:"fal.ai",buildBody:xw,tags:[],...a}}function tp(e,t=$i){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:f,...m}=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:f??.7,...m,model:e,max_tokens:Qm(c??l,t),usage:{include:!0}}}}function np(e,t=$i){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:f,image_config:m,temperature:p,...g}=n,v=[{type:"text",text:o}];return typeof i=="string"&&i.length>0&&v.push({type:"image_url",image_url:{url:i}}),{messages:Array.isArray(f)?f:[{role:"user",content:v}],temperature:p??.7,...g,model:e,...typeof a=="string"&&a.length>0?{image_config:{aspect_ratio:a}}:{},max_tokens:Qm(c??l,t),usage:{include:!0}}}}function le(e,t,n,r,s,o,i){let a=i?.maxOutputTokens??ww(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:f,maxOutputTokens:m,...p}=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: ${al}); 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:`${Zm}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:tp(r,a),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:s,outputPerMillion:o,...c>0?{perRequestFeeCents:c}:{}},...p}}function il(e,t,n,r,s,o){let i=o?.maxOutputTokens??$i,{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: ${al}); 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:`${Zm}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:np(r,i),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...c}}var cl=[ye("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"]}),ye("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:Pi}),ye("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:Pi}),ye("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:Pi}),ye("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"]}),il("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),il("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}}),il("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}}),ye("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"]}),ye("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"]}),ye("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"]}),ye("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"]}),ye("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"]}),ye("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"]}),ye("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"]}),ye("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"]}),ye("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"]}),kw("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}}}),ye("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"]}),ye("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"]}),ye("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"]}),ye("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-4-8","Claude Opus 4.8","Anthropic's newest flagship. 1M context, strongest reasoning + coding.","anthropic/claude-opus-4.8",15,75,{tags:["llm","claude","anthropic","reasoning","coding","newest"]}),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.8 Fast","Fast Opus variant with lower latency.","anthropic/claude-opus-4.8-fast",10,50,{tags:["llm","claude","anthropic","fast"]}),le("or-claude-haiku","Claude Haiku 4.5","Anthropic's fastest model. Great for quick tasks, chat, and simple reasoning.","anthropic/claude-haiku-4.5",1,5,{tags:["llm","claude","anthropic","fast"]}),le("or-gemini-pro","Gemini 2.5 Flash","Google's fast multimodal model. Good for general tasks with long context.","google/gemini-2.5-flash",.3,2.5,{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.1 Pro","Google's flagship frontier model for deep reasoning, multimodal analysis, and agentic coding.","google/gemini-3.1-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-2512",.5,1.5,{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:Jm,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:Tw,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=>Pi({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"]},ye("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"}),ye("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:Jm,tags:["onchain","prices","allium","crypto","legacy"]}];function os(e){return cl.find(t=>t.id===e)}var rp=1,sp=["pick_one","fan_out"],op=["concat","dedupe_by_url","top_k_by_score"],Rw=8,Iw=_.object({type:_.string().min(1),description:_.string().min(1),enum:_.array(_.string()).optional(),default:_.unknown().optional(),minimum:_.number().optional(),maximum:_.number().optional()}),Pw=_.object({toolId:_.string().min(1),notes:_.string().min(1)}),$w=_.string().regex(/^[a-z0-9_-]{1,32}$/,"tier key must be 1-32 chars [a-z0-9_-]"),Ow=_.object({providers:_.array(_.string().min(1)).min(1).max(Rw),merge:_.enum(op),maxResults:_.number().int().positive().optional()}),ip=_.object({mode:_.enum(sp).default("pick_one"),intro:_.string().min(1),defaultTier:_.string().min(1),tiers:_.record($w,Pw).refine(e=>Object.keys(e).length>0,{message:"must have at least one tier"}),fanOut:Ow.optional(),guidance:_.string().min(1),inputProperties:_.record(_.string(),Iw),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"]}),Mw=_.object({version:_.literal(rp),generatedAt:_.string().datetime(),tools:_.record(_.string().regex(ol,"tool name must match MCP naming rules"),ip).refine(e=>Object.keys(e).length>0,{message:"manifest must have at least one tool"})});var Nw=[{type:"integer",matches:e=>typeof e=="number"&&Number.isInteger(e),phrase:"an integer"},{type:"number",matches:e=>typeof e=="number"&&Number.isFinite(e),phrase:"a number"},{type:"string",matches:e=>typeof e=="string",phrase:"a string"},{type:"boolean",matches:e=>typeof e=="boolean",phrase:"a boolean"},{type:"array",matches:e=>Array.isArray(e),phrase:"an array"},{type:"object",matches:e=>typeof e=="object"&&e!==null&&!Array.isArray(e),phrase:"an object"}];function Lw(e,t){let r=(Array.isArray(t.type)?t.type:t.type!==void 0?[t.type]:[]).flatMap(o=>Nw.filter(i=>i.type===o)),s=new Set(r.filter(o=>o.matches(e)).map(o=>o.type));return{declared:r,matched:s}}function ll(e,t,n){if(n.enum&&!n.enum.includes(t))return`${e} must be one of: ${n.enum.map(String).join(", ")}.`;let{declared:r,matched:s}=Lw(t,n);if(r.length>0&&s.size===0)return`${e} must be ${r.map(o=>o.phrase).join(" or ")}.`;if(s.has("string")&&typeof t=="string"){if(t.trim()==="")return`${e} cannot be empty.`;if(n.minLength!==void 0&&t.length<n.minLength)return`${e} is too short.`;if(n.maxLength!==void 0&&t.length>n.maxLength)return`${e} is too long.`}if(typeof t=="number"){if(n.minimum!==void 0&&t<n.minimum)return`${e} must be at least ${n.minimum}.`;if(n.maximum!==void 0&&t>n.maximum)return`${e} must be at most ${n.maximum}.`}return null}var Ma=R(as());var Ui=require("child_process"),vp=require("util"),wp=R(require("crypto")),ne=R(require("fs")),Sp=R(require("os")),Oe=R(require("path"));wt();var ct=(0,vp.promisify)(Ui.execFile),uS=6e4,dS=()=>process.platform==="darwin",Cn=()=>process.platform==="win32",En=Oe.join(Sp.homedir(),".visa-mcp","bin"),br=Oe.join(En,"Visa CLI"),Xt=Oe.join(En,"visa-keychain-win.exe"),xp=Oe.join(__dirname,"..","native"),dp="6",fp=Oe.join(En,"visa-keychain.version"),mp=Oe.join(En,"visa-keychain.sha256"),pp="1",gp=Oe.join(En,"visa-keychain-win.version"),hp=Oe.join(En,"visa-keychain-win.sha256"),Tp=[Oe.join(xp,"bin","win32-x64","visa-keychain-win.exe"),Oe.resolve(__dirname,"..","..","native","bin","win32-x64","visa-keychain-win.exe"),Oe.resolve(__dirname,"..","native","bin","win32-x64","visa-keychain-win.exe")];function Mi(e){let t=ne.readFileSync(e);return wp.createHash("sha256").update(t).digest("hex")}function fS(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 yp(e){let t=typeof e?.message=="string"?e.message:"";return e?.code==="ETIMEDOUT"||e?.killed===!0||/timed out|timeout/i.test(t)}function _p(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 ul(){try{if(ne.readFileSync(fp,"utf-8").trim()===dp&&ne.existsSync(br)){let r=ne.readFileSync(mp,"utf-8").trim();if(Mi(br)!==r)h.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),ne.unlinkSync(br);else return br}}catch{}let e=Oe.join(xp,"visa-keychain.m");if(ne.existsSync(e)||(e=Oe.resolve(__dirname,"..","..","native","visa-keychain.m")),ne.existsSync(e)||(e=Oe.resolve(__dirname,"..","native","visa-keychain.m")),!ne.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");ne.mkdirSync(En,{recursive:!0,mode:448});try{await ct("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",br,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=Mi(br);return ne.writeFileSync(mp,t,{mode:384}),ne.writeFileSync(fp,dp,{mode:384}),br}function Ap(){for(let e of Tp)if(ne.existsSync(e))return e;return null}async function cs(){try{if(ne.readFileSync(gp,"utf-8").trim()===pp&&ne.existsSync(Xt)){let r=ne.readFileSync(hp,"utf-8").trim();if(Mi(Xt)!==r)h.warn("binary:hash-mismatch:win32",{message:"Windows binary hash mismatch. Redeploying."}),ne.unlinkSync(Xt);else return Xt}}catch{}let e=Ap();if(!e)throw new Error(`visa-keychain-win.exe not found in package. Reinstall @visa/cli.
143
+ If building from source, run native/build-win.bat first.`);ne.mkdirSync(En,{recursive:!0}),ne.copyFileSync(e,Xt);let t=Mi(Xt);return ne.writeFileSync(hp,t,{mode:384}),ne.writeFileSync(gp,pp,{mode:384}),Xt}async function mS(){return Cn()?cs():ul()}var Ni="visa-cli",Li="attestation-key";async function pS(e){try{await ct("security",["delete-generic-password","-s",Ni,"-a",Li],{timeout:5e3})}catch{}await ct("security",["add-generic-password","-s",Ni,"-a",Li,"-w",e],{timeout:5e3})}function gS(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 hS(){try{let{stdout:e}=await ct("security",["find-generic-password","-s",Ni,"-a",Li,"-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:gS(e)}}}async function dl(){let e=await hS();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 kp(e){let t=await mS(),n;try{n=(await ct(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 fS(n)}var bp=!1;function yS(){if(!Cn())return!1;try{return ne.existsSync(Xt)||Ap()!==null?!0:(bp||(bp=!0,h.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:Xt,searchedPrebuiltPaths:Tp})),!1)}catch{return!1}}function de(){return Fr()||dS()?!0:Cn()?yS():!1}async function Di(){if(Cn()){let s=await cs(),{stdout:o}=await ct(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 kp(["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 pS(n),r}async function ji(){if(Cn())try{let e=await cs(),{stdout:t}=await ct(e,["public-key"],{timeout:1e4});return t.trim().startsWith("OK:")}catch{return!1}return await dl()!==null}async function Cp(){if(Fr())return"mock-public-key-spki";if(Cn()){let n=await cs(),{stdout:r}=await ct(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 dl();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await ul();return new Promise((n,r)=>{let s=(0,Ui.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 Rn(e,t,n={}){if(Fr())return Promise.resolve(Ld());let r=n.timeoutMs??uS;if(Cn()){let a=await cs(),c=["sign",e];t&&c.push(t);let l;try{l=(await ct(a,c,{timeout:r})).stdout}catch(d){throw yp(d)?_p(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 dl();if(!s)throw new Error("Attestation key not found. Run setup to generate a new key.");let o=await ul(),i=["sign",e];return t&&i.push(t),new Promise((a,c)=>{let l=(0,Ui.execFile)(o,i,{timeout:r},(u,d)=>{let f=(d||"").trim();if(u){f.startsWith("ERROR:")?c(new Error(f.slice(6))):yp(u)?c(_p(r)):c(new Error(u.stderr?.trim()||u.message||"Unknown error"));return}f.startsWith("OK:")?a(f.slice(3)):c(new Error(f.startsWith("ERROR:")?f.slice(6):"Unknown error"))});l.stdin.write(s),l.stdin.end()})}async function Bi(){if(Cn()){try{let e=await cs();await ct(e,["delete-key"],{timeout:1e4})}catch{}return}try{await ct("security",["delete-generic-password","-s",Ni,"-a",Li],{timeout:5e3})}catch{}try{await kp(["delete-key"])}catch{}}wt();var _S=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],bS=[..._S.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 ml(e,t=bS){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=fl(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(fl(r.match.provider)))&&r.match.keywords.every(s=>n.includes(fl(s))))return r.targetToolId;return null}function fl(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}wt();qt();var uo={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_anthropic:{toolId:"or-claude-opus",notes:"Claude Opus 4.7. Anthropic frontier model for complex tasks."},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_anthropic (Claude Opus, highest quality Anthropic tier; warn user it is 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 In(e,t,n){if(!Rp(e))return xS(e,n);let r=Ep[e];if(!r)return e;let s=Object.keys(r.tiers),o=t||s[0],i=TS(e,o,n);return i||AS(e,r,o,s)}function xS(e,t){return ml({requestedTool:e,intentText:t})??e}function TS(e,t,n){return ml({requestedTool:e,metaTool:e,tier:t,intentText:n})}function AS(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 Ep=uo;function Rp(e){return e in Ep}var fo=Object.keys(uo);function pl(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function Ip(e=process.env){return pl(e)!==null}var kS=new Set(["false","0","no","off","disable","disabled"]),CS=new Set(["true","1","yes","on","enable","enabled"]);function Pp(e){let t=(e??"").trim().toLowerCase();return t?kS.has(t)?!1:!!CS.has(t):!0}function $p(e=process.env){return Pp(e.VISA_CLI_PARENTLESS_SINGLE_CALL)}function Op(e=process.env){return Pp(e.VISA_CLI_PARENTLESS_BATCH)}var Ay=require("child_process"),xe=R(require("crypto")),mt=R(require("fs")),$o=R(require("os")),Na=R(require("path"));function kt(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"?Hr(s):null,i=Array.isArray(n.urls)?n.urls[0]:void 0,c=typeof i=="string"&&i.startsWith("data:")?Hr(i):null;if(!o&&!c)return e;let l=o??c,u=o?"content":"urls",d;try{d=Ds(l,{tag:ES(r,n)})}catch(m){return{...n,_inline_media_warning:`Failed to persist inline media to disk: ${m instanceof Error?m.message:String(m)}`}}let f={...n,filePath:d.filePath,mime:d.mime,bytes:d.bytes};return u==="urls"?f.urls=void 0:(f.content=Array.isArray(n.content)?[...n.content]:[{}],f.content[0]={...f.content[0]??{},text:`[inline media saved to ${d.filePath}]`}),f}function ES(e,t){let n=typeof t.transactionId=="string"?t.transactionId:typeof t.transaction_id=="string"?t.transaction_id:null;return n?`${e}-${n}`:e}wt();var gl=!1;async function vr(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")||!de())throw r;if(h.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(gl)throw h.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;gl=!0,h.info("attestation:starting-browser-recovery");try{let o=await n();if(!o.success)throw h.error("attestation:browser-recovery-failed",{message:o.message}),r;let i=await Di();await e.registerAttestationKey(i),await e.setBiometricPreference({required:!0}),h.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),h.info("attestation:key-reregistered-after-recovery");let a=await t();return gl=!1,a}catch(o){throw h.error("attestation:recovery-failure",{error:o.message}),r}}throw r}}function Ct(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}async function Fi(e,t){if(!de())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 ji())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 Ct(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."}}qt();var Mp="3.4.8-rc.0";function hl(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function Hi(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=xi(t);return s!==void 0?{value:s,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function Ke(e){return e==null?"\u2014":e?"yes":"no"}function Vi(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function RS(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function IS(){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=Gc("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:qc,source:{kind:"default"}}}async function mo(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=Kc("auth.serverUrl"),i=Pe(),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:Ke(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:Ke(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:Ke(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:de(),formatted:Ke(de()),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:Vi(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:Vi(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:Vi(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:Vi(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 f=t?.cards?.find(y=>y.isDefault)??t?.cards?.[0];f&&r.push({key:"cards.default",value:{brand:f.brand??null,last4:f.last4},formatted:`${f.brand||"card"} \u2022\u2022\u2022\u2022 ${f.last4}`,source:{kind:"server"}});let m=IS();r.push({key:"credit.sessionCapCents",value:m.value,formatted:RS(m.value),source:m.source});let p=ym();p.length>0&&r.push({key:"settings.retired",value:p.map(y=>y.key),formatted:p.map(y=>y.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${p.map(y=>`visa-cli config unset ${y.key}`).join(" && ")}`});let g=Hi("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:g.value,formatted:Ke(g.value),source:g.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let v=Hi("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:v.value,formatted:Ke(v.value),source:v.source});let A=St(),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:!A,formatted:Ke(!A),source:b});let w=Hi("VISA_META_TOOLS","tools.meta","opt-in");r.push({key:"tools.meta",value:w.value,formatted:Ke(w.value),source:w.source,hint:"Meta-tools are deprecated and off by default. Re-enable with `visa-cli config set tools.meta true`. Restart Claude Code for changes to take effect."});let S=Hi("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:S.value,formatted:Ke(S.value),source:S.source});let E=process.env.VISA_DRY_RUN,I=Ip();if(r.push({key:"tools.dryRun",value:I,formatted:Ke(I),source:E===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:Mp,formatted:Mp,source:{kind:"default"}}),e.includeDev){let y=process.env.VISA_MOCK_KEYCHAIN,T=dn();r.push({key:"dev.mockKeychain",value:T,formatted:Ke(T),source:hl("VISA_MOCK_KEYCHAIN",!!y),hint:rc()});let z=process.env.VISA_MOCK_TOUCHID,Z=Fr();r.push({key:"dev.mockTouchid",value:Z,formatted:Ke(Z),source:hl("VISA_MOCK_TOUCHID",!!z),hint:rc()});let H=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!H,formatted:Ke(!!H),source:hl("VISA_CLI_DEBUG",!!H)})}return{entries:r,statusError:n}}function PS(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 Np(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}(${PS(o.source)})`),t.verbose&&o.hint&&s.push(` ${"\u21B3".padStart(n)} ${o.hint}`)}return s.join(`
144
+ `)}function Lp(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 Up(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"}]}}}qt();wt();var Pn=require("fs"),jp=require("os"),yl=require("path"),$S=(0,yl.join)((0,jp.homedir)(),".visa-mcp"),Dp=(0,yl.join)($S,"mcp-session-budget.json");function qi(){try{(0,Pn.existsSync)(Dp)&&(0,Pn.unlinkSync)(Dp)}catch{}}var bl=require("crypto"),ut=R(as()),Sr=null,Ge=0,On=0,Ve=0,$n=null,vl=null,wl=null,wr=Promise.resolve();function OS(e){return Number((0,ut.fromCents)(e))}function Fp(e){return(0,ut.toCents)((0,ut.micros)(BigInt(e)))}function Bp(e){return(0,ut.toWire)((0,ut.fromCents)(e))}function _l(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Ki(e){return typeof e=="string"&&/^\d+$/.test(e)}var MS=43,NS=new RegExp(`^[A-Za-z0-9_-]{${MS}}$`);function LS(e){return typeof e=="string"&&NS.test(e)}function US(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||Sr&&e.session_id!==Sr||typeof e.nonce!="string"||e.nonce.length===0||!LS(e.server_signature)||!_l(e.cumulative)||!_l(e.remaining)||!_l(e.delta)||e.cumulative<Ge||Ve>0&&e.cumulative>Ve||Ve>0&&e.remaining>Ve||e.cumulative_micros!==void 0&&!Ki(e.cumulative_micros)||e.remaining_micros!==void 0&&!Ki(e.remaining_micros)||e.delta_micros!==void 0&&!Ki(e.delta_micros)||e.reserved_micros!==void 0&&!Ki(e.reserved_micros))}function Zt(e){Sr=e,Ge=0,On=0,Ve=0,$n=null,vl=null,wl=null,wr=Promise.resolve()}function po(e){Ve=Math.max(0,Math.floor(e))}function Sl(){return Sr}function xl(e){if(!Sr)return null;let t=Ge+On;return Ve>0&&t>Ve&&(t=Ve),{session_budget_id:Sr,cumulative_micros:OS(t),nonce:(0,bl.randomUUID)(),idempotency_key:e||(0,bl.randomUUID)()}}function go(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 US(r)?(Ge=Math.max(Ge,r.cumulative),On=0,$n=r,r):null}function Hp(){return $n}function Tl(e){let t=Fp(e.cumulative_micros);Ge=Math.max(Ge,t),On=0;let n={status:"accepted",session_id:e.session_budget_id,cumulative:Ge,remaining:Math.max(0,Ve-Ge),delta:0,cumulative_micros:Bp(Ge),remaining_micros:Bp(Math.max(0,Ve-Ge)),delta_micros:"0",nonce:e.nonce};return $n=n,n}function ho(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,ut.toCents)((0,ut.micros)(n));if(!Number.isFinite(r)||r<0)return;vl=t;let s=e,o=typeof s.session_id=="string"?s.session_id:Sr??"";$n?(typeof s.remaining_micros=="string"&&/^\d+$/.test(s.remaining_micros)&&($n.remaining_micros=s.remaining_micros),typeof s.charged_micros=="string"&&/^\d+$/.test(s.charged_micros)&&($n.delta_micros=s.charged_micros)):$n={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 Vp(e){let t=e.receipt??null;wl={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:Fp(e.voucher.cumulative_micros),estimatedCumulativeCents:Gi(),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 qp(){return wl}function Kp(){return Ge}function Gp(){return vl}function Gi(){let e=Ge+On;return Ve>0&&e>Ve&&(e=Ve),e}function Al(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return wr=wr.then(()=>{On+=t}),wr}function yo(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return wr=wr.then(()=>{On=Math.max(0,On-t)}),wr}var DS=10,jS=1,fe=null,Wp=Promise.resolve();function kl(e){let t=Wp.catch(()=>{}).then(e);return Wp=t.then(()=>{},()=>{}),t}var Se=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 Cl(e,t,n){return kl(()=>Yp(e,t,n))}async function Yp(e,t,n){if(qi(),fe&&new Date(fe.expiresAt).getTime()>Date.now())return Sl()!==fe.budgetId&&(Zt(fe.budgetId),po(fe.totalCents)),h.info("mcp-session:active-hit",{budgetId:fe.budgetId,tool:n.toolName,remainingEstimatedCents:fe.totalCents-Gi()}),{budgetId:fe.budgetId,isFresh:!1,totalCents:fe.totalCents,requestedCapCents:fe.totalCents,appliedCapCents:fe.totalCents,clampedReason:null};fe&&(fe=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"?jS:DS,i=Math.max(o,Math.ceil(n.minRequiredCents??o));if(r.balanceCents<i)throw new Se(r.balanceCents,i);let a=n.capCentsOverride??vm(),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 m=d.error||"unknown error";throw new Error(`Failed to open credit session: ${m}`)}let f={budgetId:d.budget.id,expiresAt:d.budget.expiresAt,totalCents:d.budget.totalCents,createdAt:d.budget.createdAt};return fe=f,Zt(f.budgetId),po(f.totalCents),h.info("mcp-session:opened",{budgetId:f.budgetId,capCents:f.totalCents,requestedCapCents:a,clampedReason:l,sessionKind:s,expiresAt:f.expiresAt,tool:n.toolName}),{budgetId:f.budgetId,isFresh:!0,totalCents:f.totalCents,requestedCapCents:a,appliedCapCents:f.totalCents,clampedReason:l}}async function zp(e,t,n){return kl(async()=>{let s=Mn()?await Jp(e):null,o=await Yp(e,t,n);return{budgetId:o.budgetId,totalCents:o.totalCents,closedPrevious:s,requestedCapCents:o.requestedCapCents,appliedCapCents:o.appliedCapCents,clampedReason:o.clampedReason}})}async function Jp(e){let n=Mn()?.budgetId??Sl(),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){h.warn("mcp-session:close-server-failed",{budgetId:n,error:i?.message||String(i)})}return qi(),fe=null,Zt(null),{closedServerSide:r,budgetId:n,finalCumulativeCents:s,finalCumulativeMicros:o}}async function Wi(e){return kl(()=>Jp(e))}function Mn(){return qi(),fe?new Date(fe.expiresAt).getTime()<=Date.now()?(fe=null,Zt(null),null):{budgetId:fe.budgetId,totalCents:fe.totalCents,lastReceiptCumulative:Kp(),lastReceiptCumulativeMicros:Hp()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:Gp(),estimatedCumulative:Gi(),lastToolSpend:qp(),expiresAt:fe.expiresAt}:null}var Zp=R(as()),Xp=10000n;function BS(e){return e<=0n?0:Number((e+Xp-1n)/Xp)}function Qp(e){return BS((0,Zp.fromUsd)(e))}var Yi=R(as()),FS=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;function zi(e){if(typeof e!="string"||!FS.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,Yi.toDisplay)((0,Yi.fromCents)(s),{symbol:""})}}var Ji="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.",eg="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.";qt();var fy=Promise.resolve();function VA(e,t){if(e)try{let n=(0,Ma.fromWire)(e),r=n%10000n===0n?2:6;return(0,Ma.toDisplay)(n,{decimals:r})}catch{}return`$${(t/100).toFixed(2)}`}var my=!1,py=!1,gy=!1;function La(e){let t=fy.catch(()=>{}).then(e);return fy=t.then(()=>{},()=>{}),t}async function ky(e){let t=await Te(()=>Cl(U,et,{toolName:e.toolId,userContext:e.userContext}));await Al(e.estimatedAmountCents);let n=xl(e.idempotencyKey);if(!n)throw await yo(e.estimatedAmountCents),new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await XA(),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 Ht){let d=Math.min(Math.max(u.retryAfterSecs,0),5)*1e3;h.warn("mcp-session:lock-contended-retrying",{tool:e.toolId,retryAfterSecs:u.retryAfterSecs}),await new Promise(f=>setTimeout(f,d)),{data:s,voucherReceiptHeader:o}=await i()}else throw u}}catch(u){if(await yo(e.estimatedAmountCents),u instanceof Yr){if(h.warn("mcp-session:server-invalidated-budget",{code:u.code,budgetId:u.budgetId??t.budgetId,tool:e.toolId}),await Wi(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 gy||(gy=!0,console.error(`[visa-cli] Your session was closed by another process; reopened automatically as pay-as-you-go.
145
+ To require an explicit session approval instead, set VISA_REQUIRE_EXPLICIT_SESSION=true.`)),h.info("mcp-session:falling-back-to-payg",{code:u.code,tool:e.toolId}),Cy(e)}throw u instanceof Ht?(h.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=go(o)??(n?Tl(n):null);if(ho(s?.receipt_v2),Vp({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),Fu(s))return kt(s);let c=await Bu();if(e.idempotencyKey&&Hu(s,c,e.idempotencyKey))return kt(s);let l=c?Io(c):null;return kt(Vu(s,r,l))}function Qe(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function Pa(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(Pa).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${Pa(r)}`).join(",")}}`}function ju(e,t,n,r){let s=xe.createHash("sha256").update(`${n}:${Pa(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${s}`}function qA(e,t){return`${e}:${t}`}function KA(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 $a(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,s=ft(r),o=s!==null?s.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=KA(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),c=i!=null?String(i):a;return{batch_id:e,item_id:qA(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 Cy(e){return Te(()=>WA(e))}async function Ey(e,t,n){if(Fu(e))return kt(e);let r=await Bu();if(n&&Hu(e,r,n))return kt(e);let s=r?Io(r):null;return kt(Vu(e,t,s))}async function GA(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 et("shortcut_call",t,e.toolId,n,e.userContext);h.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 go(i),ho(o?.receipt_v2),h.info("parentless-single-call:completed",{tool:e.toolId}),Ey(o,e.beforeBalanceMicros,e.idempotencyKey)}async function WA(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 Se(n.balanceCents,t);let r=t,s=Io(n);if($p()&&!my){let u=e.idempotencyKey??xe.randomUUID();try{return await GA({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 vt)my=!0,h.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 et("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),po(a.budget.totalCents),h.info("on-demand-session:opened",{budgetId:c,capCents:a.budget.totalCents,tool:e.toolId});let l=!1;try{await Al(e.estimatedAmountCents);let u=xl(e.idempotencyKey);if(!u)throw await yo(e.estimatedAmountCents),new Error(`Internal: mintVoucher returned null after on-demand session-open ${c}`);let{data:d,voucherReceiptHeader:f}=await U.shortcutWithSession(e.toolId,u,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(go(f)||Tl(u),l=!0,ho(d?.receipt_v2),Fu(d))return kt(d);let m=await Bu();if(e.idempotencyKey&&Hu(d,m,e.idempotencyKey))return kt(d);let p=m?Io(m):null;return kt(Vu(d,s,p))}catch(u){throw l||await yo(e.estimatedAmountCents),u}finally{try{await U.closeSession(c)}catch(u){h.warn("on-demand-session:close-failed",{budgetId:c,error:u?.message||String(u)})}Zt(null),h.info("on-demand-session:closed",{budgetId:c,tool:e.toolId})}}async function Gn(e){return La(async()=>Mn()?ky(e):Cy(e))}function Ua(){return Pe()}var U=new qe(()=>G.getSessionToken());function ft(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function Io(e){return ft(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function YA(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 zA(e){let t=ft(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=ft(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=ft(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function Ro(e,t="INVALID_TOOL_PARAMS",n){return{success:!1,error_code:t,code:t,error:e,message:e,...n??{}}}function JA(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 XA(){try{let e=await U.getBalance();return e.success?Io(e):null}catch{return null}}async function Bu(){try{let e=await U.getBalance();return e.success?e:null}catch{return null}}function Fu(e){if(!e||e.success===!1)return!1;let t=ft(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=ft(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 Hu(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=ft(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 Vu(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 ZA="3.4.8-rc.0",FP=["","","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',"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Generate an image of a sunset over Tokyo" \u2192 discover_tools \u2192 execute_tool','\u2022 "Make a 4-second video of a penguin juggling" \u2192 discover_tools \u2192 execute_tool','\u2022 "Make a song about coding late at night" \u2192 discover_tools \u2192 execute_tool','\u2022 "Run a reasoning model on this prompt" \u2192 discover_tools \u2192 execute_tool','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
146
+ `);function pt(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=Vs(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(_m())return{opened:!1,url:t,blockedReason:"suppressed"};let n=yc();if(n.headless)return h.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let r=Zd(t,Ua());if(!r)return h.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let s=ef(r);return s?((0,Ay.execFile)(s.cmd,s.args,o=>{o&&h.warn(`Browser open failed: ${o.message}. URL: ${r}`)}),{opened:!0,url:r}):(h.info(`No browser command for platform "${$o.platform()}". URL: ${r}`),{opened:!1,url:r,blockedReason:"unsupported_platform"})}async function Te(e){return vr(U,e,Uy)}var Ry="get_cards",Iy="set_default_card";function QA(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 '${Ry}' to see enrolled cards and '${Iy}' to switch, then retry the original request.`}function ek(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 '${Ry}' to see enrolled cards and '${Iy}' to switch. Do not retry automatically.`}function gt(e,t){let n=e.retryable?QA(e.code,e.retryAfter):ek(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 tk(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 ks=null,nk=3e4;function Py(){ks=null}var Kn=class extends Error{constructor(n){super(`${Oa()} attestation is required for this action, but it is not available in this MCP process. `+qu());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function Da(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. `+qu()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function rk(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:Ji,agent_guidance:eg}}function Oa(){return process.platform==="darwin"?"Touch ID":"local biometric"}function qu(){return process.platform==="darwin"?"Run the action from an interactive terminal with Touch ID access, or call auth_recovery to re-sync a drifted local attestation key, 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. Call auth_recovery to re-sync a drifted local attestation key, or use reset with confirm:true to clear stale server biometric state through GitHub re-authentication."}async function sk(e){let t=Date.now();if(ks&&ks.expiresAt>t)return{required:ks.required,hasRegisteredKey:ks.hasRegisteredKey};try{let n=await U.getStatus(e),r=Ct(n),s=n.attestationRequired!==!1;return ks={required:s,hasRegisteredKey:r,expiresAt:t+nk},{required:s,hasRegisteredKey:r}}catch{return{required:!0,hasRegisteredKey:!0}}}async function et(e,t,n,r,s,o){if(!o?.forceRequired){let i=await sk(s);if(!i.required){h.info("attestation:skipped-by-server-policy",{context:e});return}if(!i.hasRegisteredKey){h.info("attestation:skipped-no-registered-key",{context:e});return}}if(!de())throw h.warn("attestation:unavailable",{context:e}),new Kn(e);h.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");h.info("touchid:prompt",{context:e,amount:t,merchant:n});let c=await Rn(a,r);return h.info("attestation:success",{context:e,amount:t,merchant:n}),{signature:c,nonce:i,amount:t,merchant:n}}catch(i){throw/cancel|dismiss/i.test(i.message??"")?(h.warn("attestation:cancelled",{context:e,merchant:n}),new Error("Touch ID was cancelled or dismissed. For automated environments (CI, scripts, MCP hooks without user present), run `visa-cli config biometric off` to enable paid calls without Touch ID.")):(h.error("attestation:failure",{context:e,amount:t,merchant:n,error:i.message}),i)}}var hy="[dry-run] https://placeholder.visa-cli.dev/image.png",ok=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"]),ik=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 ak(e,t){return t==="run_llm"||e.startsWith("or-")?"llm":t==="generate_image"||ok.has(e)?"image":t==="generate_video"||ik.has(e)?"video":ck(e)?"media":null}function ck(e){let t=os(e);return t?!ja(t):!1}function lk(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function uk(e){return e==="llm"?"OpenRouter":"fal.ai"}function Cs(e,t,n,r){let s={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:uk(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${lk(n)}`;return{...s,content:i,data:{content:i,model:t,dry_run:!0}}}return{...s,urls:[hy],data:{[e==="video"?"videoUrl":e==="image"?"imageUrl":"url"]:hy,metadata:{dry_run:!0}}}}async function Lu(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:xe.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){h.warn("dry_run:telemetry_failed",{tool:e.toolName,error:s?.message||String(s),mode:t})}}var dk="https://openrouter.ai/api/v1/chat/completions",fk="openrouter/free",mk=50,pk=15e3;function gk(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 hk(e,t,n){let r=process.env.OPENROUTER_API_KEY;if(!r)return h.warn("preflight:no_openrouter_key_falling_back_to_mock",{tool:e}),{result:Cs("llm",e,t,n),degraded:!0,resolvedModel:null};let s=gk(t),o;try{o=await bt(dk,{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:fk,messages:[{role:"user",content:s}],max_tokens:mk}),timeoutMs:pk})}catch(u){return h.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:Cs("llm",e,t,n),degraded:!0,resolvedModel:null}}if(!o.ok){let u=await o.text().catch(()=>"");return h.warn("preflight:openrouter_http_error_falling_back_to_mock",{tool:e,status:o.status,bodyExcerpt:u.slice(0,200)}),{result:Cs("llm",e,t,n),degraded:!0,resolvedModel:null}}let i;try{i=await o.json()}catch(u){return h.warn("preflight:openrouter_invalid_json_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:Cs("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 Oo(e,t,n,r){let s=pl();if(!s)return null;let o=ak(e,r);if(!o)return null;let i=Date.now();if(s==="mock"){let l=Cs(o,e,t,r);return await Lu({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:l,userContext:n,startedAt:i,mode:"mock"}),h.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:o,mode:s}),l}if(o!=="llm"){h.warn("preflight:not_supported_for_kind_falling_back_to_mock",{tool:e,kind:o});let l=Cs(o,e,t,r);return await Lu({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 hk(e,t,r);return await Lu({toolName:r??e,resolvedModel:c??(r&&r!==e?e:null),toolParams:t,result:a,userContext:n,startedAt:i,mode:"preflight"}),h.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:o,mode:s}),a}async function cn(e,t,n,r){let s=await U.paymentPreview({tool:e,url:t,...r&&Object.keys(r).length>0?{params:r}:{}},n);if(!s||!s.merchantName||s.amount===void 0||s.amount===null||s.amount<0)throw new Error("Could not determine payment amount and merchant. Try again.");if(!Number.isFinite(s.amount)||s.amount<0||s.amount>999999)throw new Error(`Invalid payment amount: ${s.amount}. Payment rejected for safety.`);return s}function ln(e){return Qp(e.amount)}function yk(e,t,n){return n.has(e.resolvedTool)?0:Math.max(1,ln(t[e.resolvedTool]))}function _k(){return Na.join($o.homedir(),".visa-mcp","allium-results")}var HP=16*1024,VP=50*1024*1024;function bk(){let e=_k();try{if(!mt.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=mt.readdirSync(e),n=0,r=0;for(let s of t)try{let o=mt.statSync(Na.join(e,s));o.isFile()&&(n+=o.size,r++)}catch{}return{file_count:r,size_bytes:n,path:e}}catch(t){return h.warn("allium:disk_usage_error",{error:t.message}),{file_count:0,size_bytes:0,path:e}}}var yy=3600*1e3,Uu=0;function vk(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function Mo(e){if(!bm()&&!(Date.now()<Uu))try{if(!await G.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}}),h.info("feed:submitted",{tool:e.tool,mediaType:e.mediaType,transactionId:e.transactionId})}catch(t){if(vk(t)){let n=Uu===0;Uu=Date.now()+yy,n&&h.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:yy});return}h.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function wk(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})`;h.info("payment:attempt",{tool:"get_visa_smi",amount:a,merchant:i});try{return await Te(async()=>{let l=await et("get_visa_smi",a,i,c),u=await U.getVisaSmi({state:n,county:r,start_date:s,end_date:o,attestation:l,idempotencyKey:xe.randomUUID()},t);return u.success?h.info("payment:success",{tool:"get_visa_smi",merchant:i,charged_cents:u.charged_cents}):h.warn("payment:declined",{tool:"get_visa_smi",merchant:i,message:u.error}),u})}catch(l){if(l instanceof he)return h.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:l.code,retryable:l.retryable}),gt(l,{amount:a,merchantName:i,description:"Visa SMI data"});throw h.error("payment:failure",{tool:"get_visa_smi",merchant:i,error:l.message}),l}}async function Sk(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 Oo("generate_image_card",e,t);if(n)return n;let r=await cn("generate_image_card",void 0,t),s=xe.randomUUID();h.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await Te(async()=>{let o;try{o=await Gn({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:ln(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof Se)return Qe(i);throw i}return h.info("payment:success",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>pt(i)),Mo({prompt:e.prompt,tool:"generate_image_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):h.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof he)return h.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),gt(o,r);throw un(o,{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName}),o}}async function xk(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 Oo("generate_image_fast_card",e,t);if(n)return n;let r=await cn("generate_image_fast_card",void 0,t),s=xe.randomUUID();h.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await Te(async()=>{let o;try{o=await Gn({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:ln(r),userContext:t,timeoutMs:6e4,idempotencyKey:s})}catch(i){if(i instanceof Se)return Qe(i);throw i}return h.info("payment:success",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>pt(i)),Mo({prompt:e.prompt,tool:"generate_image_fast_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):h.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof he)return h.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),gt(o,r);throw un(o,{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName}),o}}async function Tk(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 Oo("generate_video_tempo_card",e,t);if(n)return n;let r=await cn("generate_video_tempo_card",void 0,t),s=xe.randomUUID();h.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await Te(async()=>{let o;try{o=await Gn({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:ln(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof Se)return Qe(i);throw i}return h.info("payment:success",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>pt(i)),Mo({prompt:e.prompt,tool:"generate_video_tempo_card",mediaUrl:o.urls[0],mediaType:"video",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):h.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof he)return h.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),gt(o,r);throw un(o,{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName}),o}}async function Ak(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 cn("generate_music_tempo_card",void 0,t),r=xe.randomUUID();h.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await Te(async()=>{let s;try{s=await Gn({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:ln(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(o){if(o instanceof Se)return Qe(o);throw o}return h.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=>pt(o)),Mo({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,h.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):h.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof he)return h.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),gt(s,n);throw un(s,{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName}),s}}async function kk(e,t){let n=await cn("check_music_status_tempo_card",void 0,t),r=xe.randomUUID();h.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await Te(async()=>{let s;try{s=await Gn({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:ln(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof Se)return Qe(o);throw o}return h.info("payment:success",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),s.urls?.length&&s.urls.forEach(o=>pt(o)),s})}catch(s){if(s instanceof he)return h.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),gt(s,n);throw un(s,{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName}),s}}async function Ck(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 cn("query_onchain_prices",void 0,t),r=xe.randomUUID();h.info("payment:attempt",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName});try{return await Te(async()=>{let s;try{s=await Gn({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:ln(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof Se)return Qe(o);throw o}if(h.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 he)return h.warn("payment:declined",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),gt(s,n);throw un(s,{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName}),s}}var Ek=["generate_music_tempo_card"],As=10,_y=5,by=new Map;function vy(e){let t=by.get(e);if(t!==void 0)return t;let r=os(e)?.isAsync===!0||Ek.includes(e);return by.set(e,r),r}var Rk=36e4,Ik=18e4,Pk=15e3,$k=12e4,Ok=2e3;function Du(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}function Mk(e,t){return xe.createHash("sha256").update(`${e}:${Pa(t)}`).digest("hex")}function Nk(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,...$a(n,r,o)});let l=0,u=0n;if(o?.success!==!1){let d=ft(o?.amountMicros??o?.amount_micros),f=typeof o?.amount=="number"?o.amount:i?.amount??0;d!==null&&d>0n?u+=d:u+=BigInt(Math.round(f*1e6)),l+=f}return o?.urls&&o.urls.forEach(d=>pt(d)),{deltaCharged:l,deltaMicros:u}}function Lk(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,f=t.filter(A=>A?.success===!1).length,m=t.length-f,p=t.flatMap(A=>Array.isArray(A?.urls)?A.urls:[]),g=l>0n?Number(l)/1e6:Math.round((c+Number.EPSILON)*100)/100,v=m===0?"failure":f===0?"success":"partial";return h.info("payment:success",{tool:"batch",batchTool:o,count:n.length,totalAmount:a,totalCharged:g,merchant:i,successCount:m,failedCount:f,outcome:v,mode:d,batchId:u}),{success:m>0,outcome:v,batch_id:u,tool:s?r[0]:o,count:n.length,successCount:m,failedCount:f,totalCharged:g,...l>0n?{totalChargedMicros:l.toString(),amountMicros:l.toString(),amount_micros:l.toString()}:{},merchantName:i,results:t,...p.length?{urls:p}:{}}}async function Uk(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:f,batchId:m,userContext:p}=e,g=i,v=await U.getBalance();if(!v.success)throw new Error(`Could not read balance: ${v.error||"unknown error"}`);if(v.balanceCents<g)throw new Se(v.balanceCents,g);let A=`batch-${m}`,b=`spend up to $${(g/100).toFixed(2)} across a batch of ${t.length}`,{batchParentId:w}=await Te(async()=>{let y=await et("batch_open",g,A,b,p,{forceRequired:!0}),T=y?.nonce??(await U.getAttestationChallenge()).nonce;h.info("parentless-batch:open-attempt",{batchTool:l,count:t.length,approvedTotalCents:g,attested:!!y});let{batch_parent_id:z}=await U.batchOpen({...y?{attestation:y}:{},nonce:T,approved_total_cents:g,batch_id:m});return{batchParentId:z}});h.info("parentless-batch:opened",{batchTool:l,count:t.length,batchParentId:w});let S=[],E=0,I=0n;try{for(let y=0;y<t.length;y+=1){let T=t[y],z=n[T.resolvedTool],Z=r.has(T.resolvedTool);try{let H;if(Z)H=await U.shortcut(T.resolvedTool,T.params,f,p,"batch");else{let{data:X,voucherReceiptHeader:Ms}=await U.shortcutParentlessBatchItem(T.resolvedTool,{batch_parent_id:w,batch_id:m,batch_index:y,batch_request_hash:Mk(T.resolvedTool,T.params),item_ceiling_cents:o[y],idempotency_key:ju(m,y,T.resolvedTool,T.params)},T.params,f,p,"batch");go(Ms),ho(X?.receipt_v2),H=await Ey(X,null,ju(m,y,T.resolvedTool,T.params))}let{deltaCharged:be,deltaMicros:se}=Nk({results:S,batchId:m,index:y,item:T,itemResult:H,preview:z,isFree:Z,catalogName:s[T.resolvedTool]?.name});E+=be,I+=se}catch(H){if(H instanceof Se&&S.length===0)return Qe(H);h.warn("payment:batch-item-failed",{tool:T.resolvedTool,index:y,error:H?.message||String(H)}),S.push({success:!1,tool:T.resolvedTool,...$a(m,y),error:H?.message||String(H)})}}return Lk({results:S,resolvedItems:t,uniqueTools:a,isHomogeneous:c,primaryTool:l,merchantNames:u,totalAmount:d,totalCharged:E,totalChargedMicros:I,batchId:m,mode:"parentless"})}catch(y){if(y instanceof he)return h.warn("payment:declined",{tool:"batch",batchTool:l,count:t.length,totalAmount:d,merchant:u,code:y.code,retryable:y.retryable}),gt(y,{amount:d,merchantName:u});throw un(y,{tool:"batch",batchTool:l,count:t.length,totalAmount:d,merchant:u}),y}}async function Dk(e,t){let n;if(Array.isArray(e.requests)&&e.requests.length>As)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${As} 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 z=In(T,y.tier||e.tier,y.prompt??t),{tool:Z,tool_id:H,tier:be,params:se,...X}=y,Ms=se&&typeof se=="object"?{...se,...X}:X;return{resolvedTool:z,params:Ms}});else if(e.tool){let y=In(e.tool,e.tier,e.params?.prompt??t);if(e.count!==void 0){if(!Number.isSafeInteger(e.count)||e.count<1)return Du("BATCH_INVALID_COUNT","Batch count must be a positive integer.");if(e.count>As)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${As} items. Please split into smaller batches.`}}n=(e.requests||(e.count!==void 0&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(z=>({resolvedTool:y,params:z}))}else return Du("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return Du("BATCH_EMPTY","Batch requires at least one item.");if(n.length>As)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${As} items. Please split into smaller batches.`};if([...new Set(n.map(y=>y.resolvedTool))].some(vy)&&n.length>_y)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${_y} 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 Dy(y);let l=new Set(i.filter(y=>c[y]&&ja(c[y]))),u={};for(let y of i)l.has(y)||(u[y]=await cn(y,void 0,t));let d=0;for(let y of n)d+=u[y.resolvedTool]?.amount??0;let f=n.map(y=>yk(y,u,l)),m=f.reduce((y,T)=>y+T,0),p=[...new Set([...Object.values(u).map(y=>y.merchantName),...i.filter(y=>l.has(y)).map(y=>c[y]?.name??y)])].join(", "),g=a?i[0]:"mixed";h.info("payment:attempt",{tool:"batch",batchTool:g,count:n.length,totalAmount:d,merchant:p,heterogeneous:!a});let v=n.some(y=>vy(y.resolvedTool)),A=n.some(y=>y.resolvedTool.startsWith("or-")||y.resolvedTool==="run_llm"||y.resolvedTool==="execute_tool"),b=v?Rk:A?Ik+n.length*Pk:$k+n.length*Ok,w=xe.randomUUID(),S=[],E=0,I=0n;return La(async()=>{let y=!Mn();if(Op()&&!py&&y&&m>0)try{return await Uk({resolvedItems:n,previews:u,freeTools:l,catalogEntries:c,itemCeilingCents:f,batchCeilingCents:m,uniqueTools:i,isHomogeneous:a,primaryTool:g,merchantNames:p,totalAmount:d,timeoutMs:b,batchId:w,userContext:t})}catch(T){if(T instanceof vt)py=!0,h.info("parentless-batch:falling-back-to-session",{batchTool:g,count:n.length,status:T.status,serverErrorCode:T.serverErrorCode});else{if(T instanceof Se)return Qe(T);throw T}}if(y&&m>0)try{let T=m;await Te(()=>Cl(U,et,{toolName:"batch",userContext:t,sessionKind:"one_shot",minRequiredCents:T,capCentsOverride:T}))}catch(T){return T instanceof Se?Qe(T):(h.warn("payment:batch-prewarm-failed",{batchTool:g,count:n.length,error:T?.message||String(T)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:T?.message||"Failed to authenticate batch session",tool:g,count:n.length,failedCount:n.length,results:[]})}try{for(let se=0;se<n.length;se+=1){let X=n[se],Ms=u[X.resolvedTool];try{let ue=l.has(X.resolvedTool)?await U.shortcut(X.resolvedTool,X.params,b,t,"batch"):await ky({toolId:X.resolvedTool,toolParams:X.params,estimatedAmountCents:f[se],userContext:t,metaTool:"batch",timeoutMs:b,idempotencyKey:ju(w,se,X.resolvedTool,X.params)});if(l.has(X.resolvedTool)&&ue&&typeof ue=="object"&&!Array.isArray(ue)&&ue.merchantName==null&&(ue.merchantName=c[X.resolvedTool]?.name??X.resolvedTool),S.push({success:ue?.success!==!1,tool:X.resolvedTool,...ue,...$a(w,se,ue)}),ue?.success!==!1){let Ns=ft(ue?.amountMicros??ue?.amount_micros),kd=typeof ue?.amount=="number"?ue.amount:Ms?.amount??0;Ns!==null&&Ns>0n?I+=Ns:I+=BigInt(Math.round(kd*1e6)),E+=kd}ue?.urls&&ue.urls.forEach(Ns=>pt(Ns))}catch(ue){if(ue instanceof Se&&S.length===0)return Qe(ue);h.warn("payment:batch-item-failed",{tool:X.resolvedTool,index:se,error:ue?.message||String(ue)}),S.push({success:!1,tool:X.resolvedTool,...$a(w,se),error:ue?.message||String(ue)})}}let T=S.filter(se=>se?.success===!1).length,z=S.length-T,Z=S.flatMap(se=>Array.isArray(se?.urls)?se.urls:[]),H=I>0n?Number(I)/1e6:Math.round((E+Number.EPSILON)*100)/100,be=z===0?"failure":T===0?"success":"partial";return h.info("payment:success",{tool:"batch",batchTool:g,count:n.length,totalAmount:d,totalCharged:H,merchant:p,successCount:z,failedCount:T,outcome:be,mode:"session",batchId:w}),{success:z>0,outcome:be,batch_id:w,tool:a?i[0]:g,count:n.length,successCount:z,failedCount:T,totalCharged:H,...I>0n?{totalChargedMicros:I.toString(),amountMicros:I.toString(),amount_micros:I.toString()}:{},merchantName:p,results:S,...Z.length?{urls:Z}:{}}}catch(T){if(T instanceof he)return h.warn("payment:declined",{tool:"batch",batchTool:g,count:n.length,totalAmount:d,merchant:p,code:T.code,retryable:T.retryable}),gt(T,{amount:d,merchantName:p});throw un(T,{tool:"batch",batchTool:g,count:n.length,totalAmount:d,merchant:p}),T}finally{if(y){let T=await Wi(U);h.info("batch-session:closed",{budgetId:T.budgetId,closedServerSide:T.closedServerSide})}}})}function jk(){let e=!1,t;try{let r=Na.join($o.homedir(),".claude","settings.json");if(mt.existsSync(r)){let s=JSON.parse(mt.readFileSync(r,"utf-8")),o=typeof s.statusLine=="object"?s.statusLine.command:"";e=bn(o)}}catch{}let n=ci();return n||(t="visa-cli config hud enable"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function Bk(e){let[t,n]=await Promise.all([U.getStatus(e),U.getBalance().catch(o=>(h.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=bk();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=jk(),!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=ZA,Array.isArray(t.cards)&&(t.cards=t.cards.map(o=>({...o,displayName:Ku(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=Mn();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 Ku(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 $y(e,t){try{let r=((await U.getStatus(t)).cards||[]).find(s=>s?.id===e);if(r)return Ku(r)}catch(n){h.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function Fk(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:Ku(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 Hk(e,t){return await U.getTransactions({limit:e.limit,offset:e.offset},t)}async function Vk(e,t){return await U.feedback(e.message,e.transaction_id,t)}async function qk(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Lr("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=zi(String(e.amount));if(n.ok===!1)return{success:!1,error:n.error};let r=n.cents,s=r/100,o=xe.randomUUID();h.info("buy_credits:attempt",{amountCents:r});try{return await Te(async()=>{let i=await et("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){h.info("buy_credits:success",{amountCents:r,balanceCents:a.balanceCents,balanceMicros:a.balanceMicros});let c=VA(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 h.warn("buy_credits:failed",{amountCents:r,error:a.error}),a})}catch(i){if(i instanceof Kn)return rk();if(i instanceof st)return h.warn("buy_credits:ambiguous",{amountCents:r,code:i.code,transactionId:i.transactionId}),tk(i);throw h.error("buy_credits:failure",{amountCents:r,error:i.message}),i}}function Lr(e,t){return{success:!1,error:t,code:e,message:t}}async function Kk(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Lr("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 Lr("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 Lr("INVALID_VALUE","dailyLimit must be at least $1");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return Lr("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");h.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await Te(async()=>{let n=await et("spending-controls",0,"","update spending controls"),r=await U.updateSpendingControls({maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit,confirm:!0,attestation:n},t);return h.info("spending_controls:success",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit}),r})}catch(n){if(h.error("spending_controls:failure",{error:n.message}),n instanceof Kn)return Da(n,"update_spending_controls");if(String(n?.message||n).includes("Attestation required"))return Lr("ATTESTATION_REQUIRED","Changing spending controls requires local attestation, even when payment biometric prompts are disabled.");throw n}}async function Gk(e){let t=await mo({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 Gu=new Set(["auth.serverUrl"]);function Po(){return Object.keys(nr).filter(e=>!Gu.has(e)).sort()}function Oy(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:Po()}}async function Wk(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(Gu.has(e.key))return h.warn("config:set:rejected:mcp-forbidden",{key:e.key}),Oy(e.key,"set");h.info("config:set",{key:e.key});try{let t=Ti(e.key,e.value);return h.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 ot?"UNKNOWN_KEY":t instanceof Vt?"SERVER_CONTROLLED":t instanceof vn?"RETIRED_KEY":"INVALID_VALUE",r=t instanceof ot?`Unknown setting "${e.key}". MCP-settable keys: ${Po().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return h.warn("config:set:rejected",{key:e.key,code:n,error:r}),{success:!1,error:r,code:n,settableKeys:Po()}}}async function Yk(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(Gu.has(e.key))return h.warn("config:unset:rejected:mcp-forbidden",{key:e.key}),Oy(e.key,"unset");h.info("config:unset",{key:e.key});try{let t=Ai(e.key);return h.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 ot?"UNKNOWN_KEY":t instanceof Vt?"SERVER_CONTROLLED":t instanceof vn?"RETIRED_KEY":"INVALID_VALUE",r=t instanceof ot?`Unknown setting "${e.key}". MCP-settable keys: ${Po().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return h.warn("config:unset:rejected",{key:e.key,code:n,error:r}),{success:!1,error:r,code:n,settableKeys:Po()}}}async function zk(e){let t=await U.getStatus(e),n=t.attestationRequired!==!1,r=Ct(t),s=de(),o=n?r?s?`${Oa()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${Oa()} is not available in this process. ${qu()}`:"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 Jk(e){h.info("biometric:on");let t=await Fi(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?(Py(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:n.error||"unknown error"}}async function Xk(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Lr("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.");h.info("biometric:off");try{return await Te(async()=>{let n=await U.getStatus(t),r;if(Ct(n)&&(r=await et("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${Oa()} 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 Py(),{success:!0,required:!1,message:"Touch ID is no longer required for payments."}})}catch(n){if(h.error("biometric:off:failure",{error:n.message}),n instanceof Kn)return Da(n,"biometric_off");throw n}}var wy=3e4,Zk=3e5;async function My(e,t,n="login"){let r=xe.randomUUID(),s=`${e}${e.includes("?")?"&":"?"}state=${r}`,o=pt(s);return!o.opened&&o.blockedReason!=="non_internal_host"&&o.blockedReason!=="invalid_url"?Ny(s,o,n):o.opened?{...await Ly(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 Ny(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 Ly(e,t,n="login"){let r=Date.now()+Zk;for(;Date.now()<r;)try{let o=await fetch(`${Ua()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:wy,...t&&{user_context:t}}),signal:AbortSignal.timeout(wy+5e3)});if(!o.ok){await hn(o,a=>{h.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 h.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=Up(a);if(n!=="enrollment"&&i.sessionToken){await G.saveSessionToken(i.sessionToken);let u=i.user||"",d=i.last4||"****";return h.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 h.info("auth:card_added",{last4:l,bonusCents:a}),{success:!0,message:`Card ending in ${l} enrolled and ready for payments.`,...c||{}}}}catch{await hn(void 0,o=>{h.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 Uy(e){let t=xe.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=pt(n.recoveryUrl);return!r.opened&&r.blockedReason!=="non_internal_host"&&r.blockedReason!=="invalid_url"?Ny(n.recoveryUrl,r,"attestation-recovery"):r.opened?{...await Ly(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 Qk(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."};h.info("cards:remove_attempt",{cardId:n});let r=`remove-card:${n}`,s=`remove ${await $y(n,t)}`;try{return await Te(async()=>{let o=await et(r,0,"",s,t,{forceRequired:!0}),i=await U.removeCard(n,{attestation:o},t);return h.info("cards:remove_success",{cardId:n,promotedId:i?.promotedId??null}),i})}catch(o){if(h.error("cards:remove_failure",{cardId:n,error:o.message}),o instanceof Kn)return Da(o,"remove_card");throw o}}async function eC(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."};h.info("cards:set_default_attempt",{cardId:n});let r=`set-default-card:${n}`,s=`set ${await $y(n,t)} as default`;try{return await Te(async()=>{let o=await et(r,0,"",s,t,{forceRequired:!0}),i=await U.setDefaultCard(n,{attestation:o},t);return h.info("cards:set_default_success",{cardId:n}),i})}catch(o){if(h.error("cards:set_default_failure",{cardId:n,error:o.message}),o instanceof Kn)return Da(o,"set_default_card");throw o}}async function tC(e){return h.info("auth:login_attempt"),My(`${Ua()}/login`,e)}function nC(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 rC(e={},t){let n;try{n=nC(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return La(async()=>{let r=await Te(()=>zp(U,et,{toolName:"start_session",userContext:t,capCentsOverride:n}));h.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 sC(){let e=Mn();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 oC(){return La(async()=>{let e=Mn();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 Wi(U);h.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=zA(e),r=ft(t.finalCumulativeMicros),s=r??(typeof t.finalCumulativeCents=="number"?BigInt(Math.max(0,t.finalCumulativeCents))*10000n:n.micros),o=Number(s/10000n);return h.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 ${YA(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 iC(e){if(h.info("auth:add_card_attempt"),!await G.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 My(`${Ua()}/enroll-card?code=${encodeURIComponent(n)}`,e,"enrollment")}async function Sy(){if(await G.clearAll(),de())try{await Bi()}catch{}}async function aC(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};if(h.info("reset:attempt"),e.localOnly)return await Sy(),h.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&&Ct(r)){let s=await Uy(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}`};h.warn("reset:server_attestation_status_unavailable",{error:s})}try{await U.logout(void 0,t)}catch{}return await Sy(),h.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 cC(e){let t=e.query?.trim()||void 0,n=e.category?.trim()||void 0,r=!t&&!n;h.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((f,m)=>`${m+1}. **${f.name}** (${f.id})
147
147
  ${f.description}
148
- Provider: ${f.provider} | Price: ${Sy(f)}${xy(f)}
148
+ Provider: ${f.provider} | Price: ${xy(f)}${Ty(f)}
149
149
  Params: ${Object.keys(f.inputSchema?.properties||f.inputSchema||{}).join(", ")||"none"}`).join(`
150
150
 
151
151
  `);return`## ${l.length<=3?l.toUpperCase():l.charAt(0).toUpperCase()+l.slice(1)}
@@ -158,61 +158,61 @@ ${c}
158
158
 
159
159
  Use execute_tool with the tool id and required params to run any of these.`}],_tools:o}}let i=o.map((a,c)=>`${c+1}. **${a.name}** (${a.id})
160
160
  ${a.description}
161
- Provider: ${a.provider} | Category: ${a.category} | Price: ${Sy(a)}${xy(a)}
161
+ Provider: ${a.provider} | Category: ${a.category} | Price: ${xy(a)}${Ty(a)}
162
162
  Params: ${Object.keys(a.inputSchema?.properties||a.inputSchema||{}).join(", ")||"none"}`).join(`
163
163
 
164
164
  `);return h.info("catalog:discovered",{count:o.length}),{content:[{type:"text",text:`Found ${o.length} tool(s):
165
165
 
166
166
  ${i}
167
167
 
168
- Use execute_tool with the tool id and required params to run any of these.`}],_tools:o}}catch(s){throw h.error("catalog:discover:error",{error:s.message}),new Error(`Failed to search tool catalog: ${s.message}`)}}function Sy(e){return e.priceDisplay??`$${(e.priceCents/100).toFixed(2)}`}function xy(e){let t=e.protocol;return t==="mpp"||t==="x402"?" | Paid from your prepaid balance":""}function cE(e,t){return t==="image"||t==="video"||t==="audio"?t:e?.match(/\.(mp4|webm|mov)/)?"video":"image"}function lE(e,t,n){let r=e.inputSchema;if(!r||r.type!=="object")return null;let s=r.properties??{},o=n??e.id;if(r.additionalProperties!==!0){for(let a of Object.keys(t))if(!Object.prototype.hasOwnProperty.call(s,a)){let c=Object.keys(s),l=c.length>0?` Expected: ${c.join(", ")}.`:"";return`Unknown parameter "${a}" for ${o}.${l}`}}let i=(r.required??[]).filter(a=>!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0);if(i.length>1)return`${i.join(", ")} are required for ${o}.`;for(let a of r.required??[]){if(!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0)return`${a} is required for ${o}.`;if(t[a]===null)return`${a} cannot be null.`;if(typeof t[a]=="string"&&t[a].trim()==="")return`${a} cannot be empty.`}for(let[a,c]of Object.entries(t)){let l=s[a];if(!l||c===void 0||c===null)continue;let u=cl(a,c,l);if(u)return u}return null}async function Uy(e){let t=os(e);if(t)return t;try{return await U.catalogTool(e)}catch(n){return h.warn("catalog:resolve:error",{tool:e,error:n?.message||String(n)}),null}}function Da(e){let t=e.executionMode,n=e.accessMode,r=e.pricingMode;if(typeof t=="string"&&t.startsWith("paid")||n==="paid"||r==="fixed"||r==="dynamic"||r==="token")return!1;let s=e.priceCents,o=e.pricing;return t==="free_authenticated"||n==="free"||o?.free===!0||s===0||o?.amount===0}function uE(e){let t=e;return t.platformRoute===!0||typeof t.platformMerchantSlug=="string"||t.executionKind==="platform_proxy"}function dE(e){let n=e.inputSchema?.properties;return!!n&&typeof n=="object"&&Object.keys(n).length>0}function fE(e){return Da(e)&&uE(e)&&!dE(e)}function mE(e){return e.split(/[-_]/).filter(t=>t.length>0&&!/^[0-9a-f]{8,}$/i.test(t)).join(" ").trim()}async function pE(e){let t=mE(e);if(!t)return[];try{return((await U.catalogSearch(t,void 0)).tools||[]).filter(r=>r.id!==e).slice(0,3).map(r=>({tool_id:r.id,name:r.name}))}catch(n){return h.warn("catalog:suggest:error",{tool:e,error:n?.message||String(n)}),[]}}async function gE(e,t,n="execute_tool"){let{tool_id:r,params:s,...o}=e,i=s||o;if(!r)return Co("tool_id is required. Use discover_tools first to find available tools.","MISSING_TOOL_ID");h.info("catalog:execute",{tool:r,metaTool:n});let a=await Uy(r);if(!a){let p=await pE(r),g=p.length?` Did you mean: ${p.map(v=>v.tool_id).join(", ")}?`:"";return Co(`Unknown tool: '${r}'.${g} Use discover_tools first to find available tools.`,"UNKNOWN_TOOL",p.length?{suggestions:p}:void 0)}if(a.deprecated){let p=a.replacementTool?` Use '${a.replacementTool}' instead.`:"";return Co(`Tool '${r}' is deprecated and is no longer available for new paid calls.${p}`,"DEPRECATED_TOOL")}if(a.status==="unavailable"){let p=a.unavailableReason,g=a.killSwitchFlag,v=p==="flag_state_unknown"?`Tool '${r}' is temporarily unavailable: feature flag state could not be resolved.`:`Tool '${r}' is temporarily disabled.`;return h.info("catalog:execute:surface_disabled",{tool:r,metaTool:n,unavailableReason:p??null,killSwitchFlag:g??null}),Co(v,"SURFACE_DISABLED",{tool_id:r,...p?{unavailable_reason:p}:{},...g?{flag:g}:{}})}let l=n&&n!=="execute_tool"?n:void 0,u=fE(a)?null:lE(a,i,l);if(u)return h.info("catalog:execute:validation_failed",{tool:r,metaTool:n,error:u}),Co(u);let d=await Po(r,i,t,n);if(d)return d;if(Da(a)){h.info("catalog:execute:free",{tool:r,metaTool:n});let p=await U.shortcut(r,i,6e4,t,n);return p&&typeof p=="object"&&!Array.isArray(p)&&p.merchantName==null&&(p.merchantName=a.name??r),p}let f=await cn(r,void 0,t,i),m=xe.randomUUID();h.info("payment:attempt",{tool:r,amount:f.amount,merchant:f.merchantName});try{return await Te(async()=>{let p;try{p=await Gn({toolId:r,toolParams:i,estimatedAmountCents:ln(f),userContext:t,metaTool:n,timeoutMs:12e4,idempotencyKey:m})}catch(g){if(g instanceof Se)return Qe(g);throw g}if(h.info("payment:success",{tool:r,amount:f.amount,merchant:f.merchantName,mode:"session"}),p&&typeof p=="object"&&!Array.isArray(p)&&p.merchantName==null&&(p.merchantName=a?.name??r),p.urls?.length){p.urls.forEach(v=>pt(v));let g=cE(p.urls[0],p.mediaType);Oo({prompt:i.prompt||`${r} execution`,tool:r,mediaUrl:p.urls[0],mediaType:g,cost:p.amount??f.amount,transactionId:p.transactionId,userContext:t})}return p})}catch(p){return p instanceof he?(h.warn("payment:declined",{tool:r,amount:f.amount,merchant:f.merchantName,code:p.code,retryable:p.retryable}),gt(p,f)):(Dy(p?.message)?h.warn("payment:ambiguous",{tool:r,amount:f.amount,merchant:f.merchantName,error:p.message,note:"Polling/timeout error on async tool \u2014 call may have succeeded. Verify via `visa-cli transactions list`."}):h.error("payment:failure",{tool:r,amount:f.amount,merchant:f.merchantName,error:p.message}),zk({toolId:r,surface:n,merchantName:f.merchantName,amount:f.amount,message:p?.message||"Tool execution failed."}))}}function Dy(e){return e?/\b(task_id|polling?|timeout|timed out|queue|IN_QUEUE|aborted)\b/i.test(e):!1}function un(e,t){let n={...t,error:e?.message};Dy(e?.message)?h.warn("payment:ambiguous",n):h.error("payment:failure",n)}async function hE(e){if(!e.name)return{success:!1,error:"name is required"};try{let{registerName:t,ensureMailbox:n}=await Promise.resolve().then(()=>(Ts(),Eo)),r=await t(e.name);return await n(e.name),{success:!0,...r}}catch(t){let{CardRequiredError:n}=await Promise.resolve().then(()=>(Aa(),Yh));return t instanceof n?{success:!1,card_required:!0,reason:t.reason,enroll_url:t.enrollUrl,error:t.message,message:`${t.message} Enroll a card here: ${t.enrollUrl} \u2014 then ask me to register again.`}:{success:!1,error:t instanceof Error?t.message:String(t)}}}async function yE(e){if(!e.name)return{success:!1,error:"name is required"};try{let{resolveMeshName:t}=await Promise.resolve().then(()=>(Ts(),Eo));return{success:!0,...await t(e.name)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async function _E(e){if(!e.to||!e.text)return{success:!1,error:"to and text are required"};try{let{sendVia:t,resolveActingName:n}=await Promise.resolve().then(()=>(Ts(),Eo)),r=e.as??n(void 0);return{success:!0,...await t(r,e.to,e.text)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async function bE(e){try{let{readInbox:t,resolveActingName:n,meshName:r}=await Promise.resolve().then(()=>(Ts(),Eo)),s=e.as??n(void 0),o=await t(s,e.limit??20,!!e.clear);return{success:!0,as:r(s),count:o.length,messages:o}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}var lt=class{static async subwayRegister(t){return hE(t||{})}static async subwayFind(t){return yE(t||{})}static async subwaySend(t){return _E(t||{})}static async subwayInbox(t){return bE(t||{})}static async getStatus(t){return jA(t)}static async getVisaSmi(t,n){return vA(t,n)}static async getCards(t){return BA(t)}static async transactionHistory(t,n){return FA(t||{},n)}static async feedback(t,n){return HA(t,n)}static async updateSpendingControls(t,n){return qA(t,n)}static async configList(t){return KA(t||{})}static async configSet(t){return GA(t||{})}static async configUnset(t){return WA(t||{})}static async biometricStatus(t){return YA(t)}static async biometricOn(t){return zA(t)}static async biometricOff(t,n){return JA(t,n)}static async reset(t,n){return iE(t,n)}static async login(t){return eE(t)}static async closeSession(t){return sE()}static async startSession(t,n){return nE(t||{},n)}static async getSessionStatus(t){return rE()}static async addCard(t){return oE(t)}static async removeCard(t,n){return ZA(t,n)}static async setDefaultCard(t,n){return QA(t,n)}static async buyCredits(t,n){return VA(t,n)}static async batch(t,n){return UA(t,n)}static async discoverTools(t){return aE(t)}static async executeTool(t,n,r="execute_tool"){return gE(t,n,r)}static async shortcut(t,n,r){switch(t){case"generate_image_card":return wA(n,r);case"generate_image_fast_card":return SA(n,r);case"generate_video_tempo_card":return xA(n,r);case"generate_music_tempo_card":return TA(n,r);case"check_music_status_tempo_card":return kA(n,r);case"query_onchain_prices_card":return AA(n,r);default:{let s=await Po(t,n,r);if(s)return s;let o=await cn(t,void 0,r,n);h.info("payment:attempt",{tool:t});try{let i=await Gn({toolId:t,toolParams:n,estimatedAmountCents:ln(o),userContext:r,timeoutMs:6e4});return h.info("payment:success",{tool:t,mode:"session"}),i.urls?.length&&i.urls.forEach(a=>pt(a)),i}catch(i){if(i instanceof Se)return Qe(i);if(i instanceof he)return h.warn("payment:declined",{tool:t,code:i.code,retryable:i.retryable}),gt(i,o);throw un(i,{tool:t}),i}}}}static async submitFeedback(t,n,r){h.info("feedback:submit",{length:t.length,transactionId:n,hasContext:!!r});try{let s=await U.submitFeedback(t,n,r);return h.info("feedback:submitted",{transactionId:n}),s}catch(s){let o=s instanceof Error?s.message:"Unknown error";throw h.error("feedback:error",{error:o,transactionId:n}),s}}static async getFeedback(t,n){h.info("feedback:list",{limit:t||20});try{let r=await U.getFeedback(t,n);return h.info("feedback:listed",{count:r?.feedback?.length||0}),r}catch(r){let s=r instanceof Error?r.message:"Unknown error";throw h.error("feedback:error",{error:s}),r}}};wt();function jy(e,t=process.stderr){if(St()||!e?.updateAvailable)return!1;let{latestVersion:n}=e.updateAvailable;if(!n)return!1;let r=`Update available: v${n}. Run: visa-cli update`;return t.write(`
168
+ Use execute_tool with the tool id and required params to run any of these.`}],_tools:o}}catch(s){throw h.error("catalog:discover:error",{error:s.message}),new Error(`Failed to search tool catalog: ${s.message}`)}}function xy(e){return e.priceDisplay??`$${(e.priceCents/100).toFixed(2)}`}function Ty(e){let t=e.protocol;return t==="mpp"||t==="x402"?" | Paid from your prepaid balance":""}function lC(e,t){return t==="image"||t==="video"||t==="audio"?t:e?.match(/\.(mp4|webm|mov)/)?"video":"image"}function uC(e,t,n){let r=e.inputSchema;if(!r||r.type!=="object")return null;let s=r.properties??{},o=n??e.id;if(r.additionalProperties!==!0){for(let a of Object.keys(t))if(!Object.prototype.hasOwnProperty.call(s,a)){let c=Object.keys(s),l=c.length>0?` Expected: ${c.join(", ")}.`:"";return`Unknown parameter "${a}" for ${o}.${l}`}}let i=(r.required??[]).filter(a=>!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0);if(i.length>1)return`${i.join(", ")} are required for ${o}.`;for(let a of r.required??[]){if(!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0)return`${a} is required for ${o}.`;if(t[a]===null)return`${a} cannot be null.`;if(typeof t[a]=="string"&&t[a].trim()==="")return`${a} cannot be empty.`}for(let[a,c]of Object.entries(t)){let l=s[a];if(!l||c===void 0||c===null)continue;let u=ll(a,c,l);if(u)return u}return null}async function Dy(e){let t=os(e);if(t)return t;try{return await U.catalogTool(e)}catch(n){return h.warn("catalog:resolve:error",{tool:e,error:n?.message||String(n)}),null}}function ja(e){let t=e.executionMode,n=e.accessMode,r=e.pricingMode;if(typeof t=="string"&&t.startsWith("paid")||n==="paid"||r==="fixed"||r==="dynamic"||r==="token")return!1;let s=e.priceCents,o=e.pricing;return t==="free_authenticated"||n==="free"||o?.free===!0||s===0||o?.amount===0}function dC(e){let t=e;return t.platformRoute===!0||typeof t.platformMerchantSlug=="string"||t.executionKind==="platform_proxy"}function fC(e){let n=e.inputSchema?.properties;return!!n&&typeof n=="object"&&Object.keys(n).length>0}function mC(e){return ja(e)&&dC(e)&&!fC(e)}function pC(e){return e.split(/[-_]/).filter(t=>t.length>0&&!/^[0-9a-f]{8,}$/i.test(t)).join(" ").trim()}async function gC(e){let t=pC(e);if(!t)return[];try{return((await U.catalogSearch(t,void 0)).tools||[]).filter(r=>r.id!==e).slice(0,3).map(r=>({tool_id:r.id,name:r.name}))}catch(n){return h.warn("catalog:suggest:error",{tool:e,error:n?.message||String(n)}),[]}}async function hC(e,t,n="execute_tool"){let{tool_id:r,params:s,...o}=e,i=s||o;if(!r)return Ro("tool_id is required. Use discover_tools first to find available tools.","MISSING_TOOL_ID");h.info("catalog:execute",{tool:r,metaTool:n});let a=await Dy(r);if(!a){let p=await gC(r),g=p.length?` Did you mean: ${p.map(v=>v.tool_id).join(", ")}?`:"";return Ro(`Unknown tool: '${r}'.${g} Use discover_tools first to find available tools.`,"UNKNOWN_TOOL",p.length?{suggestions:p}:void 0)}if(a.deprecated){let p=a.replacementTool?` Use '${a.replacementTool}' instead.`:"";return Ro(`Tool '${r}' is deprecated and is no longer available for new paid calls.${p}`,"DEPRECATED_TOOL")}if(a.status==="unavailable"){let p=a.unavailableReason,g=a.killSwitchFlag,v=p==="flag_state_unknown"?`Tool '${r}' is temporarily unavailable: feature flag state could not be resolved.`:`Tool '${r}' is temporarily disabled.`;return h.info("catalog:execute:surface_disabled",{tool:r,metaTool:n,unavailableReason:p??null,killSwitchFlag:g??null}),Ro(v,"SURFACE_DISABLED",{tool_id:r,...p?{unavailable_reason:p}:{},...g?{flag:g}:{}})}let l=n&&n!=="execute_tool"?n:void 0,u=mC(a)?null:uC(a,i,l);if(u)return h.info("catalog:execute:validation_failed",{tool:r,metaTool:n,error:u}),Ro(u);let d=await Oo(r,i,t,n);if(d)return d;if(ja(a)){h.info("catalog:execute:free",{tool:r,metaTool:n});let p=await U.shortcut(r,i,6e4,t,n);return p&&typeof p=="object"&&!Array.isArray(p)&&p.merchantName==null&&(p.merchantName=a.name??r),p}let f=await cn(r,void 0,t,i),m=xe.randomUUID();h.info("payment:attempt",{tool:r,amount:f.amount,merchant:f.merchantName});try{return await Te(async()=>{let p;try{p=await Gn({toolId:r,toolParams:i,estimatedAmountCents:ln(f),userContext:t,metaTool:n,timeoutMs:12e4,idempotencyKey:m})}catch(g){if(g instanceof Se)return Qe(g);throw g}if(h.info("payment:success",{tool:r,amount:f.amount,merchant:f.merchantName,mode:"session"}),p&&typeof p=="object"&&!Array.isArray(p)&&p.merchantName==null&&(p.merchantName=a?.name??r),p.urls?.length){p.urls.forEach(v=>pt(v));let g=lC(p.urls[0],p.mediaType);Mo({prompt:i.prompt||`${r} execution`,tool:r,mediaUrl:p.urls[0],mediaType:g,cost:p.amount??f.amount,transactionId:p.transactionId,userContext:t})}return p})}catch(p){return p instanceof he?(h.warn("payment:declined",{tool:r,amount:f.amount,merchant:f.merchantName,code:p.code,retryable:p.retryable}),gt(p,f)):(jy(p?.message)?h.warn("payment:ambiguous",{tool:r,amount:f.amount,merchant:f.merchantName,error:p.message,note:"Polling/timeout error on async tool \u2014 call may have succeeded. Verify via `visa-cli transactions list`."}):h.error("payment:failure",{tool:r,amount:f.amount,merchant:f.merchantName,error:p.message}),JA({toolId:r,surface:n,merchantName:f.merchantName,amount:f.amount,message:p?.message||"Tool execution failed."}))}}function jy(e){return e?/\b(task_id|polling?|timeout|timed out|queue|IN_QUEUE|aborted)\b/i.test(e):!1}function un(e,t){let n={...t,error:e?.message};jy(e?.message)?h.warn("payment:ambiguous",n):h.error("payment:failure",n)}async function yC(e){if(!e.name)return{success:!1,error:"name is required"};try{let{registerName:t,ensureMailbox:n}=await Promise.resolve().then(()=>(Ts(),Eo)),r=await t(e.name);return await n(e.name),{success:!0,...r}}catch(t){let{CardRequiredError:n}=await Promise.resolve().then(()=>(Ca(),zh));return t instanceof n?{success:!1,card_required:!0,reason:t.reason,enroll_url:t.enrollUrl,error:t.message,message:`${t.message} Enroll a card here: ${t.enrollUrl} \u2014 then ask me to register again.`}:{success:!1,error:t instanceof Error?t.message:String(t)}}}async function _C(e){if(!e.name)return{success:!1,error:"name is required"};try{let{resolveMeshName:t}=await Promise.resolve().then(()=>(Ts(),Eo));return{success:!0,...await t(e.name)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async function bC(e){if(!e.to||!e.text)return{success:!1,error:"to and text are required"};try{let{sendVia:t,resolveActingName:n}=await Promise.resolve().then(()=>(Ts(),Eo)),r=e.as??n(void 0);return{success:!0,...await t(r,e.to,e.text)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async function vC(e){try{let{readInbox:t,resolveActingName:n,meshName:r}=await Promise.resolve().then(()=>(Ts(),Eo)),s=e.as??n(void 0),o=await t(s,e.limit??20,!!e.clear);return{success:!0,as:r(s),count:o.length,messages:o}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}var lt=class{static async subwayRegister(t){return yC(t||{})}static async subwayFind(t){return _C(t||{})}static async subwaySend(t){return bC(t||{})}static async subwayInbox(t){return vC(t||{})}static async getStatus(t){return Bk(t)}static async getVisaSmi(t,n){return wk(t,n)}static async getCards(t){return Fk(t)}static async transactionHistory(t,n){return Hk(t||{},n)}static async feedback(t,n){return Vk(t,n)}static async updateSpendingControls(t,n){return Kk(t,n)}static async configList(t){return Gk(t||{})}static async configSet(t){return Wk(t||{})}static async configUnset(t){return Yk(t||{})}static async biometricStatus(t){return zk(t)}static async biometricOn(t){return Jk(t)}static async biometricOff(t,n){return Xk(t,n)}static async reset(t,n){return aC(t,n)}static async login(t){return tC(t)}static async closeSession(t){return oC()}static async startSession(t,n){return rC(t||{},n)}static async getSessionStatus(t){return sC()}static async addCard(t){return iC(t)}static async removeCard(t,n){return Qk(t,n)}static async setDefaultCard(t,n){return eC(t,n)}static async buyCredits(t,n){return qk(t,n)}static async batch(t,n){return Dk(t,n)}static async discoverTools(t){return cC(t)}static async executeTool(t,n,r="execute_tool"){return hC(t,n,r)}static async shortcut(t,n,r){switch(t){case"generate_image_card":return Sk(n,r);case"generate_image_fast_card":return xk(n,r);case"generate_video_tempo_card":return Tk(n,r);case"generate_music_tempo_card":return Ak(n,r);case"check_music_status_tempo_card":return kk(n,r);case"query_onchain_prices_card":return Ck(n,r);default:{let s=await Oo(t,n,r);if(s)return s;let o=await cn(t,void 0,r,n);h.info("payment:attempt",{tool:t});try{let i=await Gn({toolId:t,toolParams:n,estimatedAmountCents:ln(o),userContext:r,timeoutMs:6e4});return h.info("payment:success",{tool:t,mode:"session"}),i.urls?.length&&i.urls.forEach(a=>pt(a)),i}catch(i){if(i instanceof Se)return Qe(i);if(i instanceof he)return h.warn("payment:declined",{tool:t,code:i.code,retryable:i.retryable}),gt(i,o);throw un(i,{tool:t}),i}}}}static async submitFeedback(t,n,r){h.info("feedback:submit",{length:t.length,transactionId:n,hasContext:!!r});try{let s=await U.submitFeedback(t,n,r);return h.info("feedback:submitted",{transactionId:n}),s}catch(s){let o=s instanceof Error?s.message:"Unknown error";throw h.error("feedback:error",{error:o,transactionId:n}),s}}static async getFeedback(t,n){h.info("feedback:list",{limit:t||20});try{let r=await U.getFeedback(t,n);return h.info("feedback:listed",{count:r?.feedback?.length||0}),r}catch(r){let s=r instanceof Error?r.message:"Unknown error";throw h.error("feedback:error",{error:s}),r}}};wt();function By(e,t=process.stderr){if(St()||!e?.updateAvailable)return!1;let{latestVersion:n}=e.updateAvailable;if(!n)return!1;let r=`Update available: v${n}. Run: visa-cli update`;return t.write(`
169
169
  \x1B[33m\u2191 ${r}\x1B[0m
170
- `),!0}function Fy(e){let t=Array.isArray(e.inputSchema?.required)?e.inputSchema.required.filter(o=>typeof o=="string"):[],n=e.inputSchema?.properties&&typeof e.inputSchema.properties=="object"?e.inputSchema.properties:{};if(t.length>0){let o={};for(let i of t)o[i]=By(i,n[i]?.description);return o}let r=Object.keys(n).slice(0,2);if(r.length===0)return{prompt:"a lobster"};let s={};for(let o of r)s[o]=By(o,n[o]?.description);return s}function By(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 vE(e){let t=Mt(e.referralCode,"");if(!t)return[];let n=["Referrals",` Your code ${t}`],r=Mt(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 wE=20;function Vy(e,t,n,r){let s=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=CE(e.spendingControls).dailyLimit,a=Math.max(0,Mo(e.dailyCardFundedTopupSpent??e.dailySpent)),c=i>0?Math.min(i,Math.max(0,Mo(e.dailyCardFundedTopupRemaining??e.dailyRemaining??i-a))):0,l=i>0?Math.min(1,a/i):0,d=(Array.isArray(t)?t:[]).filter(TE),f=d.slice(0,3),m=kE(d,3),p=(e.cards??[]).slice(0,3),g=r.latestVersion?Ur(r.latestVersion):"",v=r.updateCheckDisabled?"update checks disabled":g?`update ready: v${g}`:"up to date",k=Math.round(l*100),b=Mt(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} | ${v}`,`Top-up meter: ${Hy(l)} ${String(k).padStart(3," ")}% | remaining ${Cs(c)}/day | daily top-up cap ${Cs(i)}`,"","Card top-ups",` Remaining ${Cs(c)} / ${Cs(i)}`,` Usage ${Hy(l)} ${k}%`,` Top-ups today ${Cs(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...p.length>0?p.map(I=>` ${EE(I)}`):[" No cards enrolled"],"","Last 3 services",...m.length>0?m.map((I,y)=>` ${y+1}. ${I}`):[" No paid services yet"],"","Recent receipts",...f.length>0?f.map(I=>` ${AE(I)}`):[" No receipts yet"]],C=vE(e);return C.length>0&&S.push("",...C),g&&!r.updateCheckDisabled?(S.push("",`Update: v${g} ready \u2014 run \`visa-cli update\``),r.updateMessage&&S.push(` ${Ur(r.updateMessage)}`)):r.updateMessage&&S.push("",`Update: ${Ur(r.updateMessage)}`),`${S.join(`
170
+ `),!0}function Hy(e){let t=Array.isArray(e.inputSchema?.required)?e.inputSchema.required.filter(o=>typeof o=="string"):[],n=e.inputSchema?.properties&&typeof e.inputSchema.properties=="object"?e.inputSchema.properties:{};if(t.length>0){let o={};for(let i of t)o[i]=Fy(i,n[i]?.description);return o}let r=Object.keys(n).slice(0,2);if(r.length===0)return{prompt:"a lobster"};let s={};for(let o of r)s[o]=Fy(o,n[o]?.description);return s}function Fy(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 wC(e){let t=Mt(e.referralCode,"");if(!t)return[];let n=["Referrals",` Your code ${t}`],r=Mt(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 SC=20;function qy(e,t,n,r){let s=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=RC(e.spendingControls).dailyLimit,a=Math.max(0,No(e.dailyCardFundedTopupSpent??e.dailySpent)),c=i>0?Math.min(i,Math.max(0,No(e.dailyCardFundedTopupRemaining??e.dailyRemaining??i-a))):0,l=i>0?Math.min(1,a/i):0,d=(Array.isArray(t)?t:[]).filter(AC),f=d.slice(0,3),m=kC(d,3),p=(e.cards??[]).slice(0,3),g=r.latestVersion?Ur(r.latestVersion):"",v=r.updateCheckDisabled?"update checks disabled":g?`update ready: v${g}`:"up to date",A=Math.round(l*100),b=Mt(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} | ${v}`,`Top-up meter: ${Vy(l)} ${String(A).padStart(3," ")}% | remaining ${Es(c)}/day | daily top-up cap ${Es(i)}`,"","Card top-ups",` Remaining ${Es(c)} / ${Es(i)}`,` Usage ${Vy(l)} ${A}%`,` Top-ups today ${Es(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...p.length>0?p.map(I=>` ${EC(I)}`):[" No cards enrolled"],"","Last 3 services",...m.length>0?m.map((I,y)=>` ${y+1}. ${I}`):[" No paid services yet"],"","Recent receipts",...f.length>0?f.map(I=>` ${CC(I)}`):[" No receipts yet"]],E=wC(e);return E.length>0&&S.push("",...E),g&&!r.updateCheckDisabled?(S.push("",`Update: v${g} ready \u2014 run \`visa-cli update\``),r.updateMessage&&S.push(` ${Ur(r.updateMessage)}`)):r.updateMessage&&S.push("",`Update: ${Ur(r.updateMessage)}`),`${S.join(`
171
171
  `)}
172
- `}function SE(e){return e.tool_name!=null}function xE(e){return Mo(e.amount)===0&&e.status==="failed"}function TE(e){return SE(e)&&!xE(e)}function kE(e,t=1/0){let n=new Set,r=[];for(let s of e){if(r.length>=t)break;let o=Mt(s.merchant_name,"Unknown merchant"),i=Mt(s.tool_name,"unknown_tool"),a=`${o} :: ${i}`;n.has(a)||(n.add(a),r.push(`${o} [${i}]`))}return r}function AE(e){let t=Mt(e.merchant_name,"Unknown merchant"),n=Mt(e.tool_name,"unknown_tool"),r=Cs(Mo(e.amount)),s=Mt(e.status,"unknown"),o=RE(e.created_at);return`${r} ${s.padEnd(9)} ${t} [${n}] ${o}`}function EE(e){let t=Mt(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function CE(e){return{dailyLimit:Mo(e?.daily_limit??e?.dailyLimit??0)}}function Mo(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function Cs(e){return`$${e.toFixed(2)}`}function Hy(e,t=wE){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function Mt(e,t){let n=Ur(e??"").trim();return n.length>0?n:t}function RE(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?Mt(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function Ur(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 IE=/^[1-9]\d{0,9}$/;function Gu(e){if(!IE.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 qy(e){let t=Ur(e.brand||"Visa"),n=Ur(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 Nt=R(require("fs")),_e=R(require("path")),$E=["npm","pnpm","yarn","bun"],PE=/\s+/,OE=process.platform==="win32"?"visa-cli.cmd":"visa-cli",Wu=["node_modules","@visa","cli"];function ME(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(PE)[0]??"",r=n.indexOf("/"),s=r===-1?n:n.slice(0,r);return $E.includes(s)?s:void 0}function Yu(e){if(!e)return;let t=e;try{t=Nt.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 NE(e=process.argv[1]){return ME()??Yu(process.env.npm_execpath)??Yu(process.env.npm_node_execpath)??Yu(e)}function LE(e=process.env.PATH??""){let t=[];for(let n of e.split(_e.delimiter))n&&t.push(n);return t}function UE(e=process.env.PATH??""){let t=new Set,n=[];for(let r of LE(e))try{let s=_e.join(r,OE);Nt.accessSync(s,Nt.constants.X_OK);let o=_e.resolve(s);t.has(o)||(t.add(o),n.push(s))}catch{}return n}function Ky(e){try{let t=Nt.readFileSync(_e.join(e,"package.json"),"utf-8"),n=JSON.parse(t);if(n.name==="@visa/cli"&&typeof n.version=="string")return n.version}catch{}}function DE(e){let t=_e.resolve(e).split(_e.sep);for(let n=t.length-Wu.length;n>=0;n--)if(Wu.every((r,s)=>t[n+s]===r)){let r=t.slice(0,n+Wu.length).join(_e.sep)||_e.sep;if(Ky(r))return r}}function jE(e){if(!e)return;let t=_e.normalize(e),n=t.split(_e.sep),r=o=>o.every((a,c)=>n[n.length-o.length+c]===a)?n.slice(0,-o.length).join(_e.sep)||_e.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 BE(e,t){let n=_e.resolve(e);try{n=Nt.realpathSync(e)}catch{}let r=DE(n);return{binPath:e,realPath:n,packageRoot:r,version:r?Ky(r):void 0,prefix:jE(r),isActive:n===t}}function FE(e,t=process.env.PATH??""){let n=e??process.argv[1],r=n?_e.resolve(n):"";try{n&&(r=Nt.realpathSync(n))}catch{}let s=e?[e]:[n,...UE(t)].filter(Boolean),o=new Map;for(let d of s){let f=BE(d,r),m=o.get(f.realPath);o.set(f.realPath,m?{...f,binPath:m.binPath}:f)}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 HE(e,t=process.platform){return/^[A-Za-z0-9_./:@+-]+$/.test(e)?e:t==="win32"?`"${e.replace(/"/g,'""')}"`:`'${e.replace(/'/g,"'\\''")}'`}function zu(e,t,n,r={}){let s=t??NE(n)??"npm",o=r.withDiagnostics?FE(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 ${HE(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 VE(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 Ju(e,t){if(!e.hasConflictingInstalls)return null;let n=["Multiple Visa CLI installs detected.",...e.installs.map(VE)];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(`
173
- `)}var Wa=R(as());function qE(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function Gy(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=qE(e);return e.attestationRequired!==!1||t?{canContinue:!1,message:"Biometric attestation is unavailable, but this account requires a registered local attestation key.",hint:"Options: (1) Re-run setup from a device with Touch ID (Mac) or Windows Hello (PC). (2) Server/CI with no display: from a browser-authenticated device run `visa-cli config biometric off`, then re-run setup here \u2014 setup succeeds once the server no longer requires a local key."}:{canContinue:!0,message:"Biometric attestation is unavailable; continuing only because server biometric policy is disabled and no attestation key is registered."}}async function Wy(){await G.deleteSessionToken()}var Jy=R(require("crypto"));xa();var We=R(require("fs")),ja=R(require("os")),Rs=R(require("path")),Xy=R(require("node:readline")),Xu="3.4.7-rc.1",KE=process.env.PORTER_API_URL??"https://porter-travel.up.railway.app",GE=process.env.TAP_REGISTRY_URL??"https://tap-production-eff9.up.railway.app",No=Rs.join(ja.homedir(),".visa-cli","agents");function WE(){return!!(process.env.VISA_DEV==="1"||Xu==="0.0.0"||Xu.startsWith("0.0.")||/-rc\.|-beta\./.test(Xu))}function YE(){We.mkdirSync(No,{recursive:!0,mode:448})}function ed(e){return Rs.join(No,`${e}.json`)}function Zu(){return We.existsSync(No)?We.readdirSync(No).filter(e=>e.endsWith(".json")).map(e=>Rs.join(No,e)):[]}function zE(e){let t=ed(e);return We.existsSync(t)?JSON.parse(We.readFileSync(t,"utf8")):null}function JE(e){YE();let t=ed(e.agent_id);We.writeFileSync(t,JSON.stringify(e,null,2),{mode:384})}async function Qu(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 Yy=Qu;function XE(){let{secretKey:e}=jh(),t=Fh(e);return{publicKeyB64url:t.x,privateJwk:t}}function Zy(e,t){let n=xo(t);return vs(So(n,new TextEncoder().encode(e)))}async function ZE(e){let{publicKeyB64url:t,privateJwk:n}=XE(),r=new Date().toISOString(),s=`tap:register:v1:${e.name}:${r}`,o=Zy(s,n),i=await Qu(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 Qu(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 JE(c),c}async function Qy(e){let t=await Yy(e.porter_url,"GET",`/api/v1/tap/challenge?public_key=${encodeURIComponent(e.public_key_b64url)}`),n=Zy(t.challenge,e.private_key_jwk),r=await Yy(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 QE(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=xo(e),l=So(c,new TextEncoder().encode(a));return`${a}.${vs(l)}`}var eC=["visa_authorize_payment"],tC={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 nC(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 rC(e,t){let n=Math.floor(Date.now()/1e3),r=n+300,s=`vpid_${Jy.randomBytes(16).toString("hex")}`,o=process.env.VISACLI_ISSUER??e.tap_registry_url??e.porter_url;return{jwt:QE(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 sC(e){let t=`${e.porter_url.replace(/\/+$/,"")}/api/mcp`,n=null,r=0;async function s(f=!1){if(!f&&n&&Date.now()<r-6e4)return n;let{token:m,expiresInSeconds:p}=await Qy(e);return n=m,r=Date.now()+p*1e3,m}function o(f){process.stdout.write(JSON.stringify(f)+`
174
- `)}function i(f,m,p){o({jsonrpc:"2.0",id:f??null,error:{code:m,message:p}})}function a(f,m,p){if(m==="visa_authorize_payment"){let g=nC(p);if(!g.ok){i(f,-32602,g.error);return}let v=g.value;try{let{jwt:k,jti:b,expiresAt:w}=rC(e,v);o({jsonrpc:"2.0",id:f,result:{content:[{type:"text",text:["\u2713 Payment authorized \u2014 pass this JWT as visa_payment_id at checkout:","",k,"",` agent: ${e.agent_id}`,` merchant: ${v.merchant}`,` amount: ${v.amount} ${v.currency.toUpperCase()}`,` jti: ${b}`,` expires: ${new Date(w*1e3).toISOString()}`].join(`
175
- `)},{type:"text",text:JSON.stringify({visa_payment_id:k,jti:b,agent_id:e.agent_id,amount:v.amount,currency:v.currency.toUpperCase(),merchant:v.merchant,expires_at:w})}]}})}catch(k){i(f,-32603,`failed to sign visa_payment_id: ${k instanceof Error?k.message:String(k)}`)}return}i(f,-32601,`unknown synthetic tool: ${m}`)}async function c(f){if(f.method==="tools/call"){let p=f.params??{};if(typeof p.name=="string"&&eC.includes(p.name)){a(f.id,p.name,p.arguments??{});return}}let m=0;for(;m<2;){m+=1;let p=await s(m>1),g;try{g=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","X-TAP-Token":p},body:JSON.stringify(f)})}catch(k){i(f.id,-32e3,`network error talking to porter: ${k instanceof Error?k.message:String(k)}`);return}if(g.status===401&&m===1){n=null;continue}if(!g.ok){let k=await g.text().catch(()=>"");i(f.id,-32e3,`porter returned ${g.status}: ${k.slice(0,400)}`);return}if((g.headers.get("content-type")??"").includes("text/event-stream"))await u(g,f);else{let k=await g.text();if(k.trim()){let b=JSON.parse(k);l(f,b),o(b)}}return}}function l(f,m){if(f.method!=="tools/list")return;let p=m.result;!p||!Array.isArray(p.tools)||p.tools.some(g=>g.name==="visa_authorize_payment")||p.tools.push(tC)}async function u(f,m){let p=f.body?.getReader();if(!p)return;let g=new TextDecoder,v="";for(;;){let{done:k,value:b}=await p.read();if(k)break;v+=g.decode(b,{stream:!0});let w;for(;(w=v.indexOf(`
172
+ `}function xC(e){return e.tool_name!=null}function TC(e){return No(e.amount)===0&&e.status==="failed"}function AC(e){return xC(e)&&!TC(e)}function kC(e,t=1/0){let n=new Set,r=[];for(let s of e){if(r.length>=t)break;let o=Mt(s.merchant_name,"Unknown merchant"),i=Mt(s.tool_name,"unknown_tool"),a=`${o} :: ${i}`;n.has(a)||(n.add(a),r.push(`${o} [${i}]`))}return r}function CC(e){let t=Mt(e.merchant_name,"Unknown merchant"),n=Mt(e.tool_name,"unknown_tool"),r=Es(No(e.amount)),s=Mt(e.status,"unknown"),o=IC(e.created_at);return`${r} ${s.padEnd(9)} ${t} [${n}] ${o}`}function EC(e){let t=Mt(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function RC(e){return{dailyLimit:No(e?.daily_limit??e?.dailyLimit??0)}}function No(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function Es(e){return`$${e.toFixed(2)}`}function Vy(e,t=SC){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function Mt(e,t){let n=Ur(e??"").trim();return n.length>0?n:t}function IC(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?Mt(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function Ur(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 PC=/^[1-9]\d{0,9}$/;function Wu(e){if(!PC.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 Ky(e){let t=Ur(e.brand||"Visa"),n=Ur(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 Nt=R(require("fs")),_e=R(require("path")),$C=["npm","pnpm","yarn","bun"],OC=/\s+/,MC=process.platform==="win32"?"visa-cli.cmd":"visa-cli",Yu=["node_modules","@visa","cli"];function NC(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(OC)[0]??"",r=n.indexOf("/"),s=r===-1?n:n.slice(0,r);return $C.includes(s)?s:void 0}function zu(e){if(!e)return;let t=e;try{t=Nt.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 LC(e=process.argv[1]){return NC()??zu(process.env.npm_execpath)??zu(process.env.npm_node_execpath)??zu(e)}function UC(e=process.env.PATH??""){let t=[];for(let n of e.split(_e.delimiter))n&&t.push(n);return t}function DC(e=process.env.PATH??""){let t=new Set,n=[];for(let r of UC(e))try{let s=_e.join(r,MC);Nt.accessSync(s,Nt.constants.X_OK);let o=_e.resolve(s);t.has(o)||(t.add(o),n.push(s))}catch{}return n}function Gy(e){try{let t=Nt.readFileSync(_e.join(e,"package.json"),"utf-8"),n=JSON.parse(t);if(n.name==="@visa/cli"&&typeof n.version=="string")return n.version}catch{}}function jC(e){let t=_e.resolve(e).split(_e.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(_e.sep)||_e.sep;if(Gy(r))return r}}function BC(e){if(!e)return;let t=_e.normalize(e),n=t.split(_e.sep),r=o=>o.every((a,c)=>n[n.length-o.length+c]===a)?n.slice(0,-o.length).join(_e.sep)||_e.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 FC(e,t){let n=_e.resolve(e);try{n=Nt.realpathSync(e)}catch{}let r=jC(n);return{binPath:e,realPath:n,packageRoot:r,version:r?Gy(r):void 0,prefix:BC(r),isActive:n===t}}function HC(e,t=process.env.PATH??""){let n=e??process.argv[1],r=n?_e.resolve(n):"";try{n&&(r=Nt.realpathSync(n))}catch{}let s=e?[e]:[n,...DC(t)].filter(Boolean),o=new Map;for(let d of s){let f=FC(d,r),m=o.get(f.realPath);o.set(f.realPath,m?{...f,binPath:m.binPath}:f)}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 VC(e,t=process.platform){return/^[A-Za-z0-9_./:@+-]+$/.test(e)?e:t==="win32"?`"${e.replace(/"/g,'""')}"`:`'${e.replace(/'/g,"'\\''")}'`}function Ju(e,t,n,r={}){let s=t??LC(n)??"npm",o=r.withDiagnostics?HC(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 ${VC(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 qC(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 Xu(e,t){if(!e.hasConflictingInstalls)return null;let n=["Multiple Visa CLI installs detected.",...e.installs.map(qC)];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(`
173
+ `)}var Ya=R(as());function KC(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function Wy(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=KC(e);return e.attestationRequired!==!1||t?{canContinue:!1,message:"Biometric attestation is unavailable, but this account requires a registered local attestation key.",hint:"Options: (1) Re-run setup from a device with Touch ID (Mac) or Windows Hello (PC). (2) Server/CI with no display: from a browser-authenticated device run `visa-cli config biometric off`, then re-run setup here \u2014 setup succeeds once the server no longer requires a local key."}:{canContinue:!0,message:"Biometric attestation is unavailable; continuing only because server biometric policy is disabled and no attestation key is registered."}}async function Yy(){await G.deleteSessionToken()}var Xy=R(require("crypto"));Ta();var We=R(require("fs")),Ba=R(require("os")),Rs=R(require("path")),Zy=R(require("node:readline")),Zu="3.4.8-rc.0",GC=process.env.PORTER_API_URL??"https://porter-travel.up.railway.app",WC=process.env.TAP_REGISTRY_URL??"https://tap-production-eff9.up.railway.app",Lo=Rs.join(Ba.homedir(),".visa-cli","agents");function YC(){return!!(process.env.VISA_DEV==="1"||Zu==="0.0.0"||Zu.startsWith("0.0.")||/-rc\.|-beta\./.test(Zu))}function zC(){We.mkdirSync(Lo,{recursive:!0,mode:448})}function td(e){return Rs.join(Lo,`${e}.json`)}function Qu(){return We.existsSync(Lo)?We.readdirSync(Lo).filter(e=>e.endsWith(".json")).map(e=>Rs.join(Lo,e)):[]}function JC(e){let t=td(e);return We.existsSync(t)?JSON.parse(We.readFileSync(t,"utf8")):null}function XC(e){zC();let t=td(e.agent_id);We.writeFileSync(t,JSON.stringify(e,null,2),{mode:384})}async function ed(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 zy=ed;function ZC(){let{secretKey:e}=Bh(),t=Hh(e);return{publicKeyB64url:t.x,privateJwk:t}}function Qy(e,t){let n=To(t);return vs(xo(n,new TextEncoder().encode(e)))}async function QC(e){let{publicKeyB64url:t,privateJwk:n}=ZC(),r=new Date().toISOString(),s=`tap:register:v1:${e.name}:${r}`,o=Qy(s,n),i=await ed(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 ed(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 XC(c),c}async function e_(e){let t=await zy(e.porter_url,"GET",`/api/v1/tap/challenge?public_key=${encodeURIComponent(e.public_key_b64url)}`),n=Qy(t.challenge,e.private_key_jwk),r=await zy(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 eE(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=To(e),l=xo(c,new TextEncoder().encode(a));return`${a}.${vs(l)}`}var tE=["visa_authorize_payment"],nE={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 rE(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 sE(e,t){let n=Math.floor(Date.now()/1e3),r=n+300,s=`vpid_${Xy.randomBytes(16).toString("hex")}`,o=process.env.VISACLI_ISSUER??e.tap_registry_url??e.porter_url;return{jwt:eE(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 oE(e){let t=`${e.porter_url.replace(/\/+$/,"")}/api/mcp`,n=null,r=0;async function s(f=!1){if(!f&&n&&Date.now()<r-6e4)return n;let{token:m,expiresInSeconds:p}=await e_(e);return n=m,r=Date.now()+p*1e3,m}function o(f){process.stdout.write(JSON.stringify(f)+`
174
+ `)}function i(f,m,p){o({jsonrpc:"2.0",id:f??null,error:{code:m,message:p}})}function a(f,m,p){if(m==="visa_authorize_payment"){let g=rE(p);if(!g.ok){i(f,-32602,g.error);return}let v=g.value;try{let{jwt:A,jti:b,expiresAt:w}=sE(e,v);o({jsonrpc:"2.0",id:f,result:{content:[{type:"text",text:["\u2713 Payment authorized \u2014 pass this JWT as visa_payment_id at checkout:","",A,"",` agent: ${e.agent_id}`,` merchant: ${v.merchant}`,` amount: ${v.amount} ${v.currency.toUpperCase()}`,` jti: ${b}`,` expires: ${new Date(w*1e3).toISOString()}`].join(`
175
+ `)},{type:"text",text:JSON.stringify({visa_payment_id:A,jti:b,agent_id:e.agent_id,amount:v.amount,currency:v.currency.toUpperCase(),merchant:v.merchant,expires_at:w})}]}})}catch(A){i(f,-32603,`failed to sign visa_payment_id: ${A instanceof Error?A.message:String(A)}`)}return}i(f,-32601,`unknown synthetic tool: ${m}`)}async function c(f){if(f.method==="tools/call"){let p=f.params??{};if(typeof p.name=="string"&&tE.includes(p.name)){a(f.id,p.name,p.arguments??{});return}}let m=0;for(;m<2;){m+=1;let p=await s(m>1),g;try{g=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","X-TAP-Token":p},body:JSON.stringify(f)})}catch(A){i(f.id,-32e3,`network error talking to porter: ${A instanceof Error?A.message:String(A)}`);return}if(g.status===401&&m===1){n=null;continue}if(!g.ok){let A=await g.text().catch(()=>"");i(f.id,-32e3,`porter returned ${g.status}: ${A.slice(0,400)}`);return}if((g.headers.get("content-type")??"").includes("text/event-stream"))await u(g,f);else{let A=await g.text();if(A.trim()){let b=JSON.parse(A);l(f,b),o(b)}}return}}function l(f,m){if(f.method!=="tools/list")return;let p=m.result;!p||!Array.isArray(p.tools)||p.tools.some(g=>g.name==="visa_authorize_payment")||p.tools.push(nE)}async function u(f,m){let p=f.body?.getReader();if(!p)return;let g=new TextDecoder,v="";for(;;){let{done:A,value:b}=await p.read();if(A)break;v+=g.decode(b,{stream:!0});let w;for(;(w=v.indexOf(`
176
176
 
177
- `))>=0;){let S=v.slice(0,w);v=v.slice(w+2);for(let C of S.split(`
178
- `))if(C.startsWith("data: ")){let I=C.slice(6).trim();if(!I)continue;try{let y=JSON.parse(I);l(m,y),o(y)}catch{}}}}}await s().catch(()=>{});let d=Xy.createInterface({input:process.stdin,terminal:!1});for await(let f of d){let m=f.trim();if(!m)continue;let p;try{p=JSON.parse(m)}catch{continue}c(p)}}function zy(e){let t=Zu();if(t.length===0)throw new Error("No agents registered. Run `visa-cli agent register` first.");if(e){let n=zE(e);if(!n)throw new Error(`Agent not found: ${e}`);return n}if(t.length>1){let n=t.map(r=>Rs.basename(r,".json")).map(r=>` - ${r}`).join(`
177
+ `))>=0;){let S=v.slice(0,w);v=v.slice(w+2);for(let E of S.split(`
178
+ `))if(E.startsWith("data: ")){let I=E.slice(6).trim();if(!I)continue;try{let y=JSON.parse(I);l(m,y),o(y)}catch{}}}}}await s().catch(()=>{});let d=Zy.createInterface({input:process.stdin,terminal:!1});for await(let f of d){let m=f.trim();if(!m)continue;let p;try{p=JSON.parse(m)}catch{continue}c(p)}}function Jy(e){let t=Qu();if(t.length===0)throw new Error("No agents registered. Run `visa-cli agent register` first.");if(e){let n=JC(e);if(!n)throw new Error(`Agent not found: ${e}`);return n}if(t.length>1){let n=t.map(r=>Rs.basename(r,".json")).map(r=>` - ${r}`).join(`
179
179
  `);throw new Error(`Multiple agents registered \u2014 pass --agent <id>:
180
- ${n}`)}return JSON.parse(We.readFileSync(t[0],"utf8"))}function e_(e){if(!WE())return;let t=e.command("agent").description("(dev/rc) Manage agent identities for AI clients. Pre-kernel fallback \u2014 graduates to kernel signing once available.");t.command("register").description("Provision an Ed25519 keypair, publish in the tap-stack registry, and authorize with porter.").option("--porter <url>","Porter merchant URL",KE).option("--registry <url>","TAP registry URL (publishes the JWKS)",GE).option("--name <name>","Human-readable name for this agent",`${process.env.USER??"user"}@${ja.hostname()}`).action(async n=>{try{let r=await ZE({registryUrl:n.registry,porterUrl:n.porter,name:n.name}),s=Zu().length>1?` --agent ${r.agent_id}`:"";process.stdout.write(["\u2713 Agent registered",` agent_id: ${r.agent_id} (kid for visa_payment_id JWTs)`,` tap registry: ${r.tap_registry_url}`,` porter: ${r.porter_url}`,` tap_account: ${r.tap_account_id} (porter x-tap-token)`,` name: ${r.name}`,` key file: ${ed(r.agent_id)}`,"","Next \u2014 add porter to your AI client (visa-cli will inject the TAP token automatically):","",` claude mcp add porter -- visa-cli agent proxy${s}`,"",'Now ask Claude: "search flights from JFK to CDG on 2026-09-15."',""].join(`
180
+ ${n}`)}return JSON.parse(We.readFileSync(t[0],"utf8"))}function t_(e){if(!YC())return;let t=e.command("agent").description("(dev/rc) Manage agent identities for AI clients. Pre-kernel fallback \u2014 graduates to kernel signing once available.");t.command("register").description("Provision an Ed25519 keypair, publish in the tap-stack registry, and authorize with porter.").option("--porter <url>","Porter merchant URL",GC).option("--registry <url>","TAP registry URL (publishes the JWKS)",WC).option("--name <name>","Human-readable name for this agent",`${process.env.USER??"user"}@${Ba.hostname()}`).action(async n=>{try{let r=await QC({registryUrl:n.registry,porterUrl:n.porter,name:n.name}),s=Qu().length>1?` --agent ${r.agent_id}`:"";process.stdout.write(["\u2713 Agent registered",` agent_id: ${r.agent_id} (kid for visa_payment_id JWTs)`,` tap registry: ${r.tap_registry_url}`,` porter: ${r.porter_url}`,` tap_account: ${r.tap_account_id} (porter x-tap-token)`,` name: ${r.name}`,` key file: ${td(r.agent_id)}`,"","Next \u2014 add porter to your AI client (visa-cli will inject the TAP token automatically):","",` claude mcp add porter -- visa-cli agent proxy${s}`,"",'Now ask Claude: "search flights from JFK to CDG on 2026-09-15."',""].join(`
181
181
  `))}catch(r){process.stderr.write(`agent register failed: ${r instanceof Error?r.message:String(r)}
182
- `),process.exit(1)}}),t.command("token").description("Mint a fresh 24h TAP token for the registered agent.").option("--agent <id>","Specific agent_id (required if more than one is registered)").option("--export","Print as `export X_TAP_TOKEN=\u2026` for shell sourcing",!1).action(async n=>{try{let r=zy(n.agent),{token:s,expiresInSeconds:o}=await Qy(r);n.export?process.stdout.write(`export X_TAP_TOKEN='${s}'
182
+ `),process.exit(1)}}),t.command("token").description("Mint a fresh 24h TAP token for the registered agent.").option("--agent <id>","Specific agent_id (required if more than one is registered)").option("--export","Print as `export X_TAP_TOKEN=\u2026` for shell sourcing",!1).action(async n=>{try{let r=Jy(n.agent),{token:s,expiresInSeconds:o}=await e_(r);n.export?process.stdout.write(`export X_TAP_TOKEN='${s}'
183
183
  `):process.stdout.write(`${s}
184
184
  `),process.stderr.write(`# expires in ${Math.round(o/3600)}h \xB7 agent ${r.agent_id}
185
185
  `)}catch(r){process.stderr.write(`agent token failed: ${r instanceof Error?r.message:String(r)}
186
- `),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=zy(n.agent);await sC(r)}catch(r){process.stderr.write(`agent proxy failed: ${r instanceof Error?r.message:String(r)}
187
- `),process.exit(1)}}),t.command("list").description("List registered agents.").action(()=>{let n=Zu();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(We.readFileSync(r,"utf8"));process.stdout.write(`${s.agent_id} ${s.porter_url} ${s.name}
188
- `)}})}Zl();Ts();Aa();var oC="3.4.7-rc.1";async function t_(e){let t=await Iu(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: ${Ao} (mesh="${t.mesh}")`),console.log(` chat: visa subway listen --as ${e} | visa subway send --as ${e} <to> "<text>"`)}var Lo=(e,t)=>{if(t instanceof an){console.error(`\u2717 ${e}: ${t.message}`),console.error(` \u2192 enroll a card: ${t.enrollUrl}`),console.error(" \u2192 then re-run: visa register <name>"),process.exitCode=1;return}console.error(`\u2717 ${e} failed: ${t instanceof Error?t.message:String(t)}`),process.exitCode=1};function n_(e){if(!Au(oC))return;e.command("register <name>").description(`Register a name on the "${Re}" Subway mesh (reuses your CLI agent key \u2014 no TAP setup needed).`).action(async n=>{try{await t_(n)}catch(r){Lo("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 t_(n)}catch(r){Lo("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=Ra(s.as),i=await Pu(o,n,r);console.log(`\u2713 sent to ${i.to} as ${i.as}`)}catch(o){Lo("send",o)}}),t.command("find <name>").description("Look up another agent on the .visa relay \u2014 is it live, and who is it?").action(async n=>{try{let r=await $u(n);r.found?(console.log(`\u2713 ${r.relayName} is live`),console.log(` peer: ${r.peerId}`)):(console.log(`\u2717 ${r.relayName} not found${r.error?` (${r.error})`:""}`),process.exitCode=1)}catch(r){Lo("find",r)}}),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=Ra(n.as),s=Ss(r,{autoReconnect:!0});await xs(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 ${Er(r)} on "${Re}" 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){Lo("listen",r)}}),t.command("whoami").description("List names this CLI has registered on the relay.").action(()=>{let n=Ou();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}`)})}wt();qt();var iC=["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 aC(){let e=new Set;for(let t of iC)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of uo)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var _P=aC();var td=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 xP=new Set(uo),TP=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...td,...uo]);qt();var W=R(require("fs")),F=R(require("path")),r_=R(require("os")),me=r_.homedir(),cC=["Claude_","Anthropic.ClaudeDesktop_"],Is=class extends Error{constructor(n,r,s){super(uC(n,r,s));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function s_(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
189
- `)}function lC(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=s_(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function uC(e,t,n){let r=t.replace(me,"~"),s=s_(n).split(`
190
- `).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 Uo(){return process.env.APPDATA||F.join(me,"AppData","Roaming")}function dC(){return process.env.LOCALAPPDATA||F.join(me,"AppData","Local")}function nd(e){return process.platform==="win32"?e.win32:e.posix}function o_(){if(process.platform!=="win32")return;let e=F.join(dC(),"Packages");if(W.existsSync(e))try{let t=W.readdirSync(e,"utf-8");for(let n of cC){let r=t.filter(s=>s.startsWith(n)).sort()[0];if(r)return F.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function i_(){if(process.platform==="win32"){let e=o_();return e?F.join(e,"claude_desktop_config.json"):F.join(Uo(),"Claude","claude_desktop_config.json")}return F.join(me,"Library","Application Support","Claude","claude_desktop_config.json")}function a_(){if(process.platform!=="win32")return[F.join(me,"Library","Application Support","Claude")];let e=[F.join(Uo(),"Claude")],t=o_();return t&&e.push(t),e}function Ba(e){return e.id==="claude-desktop"?i_():e.globalConfigPath}function fC(e){return e.id==="claude-desktop"?a_():e.detectPaths}var ht=[{id:"claude",displayName:"Claude Code",globalConfigPath:F.join(me,".claude.json"),configKey:"mcpServers",detectPaths:[F.join(me,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:i_(),configKey:"mcpServers",detectPaths:a_(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:F.join(me,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[F.join(me,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:F.join(me,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[F.join(me,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:F.join(me,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[F.join(me,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:nd({win32:F.join(Uo(),"Roo","mcp_settings.json"),posix:F.join(me,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[F.join(me,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:F.join(me,".vscode","mcp.json"),configKey:"servers",detectPaths:[F.join(me,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:nd({win32:F.join(Uo(),"Zed","settings.json"),posix:F.join(me,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:nd({win32:[F.join(Uo(),"Zed")],posix:[F.join(me,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:F.join(me,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[F.join(me,".codex")],postInstallHint:"Restart Codex to connect."}];function rd(e){return ht.find(t=>t.id===e)}function Do(e){return fC(e).some(t=>{if(t.includes("*")){let n=F.dirname(t),r=F.basename(t).replaceAll("*","");if(!W.existsSync(n))return!1;try{return W.readdirSync(n).some(s=>s.startsWith(r))}catch{return!1}}return W.existsSync(t)})}function c_(){return{command:"node",args:[F.resolve(__dirname,"mcp-server/index.js")]}}function sd(e,t){return t==="project"?"json":e.configFormat??"json"}function mC(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 od(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 id(e,t){let n=e.split(`
191
- `),r=od(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]]=mC(i[2]))}return Object.keys(s).length>0?s:void 0}function pC(e,t,n){let r=`[${n.args.map(c=>`"${c}"`).join(", ")}]`,s=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],o=e.split(`
192
- `),i=od(o,t);if(i){o.splice(i.start,i.end-i.start,...s);let c=o.join(`
186
+ `),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=Jy(n.agent);await oE(r)}catch(r){process.stderr.write(`agent proxy failed: ${r instanceof Error?r.message:String(r)}
187
+ `),process.exit(1)}}),t.command("list").description("List registered agents.").action(()=>{let n=Qu();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(We.readFileSync(r,"utf8"));process.stdout.write(`${s.agent_id} ${s.porter_url} ${s.name}
188
+ `)}})}Ql();Ts();Ca();var iE="3.4.8-rc.0";async function n_(e){let t=await Pu(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: ${Co} (mesh="${t.mesh}")`),console.log(` chat: visa subway listen --as ${e} | visa subway send --as ${e} <to> "<text>"`)}var Uo=(e,t)=>{if(t instanceof an){console.error(`\u2717 ${e}: ${t.message}`),console.error(` \u2192 enroll a card: ${t.enrollUrl}`),console.error(" \u2192 then re-run: visa register <name>"),process.exitCode=1;return}console.error(`\u2717 ${e} failed: ${t instanceof Error?t.message:String(t)}`),process.exitCode=1};function r_(e){if(!Cu(iE))return;e.command("register <name>").description(`Register a name on the "${Re}" Subway mesh (reuses your CLI agent key \u2014 no TAP setup needed).`).action(async n=>{try{await n_(n)}catch(r){Uo("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 n_(n)}catch(r){Uo("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=Ia(s.as),i=await Ou(o,n,r);console.log(`\u2713 sent to ${i.to} as ${i.as}`)}catch(o){Uo("send",o)}}),t.command("find <name>").description("Look up another agent on the .visa relay \u2014 is it live, and who is it?").action(async n=>{try{let r=await $u(n);r.found?(console.log(`\u2713 ${r.relayName} is live`),console.log(` peer: ${r.peerId}`)):(console.log(`\u2717 ${r.relayName} not found${r.error?` (${r.error})`:""}`),process.exitCode=1)}catch(r){Uo("find",r)}}),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=Ia(n.as),s=Ss(r,{autoReconnect:!0});await xs(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 ${Cr(r)} on "${Re}" 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){Uo("listen",r)}}),t.command("whoami").description("List names this CLI has registered on the relay.").action(()=>{let n=Mu();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}`)})}wt();qt();var aE=["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 cE(){let e=new Set;for(let t of aE)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of fo)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var b$=cE();var nd=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 T$=new Set(fo),A$=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...nd,...fo]);qt();var W=R(require("fs")),F=R(require("path")),s_=R(require("os")),me=s_.homedir(),lE=["Claude_","Anthropic.ClaudeDesktop_"],Is=class extends Error{constructor(n,r,s){super(dE(n,r,s));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function o_(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
189
+ `)}function uE(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=o_(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function dE(e,t,n){let r=t.replace(me,"~"),s=o_(n).split(`
190
+ `).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 Do(){return process.env.APPDATA||F.join(me,"AppData","Roaming")}function fE(){return process.env.LOCALAPPDATA||F.join(me,"AppData","Local")}function rd(e){return process.platform==="win32"?e.win32:e.posix}function i_(){if(process.platform!=="win32")return;let e=F.join(fE(),"Packages");if(W.existsSync(e))try{let t=W.readdirSync(e,"utf-8");for(let n of lE){let r=t.filter(s=>s.startsWith(n)).sort()[0];if(r)return F.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function a_(){if(process.platform==="win32"){let e=i_();return e?F.join(e,"claude_desktop_config.json"):F.join(Do(),"Claude","claude_desktop_config.json")}return F.join(me,"Library","Application Support","Claude","claude_desktop_config.json")}function c_(){if(process.platform!=="win32")return[F.join(me,"Library","Application Support","Claude")];let e=[F.join(Do(),"Claude")],t=i_();return t&&e.push(t),e}function Fa(e){return e.id==="claude-desktop"?a_():e.globalConfigPath}function mE(e){return e.id==="claude-desktop"?c_():e.detectPaths}var ht=[{id:"claude",displayName:"Claude Code",globalConfigPath:F.join(me,".claude.json"),configKey:"mcpServers",detectPaths:[F.join(me,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:a_(),configKey:"mcpServers",detectPaths:c_(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:F.join(me,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[F.join(me,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:F.join(me,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[F.join(me,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:F.join(me,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[F.join(me,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:rd({win32:F.join(Do(),"Roo","mcp_settings.json"),posix:F.join(me,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[F.join(me,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:F.join(me,".vscode","mcp.json"),configKey:"servers",detectPaths:[F.join(me,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:rd({win32:F.join(Do(),"Zed","settings.json"),posix:F.join(me,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:rd({win32:[F.join(Do(),"Zed")],posix:[F.join(me,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:F.join(me,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[F.join(me,".codex")],postInstallHint:"Restart Codex to connect."}];function sd(e){return ht.find(t=>t.id===e)}function jo(e){return mE(e).some(t=>{if(t.includes("*")){let n=F.dirname(t),r=F.basename(t).replaceAll("*","");if(!W.existsSync(n))return!1;try{return W.readdirSync(n).some(s=>s.startsWith(r))}catch{return!1}}return W.existsSync(t)})}function l_(){return{command:"node",args:[F.resolve(__dirname,"mcp-server/index.js")]}}function od(e,t){return t==="project"?"json":e.configFormat??"json"}function pE(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 id(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 ad(e,t){let n=e.split(`
191
+ `),r=id(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]]=pE(i[2]))}return Object.keys(s).length>0?s:void 0}function gE(e,t,n){let r=`[${n.args.map(c=>`"${c}"`).join(", ")}]`,s=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],o=e.split(`
192
+ `),i=id(o,t);if(i){o.splice(i.start,i.end-i.start,...s);let c=o.join(`
193
193
  `);return c.endsWith(`
194
194
  `)?c:c+`
195
195
  `}let a=e.trimEnd();return a+(a.length>0?`
196
196
 
197
197
  `:"")+s.join(`
198
198
  `)+`
199
- `}function gC(e,t){let n=e.split(`
200
- `),r=od(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
199
+ `}function hE(e,t){let n=e.split(`
200
+ `),r=id(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
201
201
  `).replace(/\n{3,}/g,`
202
202
 
203
- `)):e}function jo(e,t="global"){let n=t==="project"?F.join(process.cwd(),".mcp.json"):Ba(e);try{let r=F.dirname(n);W.existsSync(r)||W.mkdirSync(r,{recursive:!0});let s=sd(e,t),o=c_();if(s==="toml"){let i=W.existsSync(n)?W.readFileSync(n,"utf-8"):"",a=pC(i,"visa-cli",o);W.writeFileSync(n,a)}else{let i={};if(W.existsSync(n))try{i=JSON.parse(W.readFileSync(n,"utf-8"))}catch{i={}}i[e.configKey]=i[e.configKey]||{},i[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(o):o,W.writeFileSync(n,JSON.stringify(i,null,2)+`
204
- `)}}catch(r){throw lC(r)?new Is(e,n,r):r}return{installed:!0,configPath:n,message:e.postInstallHint}}function ad(e,t="global"){let n=t==="project"?F.join(process.cwd(),".mcp.json"):Ba(e);if(!W.existsSync(n))return{removed:!1,configPath:n};if(sd(e,t)==="toml"){let i=W.readFileSync(n,"utf-8");return id(i,"visa-cli")?(W.writeFileSync(n,gC(i,"visa-cli")),{removed:!0,configPath:n}):{removed:!1,configPath:n}}let s;try{s=JSON.parse(W.readFileSync(n,"utf-8"))}catch{return{removed:!1,configPath:n}}let o=s[e.configKey];return!o||!o["visa-cli"]?{removed:!1,configPath:n}:(delete o["visa-cli"],W.writeFileSync(n,JSON.stringify(s,null,2)+`
205
- `),{removed:!0,configPath:n})}function l_(e,t="global"){let n=t==="project"?F.join(process.cwd(),".mcp.json"):Ba(e);if(!W.existsSync(n))return!1;if(sd(e,t)==="toml")try{let s=W.readFileSync(n,"utf-8");return!!id(s,"visa-cli")}catch{return!1}try{return!!JSON.parse(W.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function hC(e){if(!e||typeof e!="object")return;let t=e;if(t.command!=="node"||!Array.isArray(t.args)||t.args.length===0)return;let n=t.args[t.args.length-1];if(!(typeof n!="string"||n.length===0))return n}function yC(e,t){if(e===t)return!0;let n=F.resolve(e),r=F.resolve(t);if(n===r)return!0;try{let s=W.realpathSync(n),o=W.realpathSync(r);return s===o}catch{return!1}}function Bo(){let e=c_(),t=e.args[e.args.length-1],n=[];for(let r of ht){let s=Ba(r);if(!W.existsSync(s))continue;let o=r.configFormat??"json",i;if(o==="toml")try{let l=W.readFileSync(s,"utf-8");i=id(l,"visa-cli")}catch{continue}else{let l;try{l=JSON.parse(W.readFileSync(s,"utf-8"))}catch{continue}i=l?.[r.configKey]?.["visa-cli"]}if(!i)continue;let a=hC(i);if(!a||yC(a,t))continue;let c=W.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:s,currentPath:a,expectedPath:t,staleReason:c})}return n}function cd(e){return{configPath:jo(e.client,"global").configPath}}var fd=(0,b_.promisify)(__.execFile);function ld(){let e=Bt();setImmediate(()=>{Ec(e,{getCommand:()=>mi(process.execPath,process.argv[1])})})}process.stdout.on("error",e=>{throw e.code==="EPIPE"&&process.exit(0),e});process.stderr.on("error",e=>{throw e.code==="EPIPE"&&process.exit(0),e});function SC(e){let t=re.homedir(),n=s=>s.replace(t,"~"),r=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
206
- ${r}: ${n(e.currentPath)}`}function v_(e,t){if(e.length===0){console.log(`${t} \u2713 All MCP client configs are up to date.`);return}console.log(`${t} Found ${e.length} stale MCP config ${e.length===1?"entry":"entries"}:`);for(let n of e)console.log(SC(n))}function u_(e){console.log(` ! ${e.client.displayName} skipped: ${e.message}`)}function Lt(){this.help({error:!1})}var J=new y_.Command,xC=new Set(["pay",...td]),Va=null,Fo=!1;function pe(){return Va=new qe(()=>G.getSessionToken()),Va}function d_(e){if(e instanceof er)return!0;let t=e instanceof Error?e.message:"";return/attestation required|invalid signature|rotate biometric key|biometric key/i.test(t)}var f_=0,m_="",TC="attestation-key-rotation",kC="api-keys-create",p_=0,g_="",AC=12e3;async function EC(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:f_,merchant:m_,context:TC})).toString("base64");return{signature:await Rn(n,"verify Visa CLI Touch ID setup"),nonce:t,amount:f_,merchant:m_}}async function CC(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:p_,merchant:g_,context:kC})).toString("base64");return{signature:await Rn(n,"create a Visa Key",{timeoutMs:AC}),nonce:t,amount:p_,merchant:g_}}async function RC(e){let t=await e.getStatus();return t.attestationRequired!==!1||Et(t)}async function IC(e){let t=await Ap(),n=await EC(e);await e.registerAttestationKey(t,n)}async function w_(e,t,n=!1){let r=await Ui();console.log(" Attestation key generated."),await e.registerAttestationKey(r),console.log(" Attestation key registered with server."),t&&(await e.setBiometricPreference({required:!0}),n&&h.info("attestation:requirement-restored-after-recovery",{surface:"setup"}),console.log(n?" Touch ID requirement re-enabled after biometric recovery.":" Touch ID requirement enabled."))}async function ud(e){if(!await gd(e))throw new Error("Could not clear stale server biometric state. Run `visa-cli config reset`, then `visa-cli setup`.");await w_(e,!0,!0)}function Ya(e){return async()=>{let t=await gd(e);return{success:t,...t?{}:{message:"Biometric recovery was not completed."}}}}async function $C(e){let r=Date.now()+3e5;for(;Date.now()<r;)try{let s=await globalThis.fetch(`${$e()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:3e4}),signal:AbortSignal.timeout(35e3)});if(!s.ok){await hn(s,i=>{h.warn("auth_status:retry_after_http_error",{status:s.status,delayMs:i})});continue}let o=await s.json();if(o.status==="pending")continue;if(o.status==="complete"&&o.attestationCleared)return;if(o.status==="expired")throw new Error("Biometric reset session expired. Please run visa-cli config reset again.");if(o.status==="error")throw new Error(o.error||"Biometric reset failed. Please try again.")}catch(s){if(s?.message&&!/fetch failed|network|abort/i.test(s.message))throw s;await hn(void 0,o=>{h.warn("auth_status:retry_after_network_error",{delayMs:o})})}throw new Error("Biometric reset timed out after 5 minutes. Please run visa-cli config reset again.")}async function gd(e){let t;try{t=await e.getStatus()}catch(s){let o=s?.message||"";if(/not logged in|session.*expired|no local credentials/i.test(o))return!1;throw new Error(`Could not check server biometric state: ${o||"unknown error"}`)}if(!Et(t))return!1;let n=Ga.randomUUID(),r=await e.startAttestationRecovery(n);if(!r.success||!r.recoveryUrl)throw new Error(r.error||"Could not start biometric reset.");return console.log(" Server biometric key found. Opening GitHub to confirm reset..."),await yc(r.recoveryUrl),await $C(n),console.log(" Server biometric state cleared."),!0}function Ho(e){return`$${(e/100).toFixed(2)}`}function PC(e){return typeof e=="number"?Ho(e):"no cap"}function qa(e,t,n=!1){if(!e){let i=Ho(t);return n&&t>=0?`+${i}`:i}let r=(0,Wa.fromWire)(e),s=r%10000n===0n?2:6,o=(0,Wa.toDisplay)(r,{decimals:s});return n&&r>=0n?`+${o}`:o}function OC(e){return qa(e,0)}function MC(e){let t=`visa-cli-${re.hostname()||"local"}`,n=(e?.trim()||t).trim();if(!n)throw new Error("Visa Key label is required.");if(n.length>128)throw new Error("Visa Key label must be 128 characters or fewer.");return n}function NC(e){if(!e)return;let t=e.split(",").map(o=>o.trim()).filter(Boolean),n=Array.from(new Set(t)),r=n.find(o=>o.length>64);if(r)throw new Error(`Tool id is too long: ${r}`);let s=n.find(o=>xC.has(o));if(s)throw new Error(`Tool id "${s}" is retired for direct API-key access. Use category meta-tools or discover/execute instead.`);return n}var md=!1;async function S_(e){let t=(0,pd.createInterface)({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function LC(e,t=!1){let n=tm(e,{json:t,isTTY:process.stdin.isTTY===!0});if(n!==void 0)return n;if(await Pc("Use recommended Visa Key caps ($5/day and $25 total)? Without caps, leaked keys can spend from prepaid balance until revoked.",!0))return md=!0,500;let s=await S_("Daily cap USD (1-100): ");if(!s)throw new Error("--daily-cap is required when declining the recommended daily cap.");return Mc(s)}async function UC(e,t=!1){let n=nm(e,{json:t,isTTY:process.stdin.isTTY===!0,recommendedCapsAccepted:md});if(n!==void 0)return md=!1,n;let r=await S_("Cumulative cap USD (1-10000, default 25): ");return Nc(r||"25")}function DC(e){return e&&e.length>0?e.join(", "):"all tools"}function x_(e,t){if(!e)return{};try{let n=JSON.parse(e);if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`${t} must be a JSON object.`);return n}catch(n){throw new Error(`${t} must be valid JSON: ${n.message}`)}}function za(e,t={}){let n=t.format&&ti(t.format)?t.format:void 0;if(t.json||n!==void 0){let i=t.command??"tool.run",a=n??"json",c,l=e?.content?.[0]?.text;typeof l=="string"&&(c=l);let u=Array.isArray(e?.urls)&&typeof e.urls[0]=="string"?e.urls[0]:void 0;if(!c&&u&&u.startsWith("data:")&&(c=u),c)try{let d=Hr(c);if(d){let f=typeof e?.merchantName=="string"?e.merchantName:"media",m=typeof e?.transactionId=="string"?`${f}-${e.transactionId}`:f,p=Ds(d,{tag:m}),g=fc(i,e);g.success&&(g.filePath=p.filePath,g.mime=p.mime,g.bytes=p.bytes,u&&u.startsWith("data:")&&(g.urls=void 0)),Hs(g,a);return}}catch(d){Hs(js(i,`Failed to save inline media: ${d instanceof Error?d.message:String(d)}`),a),process.exitCode=k_;return}Hs(fc(i,e),a);return}if(e?.content?.[0]?.text&&typeof e.content[0].text=="string"){try{let i=Hr(e.content[0].text);if(i){let a=typeof e?.merchantName=="string"?e.merchantName:"media",c=typeof e?.transactionId=="string"?`${a}-${e.transactionId}`:a,l=Ds(i,{tag:c});console.log("Saved inline image to file:"),console.log(` ${l.filePath}`),console.log(` (${l.mime}, ${(l.bytes/1024).toFixed(1)} KB)`),console.log(` Open with: open "${l.filePath}"`);return}}catch(i){console.error(`(warning: could not save inline image to disk: ${i instanceof Error?i.message:String(i)})`)}console.log(e.content[0].text);return}let s=Array.isArray(e?.urls)?e.urls:Array.isArray(e?.receipt?.urls)?e.receipt.urls:[];if(e?.success===!1){let i=JSON.stringify(e,null,2);console.log("Result:"),console.log(i);return}if(Hd(e)){console.log("In Queue"),dc(e);let i=typeof e?.request_id=="string"?e.request_id:"<request_id>",c=`visa-cli merchants run check_fal_status --json '{"model_path":"${typeof e?.model_path=="string"?e.model_path:"<model_path>"}","request_id":"${i}"}'`;console.log(`
203
+ `)):e}function Bo(e,t="global"){let n=t==="project"?F.join(process.cwd(),".mcp.json"):Fa(e);try{let r=F.dirname(n);W.existsSync(r)||W.mkdirSync(r,{recursive:!0});let s=od(e,t),o=l_();if(s==="toml"){let i=W.existsSync(n)?W.readFileSync(n,"utf-8"):"",a=gE(i,"visa-cli",o);W.writeFileSync(n,a)}else{let i={};if(W.existsSync(n))try{i=JSON.parse(W.readFileSync(n,"utf-8"))}catch{i={}}i[e.configKey]=i[e.configKey]||{},i[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(o):o,W.writeFileSync(n,JSON.stringify(i,null,2)+`
204
+ `)}}catch(r){throw uE(r)?new Is(e,n,r):r}return{installed:!0,configPath:n,message:e.postInstallHint}}function cd(e,t="global"){let n=t==="project"?F.join(process.cwd(),".mcp.json"):Fa(e);if(!W.existsSync(n))return{removed:!1,configPath:n};if(od(e,t)==="toml"){let i=W.readFileSync(n,"utf-8");return ad(i,"visa-cli")?(W.writeFileSync(n,hE(i,"visa-cli")),{removed:!0,configPath:n}):{removed:!1,configPath:n}}let s;try{s=JSON.parse(W.readFileSync(n,"utf-8"))}catch{return{removed:!1,configPath:n}}let o=s[e.configKey];return!o||!o["visa-cli"]?{removed:!1,configPath:n}:(delete o["visa-cli"],W.writeFileSync(n,JSON.stringify(s,null,2)+`
205
+ `),{removed:!0,configPath:n})}function u_(e,t="global"){let n=t==="project"?F.join(process.cwd(),".mcp.json"):Fa(e);if(!W.existsSync(n))return!1;if(od(e,t)==="toml")try{let s=W.readFileSync(n,"utf-8");return!!ad(s,"visa-cli")}catch{return!1}try{return!!JSON.parse(W.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function yE(e){if(!e||typeof e!="object")return;let t=e;if(t.command!=="node"||!Array.isArray(t.args)||t.args.length===0)return;let n=t.args[t.args.length-1];if(!(typeof n!="string"||n.length===0))return n}function _E(e,t){if(e===t)return!0;let n=F.resolve(e),r=F.resolve(t);if(n===r)return!0;try{let s=W.realpathSync(n),o=W.realpathSync(r);return s===o}catch{return!1}}function Fo(){let e=l_(),t=e.args[e.args.length-1],n=[];for(let r of ht){let s=Fa(r);if(!W.existsSync(s))continue;let o=r.configFormat??"json",i;if(o==="toml")try{let l=W.readFileSync(s,"utf-8");i=ad(l,"visa-cli")}catch{continue}else{let l;try{l=JSON.parse(W.readFileSync(s,"utf-8"))}catch{continue}i=l?.[r.configKey]?.["visa-cli"]}if(!i)continue;let a=yE(i);if(!a||_E(a,t))continue;let c=W.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:s,currentPath:a,expectedPath:t,staleReason:c})}return n}function ld(e){return{configPath:Bo(e.client,"global").configPath}}var md=(0,v_.promisify)(b_.execFile);function ud(){let e=Bt();setImmediate(()=>{Ec(e,{getCommand:()=>pi(process.execPath,process.argv[1])})})}process.stdout.on("error",e=>{throw e.code==="EPIPE"&&process.exit(0),e});process.stderr.on("error",e=>{throw e.code==="EPIPE"&&process.exit(0),e});function xE(e){let t=re.homedir(),n=s=>s.replace(t,"~"),r=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
206
+ ${r}: ${n(e.currentPath)}`}function w_(e,t){if(e.length===0){console.log(`${t} \u2713 All MCP client configs are up to date.`);return}console.log(`${t} Found ${e.length} stale MCP config ${e.length===1?"entry":"entries"}:`);for(let n of e)console.log(xE(n))}function d_(e){console.log(` ! ${e.client.displayName} skipped: ${e.message}`)}function Lt(){this.help({error:!1})}var J=new __.Command,TE=new Set(["pay",...nd]),qa=null,Ho=!1;function pe(){return qa=new qe(()=>G.getSessionToken()),qa}function f_(e){if(e instanceof er)return!0;let t=e instanceof Error?e.message:"";return/attestation required|invalid signature|rotate biometric key|biometric key/i.test(t)}var m_=0,p_="",AE="attestation-key-rotation",kE="api-keys-create",g_=0,h_="",CE=12e3;async function EE(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:m_,merchant:p_,context:AE})).toString("base64");return{signature:await Rn(n,"verify Visa CLI Touch ID setup"),nonce:t,amount:m_,merchant:p_}}async function RE(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:g_,merchant:h_,context:kE})).toString("base64");return{signature:await Rn(n,"create a Visa Key",{timeoutMs:CE}),nonce:t,amount:g_,merchant:h_}}async function IE(e){let t=await e.getStatus();return t.attestationRequired!==!1||Ct(t)}async function PE(e){let t=await Cp(),n=await EE(e);await e.registerAttestationKey(t,n)}async function S_(e,t,n=!1){let r=await Di();console.log(" Attestation key generated."),await e.registerAttestationKey(r),console.log(" Attestation key registered with server."),t&&(await e.setBiometricPreference({required:!0}),n&&h.info("attestation:requirement-restored-after-recovery",{surface:"setup"}),console.log(n?" Touch ID requirement re-enabled after biometric recovery.":" Touch ID requirement enabled."))}async function dd(e){if(!await hd(e))throw new Error("Could not clear stale server biometric state. Run `visa-cli config reset`, then `visa-cli setup`.");await S_(e,!0,!0)}function za(e){return async()=>{let t=await hd(e);return{success:t,...t?{}:{message:"Biometric recovery was not completed."}}}}async function $E(e){let r=Date.now()+3e5;for(;Date.now()<r;)try{let s=await globalThis.fetch(`${Pe()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:3e4}),signal:AbortSignal.timeout(35e3)});if(!s.ok){await hn(s,i=>{h.warn("auth_status:retry_after_http_error",{status:s.status,delayMs:i})});continue}let o=await s.json();if(o.status==="pending")continue;if(o.status==="complete"&&o.attestationCleared)return;if(o.status==="expired")throw new Error("Biometric reset session expired. Please run visa-cli config reset again.");if(o.status==="error")throw new Error(o.error||"Biometric reset failed. Please try again.")}catch(s){if(s?.message&&!/fetch failed|network|abort/i.test(s.message))throw s;await hn(void 0,o=>{h.warn("auth_status:retry_after_network_error",{delayMs:o})})}throw new Error("Biometric reset timed out after 5 minutes. Please run visa-cli config reset again.")}async function hd(e){let t;try{t=await e.getStatus()}catch(s){let o=s?.message||"";if(/not logged in|session.*expired|no local credentials/i.test(o))return!1;throw new Error(`Could not check server biometric state: ${o||"unknown error"}`)}if(!Ct(t))return!1;let n=Wa.randomUUID(),r=await e.startAttestationRecovery(n);if(!r.success||!r.recoveryUrl)throw new Error(r.error||"Could not start biometric reset.");return console.log(" Server biometric key found. Opening GitHub to confirm reset..."),await _c(r.recoveryUrl),await $E(n),console.log(" Server biometric state cleared."),!0}function Vo(e){return`$${(e/100).toFixed(2)}`}function OE(e){return typeof e=="number"?Vo(e):"no cap"}function Ka(e,t,n=!1){if(!e){let i=Vo(t);return n&&t>=0?`+${i}`:i}let r=(0,Ya.fromWire)(e),s=r%10000n===0n?2:6,o=(0,Ya.toDisplay)(r,{decimals:s});return n&&r>=0n?`+${o}`:o}function ME(e){return Ka(e,0)}function NE(e){let t=`visa-cli-${re.hostname()||"local"}`,n=(e?.trim()||t).trim();if(!n)throw new Error("Visa Key label is required.");if(n.length>128)throw new Error("Visa Key label must be 128 characters or fewer.");return n}function LE(e){if(!e)return;let t=e.split(",").map(o=>o.trim()).filter(Boolean),n=Array.from(new Set(t)),r=n.find(o=>o.length>64);if(r)throw new Error(`Tool id is too long: ${r}`);let s=n.find(o=>TE.has(o));if(s)throw new Error(`Tool id "${s}" is retired for direct API-key access. Use category meta-tools or discover/execute instead.`);return n}var pd=!1;async function x_(e){let t=(0,gd.createInterface)({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function UE(e,t=!1){let n=nm(e,{json:t,isTTY:process.stdin.isTTY===!0});if(n!==void 0)return n;if(await Oc("Use recommended Visa Key caps ($5/day and $25 total)? Without caps, leaked keys can spend from prepaid balance until revoked.",!0))return pd=!0,500;let s=await x_("Daily cap USD (1-100): ");if(!s)throw new Error("--daily-cap is required when declining the recommended daily cap.");return Nc(s)}async function DE(e,t=!1){let n=rm(e,{json:t,isTTY:process.stdin.isTTY===!0,recommendedCapsAccepted:pd});if(n!==void 0)return pd=!1,n;let r=await x_("Cumulative cap USD (1-10000, default 25): ");return Lc(r||"25")}function jE(e){return e&&e.length>0?e.join(", "):"all tools"}function T_(e,t){if(!e)return{};try{let n=JSON.parse(e);if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`${t} must be a JSON object.`);return n}catch(n){throw new Error(`${t} must be valid JSON: ${n.message}`)}}function Ja(e,t={}){let n=t.format&&ni(t.format)?t.format:void 0;if(t.json||n!==void 0){let i=t.command??"tool.run",a=n??"json",c,l=e?.content?.[0]?.text;typeof l=="string"&&(c=l);let u=Array.isArray(e?.urls)&&typeof e.urls[0]=="string"?e.urls[0]:void 0;if(!c&&u&&u.startsWith("data:")&&(c=u),c)try{let d=Hr(c);if(d){let f=typeof e?.merchantName=="string"?e.merchantName:"media",m=typeof e?.transactionId=="string"?`${f}-${e.transactionId}`:f,p=Ds(d,{tag:m}),g=mc(i,e);g.success&&(g.filePath=p.filePath,g.mime=p.mime,g.bytes=p.bytes,u&&u.startsWith("data:")&&(g.urls=void 0)),Hs(g,a);return}}catch(d){Hs(js(i,`Failed to save inline media: ${d instanceof Error?d.message:String(d)}`),a),process.exitCode=k_;return}Hs(mc(i,e),a);return}if(e?.content?.[0]?.text&&typeof e.content[0].text=="string"){try{let i=Hr(e.content[0].text);if(i){let a=typeof e?.merchantName=="string"?e.merchantName:"media",c=typeof e?.transactionId=="string"?`${a}-${e.transactionId}`:a,l=Ds(i,{tag:c});console.log("Saved inline image to file:"),console.log(` ${l.filePath}`),console.log(` (${l.mime}, ${(l.bytes/1024).toFixed(1)} KB)`),console.log(` Open with: open "${l.filePath}"`);return}}catch(i){console.error(`(warning: could not save inline image to disk: ${i instanceof Error?i.message:String(i)})`)}console.log(e.content[0].text);return}let s=Array.isArray(e?.urls)?e.urls:Array.isArray(e?.receipt?.urls)?e.receipt.urls:[];if(e?.success===!1){let i=JSON.stringify(e,null,2);console.log("Result:"),console.log(i);return}if(Vd(e)){console.log("In Queue"),fc(e);let i=typeof e?.request_id=="string"?e.request_id:"<request_id>",c=`visa-cli merchants run check_fal_status --json '{"model_path":"${typeof e?.model_path=="string"?e.model_path:"<model_path>"}","request_id":"${i}"}'`;console.log(`
207
207
  \u2139 Your request is processing. Poll for the result with:
208
208
  ${c}`);let l=JSON.stringify(e,null,2);l&&l!=="{}"&&(console.log(`
209
- Result:`),console.log(l));return}if(console.log("Done"),dc(e),s.length>0){console.log(`
209
+ Result:`),console.log(l));return}if(console.log("Done"),fc(e),s.length>0){console.log(`
210
210
  Result URLs:`);for(let i of s)console.log(` ${i}`);return}let o=JSON.stringify(e,null,2);o&&o!=="{}"&&(console.log(`
211
- Result:`),console.log(o))}var jC=new Set(["INVALID_TOOL_PARAMS","MISSING_TOOL_ID","UNKNOWN_TOOL"]),T_=0,k_=1,BC=2;function FC(e){if(e?.success!==!1)return T_;let n=(typeof e?.error_code=="string"?e.error_code:typeof e?.code=="string"?e.code:"").toUpperCase();return jC.has(n)?BC:k_}function Ja(e){let t=FC(e);t!==T_&&(process.exitCode=t)}function $s(e,t,n={}){let r=typeof n=="boolean"?{json:n}:n,s=t instanceof Error?t.message:String(t),o=r.format&&ti(r.format)?r.format:void 0;if(r.json||o!==void 0){let i=o??"json";Hs(js(e,s),i)}else console.error("Error:",s);process.exit(1)}async function HC(e,t={}){let n=await e.catalogSearch(t.query,t.category,"discover_tools",{limit:t.limit,offset:t.offset});return{tools:Array.isArray(n.tools)?n.tools:[],hidden:n.hidden}}var hd=100,yd=200;function Ka(e){let t=Number.parseInt(e,10);return Number.isNaN(t)?Number.NaN:t}function VC(e){let t=typeof e.limit=="number"&&Number.isInteger(e.limit)?Math.max(1,Math.min(e.limit,yd)):hd,n=typeof e.offset=="number"&&Number.isInteger(e.offset)?Math.max(0,e.offset):0;return{limit:t,offset:n}}function qC(e){let t=`
211
+ Result:`),console.log(o))}var BE=new Set(["INVALID_TOOL_PARAMS","MISSING_TOOL_ID","UNKNOWN_TOOL"]),A_=0,k_=1,FE=2;function HE(e){if(e?.success!==!1)return A_;let n=(typeof e?.error_code=="string"?e.error_code:typeof e?.code=="string"?e.code:"").toUpperCase();return BE.has(n)?FE:k_}function Xa(e){let t=HE(e);t!==A_&&(process.exitCode=t)}function Ps(e,t,n={}){let r=typeof n=="boolean"?{json:n}:n,s=t instanceof Error?t.message:String(t),o=r.format&&ni(r.format)?r.format:void 0;if(r.json||o!==void 0){let i=o??"json";Hs(js(e,s),i)}else console.error("Error:",s);process.exit(1)}async function VE(e,t={}){let n=await e.catalogSearch(t.query,t.category,"discover_tools",{limit:t.limit,offset:t.offset});return{tools:Array.isArray(n.tools)?n.tools:[],hidden:n.hidden}}var yd=100,_d=200;function Ga(e){let t=Number.parseInt(e,10);return Number.isNaN(t)?Number.NaN:t}function qE(e){let t=typeof e.limit=="number"&&Number.isInteger(e.limit)?Math.max(1,Math.min(e.limit,_d)):yd,n=typeof e.offset=="number"&&Number.isInteger(e.offset)?Math.max(0,e.offset):0;return{limit:t,offset:n}}function KE(e){let t=`
212
212
  Options:
213
213
  `,n=`
214
214
  Commands:
215
- `,r=e.indexOf(t),s=e.indexOf(n);if(r===-1||s===-1||r>s)return e;let o=f=>{let p=e.slice(f+1).search(/\n[A-Z][A-Za-z ]+:\n/);return p===-1?e.length:f+1+p},i=o(r),a=o(s),c=e.slice(0,r),l=e.slice(r,i),u=e.slice(s,a),d=e.slice(a);return`${c}${u}${l}${d}`}function KC(e){if(!e.startsWith("Usage: "))return e;let t=e.indexOf(`
215
+ `,r=e.indexOf(t),s=e.indexOf(n);if(r===-1||s===-1||r>s)return e;let o=f=>{let p=e.slice(f+1).search(/\n[A-Z][A-Za-z ]+:\n/);return p===-1?e.length:f+1+p},i=o(r),a=o(s),c=e.slice(0,r),l=e.slice(r,i),u=e.slice(s,a),d=e.slice(a);return`${c}${u}${l}${d}`}function GE(e){if(!e.startsWith("Usage: "))return e;let t=e.indexOf(`
216
216
 
217
217
  `);if(t===-1)return e;let n=e.slice(0,t),r=e.slice(t+2),s=r.indexOf(`
218
218
 
@@ -220,18 +220,18 @@ Commands:
220
220
 
221
221
  ${n}
222
222
 
223
- ${i}`:e}function GC(e){return e.replace(/(^|\n)(Commands:\n)([\s\S]*?)(?=\n[A-Z][A-Za-z ]+:\n|$)/g,(t,n,r,s)=>{let o=s.split(`
224
- `).map(WC).join(`
225
- `);return`${n}${r}${o}`})}function WC(e){if(!e.startsWith(" "))return e;let n=2,r=n;for(;r<e.length&&e[r]!==" "&&e[r]!==" ";)r+=1;if(r===n)return e;let s=-1;for(let c=r;c<e.length-1;c+=1){if(e[c]!==" "||e[c+1]!==" ")continue;let l=c+2;for(;l<e.length&&e[l]===" ";)l+=1;if(l<e.length){s=l;break}}if(s===-1)return e;let o=e.slice(n,r),i=e.slice(s),a=Math.max(2,s-2-o.length);return` ${o}${" ".repeat(a)}${i}`}function YC(e){return e.replace(/^(Usage: .+?) \[options\](?= |$)/gm,"$1")}function zC(e){return e.replace(/^Options:$/gm,"Flags:")}function A_(e){let t=e.helpInformation.bind(e);e.helpInformation=()=>zC(YC(GC(qC(KC(t())))));for(let n of e.commands)A_(n)}function JC(e){let t=new Map(e.map((r,s)=>[r,s]));J.commands.sort((r,s)=>{let o=t.get(r.name())??Number.MAX_SAFE_INTEGER,i=t.get(s.name())??Number.MAX_SAFE_INTEGER;return o-i})}J.name("visa-cli").description("Visa CLI - set up MCP payments, manage credentials, and monitor AI spend").version(Us().version).addHelpCommand(!1).action(Lt);J.hook("preAction",async()=>{await Bd()});J.command("setup").description("Register MCP server, authenticate, and generate attestation key").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--yes","Accept setup prompts without asking for unattended setup").option("--hud","Install the Visa HUD during setup without prompting").option("--no-hud","Skip installing the Visa HUD during setup").action(async e=>{let t=!1,n=()=>{t||(t=!0,console.log(`
223
+ ${i}`:e}function WE(e){return e.replace(/(^|\n)(Commands:\n)([\s\S]*?)(?=\n[A-Z][A-Za-z ]+:\n|$)/g,(t,n,r,s)=>{let o=s.split(`
224
+ `).map(YE).join(`
225
+ `);return`${n}${r}${o}`})}function YE(e){if(!e.startsWith(" "))return e;let n=2,r=n;for(;r<e.length&&e[r]!==" "&&e[r]!==" ";)r+=1;if(r===n)return e;let s=-1;for(let c=r;c<e.length-1;c+=1){if(e[c]!==" "||e[c+1]!==" ")continue;let l=c+2;for(;l<e.length&&e[l]===" ";)l+=1;if(l<e.length){s=l;break}}if(s===-1)return e;let o=e.slice(n,r),i=e.slice(s),a=Math.max(2,s-2-o.length);return` ${o}${" ".repeat(a)}${i}`}function zE(e){return e.replace(/^(Usage: .+?) \[options\](?= |$)/gm,"$1")}function JE(e){return e.replace(/^Options:$/gm,"Flags:")}function C_(e){let t=e.helpInformation.bind(e);e.helpInformation=()=>JE(zE(WE(KE(GE(t())))));for(let n of e.commands)C_(n)}function XE(e){let t=new Map(e.map((r,s)=>[r,s]));J.commands.sort((r,s)=>{let o=t.get(r.name())??Number.MAX_SAFE_INTEGER,i=t.get(s.name())??Number.MAX_SAFE_INTEGER;return o-i})}J.name("visa-cli").description("Visa CLI - set up MCP payments, manage credentials, and monitor AI spend").version(Us().version).addHelpCommand(!1).action(Lt);J.hook("preAction",async()=>{await Fd()});J.command("setup").description("Register MCP server, authenticate, and generate attestation key").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--yes","Accept setup prompts without asking for unattended setup").option("--hud","Install the Visa HUD during setup without prompting").option("--no-hud","Skip installing the Visa HUD during setup").action(async e=>{let t=!1,n=()=>{t||(t=!0,console.log(`
226
226
 
227
- Setup interrupted.`),console.log(" If you signed in via the browser but did not finish card enrollment, the"),console.log(" server-side enrollment may have expired. Re-run `visa-cli setup` \u2014 it will"),console.log(" resume from your current state or restart cleanly."),console.log(""),process.exit(130))};process.on("SIGINT",n);let r=()=>{process.removeListener("SIGINT",n)};try{if(e.check){let w=Bo();v_(w,"MCP config check:"),w.length>0&&(console.log("\nRun `visa-cli setup` (or `visa-cli install --repair`) to rewrite these entries."),r(),process.exit(1)),r();return}console.log("Step 1: Registering MCP server...");let s=Bo(),o=new Map(s.map(w=>[w.client.id,w])),i=new Set,a=new Set,c=new Set;for(let w of ht)if(Do(w)){let S;try{S=jo(w)}catch(y){if(y instanceof Is){u_(y),a.add(w.displayName),c.add(w.id);continue}throw y}let C=o.get(w.id),I=C?` \u2014 repaired stale ${C.staleReason} entry`:"";console.log(` \u2713 ${w.displayName} (${S.configPath.replace(re.homedir(),"~")})${I}`),C&&i.add(w.id)}let l=s.filter(w=>!i.has(w.client.id)&&!c.has(w.client.id)),u=0;for(let w of l){try{cd(w)}catch(S){if(S instanceof Is){u_(S),a.add(w.client.displayName),c.add(w.client.id);continue}throw S}console.log(` \u2713 ${w.client.displayName} (${w.configPath.replace(re.homedir(),"~")}) \u2014 repaired stale ${w.staleReason} entry`),u++}let d=i.size+u;d===0&&a.size===0?console.log(" \u2713 MCP config verified \u2014 nothing to repair."):d>0&&console.log(` \u2713 Repaired ${d} stale MCP config ${d===1?"entry":"entries"}.`),a.size>0&&console.log(` ! Skipped MCP registration for: ${Array.from(a).join(", ")}. Rerun with access to those config files to complete registration.`),console.log(`
228
- Step 2: Checking authentication...`);let f=await G.getSessionToken();if(f)try{await new qe(()=>Promise.resolve(f)).getStatus(),console.log(" Already authenticated.")}catch(w){let S=w instanceof Error?w.message:"";S.includes("session has expired")||S.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await Wy(),f=null):console.log(` Couldn't verify session (${S||"unknown error"}) \u2014 continuing with existing token.`)}if(!f){let w=null;try{let{stdout:S}=await fd("gh",["auth","token"],{timeout:5e3});w=S.trim()}catch{}if(w||(w=process.env.GITHUB_TOKEN||null),w)try{console.log(" Found GitHub token \u2014 attempting headless login...");let S=await globalThis.fetch(`${$e()}/v1/auth/token-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({github_token:w}),signal:AbortSignal.timeout(1e4)});if(S.ok){let C=await S.json();if(C.success&&C.sessionToken){let I=C.sessionToken;f=I,await G.saveSessionToken(I),console.log(` Signed in as ${C.user} (headless).`)}}else(await S.json().catch(()=>({}))).hint==="card_required"&&console.log(" GitHub token valid but no card on file \u2014 opening browser to finish onboarding...")}catch{}}if(f||(console.log(" No session found. Opening browser for GitHub login..."),f=await new Promise(async(w,S)=>{let C=Ga.randomUUID(),I=`${$e()}/login?state=${C}`;await yc(I);let y=3e4,T=300*1e3,z=Date.now()+T;for(;Date.now()<z;)try{let Z=await globalThis.fetch(`${$e()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:C,timeout:y}),signal:AbortSignal.timeout(y+5e3)});if(!Z.ok){await hn(Z,be=>{h.warn("auth_status:retry_after_http_error",{status:Z.status,delayMs:be})});continue}let H=await Z.json();if(H.status==="pending")continue;if(H.status==="expired"){S(new Error("Session expired. Please run setup again."));return}if(H.status==="complete"&&H.sessionToken){console.log(` Signed in as ${H.user}.`),w(H.sessionToken);return}}catch{await hn(void 0,Z=>{h.warn("auth_status:retry_after_network_error",{delayMs:Z})})}S(new Error("Login timed out after 5 minutes. Please run setup again."))}),await G.saveSessionToken(f),console.log(" Session token saved.")),console.log(`
229
- Step 3: Setting up authentication...`),de()){try{await fd("clang",["--version"])}catch{console.error(" Xcode Command Line Tools are required for payment authentication."),console.error(" Install them by running: xcode-select --install"),console.error(" Then re-run: visa-cli setup"),process.exit(1)}let w=pe();try{let S=await w.getStatus(),C=!0;if(Et(S))if(await Di())try{await IC(w),console.log(" Attestation key already registered with server."),console.log(" Existing local Touch ID key verified and preserved."),C=!1}catch(I){if(!d_(I))throw I;console.log(" Existing local Touch ID key does not match server biometric state."),await ud(w),C=!1}else console.log(" Server already has a biometric key, but this device has no local key."),await ud(w),C=!1;C&&await w_(w,S.attestationRequired===!1)}catch(S){let C=S?.message||"unknown error";if(d_(S)){console.log(" Server already has a biometric key for this account, but this device cannot prove access to it.");let I=!1;try{await ud(w),I=!0}catch(y){console.error(` Biometric recovery failed: ${y?.message||"unknown error"}`)}if(!I){let y=S instanceof er&&S.hint?S.hint:"Run `visa-cli config reset` to clear server-side biometric state through GitHub, then run `visa-cli setup` again.";console.error(` ${y}`),process.exit(1)}}else console.error(` Biometric setup failed: ${C}`),process.exit(1)}}else{let w=pe(),S;try{S=await w.getStatus()}catch(I){console.error(" Biometric attestation (Touch ID or Windows Hello) is unavailable in this process."),console.error(` Could not verify server biometric policy: ${I?.message||"unknown error"}`),console.error(" Re-run setup from an interactive device with Touch ID (Mac) or Windows Hello (PC) before using payment commands."),process.exit(1)}let C=Gy(S);C.canContinue||(console.error(` ${C.message}`),C.hint&&console.error(` ${C.hint}`),process.exit(1)),console.log(` ${C.message}`)}let m=Bt(),p=ce.existsSync(tt.join(re.homedir(),".claude.json")),g=e.hud===!0;if(e.hud===void 0&&p&&!e.yes&&process.stdin.isTTY&&(console.log(`
230
- Step 4: Visa HUD`),console.log(" Pin balance, card, spend, model, and session activity below the Claude Code input."),console.log(Yf()),g=await Pc(" Install the Visa HUD now?",!1)),g)if(!p)console.log(`
227
+ Setup interrupted.`),console.log(" If you signed in via the browser but did not finish card enrollment, the"),console.log(" server-side enrollment may have expired. Re-run `visa-cli setup` \u2014 it will"),console.log(" resume from your current state or restart cleanly."),console.log(""),process.exit(130))};process.on("SIGINT",n);let r=()=>{process.removeListener("SIGINT",n)};try{if(e.check){let w=Fo();w_(w,"MCP config check:"),w.length>0&&(console.log("\nRun `visa-cli setup` (or `visa-cli install --repair`) to rewrite these entries."),r(),process.exit(1)),r();return}console.log("Step 1: Registering MCP server...");let s=Fo(),o=new Map(s.map(w=>[w.client.id,w])),i=new Set,a=new Set,c=new Set;for(let w of ht)if(jo(w)){let S;try{S=Bo(w)}catch(y){if(y instanceof Is){d_(y),a.add(w.displayName),c.add(w.id);continue}throw y}let E=o.get(w.id),I=E?` \u2014 repaired stale ${E.staleReason} entry`:"";console.log(` \u2713 ${w.displayName} (${S.configPath.replace(re.homedir(),"~")})${I}`),E&&i.add(w.id)}let l=s.filter(w=>!i.has(w.client.id)&&!c.has(w.client.id)),u=0;for(let w of l){try{ld(w)}catch(S){if(S instanceof Is){d_(S),a.add(w.client.displayName),c.add(w.client.id);continue}throw S}console.log(` \u2713 ${w.client.displayName} (${w.configPath.replace(re.homedir(),"~")}) \u2014 repaired stale ${w.staleReason} entry`),u++}let d=i.size+u;d===0&&a.size===0?console.log(" \u2713 MCP config verified \u2014 nothing to repair."):d>0&&console.log(` \u2713 Repaired ${d} stale MCP config ${d===1?"entry":"entries"}.`),a.size>0&&console.log(` ! Skipped MCP registration for: ${Array.from(a).join(", ")}. Rerun with access to those config files to complete registration.`),console.log(`
228
+ Step 2: Checking authentication...`);let f=await G.getSessionToken();if(f)try{await new qe(()=>Promise.resolve(f)).getStatus(),console.log(" Already authenticated.")}catch(w){let S=w instanceof Error?w.message:"";S.includes("session has expired")||S.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await Yy(),f=null):console.log(` Couldn't verify session (${S||"unknown error"}) \u2014 continuing with existing token.`)}if(!f){let w=null;try{let{stdout:S}=await md("gh",["auth","token"],{timeout:5e3});w=S.trim()}catch{}if(w||(w=process.env.GITHUB_TOKEN||null),w)try{console.log(" Found GitHub token \u2014 attempting headless login...");let S=await globalThis.fetch(`${Pe()}/v1/auth/token-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({github_token:w}),signal:AbortSignal.timeout(1e4)});if(S.ok){let E=await S.json();if(E.success&&E.sessionToken){let I=E.sessionToken;f=I,await G.saveSessionToken(I),console.log(` Signed in as ${E.user} (headless).`)}}else(await S.json().catch(()=>({}))).hint==="card_required"&&console.log(" GitHub token valid but no card on file \u2014 opening browser to finish onboarding...")}catch{}}if(f||(console.log(" No session found. Opening browser for GitHub login..."),f=await new Promise(async(w,S)=>{let E=Wa.randomUUID(),I=`${Pe()}/login?state=${E}`;await _c(I);let y=3e4,T=300*1e3,z=Date.now()+T;for(;Date.now()<z;)try{let Z=await globalThis.fetch(`${Pe()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:E,timeout:y}),signal:AbortSignal.timeout(y+5e3)});if(!Z.ok){await hn(Z,be=>{h.warn("auth_status:retry_after_http_error",{status:Z.status,delayMs:be})});continue}let H=await Z.json();if(H.status==="pending")continue;if(H.status==="expired"){S(new Error("Session expired. Please run setup again."));return}if(H.status==="complete"&&H.sessionToken){console.log(` Signed in as ${H.user}.`),w(H.sessionToken);return}}catch{await hn(void 0,Z=>{h.warn("auth_status:retry_after_network_error",{delayMs:Z})})}S(new Error("Login timed out after 5 minutes. Please run setup again."))}),await G.saveSessionToken(f),console.log(" Session token saved.")),console.log(`
229
+ Step 3: Setting up authentication...`),de()){try{await md("clang",["--version"])}catch{console.error(" Xcode Command Line Tools are required for payment authentication."),console.error(" Install them by running: xcode-select --install"),console.error(" Then re-run: visa-cli setup"),process.exit(1)}let w=pe();try{let S=await w.getStatus(),E=!0;if(Ct(S))if(await ji())try{await PE(w),console.log(" Attestation key already registered with server."),console.log(" Existing local Touch ID key verified and preserved."),E=!1}catch(I){if(!f_(I))throw I;console.log(" Existing local Touch ID key does not match server biometric state."),await dd(w),E=!1}else console.log(" Server already has a biometric key, but this device has no local key."),await dd(w),E=!1;E&&await S_(w,S.attestationRequired===!1)}catch(S){let E=S?.message||"unknown error";if(f_(S)){console.log(" Server already has a biometric key for this account, but this device cannot prove access to it.");let I=!1;try{await dd(w),I=!0}catch(y){console.error(` Biometric recovery failed: ${y?.message||"unknown error"}`)}if(!I){let y=S instanceof er&&S.hint?S.hint:"Run `visa-cli config reset` to clear server-side biometric state through GitHub, then run `visa-cli setup` again.";console.error(` ${y}`),process.exit(1)}}else console.error(` Biometric setup failed: ${E}`),process.exit(1)}}else{let w=pe(),S;try{S=await w.getStatus()}catch(I){console.error(" Biometric attestation (Touch ID or Windows Hello) is unavailable in this process."),console.error(` Could not verify server biometric policy: ${I?.message||"unknown error"}`),console.error(" Re-run setup from an interactive device with Touch ID (Mac) or Windows Hello (PC) before using payment commands."),process.exit(1)}let E=Wy(S);E.canContinue||(console.error(` ${E.message}`),E.hint&&console.error(` ${E.hint}`),process.exit(1)),console.log(` ${E.message}`)}let m=Bt(),p=ce.existsSync(tt.join(re.homedir(),".claude.json")),g=e.hud===!0;if(e.hud===void 0&&p&&!e.yes&&process.stdin.isTTY&&(console.log(`
230
+ Step 4: Visa HUD`),console.log(" Pin balance, card, spend, model, and session activity below the Claude Code input."),console.log(zf()),g=await Oc(" Install the Visa HUD now?",!1)),g)if(!p)console.log(`
231
231
  Step 4: HUD requested, but Claude Code config was not detected.`),console.log(" Skipped. Enable later with: visa-cli config hud enable");else{console.log(`
232
- Step 4: Enabling the Visa spend HUD...`);let w=zs(m),S=w.installed==="new"||w.installed==="already-visa"||w.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${S}${w.message}`);try{let C=pe(),I=await C.getStatus(),y={currentVersion:C.getClientVersion(),latestVersion:C.lastSignals?.updateAvailable?.latestVersion,updateCheckDisabled:St()},T=Sc(I,y);xc(T,I),console.log(` Preview: ${T.split(`
232
+ Step 4: Enabling the Visa spend HUD...`);let w=zs(m),S=w.installed==="new"||w.installed==="already-visa"||w.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${S}${w.message}`);try{let E=pe(),I=await E.getStatus(),y={currentVersion:E.getClientVersion(),latestVersion:E.lastSignals?.updateAvailable?.latestVersion,updateCheckDisabled:St()},T=xc(I,y);Tc(T,I),console.log(` Preview: ${T.split(`
233
233
  `)[0]}`)}catch{}}else e.hud!==!1&&(console.log(`
234
- Step 4: Visa HUD not installed.`),console.log(" Enable later with: visa-cli config hud enable"));let v="\x1B[1m",k="\x1B[2m",b="\x1B[0m";console.log(`
234
+ Step 4: Visa HUD not installed.`),console.log(" Enable later with: visa-cli config hud enable"));let v="\x1B[1m",A="\x1B[2m",b="\x1B[0m";console.log(`
235
235
  \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
236
236
  \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557
237
237
  \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551
@@ -253,76 +253,76 @@ Step 4: Visa HUD not installed.`),console.log(" Enable later with: visa-cli co
253
253
  \u2502 Shows your balance, active card, and recent tool usage \u2502
254
254
  \u2502 on every prompt. \u2502
255
255
  \u2502 \u2502
256
- \u2502 ${k}$${b} visa-cli config hud enable \u2502
256
+ \u2502 ${A}$${b} visa-cli config hud enable \u2502
257
257
  \u2502 \u2502
258
258
  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
259
259
 
260
260
  ${v}Verify:${b} visa-cli status
261
261
  ${v}Docs:${b} https://visacli.sh
262
- `),r()}catch(s){console.error("Error:",s.message),r(),process.exit(1)}});J.command("install [client]",{hidden:!0}).description("Register MCP server with an AI client (claude, cursor, windsurf, cline, zed, ...)").option("--all","Install for all detected clients").option("--list","Show supported clients and install status").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--repair","Repair stale MCP client configs without re-running the full setup flow").option("--scope <scope>","Install scope: global or project","global").action(async(e,t)=>{try{if(t.check){let o=Bo();v_(o,"MCP config check:"),o.length>0&&process.exit(1);return}if(t.repair){let o=Bo();if(o.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of o)cd(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(re.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
262
+ `),r()}catch(s){console.error("Error:",s.message),r(),process.exit(1)}});J.command("install [client]",{hidden:!0}).description("Register MCP server with an AI client (claude, cursor, windsurf, cline, zed, ...)").option("--all","Install for all detected clients").option("--list","Show supported clients and install status").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--repair","Repair stale MCP client configs without re-running the full setup flow").option("--scope <scope>","Install scope: global or project","global").action(async(e,t)=>{try{if(t.check){let o=Fo();w_(o,"MCP config check:"),o.length>0&&process.exit(1);return}if(t.repair){let o=Fo();if(o.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of o)ld(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(re.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
263
263
  Repaired ${o.length} stale MCP config ${o.length===1?"entry":"entries"}.`);return}if(t.list){console.log(`
264
264
  \x1B[1mSupported MCP Clients\x1B[0m
265
- `),console.log(` ${"Client".padEnd(18)} ${"Detected".padEnd(10)} ${"Installed".padEnd(11)} Config Path`),console.log(` ${"\u2500".repeat(18)} ${"\u2500".repeat(10)} ${"\u2500".repeat(11)} ${"\u2500".repeat(40)}`);for(let a of ht){let c=Do(a),l=l_(a),u=c?"Yes":"No",d=l?"Yes":"No",f=a.globalConfigPath.replace(re.homedir(),"~");console.log(` ${a.displayName.padEnd(18)} ${u.padEnd(10)} ${d.padEnd(11)} ${f}`)}console.log("");return}let n=t.scope==="project"?"project":"global";if(t.all){let o=[],i=[];for(let a of ht){if(!Do(a)){i.push(a.displayName);continue}jo(a,n),o.push(a.displayName)}o.length>0&&console.log(`Installed for: ${o.join(", ")}.`),i.length>0&&console.log(`Skipped: ${i.map(a=>`${a} (not detected)`).join(", ")}.`),o.length===0&&i.length===0&&console.log("No supported clients found.");return}e||(console.error("Usage: visa-cli install <client>"),console.error(" visa-cli install --all"),console.error(" visa-cli install --list"),console.error(`
266
- Supported clients: ${ht.map(o=>o.id).join(", ")}`),process.exit(1));let r=rd(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${ht.map(o=>o.id).join(", ")}`),process.exit(1)),n==="global"&&!Do(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let s=jo(r,n);console.log(`Registered visa-cli MCP server in ${s.configPath}`),console.log(s.message)}catch(n){console.error("Error:",n.message),process.exit(1)}});J.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{Fo=!1;try{let e=pe(),[t,n]=await Promise.all([e.getStatus(),e.getTransactions().catch(s=>{if(process.env.VISA_CLI_DEBUG){let o=s instanceof Error?s.message:String(s);process.stderr.write(`[visa-cli] getTransactions failed (HUD will omit): ${o}
267
- `)}return{transactions:[]}})]),r={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:St()};process.stdout.write(Vy(t,Array.isArray(n?.transactions)?n.transactions:[],de(),r)),Fo=!0}catch(e){Fo=!1,console.error("Error:",e.message),process.exit(1)}});function XC(e){let t=e.map(qy),n=Math.max(2,...t.map(i=>i.id.length)),r=Math.max(5,...t.map(i=>i.brand.length)),s=Math.max(4,...t.map(i=>i.card.length)),o=7;console.log(`
265
+ `),console.log(` ${"Client".padEnd(18)} ${"Detected".padEnd(10)} ${"Installed".padEnd(11)} Config Path`),console.log(` ${"\u2500".repeat(18)} ${"\u2500".repeat(10)} ${"\u2500".repeat(11)} ${"\u2500".repeat(40)}`);for(let a of ht){let c=jo(a),l=u_(a),u=c?"Yes":"No",d=l?"Yes":"No",f=a.globalConfigPath.replace(re.homedir(),"~");console.log(` ${a.displayName.padEnd(18)} ${u.padEnd(10)} ${d.padEnd(11)} ${f}`)}console.log("");return}let n=t.scope==="project"?"project":"global";if(t.all){let o=[],i=[];for(let a of ht){if(!jo(a)){i.push(a.displayName);continue}Bo(a,n),o.push(a.displayName)}o.length>0&&console.log(`Installed for: ${o.join(", ")}.`),i.length>0&&console.log(`Skipped: ${i.map(a=>`${a} (not detected)`).join(", ")}.`),o.length===0&&i.length===0&&console.log("No supported clients found.");return}e||(console.error("Usage: visa-cli install <client>"),console.error(" visa-cli install --all"),console.error(" visa-cli install --list"),console.error(`
266
+ Supported clients: ${ht.map(o=>o.id).join(", ")}`),process.exit(1));let r=sd(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${ht.map(o=>o.id).join(", ")}`),process.exit(1)),n==="global"&&!jo(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let s=Bo(r,n);console.log(`Registered visa-cli MCP server in ${s.configPath}`),console.log(s.message)}catch(n){console.error("Error:",n.message),process.exit(1)}});J.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{Ho=!1;try{let e=pe(),[t,n]=await Promise.all([e.getStatus(),e.getTransactions().catch(s=>{if(process.env.VISA_CLI_DEBUG){let o=s instanceof Error?s.message:String(s);process.stderr.write(`[visa-cli] getTransactions failed (HUD will omit): ${o}
267
+ `)}return{transactions:[]}})]),r={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:St()};process.stdout.write(qy(t,Array.isArray(n?.transactions)?n.transactions:[],de(),r)),Ho=!0}catch(e){Ho=!1,console.error("Error:",e.message),process.exit(1)}});function ZE(e){let t=e.map(Ky),n=Math.max(2,...t.map(i=>i.id.length)),r=Math.max(5,...t.map(i=>i.brand.length)),s=Math.max(4,...t.map(i=>i.card.length)),o=7;console.log(`
268
268
  Cards
269
269
  `),console.log(` ${"ID".padEnd(n)} ${"Brand".padEnd(r)} ${"Card".padEnd(s)} Default`),console.log(` ${"\u2500".repeat(n)} ${"\u2500".repeat(r)} ${"\u2500".repeat(s)} ${"\u2500".repeat(o)}`);for(let i of t)console.log(` ${i.id.padEnd(n)} ${i.brand.padEnd(r)} ${i.card.padEnd(s)} ${i.default}`);console.log(`
270
270
  Use:`),console.log(" visa-cli cards default <id>"),console.log(` visa-cli cards remove <id>
271
- `)}async function E_(e,t){if(t.yes)return"confirmed";if(!process.stdin.isTTY)return"refused-non-tty";let n=(0,pd.createInterface)({input:process.stdin,output:process.stdout});try{let r=(await n.question(`${e} [y/N] `)).trim();return/^y(es)?$/i.test(r)?"confirmed":"declined"}finally{n.close()}}var Xa=J.command("cards").description("Manage enrolled payment cards").addHelpCommand(!1).action(Lt);Xa.command("list").alias("ls").description("List enrolled payment cards").action(async()=>{try{let e=await lt.getCards("visa-cli cards list"),t=Array.isArray(e.cards)?e.cards:[];if(t.length===0){console.log(e.message||"No cards enrolled. Add one with: visa-cli cards add");return}XC(t)}catch(e){console.error("Error:",e.message),process.exit(1)}});Xa.command("add").description("Add a new Visa card").action(async()=>{try{let e=await lt.addCard("visa-cli cards add");if(e?.message){console.log(e.message);return}let t=e?.card?.last4;console.log(t?`Card ending in ****${t} enrolled.`:"Card enrollment complete.")}catch(e){console.error("Error:",e.message),process.exit(1)}});Xa.command("remove <card-id>").alias("rm").description("Remove an enrolled card").option("-y, --yes","Skip the interactive confirmation prompt").action(async(e,t)=>{try{let n=Gu(e),r=await E_(`Remove card ${n}? This cannot be undone.`,t);if(r==="refused-non-tty"&&(console.error("Refusing to remove card without --yes in a non-interactive shell."),process.exit(1)),r==="declined"){console.log("Aborted.");return}let s=await lt.removeCard({cardId:n,confirm:!0},"visa-cli cards remove");s?.success===!1&&(console.error(s.error||s.message||"Failed to remove card."),process.exit(1)),console.log(s?.message||`Removed card ${n}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});Xa.command("default <card-id>").alias("set-default").description("Set the default payment card").action(async e=>{try{let t=Gu(e),n=await lt.setDefaultCard({cardId:t},"visa-cli cards default");n?.success===!1&&(console.error(n.error||n.message||"Failed to set default card."),process.exit(1)),console.log(n?.message||`Set card ${t} as default.`)}catch(t){console.error("Error:",t.message),process.exit(1)}});function ZC(e){return/timed out waiting for touch id\/device approval|attestation[_\s-]?required/i.test(e)}function _d(e){let t=e instanceof Error?e.message:String(e);console.error("Error:",t),ZC(t)&&(console.error(""),console.error("Visa Key creation requires local Touch ID/device attestation because the key is a bearer spend credential."),console.error("In headless or sandboxed agents such as Codex, the native approval prompt may not appear. Run the same `visa-cli keys create ...` command from a foreground terminal, approve Touch ID, then store the created key in your app secret store.")),t.includes("Not logged in")&&(console.error(""),console.error("Hint: if `visa-cli status` or `visa-cli setup` says you are authenticated, this process may not have access to your macOS Keychain."),console.error("In sandboxed agents such as Codex, rerun the keys command with keychain access or run it from a normal terminal.")),process.exit(1)}function QC(e){let t=e instanceof Error?e.message:String(e);return t.includes("EMPLOYEE_ONLY_FEATURE")||t.includes("Visa Key management is limited to approved rollout users")}async function bd(e){let t=Object.prototype.hasOwnProperty.call(process.env,"VISA_CLI_API_KEY"),n=process.env.VISA_CLI_API_KEY;delete process.env.VISA_CLI_API_KEY;try{return await e()}finally{t&&(process.env.VISA_CLI_API_KEY=n)}}var vd=J.command("keys").description("Create and manage Visa Keys for apps and agents").addHelpCommand(!1).action(Lt);vd.command("create [label]").description("Create a Visa Key for the authenticated approved user").option("--tools <ids>","Comma-separated allowed tool ids (default: all tools)").option("--daily-cap <usd>","Daily cap in USD, between 1 and 100").option("--total-cap <usd>","Cumulative cap in USD, between 1 and 10000").option("--no-total-cap","Create without a cumulative cap (higher risk; daily cap still applies)").option("--json","Output raw JSON").action(async(e,t)=>{try{let n=await LC(t.dailyCap,t.json),r=await UC(t.totalCap,t.json),s=await bd(async()=>{let o=pe(),i={label:MC(e),allowed_tools:NC(t.tools),daily_cap_cents:n,total_cap_cents:r};return await RC(o)?await vr(o,async()=>{let a=await CC(o);return o.createAppApiKey({...i,attestation:a})},Ya(o)):await o.createAppApiKey(i)});if(t.json){console.log(JSON.stringify(s,null,2));return}process.stdout.write(Qf(s,{authUrl:$e()}))}catch(n){_d(n)}});vd.command("list").description("List Visa Keys for the authenticated user").option("--json","Output raw JSON").action(async e=>{try{let t=await bd(async()=>await pe().listAllAppApiKeys());if(e.json){console.log(JSON.stringify(t,null,2));return}let n=t.keys||[];if(n.length===0){console.log("No Visa Keys found. Create one with: visa-cli keys create");return}console.log("Visa Keys"),console.log("");for(let r of n)console.log(`${r.id}. ${r.label} (${r.key_prefix})`),console.log(` Status: ${r.status}`),console.log(` Owner: ${r.owner}`),console.log(` Allowed tools: ${DC(r.allowed_tools)}`),console.log(` Daily cap: ${Ho(r.daily_cap_cents)}/day`),console.log(` Total cap: ${PC(r.total_cap_cents)}`),console.log(` Last used: ${r.last_used_at||"never"}`)}catch(t){_d(t)}});vd.command("revoke <id>").alias("delete").description("Revoke (or delete) a Visa Key by id").action(async e=>{try{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Error("Visa Key id must be a positive integer. Run `visa-cli keys list` first.");let n=await bd(async()=>await pe().revokeAppApiKey(t));console.log(`Revoked Visa Key ${n.revoked}.`)}catch(t){_d(t)}});async function e1(){if(await G.clearAll(),console.log(" Keychain credentials cleared."),de())try{await ji(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}}async function C_(e={}){try{if(console.log(`Resetting Visa CLI...
272
- `),e.localOnly)console.log(" Local-only reset: skipping server logout and biometric recovery.");else{let t=pe();await gd(t);try{await t.logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}}await e1(),console.log(`
273
- Reset complete.`),e.localOnly&&console.log("Run `visa-cli setup` to sign in with the GitHub account you want to use.")}catch(t){console.error("Error:",t.message),process.exit(1)}}J.command("reset",{hidden:!0}).description("Deprecated alias for `config reset`").option("--local-only","Only clear local credentials and the local biometric key; skip server-side biometric recovery").action(C_);var wd=J.command("balance").description("Manage prepaid balance").addHelpCommand(!1).action(Lt);wd.command("show").description("Show prepaid balance + recent ledger entries").action(async()=>{try{let t=await new qe(()=>G.getSessionToken()).getBalance();if(console.log(`
274
- Balance: ${qa(t.balanceMicros,t.balanceCents)}
271
+ `)}async function E_(e,t){if(t.yes)return"confirmed";if(!process.stdin.isTTY)return"refused-non-tty";let n=(0,gd.createInterface)({input:process.stdin,output:process.stdout});try{let r=(await n.question(`${e} [y/N] `)).trim();return/^y(es)?$/i.test(r)?"confirmed":"declined"}finally{n.close()}}var Za=J.command("cards").description("Manage enrolled payment cards").addHelpCommand(!1).action(Lt);Za.command("list").alias("ls").description("List enrolled payment cards").action(async()=>{try{let e=await lt.getCards("visa-cli cards list"),t=Array.isArray(e.cards)?e.cards:[];if(t.length===0){console.log(e.message||"No cards enrolled. Add one with: visa-cli cards add");return}ZE(t)}catch(e){console.error("Error:",e.message),process.exit(1)}});Za.command("add").description("Add a new Visa card").action(async()=>{try{let e=await lt.addCard("visa-cli cards add");if(e?.message){console.log(e.message);return}let t=e?.card?.last4;console.log(t?`Card ending in ****${t} enrolled.`:"Card enrollment complete.")}catch(e){console.error("Error:",e.message),process.exit(1)}});Za.command("remove <card-id>").alias("rm").description("Remove an enrolled card").option("-y, --yes","Skip the interactive confirmation prompt").action(async(e,t)=>{try{let n=Wu(e),r=await E_(`Remove card ${n}? This cannot be undone.`,t);if(r==="refused-non-tty"&&(console.error("Refusing to remove card without --yes in a non-interactive shell."),process.exit(1)),r==="declined"){console.log("Aborted.");return}let s=await lt.removeCard({cardId:n,confirm:!0},"visa-cli cards remove");s?.success===!1&&(console.error(s.error||s.message||"Failed to remove card."),process.exit(1)),console.log(s?.message||`Removed card ${n}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});Za.command("default <card-id>").alias("set-default").description("Set the default payment card").action(async e=>{try{let t=Wu(e),n=await lt.setDefaultCard({cardId:t},"visa-cli cards default");n?.success===!1&&(console.error(n.error||n.message||"Failed to set default card."),process.exit(1)),console.log(n?.message||`Set card ${t} as default.`)}catch(t){console.error("Error:",t.message),process.exit(1)}});function QE(e){return/timed out waiting for touch id\/device approval|attestation[_\s-]?required/i.test(e)}function bd(e){let t=e instanceof Error?e.message:String(e);console.error("Error:",t),QE(t)&&(console.error(""),console.error("Visa Key creation requires local Touch ID/device attestation because the key is a bearer spend credential."),console.error("In headless or sandboxed agents such as Codex, the native approval prompt may not appear. Run the same `visa-cli keys create ...` command from a foreground terminal, approve Touch ID, then store the created key in your app secret store.")),t.includes("Not logged in")&&(console.error(""),console.error("Hint: if `visa-cli status` or `visa-cli setup` says you are authenticated, this process may not have access to your macOS Keychain."),console.error("In sandboxed agents such as Codex, rerun the keys command with keychain access or run it from a normal terminal.")),process.exit(1)}function e1(e){let t=e instanceof Error?e.message:String(e);return t.includes("EMPLOYEE_ONLY_FEATURE")||t.includes("Visa Key management is limited to approved rollout users")}async function vd(e){let t=Object.prototype.hasOwnProperty.call(process.env,"VISA_CLI_API_KEY"),n=process.env.VISA_CLI_API_KEY;delete process.env.VISA_CLI_API_KEY;try{return await e()}finally{t&&(process.env.VISA_CLI_API_KEY=n)}}var wd=J.command("keys").description("Create and manage Visa Keys for apps and agents").addHelpCommand(!1).action(Lt);wd.command("create [label]").description("Create a Visa Key for the authenticated approved user").option("--tools <ids>","Comma-separated allowed tool ids (default: all tools)").option("--daily-cap <usd>","Daily cap in USD, between 1 and 100").option("--total-cap <usd>","Cumulative cap in USD, between 1 and 10000").option("--no-total-cap","Create without a cumulative cap (higher risk; daily cap still applies)").option("--json","Output raw JSON").action(async(e,t)=>{try{let n=await UE(t.dailyCap,t.json),r=await DE(t.totalCap,t.json),s=await vd(async()=>{let o=pe(),i={label:NE(e),allowed_tools:LE(t.tools),daily_cap_cents:n,total_cap_cents:r};return await IE(o)?await vr(o,async()=>{let a=await RE(o);return o.createAppApiKey({...i,attestation:a})},za(o)):await o.createAppApiKey(i)});if(t.json){console.log(JSON.stringify(s,null,2));return}process.stdout.write(em(s,{authUrl:Pe()}))}catch(n){bd(n)}});wd.command("list").description("List Visa Keys for the authenticated user").option("--json","Output raw JSON").action(async e=>{try{let t=await vd(async()=>await pe().listAllAppApiKeys());if(e.json){console.log(JSON.stringify(t,null,2));return}let n=t.keys||[];if(n.length===0){console.log("No Visa Keys found. Create one with: visa-cli keys create");return}console.log("Visa Keys"),console.log("");for(let r of n)console.log(`${r.id}. ${r.label} (${r.key_prefix})`),console.log(` Status: ${r.status}`),console.log(` Owner: ${r.owner}`),console.log(` Allowed tools: ${jE(r.allowed_tools)}`),console.log(` Daily cap: ${Vo(r.daily_cap_cents)}/day`),console.log(` Total cap: ${OE(r.total_cap_cents)}`),console.log(` Last used: ${r.last_used_at||"never"}`)}catch(t){bd(t)}});wd.command("revoke <id>").alias("delete").description("Revoke (or delete) a Visa Key by id").action(async e=>{try{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Error("Visa Key id must be a positive integer. Run `visa-cli keys list` first.");let n=await vd(async()=>await pe().revokeAppApiKey(t));console.log(`Revoked Visa Key ${n.revoked}.`)}catch(t){bd(t)}});async function t1(){if(await G.clearAll(),console.log(" Keychain credentials cleared."),de())try{await Bi(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}}async function R_(e={}){try{if(console.log(`Resetting Visa CLI...
272
+ `),e.localOnly)console.log(" Local-only reset: skipping server logout and biometric recovery.");else{let t=pe();await hd(t);try{await t.logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}}await t1(),console.log(`
273
+ Reset complete.`),e.localOnly&&console.log("Run `visa-cli setup` to sign in with the GitHub account you want to use.")}catch(t){console.error("Error:",t.message),process.exit(1)}}J.command("reset",{hidden:!0}).description("Deprecated alias for `config reset`").option("--local-only","Only clear local credentials and the local biometric key; skip server-side biometric recovery").action(R_);var Sd=J.command("balance").description("Manage prepaid balance").addHelpCommand(!1).action(Lt);Sd.command("show").description("Show prepaid balance + recent ledger entries").action(async()=>{try{let t=await new qe(()=>G.getSessionToken()).getBalance();if(console.log(`
274
+ Balance: ${Ka(t.balanceMicros,t.balanceCents)}
275
275
  `),t.ledger.length===0){console.log(` (no ledger entries \u2014 top up to begin: visa-cli balance topup --amount 5)
276
- `);return}let n=t.ledger.slice(0,20),r=[],s=t.balanceCents,o=t.balanceMicros?BigInt(t.balanceMicros):null;for(let u of n)r.push(o!=null?o.toString():String(s*1e4)),o!=null&&u.deltaMicros?o-=BigInt(u.deltaMicros):(o=null,s-=u.deltaCents);let i=19,a=11,c=13,l=18;console.log(` ${"TIMESTAMP".padEnd(i)} ${"DELTA".padStart(a)} ${"BALANCE".padStart(c)} ${"REASON".padEnd(l)} TOOL`),console.log(` ${"\u2500".repeat(i)} ${"\u2500".repeat(a)} ${"\u2500".repeat(c)} ${"\u2500".repeat(l)} ${"\u2500".repeat(20)}`),n.forEach((u,d)=>{let f=(u.createdAt||"").slice(0,19),m=qa(u.deltaMicros,u.deltaCents,!0),p=OC(r[d]),g=(u.reason??"").slice(0,l),v=u.toolName??"";console.log(` ${f.padEnd(i)} ${m.padStart(a)} ${p.padStart(c)} ${g.padEnd(l)} ${v}`)}),console.log()}catch(e){e instanceof st&&(console.error(`Top-up pending reconciliation [${e.code}]: ${e.message}`),e.transactionId&&console.error(`Transaction: ${e.transactionId}`),process.exit(1)),console.error("Error:",e.message),process.exit(1)}});wd.command("topup").description("Top up prepaid balance from your default card (same path as MCP buy_credits; Touch ID required)").requiredOption("-a, --amount <usd>","Amount in USD (e.g. 5 or 1.50)").action(async e=>{try{let t=Yi(e.amount);if(!t.ok)throw new Error(t.error);let n=t.cents,r=n/100,s=new qe(()=>G.getSessionToken());if(!de())throw new Error(zi);let o=Ga.randomUUID(),i=await vr(s,async()=>{let a;if(de()){let{nonce:c}=await s.getAttestationChallenge(),l=Buffer.from(JSON.stringify({nonce:c,amount:r,merchant:"Visa CLI Balance",context:"balance-topup"})).toString("base64");a={signature:await Rn(l,`top up balance with $${t.displayUsd}`),nonce:c,amount:r,merchant:"Visa CLI Balance"}}return s.topupBalance({amount_cents:n,idempotency_key:o,attestation:a})},Ya(s));if(i.success)console.log(`Top-up complete: +$${(n/100).toFixed(2)} \u2192 balance now ${qa(i.balanceMicros,i.balanceCents??0)}`),i.transactionId&&console.log(`Transaction: ${i.transactionId}`),yf();else{let a=i.error_code?` [${i.error_code}]`:"";console.error(`Top-up failed${a}: ${i.error||"Unknown error"}`),process.exit(1)}}catch(t){t instanceof st&&(console.error(`Top-up pending reconciliation [${t.code}]: ${t.message}`),t.transactionId&&console.error(`Transaction: ${t.transactionId}`),console.error("Do not start another top-up until this one is reconciled."),process.exit(1)),console.error("Error:",t.message),process.exit(1)}});var R_=wd.command("auto-topup").description("Show or disable automatic balance top-ups (read/disable only \u2014 re-enabling is retired pending mandate model)").addHelpCommand(!1).action(Lt);R_.command("show").description("Show current auto-topup configuration").action(async()=>{try{let t=await new qe(()=>G.getSessionToken()).getAutoTopup();if(t.targetCents==null||t.targetCents===0){console.log(`
276
+ `);return}let n=t.ledger.slice(0,20),r=[],s=t.balanceCents,o=t.balanceMicros?BigInt(t.balanceMicros):null;for(let u of n)r.push(o!=null?o.toString():String(s*1e4)),o!=null&&u.deltaMicros?o-=BigInt(u.deltaMicros):(o=null,s-=u.deltaCents);let i=19,a=11,c=13,l=18;console.log(` ${"TIMESTAMP".padEnd(i)} ${"DELTA".padStart(a)} ${"BALANCE".padStart(c)} ${"REASON".padEnd(l)} TOOL`),console.log(` ${"\u2500".repeat(i)} ${"\u2500".repeat(a)} ${"\u2500".repeat(c)} ${"\u2500".repeat(l)} ${"\u2500".repeat(20)}`),n.forEach((u,d)=>{let f=(u.createdAt||"").slice(0,19),m=Ka(u.deltaMicros,u.deltaCents,!0),p=ME(r[d]),g=(u.reason??"").slice(0,l),v=u.toolName??"";console.log(` ${f.padEnd(i)} ${m.padStart(a)} ${p.padStart(c)} ${g.padEnd(l)} ${v}`)}),console.log()}catch(e){e instanceof st&&(console.error(`Top-up pending reconciliation [${e.code}]: ${e.message}`),e.transactionId&&console.error(`Transaction: ${e.transactionId}`),process.exit(1)),console.error("Error:",e.message),process.exit(1)}});Sd.command("topup").description("Top up prepaid balance from your default card (same path as MCP buy_credits; Touch ID required)").requiredOption("-a, --amount <usd>","Amount in USD (e.g. 5 or 1.50)").action(async e=>{try{let t=zi(e.amount);if(!t.ok)throw new Error(t.error);let n=t.cents,r=n/100,s=new qe(()=>G.getSessionToken());if(!de())throw new Error(Ji);let o=Wa.randomUUID(),i=await vr(s,async()=>{let a;if(de()){let{nonce:c}=await s.getAttestationChallenge(),l=Buffer.from(JSON.stringify({nonce:c,amount:r,merchant:"Visa CLI Balance",context:"balance-topup"})).toString("base64");a={signature:await Rn(l,`top up balance with $${t.displayUsd}`),nonce:c,amount:r,merchant:"Visa CLI Balance"}}return s.topupBalance({amount_cents:n,idempotency_key:o,attestation:a})},za(s));if(i.success)console.log(`Top-up complete: +$${(n/100).toFixed(2)} \u2192 balance now ${Ka(i.balanceMicros,i.balanceCents??0)}`),i.transactionId&&console.log(`Transaction: ${i.transactionId}`),_f();else{let a=i.error_code?` [${i.error_code}]`:"";console.error(`Top-up failed${a}: ${i.error||"Unknown error"}`),process.exit(1)}}catch(t){t instanceof st&&(console.error(`Top-up pending reconciliation [${t.code}]: ${t.message}`),t.transactionId&&console.error(`Transaction: ${t.transactionId}`),console.error("Do not start another top-up until this one is reconciled."),process.exit(1)),console.error("Error:",t.message),process.exit(1)}});var I_=Sd.command("auto-topup").description("Show or disable automatic balance top-ups (read/disable only \u2014 re-enabling is retired pending mandate model)").addHelpCommand(!1).action(Lt);I_.command("show").description("Show current auto-topup configuration").action(async()=>{try{let t=await new qe(()=>G.getSessionToken()).getAutoTopup();if(t.targetCents==null||t.targetCents===0){console.log(`
277
277
  Auto-topup: disabled
278
- `);return}let n=Ho(t.targetCents),r=Ho(t.thresholdCents),s=12,o=13;console.log(),console.log(` ${"STATE".padEnd(s)} enabled`),console.log(` ${"TARGET".padEnd(s)} ${n.padStart(o)} (refill balance to this amount)`),console.log(` ${"THRESHOLD".padEnd(s)} ${r.padStart(o)} (trigger refill when balance drops below this)`),console.log(),console.log(" Disable with: visa-cli balance auto-topup disable"),console.log()}catch(e){console.error("Error:",e.message),process.exit(1)}});R_.command("disable").description("Disable auto-topup").action(async()=>{try{let t=await new qe(()=>G.getSessionToken()).disableAutoTopup();t.success||(console.error(`Auto-topup disable failed: ${t.error||"Unknown error"}`),process.exit(1)),console.log("Auto-topup disabled. Your balance will no longer refill automatically.")}catch(e){console.error("Error:",e.message),process.exit(1)}});var t1=J.command("session",{hidden:!0}).description("Inspect session budgets");t1.command("inspect <id>").description("Show a session-budget by id (e.g. sb_abc123)").action(async e=>{try{if(!e||e.length===0)throw new Error("session id required");let t=new qe(()=>G.getSessionToken()),[n,r]=await Promise.allSettled([t.getSessionBudget(e),t.getSessionLedger(e)]),s=n.status==="fulfilled"?n.value.budget:void 0,o=r.status==="fulfilled"?r.value:void 0;if(!s&&!o?.ledger?.length&&(console.error(`Session not found: ${e}`),process.exit(1)),console.log(`
278
+ `);return}let n=Vo(t.targetCents),r=Vo(t.thresholdCents),s=12,o=13;console.log(),console.log(` ${"STATE".padEnd(s)} enabled`),console.log(` ${"TARGET".padEnd(s)} ${n.padStart(o)} (refill balance to this amount)`),console.log(` ${"THRESHOLD".padEnd(s)} ${r.padStart(o)} (trigger refill when balance drops below this)`),console.log(),console.log(" Disable with: visa-cli balance auto-topup disable"),console.log()}catch(e){console.error("Error:",e.message),process.exit(1)}});I_.command("disable").description("Disable auto-topup").action(async()=>{try{let t=await new qe(()=>G.getSessionToken()).disableAutoTopup();t.success||(console.error(`Auto-topup disable failed: ${t.error||"Unknown error"}`),process.exit(1)),console.log("Auto-topup disabled. Your balance will no longer refill automatically.")}catch(e){console.error("Error:",e.message),process.exit(1)}});var n1=J.command("session",{hidden:!0}).description("Inspect session budgets");n1.command("inspect <id>").description("Show a session-budget by id (e.g. sb_abc123)").action(async e=>{try{if(!e||e.length===0)throw new Error("session id required");let t=new qe(()=>G.getSessionToken()),[n,r]=await Promise.allSettled([t.getSessionBudget(e),t.getSessionLedger(e)]),s=n.status==="fulfilled"?n.value.budget:void 0,o=r.status==="fulfilled"?r.value:void 0;if(!s&&!o?.ledger?.length&&(console.error(`Session not found: ${e}`),process.exit(1)),console.log(`
279
279
  Session: ${e}`),s){let i=(s.totalCents/100).toFixed(2),a=(s.cumulativeCents/100).toFixed(2),c=(s.remainingCents/100).toFixed(2);console.log(` Status: ${s.status}${s.expired?" (expired)":""}`),console.log(` Budget: $${i} \xB7 spent $${a} \xB7 remaining $${c}`),console.log(` Created: ${s.createdAt}`),console.log(` Expires: ${s.expiresAt}`)}if(o?.ledger?.length){console.log(`
280
280
  PSP References (CyberSource activity):`);let i=8,a=9,c=36;console.log(` ${"TYPE".padEnd(i)} ${"AMOUNT".padStart(a)} ${"CYBERSOURCE TX ID".padEnd(c)} CREATED`),console.log(` ${"\u2500".repeat(i)} ${"\u2500".repeat(a)} ${"\u2500".repeat(c)} ${"\u2500".repeat(19)}`);for(let l of o.ledger){let u=`$${(l.amountCents/100).toFixed(2)}`;console.log(` ${l.type.padEnd(i)} ${u.padStart(a)} ${(l.transactionId||"").padEnd(c)} ${(l.createdAt||"").slice(0,19)}`)}}else s&&console.log(`
281
- (no PSP references yet \u2014 no holds placed)`);console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});async function I_(e){(!e||e.trim().length===0)&&(console.log('Usage: visa-cli feedback "your message"'),process.exit(1));try{await G.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await pe().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}}J.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action(I_);J.command("update").description("Update Visa CLI to the latest stable version").action(async()=>{let e=zu(void 0,void 0,void 0,{withDiagnostics:!0}),t=e.diagnostics?Ju(e.diagnostics,e.display):null;try{t&&console.warn(`Warning: ${t}`),console.log(`Updating Visa CLI with ${e.packageManager}: ${e.display}`);let{stdout:n,stderr:r}=await fd(e.command,e.args,{timeout:5*6e4,maxBuffer:10*1024*1024});n.trim()&&process.stdout.write(n),r.trim()&&process.stderr.write(r);let s=Ec(Bt(),{force:!0});for(let o of s.messages)console.log(o);console.log("Visa CLI update complete. Restart any running MCP clients to use the new version.")}catch(n){console.error(`Update failed while running: ${e.display}`),console.error(n?.message??String(n)),process.exit(1)}});var Ut=J.command("config").description("Manage CLI configuration and local integrations").addHelpCommand(!1).action(Lt);function $_(e){return[tt.join(e,".zshrc"),tt.join(e,".bashrc"),tt.join(e,".bash_profile"),tt.join(e,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),tt.join(e,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),tt.join(e,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),tt.join(e,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),tt.join(e,".config","powershell","Microsoft.PowerShell_profile.ps1")]}function n1(e){let t=new Map;for(let n of $_(e))try{ce.existsSync(n)&&t.set(n,ce.readFileSync(n,"utf-8"))}catch{}return t}function r1(e){let t=[];for(let[n,r]of e)try{(ce.existsSync(n)?ce.readFileSync(n,"utf-8"):"")!==r&&t.push(n)}catch{}return t}function s1(e){let t=[];for(let n of $_(e))try{if(!ce.existsSync(n))continue;let r=ce.readFileSync(n,"utf-8");Ws(r)!==r.trimEnd()&&t.push(n)}catch{}return t}Ut.command("feedback",{hidden:!0}).description("Deprecated alias for `feedback`").argument("[message]","Your feedback message").action(I_);Ut.command("list").description("Show resolved config values (env vars, server state, defaults) with their source").option("--json","Output as JSON for scripting / agent consumption").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").option("--verbose","Show one-line hints beneath entries that have them").action(async e=>{try{let t=pe(),n=await fo({api:t,includeDev:!!e.dev});if(e.json){console.log(Np(n));return}n.statusError&&(console.error(`Warning: could not reach auth server (${n.statusError}).`),console.error("Server-sourced entries show '\u2014'. Log in with `visa-cli setup` if you expected values here."),console.error("")),console.log(Mp(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});Ut.command("get <key>").description("Print the resolved value of a single config key (pipe-friendly)").option("--raw","Print the underlying value as JSON instead of the formatted display string").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").action(async(e,t)=>{try{let n=pe(),s=(await fo({api:n,includeDev:!!t.dev})).entries.find(o=>o.key===e);s||(console.error(`Error: unknown config key '${e}'. Run 'visa-cli config list' to see available keys.`),process.exit(1)),t.raw?console.log(JSON.stringify(s.value)):console.log(s.formatted)}catch(n){console.error("Error:",n.message),process.exit(1)}});function o1(){return Object.entries(nr).map(([e,t])=>` ${e.padEnd(22)} (${t.type}) ${t.description}`).join(`
281
+ (no PSP references yet \u2014 no holds placed)`);console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});async function P_(e){(!e||e.trim().length===0)&&(console.log('Usage: visa-cli feedback "your message"'),process.exit(1));try{await G.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await pe().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}}J.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action(P_);J.command("update").description("Update Visa CLI to the latest stable version").action(async()=>{let e=Ju(void 0,void 0,void 0,{withDiagnostics:!0}),t=e.diagnostics?Xu(e.diagnostics,e.display):null;try{t&&console.warn(`Warning: ${t}`),console.log(`Updating Visa CLI with ${e.packageManager}: ${e.display}`);let{stdout:n,stderr:r}=await md(e.command,e.args,{timeout:5*6e4,maxBuffer:10*1024*1024});n.trim()&&process.stdout.write(n),r.trim()&&process.stderr.write(r);let s=Ec(Bt(),{force:!0});for(let o of s.messages)console.log(o);console.log("Visa CLI update complete. Restart any running MCP clients to use the new version.")}catch(n){console.error(`Update failed while running: ${e.display}`),console.error(n?.message??String(n)),process.exit(1)}});var Ut=J.command("config").description("Manage CLI configuration and local integrations").addHelpCommand(!1).action(Lt);function $_(e){return[tt.join(e,".zshrc"),tt.join(e,".bashrc"),tt.join(e,".bash_profile"),tt.join(e,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),tt.join(e,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),tt.join(e,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),tt.join(e,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),tt.join(e,".config","powershell","Microsoft.PowerShell_profile.ps1")]}function r1(e){let t=new Map;for(let n of $_(e))try{ce.existsSync(n)&&t.set(n,ce.readFileSync(n,"utf-8"))}catch{}return t}function s1(e){let t=[];for(let[n,r]of e)try{(ce.existsSync(n)?ce.readFileSync(n,"utf-8"):"")!==r&&t.push(n)}catch{}return t}function o1(e){let t=[];for(let n of $_(e))try{if(!ce.existsSync(n))continue;let r=ce.readFileSync(n,"utf-8");Ws(r)!==r.trimEnd()&&t.push(n)}catch{}return t}Ut.command("feedback",{hidden:!0}).description("Deprecated alias for `feedback`").argument("[message]","Your feedback message").action(P_);Ut.command("list").description("Show resolved config values (env vars, server state, defaults) with their source").option("--json","Output as JSON for scripting / agent consumption").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").option("--verbose","Show one-line hints beneath entries that have them").action(async e=>{try{let t=pe(),n=await mo({api:t,includeDev:!!e.dev});if(e.json){console.log(Lp(n));return}n.statusError&&(console.error(`Warning: could not reach auth server (${n.statusError}).`),console.error("Server-sourced entries show '\u2014'. Log in with `visa-cli setup` if you expected values here."),console.error("")),console.log(Np(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});Ut.command("get <key>").description("Print the resolved value of a single config key (pipe-friendly)").option("--raw","Print the underlying value as JSON instead of the formatted display string").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").action(async(e,t)=>{try{let n=pe(),s=(await mo({api:n,includeDev:!!t.dev})).entries.find(o=>o.key===e);s||(console.error(`Error: unknown config key '${e}'. Run 'visa-cli config list' to see available keys.`),process.exit(1)),t.raw?console.log(JSON.stringify(s.value)):console.log(s.formatted)}catch(n){console.error("Error:",n.message),process.exit(1)}});function i1(){return Object.entries(nr).map(([e,t])=>` ${e.padEnd(22)} (${t.type}) ${t.description}`).join(`
282
282
  `)}Ut.command("set <key> <value>").description("Persist a CLI setting to ~/.visa-mcp/settings.json").addHelpText("after",`
283
283
  Settable keys:
284
- ${o1()}`).action((e,t)=>{try{let n=xi(e,t);console.log(`Saved ${n.key}=${JSON.stringify(n.value)} \u2192 ${n.path}`),n.requiresRestart&&console.log("Restart Claude Code (or your MCP-enabled client) for the change to take effect.")}catch(n){n instanceof ot||n instanceof Vt||n instanceof vn?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});Ut.command("unset <key>").description("Remove a CLI setting from ~/.visa-mcp/settings.json (falls back to env var or default)").action(e=>{try{let t=Ti(e);t.removed?(console.log(`Removed ${t.key} from ${t.path}`),t.requiresRestart&&console.log("Restart Claude Code (or your MCP-enabled client) for the change to take effect.")):console.log(`No-op: ${t.key} was not set in ${t.path}.`)}catch(t){console.error(`Error: ${t.message}`),process.exit(1)}});Ut.command("reset").description("Log out and clear all credentials").option("--local-only","Only clear local credentials and the local biometric key; skip server-side biometric recovery").action(C_);var Sd=Ut.command("biometric").description("Manage Touch ID / biometric attestation enforcement").addHelpCommand(!1).action(Lt);Sd.command("status").description("Show current biometric enforcement state").action(async()=>{try{await G.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let n=await pe().getStatus(),r=n.attestationRequired!==!1,s=!!n.hasAttestationKey,o=de();console.log(`Server policy: Touch ID ${r?"REQUIRED":"NOT required"}`),console.log(`Attestation key registered: ${s?"yes":"no"}`),console.log(`Touch ID available on this device: ${o?"yes":"no"}`)}catch(e){console.error("Error:",e.message),process.exit(1)}});Sd.command("on").description("Require Touch ID for payments (security upgrade \u2014 no Touch ID needed)").action(async()=>{try{await G.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=pe(),n=await Bi(t);n.ok||(console.error(`Error: ${n.message}`),process.exit(1));let r=await t.setBiometricPreference({required:!0});r.success||(console.error(`Failed: ${r.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is now REQUIRED for payments.")}catch(e){console.error("Error:",e.message),process.exit(1)}});Sd.command("off").description("Disable Touch ID requirement (security downgrade \u2014 one Touch ID confirmation required)").action(async()=>{try{await G.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=pe(),n=await t.getStatus();if(n.attestationRequired===!1){console.log("Touch ID is already disabled.");return}n.hasAttestationKey&&!de()&&(console.error("Touch ID is unavailable on this device but the server has a registered key."),console.error("Disable Touch ID from a device that can sign, or contact support."),process.exit(1));let r=await vr(t,async()=>{let s;if(n.hasAttestationKey&&de())try{let{nonce:o}=await t.getAttestationChallenge(),i=0,a="",c=Buffer.from(JSON.stringify({nonce:o,amount:i,merchant:a,context:"biometric-preference"})).toString("base64");s={signature:await Rn(c,"disable Touch ID requirement"),nonce:o,amount:i,merchant:a}}catch(o){throw new Error(`Touch ID confirmation failed: ${o?.message||"cancelled"}`)}return t.setBiometricPreference({required:!1,attestation:s})},Ya(t));r.success||(console.error(`Failed: ${r.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is no longer required for payments.")}catch(e){console.error("Error:",e.message),process.exit(1)}});J.command("authorize-web-authenticator").description("Activate a passkey you registered in the browser (one Touch ID confirmation)").action(async()=>{try{await G.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=pe();(await t.getStatus()).hasAttestationKey||(console.error("No biometric key is registered on this account."),console.error("Run `visa-cli biometric on` to set up Touch ID first, then retry."),process.exit(1)),de()||(console.error("Touch ID is unavailable on this device but the server has a registered key."),console.error("Run this from a device that can sign with your registered key."),process.exit(1));let{pending:r}=await t.getPendingWebAuthenticators();if(!r||r.length===0){console.log("No passkeys are awaiting authorization."),console.log("Register a passkey at https://app.visacli.sh/account first, then re-run this.");return}console.log(`${r.length} passkey${r.length===1?"":"s"} awaiting authorization.`);let s=0;for(let o of r){let i=o.deviceLabel?` (${o.deviceLabel})`:"",a=await vr(t,async()=>{let{nonce:c}=await t.getAttestationChallenge(),l=0,u=o.credentialId,d=Buffer.from(JSON.stringify({nonce:c,amount:l,merchant:u,context:"web-authenticator-enrollment"})).toString("base64"),f=await Rn(d,`authorize web passkey${i}`);return t.authorizeWebAuthenticator({credentialId:o.credentialId,attestation:{signature:f,nonce:c,amount:l,merchant:u}})},Ya(t));a.success||(console.error(`Failed to authorize passkey${i}: ${a.error||"unknown error"}`),process.exit(1)),s++,console.log(`Authorized passkey${i}.`)}console.log(`Done \u2014 ${s} passkey${s===1?"":"s"} active. You can now disable Touch ID from app.visacli.sh with a browser passkey.`)}catch(e){console.error("Error:",e.message),process.exit(1)}});var Dr=Ut.command("shell-hud").description("Manage the shell prompt HUD (opt-in \u2014 prefer: visa-cli config hud enable)").addHelpCommand(!1).action(Lt);function P_(){let e=ci();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function O_(e){for(let t of e.messages)console.log(t);for(let t of e.errors)console.error(t);e.ok||process.exit(1)}function i1(){O_($c(void 0,{homeDir:re.homedir(),installVisaStatusLine:zs,installShellHud:ci}))}function M_(){console.log("Note: `config shell-hud enable` now installs the Claude Code statusLine HUD."),console.log(" For the explicit shell-prompt HUD, run: visa-cli config hud enable shell"),i1()}function Za(){let e=jt();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}Dr.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(P_);Dr.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(M_);Dr.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Za);Dr.command("disable").description("Disable the persistent shell HUD").action(Za);Dr.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${li()}
284
+ ${i1()}`).action((e,t)=>{try{let n=Ti(e,t);console.log(`Saved ${n.key}=${JSON.stringify(n.value)} \u2192 ${n.path}`),n.requiresRestart&&console.log("Restart Claude Code (or your MCP-enabled client) for the change to take effect.")}catch(n){n instanceof ot||n instanceof Vt||n instanceof vn?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});Ut.command("unset <key>").description("Remove a CLI setting from ~/.visa-mcp/settings.json (falls back to env var or default)").action(e=>{try{let t=Ai(e);t.removed?(console.log(`Removed ${t.key} from ${t.path}`),t.requiresRestart&&console.log("Restart Claude Code (or your MCP-enabled client) for the change to take effect.")):console.log(`No-op: ${t.key} was not set in ${t.path}.`)}catch(t){console.error(`Error: ${t.message}`),process.exit(1)}});Ut.command("reset").description("Log out and clear all credentials").option("--local-only","Only clear local credentials and the local biometric key; skip server-side biometric recovery").action(R_);var xd=Ut.command("biometric").description("Manage Touch ID / biometric attestation enforcement").addHelpCommand(!1).action(Lt);xd.command("status").description("Show current biometric enforcement state").action(async()=>{try{await G.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let n=await pe().getStatus(),r=n.attestationRequired!==!1,s=!!n.hasAttestationKey,o=de();console.log(`Server policy: Touch ID ${r?"REQUIRED":"NOT required"}`),console.log(`Attestation key registered: ${s?"yes":"no"}`),console.log(`Touch ID available on this device: ${o?"yes":"no"}`)}catch(e){console.error("Error:",e.message),process.exit(1)}});xd.command("on").description("Require Touch ID for payments (security upgrade \u2014 no Touch ID needed)").action(async()=>{try{await G.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=pe(),n=await Fi(t);n.ok||(console.error(`Error: ${n.message}`),process.exit(1));let r=await t.setBiometricPreference({required:!0});r.success||(console.error(`Failed: ${r.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is now REQUIRED for payments.")}catch(e){console.error("Error:",e.message),process.exit(1)}});xd.command("off").description("Disable Touch ID requirement (security downgrade \u2014 one Touch ID confirmation required)").action(async()=>{try{await G.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=pe(),n=await t.getStatus();if(n.attestationRequired===!1){console.log("Touch ID is already disabled.");return}n.hasAttestationKey&&!de()&&(console.error("Touch ID is unavailable on this device but the server has a registered key."),console.error("Disable Touch ID from a device that can sign, or contact support."),process.exit(1));let r=await vr(t,async()=>{let s;if(n.hasAttestationKey&&de())try{let{nonce:o}=await t.getAttestationChallenge(),i=0,a="",c=Buffer.from(JSON.stringify({nonce:o,amount:i,merchant:a,context:"biometric-preference"})).toString("base64");s={signature:await Rn(c,"disable Touch ID requirement"),nonce:o,amount:i,merchant:a}}catch(o){throw new Error(`Touch ID confirmation failed: ${o?.message||"cancelled"}`)}return t.setBiometricPreference({required:!1,attestation:s})},za(t));r.success||(console.error(`Failed: ${r.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is no longer required for payments.")}catch(e){console.error("Error:",e.message),process.exit(1)}});J.command("authorize-web-authenticator").description("Activate a passkey you registered in the browser (one Touch ID confirmation)").action(async()=>{try{await G.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=pe();(await t.getStatus()).hasAttestationKey||(console.error("No biometric key is registered on this account."),console.error("Run `visa-cli biometric on` to set up Touch ID first, then retry."),process.exit(1)),de()||(console.error("Touch ID is unavailable on this device but the server has a registered key."),console.error("Run this from a device that can sign with your registered key."),process.exit(1));let{pending:r}=await t.getPendingWebAuthenticators();if(!r||r.length===0){console.log("No passkeys are awaiting authorization."),console.log("Register a passkey at https://app.visacli.sh/account first, then re-run this.");return}console.log(`${r.length} passkey${r.length===1?"":"s"} awaiting authorization.`);let s=0;for(let o of r){let i=o.deviceLabel?` (${o.deviceLabel})`:"",a=await vr(t,async()=>{let{nonce:c}=await t.getAttestationChallenge(),l=0,u=o.credentialId,d=Buffer.from(JSON.stringify({nonce:c,amount:l,merchant:u,context:"web-authenticator-enrollment"})).toString("base64"),f=await Rn(d,`authorize web passkey${i}`);return t.authorizeWebAuthenticator({credentialId:o.credentialId,attestation:{signature:f,nonce:c,amount:l,merchant:u}})},za(t));a.success||(console.error(`Failed to authorize passkey${i}: ${a.error||"unknown error"}`),process.exit(1)),s++,console.log(`Authorized passkey${i}.`)}console.log(`Done \u2014 ${s} passkey${s===1?"":"s"} active. You can now disable Touch ID from app.visacli.sh with a browser passkey.`)}catch(e){console.error("Error:",e.message),process.exit(1)}});var Dr=Ut.command("shell-hud").description("Manage the shell prompt HUD (opt-in \u2014 prefer: visa-cli config hud enable)").addHelpCommand(!1).action(Lt);function O_(){let e=li();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function M_(e){for(let t of e.messages)console.log(t);for(let t of e.errors)console.error(t);e.ok||process.exit(1)}function a1(){M_($c(void 0,{homeDir:re.homedir(),installVisaStatusLine:zs,installShellHud:li}))}function N_(){console.log("Note: `config shell-hud enable` now installs the Claude Code statusLine HUD."),console.log(" For the explicit shell-prompt HUD, run: visa-cli config hud enable shell"),a1()}function Qa(){let e=jt();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}Dr.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(O_);Dr.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(N_);Dr.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Qa);Dr.command("disable").description("Disable the persistent shell HUD").action(Qa);Dr.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${ui()}
285
285
  `)});Dr.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,r=(d,f,m)=>{console.log(` ${f?"\u2713":"\u2717"} ${d}: ${m}`),f||(n=!1)};console.log(`Shell HUD Doctor
286
286
  `);let s=Wr();if(r("Shell detected",!!s,s??"none (zsh, bash, or PowerShell required)"),s){let d=Gs(s),f=e(d);if(r("RC file exists",f,d.replace(re.homedir(),"~")),f){let p=t(d,"utf-8").includes("visa-cli shell hud v2");r("HUD block installed",!!p,p?"found in rc file":"missing \u2014 run: visa-cli config hud enable shell")}}let o=yn(),i=e(o);if(r("Cache file",i,i?o.replace(re.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let d=JSON.parse(t(o,"utf-8")),f=Date.now()-(d.renderedAt??0),m=Math.round(f/1e3),p=m<=30;console.log(` ${p?"\u2713":"\u26A0"} Cache freshness: ${m}s old${p?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{r("Cache readable",!1,"corrupt JSON")}let a=Ks(),c=e(a),l="missing";if(c)try{l=t(a,"utf-8").trim().slice(0,80)}catch{l="unreadable"}r("Line file",c,l);let u=!1;try{u=!!await G.getSessionToken()}catch{}if(r("Auth token",u,u?"found in keychain":"missing \u2014 run: visa-cli setup"),u)try{await pe().getStatus(),r("API connectivity",!0,"GET /v1/status OK")}catch(d){let f=d instanceof Error?d.message:"unknown error";r("API connectivity",!1,f)}console.log(n?`
287
287
  All checks passed.`:`
288
- Some checks failed \u2014 see above.`),n||process.exit(1)});async function N_(e){if(!(!e.force&&gf()))try{await _c();let t=pe(),[n,r,s,o]=await Promise.allSettled([t.getStatus(),t.getBalance(),t.listAllAppApiKeys(),t.getTransactions({limit:1})]);if(n.status==="rejected")throw n.reason;let i=n.value,a=i.prepaidBalance?.cents;if(typeof a=="number"){i.balanceCents=a;let u=i.prepaidBalance?.balanceMicros;typeof u=="string"&&(i.balanceMicros=u);let d=i.prepaidBalance?.amountUsd;i.amountUsd=typeof d=="number"?d:a/100}if(r.status==="fulfilled"&&r.value.success&&(i.balanceCents=r.value.balanceCents,i.balanceMicros=r.value.balanceMicros,i.amountUsd=r.value.amountUsd),s.status==="fulfilled"&&s.value.success?i.apiKeyCount=Array.isArray(s.value.keys)?s.value.keys.length:0:s.status==="rejected"&&QC(s.reason)&&(i.apiKeyStatus="rollout_locked"),o.status==="fulfilled"){let u=o.value,f=(Array.isArray(u)?u:Array.isArray(u.transactions)?u.transactions:[]).find(m=>m&&typeof m.tool_name=="string"&&m.tool_name.length>0);f&&f.created_at&&(i.lastService={toolName:f.tool_name,createdAt:f.created_at})}let c={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:St()},l=Sc(i,c);xc(l,i)}catch(t){let n=t instanceof Error?t.message:"unknown refresh failure";hf(n)}finally{Jn()}}Dr.command("refresh").description("Refresh the shell HUD cache (no-op if cache is fresh unless --force)").option("--force","Bypass the cache freshness gate and always refresh").action(N_);var jr=J.command("shell-hud",{hidden:!0}).description("Deprecated alias for `config shell-hud`");jr.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(P_);jr.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(M_);jr.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Za);jr.command("disable").description("Disable the persistent shell HUD").action(Za);jr.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${li()}
289
- `)});jr.command("doctor").description("Show the new shell HUD doctor command").action(()=>{console.log("Run: visa-cli config shell-hud doctor")});jr.command("refresh").description("Refresh the shell HUD cache (no-op if cache is fresh unless --force)").option("--force","Bypass the cache freshness gate and always refresh").action(N_);async function L_(e){try{await _c();let t=await $f(),n=li(),r=n,s=n.split(`
290
- `)[0],o=_f();if(!t&&s.includes("loading")){process.stdout.write(`VISA | HUD not initialized \u2014 run: visa-cli config hud enable
291
- `),ld();return}if(e.json){let a=await Uf(r,t,o);process.stdout.write(`${JSON.stringify(a,null,2)}
292
- `),ld();return}let i=await Mf(r,t,o);process.stdout.write(`${i}
293
- `),ld()}catch(t){let n=t instanceof Error?t.message:"unknown error";console.error(`Failed to render Visa HUD: ${n}`),process.exit(1)}}Ut.command("statusline").description("Output the Visa HUD for agent statusline integrations").option("--json","Output structured JSON for clients that render their own HUD").action(L_);J.command("statusline",{hidden:!0}).description("Deprecated alias for `config statusline`").option("--json","Output structured JSON for clients that render their own HUD").action(L_);var Ps=Ut.command("hud").description("Manage the Visa spend HUD \u2014 one command for all surfaces").addHelpCommand(!1);Ps.description("Show which HUD surfaces are currently enabled").action(()=>{let e="\x1B[1m",t="\x1B[2m",n="\x1B[32m",r="\x1B[33m",s="\x1B[0m";console.log(`
288
+ Some checks failed \u2014 see above.`),n||process.exit(1)});async function L_(e){if(!(!e.force&&hf()))try{await bc();let t=pe(),[n,r,s,o]=await Promise.allSettled([t.getStatus(),t.getBalance(),t.listAllAppApiKeys(),t.getTransactions({limit:1})]);if(n.status==="rejected")throw n.reason;let i=n.value,a=i.prepaidBalance?.cents;if(typeof a=="number"){i.balanceCents=a;let u=i.prepaidBalance?.balanceMicros;typeof u=="string"&&(i.balanceMicros=u);let d=i.prepaidBalance?.amountUsd;i.amountUsd=typeof d=="number"?d:a/100}if(r.status==="fulfilled"&&r.value.success&&(i.balanceCents=r.value.balanceCents,i.balanceMicros=r.value.balanceMicros,i.amountUsd=r.value.amountUsd),s.status==="fulfilled"&&s.value.success?i.apiKeyCount=Array.isArray(s.value.keys)?s.value.keys.length:0:s.status==="rejected"&&e1(s.reason)&&(i.apiKeyStatus="rollout_locked"),o.status==="fulfilled"){let u=o.value,f=(Array.isArray(u)?u:Array.isArray(u.transactions)?u.transactions:[]).find(m=>m&&typeof m.tool_name=="string"&&m.tool_name.length>0);f&&f.created_at&&(i.lastService={toolName:f.tool_name,createdAt:f.created_at})}let c={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:St()},l=xc(i,c);Tc(l,i)}catch(t){let n=t instanceof Error?t.message:"unknown refresh failure";yf(n)}finally{Jn()}}Dr.command("refresh").description("Refresh the shell HUD cache (no-op if cache is fresh unless --force)").option("--force","Bypass the cache freshness gate and always refresh").action(L_);var jr=J.command("shell-hud",{hidden:!0}).description("Deprecated alias for `config shell-hud`");jr.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(O_);jr.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(N_);jr.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Qa);jr.command("disable").description("Disable the persistent shell HUD").action(Qa);jr.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${ui()}
289
+ `)});jr.command("doctor").description("Show the new shell HUD doctor command").action(()=>{console.log("Run: visa-cli config shell-hud doctor")});jr.command("refresh").description("Refresh the shell HUD cache (no-op if cache is fresh unless --force)").option("--force","Bypass the cache freshness gate and always refresh").action(L_);async function U_(e){try{await bc();let t=await $f(),n=ui(),r=n,s=n.split(`
290
+ `)[0],o=bf();if(!t&&s.includes("loading")){process.stdout.write(`VISA | HUD not initialized \u2014 run: visa-cli config hud enable
291
+ `),ud();return}if(e.json){let a=await Df(r,t,o);process.stdout.write(`${JSON.stringify(a,null,2)}
292
+ `),ud();return}let i=await Nf(r,t,o);process.stdout.write(`${i}
293
+ `),ud()}catch(t){let n=t instanceof Error?t.message:"unknown error";console.error(`Failed to render Visa HUD: ${n}`),process.exit(1)}}Ut.command("statusline").description("Output the Visa HUD for agent statusline integrations").option("--json","Output structured JSON for clients that render their own HUD").action(U_);J.command("statusline",{hidden:!0}).description("Deprecated alias for `config statusline`").option("--json","Output structured JSON for clients that render their own HUD").action(U_);var $s=Ut.command("hud").description("Manage the Visa spend HUD \u2014 one command for all surfaces").addHelpCommand(!1);$s.description("Show which HUD surfaces are currently enabled").action(()=>{let e="\x1B[1m",t="\x1B[2m",n="\x1B[32m",r="\x1B[33m",s="\x1B[0m";console.log(`
294
294
  ${e}Visa HUD Status${s}
295
- `);let o=Bt(),i=!1,a=!1;try{if(ce.existsSync(o)){let p=JSON.parse(ce.readFileSync(o,"utf-8")),g=typeof p.statusLine=="object"?p.statusLine.command:"";i=bn(g),a=!!p.statusLine&&!i}}catch{}let c=i?`${n}\u2713${s}`:`${t}\u2717${s}`,l=i?"registered in ~/.claude/settings.json":a?`${r}another HUD is configured${s} \u2014 edit settings.json to switch`:"not enabled";console.log(` ${c} ${e}Claude Code${s} (statusLine) ${l}`);let u=Zn(re.homedir()),d=u.length>0||ai(),f=d?`${n}\u2713${s}`:`${t}\u2717${s}`,m=d?`installed in shell rc file${u.length>0?` (${u.map(p=>p.replace(re.homedir(),"~")).join(", ")})`:""}`:"not installed (opt-in)";console.log(` ${f} ${e}Shell prompt${s} ${m}`),i&&d&&console.log(` ${r}!${s} ${e}Overlap${s} Claude statusLine and shell prompt HUD are both installed. Remove shell prompt output with: visa-cli config hud disable shell`),console.log(`
296
- ${e}Quick start:${s}`),i||console.log(` visa-cli config hud enable ${t}# Claude Code statusLine (recommended)${s}`),d||console.log(` visa-cli config hud enable shell ${t}# zsh/bash prompt line (opt-in)${s}`),i&&d&&console.log(` ${n}All surfaces enabled.${s}`),(i||d)&&console.log(` visa-cli config hud disable [shell] ${t}# remove a surface${s}`),console.log(` visa-cli config hud doctor ${t}# diagnose connectivity${s}`),console.log()});Ps.command("enable").description("Enable the Visa HUD \u2014 claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{O_($c(e,{homeDir:re.homedir(),installVisaStatusLine:zs,installShellHud:ci}))});Ps.command("disable").description("Disable the Visa HUD from a surface: claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{let t=e??"claude";if(t==="shell"||t==="prompt"){let o=jt();o.removed||(console.error(o.message),process.exit(1)),console.log(o.message);return}let n=yi(t);n||(console.error(`Unknown HUD surface: ${t}`),console.error("Supported: claude (default), shell, all"),process.exit(1));let r=!1,s=!1;if(n==="claude"||n==="claude-code"||n==="all"){let o=Bt(),i=Cc(o);console.log(i.message),i.removed&&(s=!0),!i.removed&&n!=="all"&&(r=!0);let a=i.status==="removed"||i.status==="missing-settings"||i.status==="missing-statusline";if(n!=="all"&&!e&&a&&!gi()&&Zn(re.homedir()).length>0){let l=jt();l.removed&&l.rcPaths&&l.rcPaths.length>0&&(console.log(`Also cleaned legacy shell-prompt HUD block from ${l.rcPaths.map(u=>u.replace(re.homedir(),"~")).join(", ")} (was leaking output above every shell prompt). Set VISA_HUD_KEEP_SHELL=1 (or true / yes / on) if you want the shell surface to stay.`),s=!0,(i.status==="missing-settings"||i.status==="missing-statusline")&&(r=!1))}}if(n==="all"){let o=jt();console.log(o.message),o.removed&&(s=!0),!o.removed&&n!=="all"&&(r=!0)}n==="all"&&!s&&(r=!0),r&&process.exit(1)});Ps.command("doctor").description("Diagnose HUD installation and connectivity across all surfaces").option("--fix","Self-heal locally fixable issues (stale cache, legacy placeholder, orphan precmd block)").option("-y, --yes","Allow --fix to remove overlapping shell HUD blocks without an interactive prompt").action(async e=>{let t=!0,n=(m,p,g)=>{console.log(` ${p?"\u2713":"\u2717"} ${m}: ${g}`),p||(t=!1)};console.log(`Visa HUD Doctor
297
- `);let r=[],s=zu(void 0,void 0,void 0,{withDiagnostics:!0}),o=s.diagnostics?Ju(s.diagnostics,s.display):null;o&&(console.log(`\u26A0 ${o}`),console.log(""));let i=Bt(),a=!1;try{if(ce.existsSync(i)){let m=JSON.parse(ce.readFileSync(i,"utf-8")),p=typeof m.statusLine=="object"?m.statusLine.command:"";a=bn(p)}}catch{}n("Claude Code statusLine",a,a?"registered":"not registered \u2014 run: visa-cli config hud enable");let c=s1(re.homedir()),l=Wr();if(n("Shell detected",!!l,l??"none (zsh, bash, or PowerShell required)"),l){let m=Gs(l),p=ce.existsSync(m);if(n("RC file exists",p,m.replace(re.homedir(),"~")),p){let v=ce.readFileSync(m,"utf-8").includes("visa-cli shell hud v2");console.log(` ${v?"\u2713":"\u2013"} Shell HUD block: ${v?"installed":"not installed (opt-in \u2014 run: visa-cli config hud enable shell)"}`)}}if(c.length>0&&console.log(` \u2713 Shell HUD rc scan: installed in ${c.map(m=>m.replace(re.homedir(),"~")).join(", ")}`),a&&c.length>0&&e.fix){let m=c.map(g=>g.replace(re.homedir(),"~")).join(", "),p=e.yes===!0;if(!p&&process.stdin.isTTY&&(p=await E_(`Remove shell prompt HUD block from ${m}?`,{})==="confirmed"),p){let g=n1(re.homedir());jt();let v=r1(g);if(v.length>0){let k=v.map(b=>b.replace(re.homedir(),"~")).join(", ");console.log(` \u2713 --fix: cleaned legacy shell-prompt HUD block from ${k}`),r.push(`removed shell precmd block from ${k}`)}}else console.log(` ! --fix: preserving shell prompt HUD block in ${m}; rerun with --yes or remove it explicitly with: visa-cli config hud disable shell`)}else a&&c.length>0&&console.log(" ! Overlap notice: Claude Code statusLine and shell prompt HUD are both installed. If the prompt output is unintended, run: visa-cli config hud disable shell \u2014 or rerun with: visa-cli config hud doctor --fix --yes");let u=yn(),d=ce.existsSync(u);if(n("HUD cache file",d,d?u.replace(re.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),d)try{let m=JSON.parse(ce.readFileSync(u,"utf-8")),p=Date.now()-(m.renderedAt??0),g=Math.round(p/1e3),v=g<=30,k=typeof m.line=="string"?m.line:"",b=k.length>0&&ui(k);if(console.log(` ${v?"\u2713":"\u26A0"} Cache freshness: ${g}s old${v?"":" (stale \u2014 will refresh on next prompt)"}`),b&&console.log(' \u26A0 Cache content: legacy placeholder (HUD will display "VISA | HUD not ready" until next successful refresh)'),e.fix&&(!v||b)){let w=!1;try{ce.rmSync(u,{force:!0}),w=!0}catch{}try{let S=Ks();ce.existsSync(S)&&(ce.rmSync(S,{force:!0}),w=!0)}catch{}if(w){let S=b?"cache held legacy placeholder":`cache was ${g}s stale`;console.log(` \u2713 --fix: cleared HUD cache (${S}); next prompt will trigger a fresh refresh`),r.push("cleared HUD cache");let C=tt.join(re.homedir(),".visa-cli","shell-hud.lock");ce.existsSync(C)&&(Jn(),console.log(" \u2713 --fix: cleared shell HUD refresh lock"),r.push("cleared shell HUD refresh lock"))}}}catch{if(console.log(" \u2717 Cache readable: corrupt JSON"),e.fix)try{ce.rmSync(u,{force:!0}),console.log(" \u2713 --fix: removed corrupt cache file; next prompt will trigger a fresh refresh"),r.push("removed corrupt cache");let m=tt.join(re.homedir(),".visa-cli","shell-hud.lock");ce.existsSync(m)&&(Jn(),console.log(" \u2713 --fix: cleared shell HUD refresh lock"),r.push("cleared shell HUD refresh lock"))}catch{t=!1}else t=!1}let f=!1;try{f=!!await G.getSessionToken()}catch{}if(n("Auth token",f,f?"found in keychain":"missing \u2014 run: visa-cli setup"),f)try{await pe().getStatus(),n("API connectivity",!0,"GET /v1/status OK")}catch(m){let p=m instanceof Error?m.message:"unknown error";n("API connectivity",!1,p)}e.fix&&(r.length===0?console.log(`
295
+ `);let o=Bt(),i=!1,a=!1;try{if(ce.existsSync(o)){let p=JSON.parse(ce.readFileSync(o,"utf-8")),g=typeof p.statusLine=="object"?p.statusLine.command:"";i=bn(g),a=!!p.statusLine&&!i}}catch{}let c=i?`${n}\u2713${s}`:`${t}\u2717${s}`,l=i?"registered in ~/.claude/settings.json":a?`${r}another HUD is configured${s} \u2014 edit settings.json to switch`:"not enabled";console.log(` ${c} ${e}Claude Code${s} (statusLine) ${l}`);let u=Zn(re.homedir()),d=u.length>0||ci(),f=d?`${n}\u2713${s}`:`${t}\u2717${s}`,m=d?`installed in shell rc file${u.length>0?` (${u.map(p=>p.replace(re.homedir(),"~")).join(", ")})`:""}`:"not installed (opt-in)";console.log(` ${f} ${e}Shell prompt${s} ${m}`),i&&d&&console.log(` ${r}!${s} ${e}Overlap${s} Claude statusLine and shell prompt HUD are both installed. Remove shell prompt output with: visa-cli config hud disable shell`),console.log(`
296
+ ${e}Quick start:${s}`),i||console.log(` visa-cli config hud enable ${t}# Claude Code statusLine (recommended)${s}`),d||console.log(` visa-cli config hud enable shell ${t}# zsh/bash prompt line (opt-in)${s}`),i&&d&&console.log(` ${n}All surfaces enabled.${s}`),(i||d)&&console.log(` visa-cli config hud disable [shell] ${t}# remove a surface${s}`),console.log(` visa-cli config hud doctor ${t}# diagnose connectivity${s}`),console.log()});$s.command("enable").description("Enable the Visa HUD \u2014 claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{M_($c(e,{homeDir:re.homedir(),installVisaStatusLine:zs,installShellHud:li}))});$s.command("disable").description("Disable the Visa HUD from a surface: claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{let t=e??"claude";if(t==="shell"||t==="prompt"){let o=jt();o.removed||(console.error(o.message),process.exit(1)),console.log(o.message);return}let n=_i(t);n||(console.error(`Unknown HUD surface: ${t}`),console.error("Supported: claude (default), shell, all"),process.exit(1));let r=!1,s=!1;if(n==="claude"||n==="claude-code"||n==="all"){let o=Bt(),i=Rc(o);console.log(i.message),i.removed&&(s=!0),!i.removed&&n!=="all"&&(r=!0);let a=i.status==="removed"||i.status==="missing-settings"||i.status==="missing-statusline";if(n!=="all"&&!e&&a&&!hi()&&Zn(re.homedir()).length>0){let l=jt();l.removed&&l.rcPaths&&l.rcPaths.length>0&&(console.log(`Also cleaned legacy shell-prompt HUD block from ${l.rcPaths.map(u=>u.replace(re.homedir(),"~")).join(", ")} (was leaking output above every shell prompt). Set VISA_HUD_KEEP_SHELL=1 (or true / yes / on) if you want the shell surface to stay.`),s=!0,(i.status==="missing-settings"||i.status==="missing-statusline")&&(r=!1))}}if(n==="all"){let o=jt();console.log(o.message),o.removed&&(s=!0),!o.removed&&n!=="all"&&(r=!0)}n==="all"&&!s&&(r=!0),r&&process.exit(1)});$s.command("doctor").description("Diagnose HUD installation and connectivity across all surfaces").option("--fix","Self-heal locally fixable issues (stale cache, legacy placeholder, orphan precmd block)").option("-y, --yes","Allow --fix to remove overlapping shell HUD blocks without an interactive prompt").action(async e=>{let t=!0,n=(m,p,g)=>{console.log(` ${p?"\u2713":"\u2717"} ${m}: ${g}`),p||(t=!1)};console.log(`Visa HUD Doctor
297
+ `);let r=[],s=Ju(void 0,void 0,void 0,{withDiagnostics:!0}),o=s.diagnostics?Xu(s.diagnostics,s.display):null;o&&(console.log(`\u26A0 ${o}`),console.log(""));let i=Bt(),a=!1;try{if(ce.existsSync(i)){let m=JSON.parse(ce.readFileSync(i,"utf-8")),p=typeof m.statusLine=="object"?m.statusLine.command:"";a=bn(p)}}catch{}n("Claude Code statusLine",a,a?"registered":"not registered \u2014 run: visa-cli config hud enable");let c=o1(re.homedir()),l=Wr();if(n("Shell detected",!!l,l??"none (zsh, bash, or PowerShell required)"),l){let m=Gs(l),p=ce.existsSync(m);if(n("RC file exists",p,m.replace(re.homedir(),"~")),p){let v=ce.readFileSync(m,"utf-8").includes("visa-cli shell hud v2");console.log(` ${v?"\u2713":"\u2013"} Shell HUD block: ${v?"installed":"not installed (opt-in \u2014 run: visa-cli config hud enable shell)"}`)}}if(c.length>0&&console.log(` \u2713 Shell HUD rc scan: installed in ${c.map(m=>m.replace(re.homedir(),"~")).join(", ")}`),a&&c.length>0&&e.fix){let m=c.map(g=>g.replace(re.homedir(),"~")).join(", "),p=e.yes===!0;if(!p&&process.stdin.isTTY&&(p=await E_(`Remove shell prompt HUD block from ${m}?`,{})==="confirmed"),p){let g=r1(re.homedir());jt();let v=s1(g);if(v.length>0){let A=v.map(b=>b.replace(re.homedir(),"~")).join(", ");console.log(` \u2713 --fix: cleaned legacy shell-prompt HUD block from ${A}`),r.push(`removed shell precmd block from ${A}`)}}else console.log(` ! --fix: preserving shell prompt HUD block in ${m}; rerun with --yes or remove it explicitly with: visa-cli config hud disable shell`)}else a&&c.length>0&&console.log(" ! Overlap notice: Claude Code statusLine and shell prompt HUD are both installed. If the prompt output is unintended, run: visa-cli config hud disable shell \u2014 or rerun with: visa-cli config hud doctor --fix --yes");let u=yn(),d=ce.existsSync(u);if(n("HUD cache file",d,d?u.replace(re.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),d)try{let m=JSON.parse(ce.readFileSync(u,"utf-8")),p=Date.now()-(m.renderedAt??0),g=Math.round(p/1e3),v=g<=30,A=typeof m.line=="string"?m.line:"",b=A.length>0&&di(A);if(console.log(` ${v?"\u2713":"\u26A0"} Cache freshness: ${g}s old${v?"":" (stale \u2014 will refresh on next prompt)"}`),b&&console.log(' \u26A0 Cache content: legacy placeholder (HUD will display "VISA | HUD not ready" until next successful refresh)'),e.fix&&(!v||b)){let w=!1;try{ce.rmSync(u,{force:!0}),w=!0}catch{}try{let S=Ks();ce.existsSync(S)&&(ce.rmSync(S,{force:!0}),w=!0)}catch{}if(w){let S=b?"cache held legacy placeholder":`cache was ${g}s stale`;console.log(` \u2713 --fix: cleared HUD cache (${S}); next prompt will trigger a fresh refresh`),r.push("cleared HUD cache");let E=tt.join(re.homedir(),".visa-cli","shell-hud.lock");ce.existsSync(E)&&(Jn(),console.log(" \u2713 --fix: cleared shell HUD refresh lock"),r.push("cleared shell HUD refresh lock"))}}}catch{if(console.log(" \u2717 Cache readable: corrupt JSON"),e.fix)try{ce.rmSync(u,{force:!0}),console.log(" \u2713 --fix: removed corrupt cache file; next prompt will trigger a fresh refresh"),r.push("removed corrupt cache");let m=tt.join(re.homedir(),".visa-cli","shell-hud.lock");ce.existsSync(m)&&(Jn(),console.log(" \u2713 --fix: cleared shell HUD refresh lock"),r.push("cleared shell HUD refresh lock"))}catch{t=!1}else t=!1}let f=!1;try{f=!!await G.getSessionToken()}catch{}if(n("Auth token",f,f?"found in keychain":"missing \u2014 run: visa-cli setup"),f)try{await pe().getStatus(),n("API connectivity",!0,"GET /v1/status OK")}catch(m){let p=m instanceof Error?m.message:"unknown error";n("API connectivity",!1,p)}e.fix&&(r.length===0?console.log(`
298
298
  --fix: no locally fixable issues found.`):console.log(`
299
299
  --fix: applied ${r.length} change${r.length===1?"":"s"} \u2014 ${r.join("; ")}.`)),console.log(t?`
300
300
  All checks passed.`:`
301
- Some checks failed \u2014 see above.`),t||process.exit(1)});Ps.command("enable-claude").description("Alias for: hud enable claude").action(()=>{let e=Bt(),t=zs(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});Ps.command("disable-claude").description("Alias for: hud disable claude").action(()=>{let e=Bt(),t=Cc(e);console.log(t.message),t.removed||process.exit(1)});var Os=J.command("merchants [slug] [sub] [args...]").description("Discover and run paid merchant tools").addHelpCommand(!1).allowExcessArguments(!0).allowUnknownOption(!0).action(async(e,t,n=[])=>{if(!e||a1.has(e)){Os.help({error:!1});return}await l1(e,t,n)});Os.command("list").description("List live platform merchants").option("--json","Print machine-readable JSON").action(async e=>{try{let n=await new qe(()=>G.getSessionToken()).listPublicMerchants();if(n.length===0){e.json?console.log(JSON.stringify({merchants:[]},null,2)):console.log(`
301
+ Some checks failed \u2014 see above.`),t||process.exit(1)});$s.command("enable-claude").description("Alias for: hud enable claude").action(()=>{let e=Bt(),t=zs(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});$s.command("disable-claude").description("Alias for: hud disable claude").action(()=>{let e=Bt(),t=Rc(e);console.log(t.message),t.removed||process.exit(1)});var Os=J.command("merchants [slug] [sub] [args...]").description("Discover and run paid merchant tools").addHelpCommand(!1).allowExcessArguments(!0).allowUnknownOption(!0).action(async(e,t,n=[])=>{if(!e||c1.has(e)){Os.help({error:!1});return}await u1(e,t,n)});Os.command("list").description("List live platform merchants").option("--json","Print machine-readable JSON").action(async e=>{try{let n=await new qe(()=>G.getSessionToken()).listPublicMerchants();if(n.length===0){e.json?console.log(JSON.stringify({merchants:[]},null,2)):console.log(`
302
302
  No live platform merchants on this auth server.
303
303
  `);return}if(e.json){console.log(JSON.stringify({merchants:n},null,2));return}let r="\x1B[1m",s="\x1B[2m",o="\x1B[0m";console.log();for(let i of n)console.log(` ${r}${i.display_name}${o} ${s}\u2014 slug: ${i.slug}${o}`);console.log(`
304
304
  ${s}Run 'visa-cli merchants tools' to browse tools by merchant.${o}
305
- `)}catch(t){console.error("Error:",t.message),process.exit(1)}});var a1=new Set(["list","tools","describe","run","refresh"]);async function xd(e){try{let n=await pe().catalogTool(e,"discover_tools");n||(console.error(`Tool not found: ${e}`),console.error('Search with: visa-cli tools --query "what you want to do"'),process.exit(1)),console.log(`
305
+ `)}catch(t){console.error("Error:",t.message),process.exit(1)}});var c1=new Set(["list","tools","describe","run","refresh"]);async function Td(e){try{let n=await pe().catalogTool(e,"discover_tools");n||(console.error(`Tool not found: ${e}`),console.error('Search with: visa-cli tools --query "what you want to do"'),process.exit(1)),console.log(`
306
306
  ${n.id}
307
307
  `),console.log(n.description),console.log(`
308
- Price`),console.log(` ${so(n.priceCents,n.priceDisplay)}`),console.log(`
308
+ Price`),console.log(` ${oo(n.priceCents,n.priceDisplay)}`),console.log(`
309
309
  Provider`),console.log(` ${n.provider} \xB7 ${n.category}`),console.log(`
310
- Inputs`);let r=n.inputSchema?.properties;if(r&&typeof r=="object"&&!Array.isArray(r)){let o=Array.isArray(n.inputSchema.required)?new Set(n.inputSchema.required):new Set,i=Object.entries(r),a=Math.max(12,...i.map(([c])=>c.length));for(let[c,l]of i){let u=o.has(c)?"required":"optional",d=Kf(l),f=d?` ${d.padEnd(8)}`:" ",m=l?.description?` - ${l.description}`:"";console.log(` ${c.padEnd(a)} ${u}${f}${m}`)}}else console.log(" No published schema. Use --json with the request body.");console.log(`
311
- Examples`);let s=Fy(n);console.log(` visa-cli merchants run ${n.id} --json '${JSON.stringify(s)}'`),n.category==="image"&&console.log(' visa-cli generate image "a lobster on a marble counter"'),console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}}async function Td(e){try{let t=pe();if(e.merchant){let i=e.merchant,a=await t.getPublicMerchantDiscover(i);a||(console.error(`Merchant not found: ${i}`),console.error("List merchants with: visa-cli merchants list"),process.exit(1));let c=a.routes.filter(u=>u.tool_id).map(u=>({id:u.tool_id,name:u.tool_id,description:u.description||"",provider:a.upstream_display??a.title,model:u.tool_id,category:u.category||"utility",priceCents:u.price_cents??0,inputSchema:u.request?.body_schema??{}})),l=e.category?c.filter(u=>u.category===e.category):c;if(e.json){console.log(JSON.stringify({merchant:i,tools:l},null,2));return}if(l.length===0){console.log(`No tools found for merchant "${i}".`);return}e.verbose?Wc(l):Tm(i,l);return}let{limit:n,offset:r}=VC(e),{tools:s,hidden:o}=await HC(t,{query:e.query,category:e.category,limit:n,offset:r});if(e.json){console.log(JSON.stringify({tools:s,hidden:o},null,2));return}if(s.length===0){if(o&&o.count>0){Yc(o);return}console.log("No merchant tools found. Try: visa-cli tools --category image");return}e.verbose?Wc(s):xm(s),o&&o.count>0&&Yc(o)}catch(t){console.error("Error:",t.message),process.exit(1)}}Os.command("tools").description("List available merchant tools").option("--category <category>","Filter by category (image, video, audio, 3d, llm)").option("--query <query>","Search by intent or keyword").option("--merchant <slug>","Scope to a single merchant (e.g. fal, openrouter)").option("--verbose","Show grouped cards with descriptions").option("--json","Print machine-readable JSON").option("--limit <n>",`Maximum tools to return (default ${hd}, max ${yd})`,Ka).option("--offset <n>","Pagination offset (default 0)",Ka).action(Td);Os.command("describe <tool>").description("Show tool schema, price, and examples").action(async e=>{await xd(e)});function c1(e){return["fal-flux-pro-ultra","fal-flux-pro","fal-flux-schnell","fal-recraft-v3","fal-ideogram-v2","fal-minimax-video","fal-wan-video","fal-kling-video","fal-ace-step-music","query_onchain_prices"].includes(e)}async function Qa(e,t,n){return c1(e)?lt.shortcut(e,t,n):lt.executeTool({tool_id:e,params:t},n,"execute_tool")}Os.command("run <tool>").description("Run any merchant tool by id").option("--json <json>","Tool parameters as a JSON object").option("--prompt <prompt>","Prompt parameter for prompt-shaped tools").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=x_(t.json,"--json");t.prompt&&(n.prompt=t.prompt),Bs({yes:t.yes}),console.log(`Running ${e}`);let r=await Qa(e,n,`visa-cli merchants run ${e}`);za(r),Ja(r)}catch(n){console.error("Error:",n.message),process.exit(1)}});Os.command("refresh").description("Hint: restart the MCP server (Claude/Cursor) to refresh discovered tools \u2014 discovery is in-process").action(()=>{console.log(`
310
+ Inputs`);let r=n.inputSchema?.properties;if(r&&typeof r=="object"&&!Array.isArray(r)){let o=Array.isArray(n.inputSchema.required)?new Set(n.inputSchema.required):new Set,i=Object.entries(r),a=Math.max(12,...i.map(([c])=>c.length));for(let[c,l]of i){let u=o.has(c)?"required":"optional",d=Gf(l),f=d?` ${d.padEnd(8)}`:" ",m=l?.description?` - ${l.description}`:"";console.log(` ${c.padEnd(a)} ${u}${f}${m}`)}}else console.log(" No published schema. Use --json with the request body.");console.log(`
311
+ Examples`);let s=Hy(n);console.log(` visa-cli merchants run ${n.id} --json '${JSON.stringify(s)}'`),n.category==="image"&&console.log(' visa-cli generate image "a lobster on a marble counter"'),console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}}async function Ad(e){try{let t=pe();if(e.merchant){let i=e.merchant,a=await t.getPublicMerchantDiscover(i);a||(console.error(`Merchant not found: ${i}`),console.error("List merchants with: visa-cli merchants list"),process.exit(1));let c=a.routes.filter(u=>u.tool_id).map(u=>({id:u.tool_id,name:u.tool_id,description:u.description||"",provider:a.upstream_display??a.title,model:u.tool_id,category:u.category||"utility",priceCents:u.price_cents??0,inputSchema:u.request?.body_schema??{}})),l=e.category?c.filter(u=>u.category===e.category):c;if(e.json){console.log(JSON.stringify({merchant:i,tools:l},null,2));return}if(l.length===0){console.log(`No tools found for merchant "${i}".`);return}e.verbose?Yc(l):Am(i,l);return}let{limit:n,offset:r}=qE(e),{tools:s,hidden:o}=await VE(t,{query:e.query,category:e.category,limit:n,offset:r});if(e.json){console.log(JSON.stringify({tools:s,hidden:o},null,2));return}if(s.length===0){if(o&&o.count>0){zc(o);return}console.log("No merchant tools found. Try: visa-cli tools --category image");return}e.verbose?Yc(s):Tm(s),o&&o.count>0&&zc(o)}catch(t){console.error("Error:",t.message),process.exit(1)}}Os.command("tools").description("List available merchant tools").option("--category <category>","Filter by category (image, video, audio, 3d, llm)").option("--query <query>","Search by intent or keyword").option("--merchant <slug>","Scope to a single merchant (e.g. fal, openrouter)").option("--verbose","Show grouped cards with descriptions").option("--json","Print machine-readable JSON").option("--limit <n>",`Maximum tools to return (default ${yd}, max ${_d})`,Ga).option("--offset <n>","Pagination offset (default 0)",Ga).action(Ad);Os.command("describe <tool>").description("Show tool schema, price, and examples").action(async e=>{await Td(e)});function l1(e){return["fal-flux-pro-ultra","fal-flux-pro","fal-flux-schnell","fal-recraft-v3","fal-ideogram-v2","fal-minimax-video","fal-wan-video","fal-kling-video","fal-ace-step-music","query_onchain_prices"].includes(e)}async function ec(e,t,n){return l1(e)?lt.shortcut(e,t,n):lt.executeTool({tool_id:e,params:t},n,"execute_tool")}Os.command("run <tool>").description("Run any merchant tool by id").option("--json <json>","Tool parameters as a JSON object").option("--prompt <prompt>","Prompt parameter for prompt-shaped tools").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=T_(t.json,"--json");t.prompt&&(n.prompt=t.prompt),Bs({yes:t.yes}),console.log(`Running ${e}`);let r=await ec(e,n,`visa-cli merchants run ${e}`);Ja(r),Xa(r)}catch(n){console.error("Error:",n.message),process.exit(1)}});Os.command("refresh").description("Hint: restart the MCP server (Claude/Cursor) to refresh discovered tools \u2014 discovery is in-process").action(()=>{console.log(`
312
312
  Platform-merchant tool discovery is cached in-process by the MCP server.`),console.log(" Cache TTL: VISA_MERCHANT_DISCOVER_TTL_MS (default 300000ms = 5min)."),console.log(` To force-refresh now, restart Claude / Cursor \u2014 the next tools/list will re-fetch.
313
- `)});async function l1(e,t,n){if(!t||t==="tools"){let r=n.indexOf("--category"),s=r!==-1?n[r+1]:void 0,o=n.includes("--verbose"),i=n.includes("--json");await Td({category:s,verbose:o,json:i,merchant:e});return}if(t==="describe"){let r=n[0];r||(console.error(`Usage: visa-cli merchants ${e} describe <tool>`),process.exit(1));try{let s=pe(),o=await s.getPublicMerchantDiscover(e);if(o||(console.error(`Merchant not found: ${e}`),console.error("List merchants with: visa-cli merchants list"),process.exit(1)),!await s.catalogTool(r,"discover_tools")){let a=o.routes.find(c=>c.tool_id===r);a||(console.error(`Tool "${r}" not found for merchant "${e}"`),console.error(`Browse with: visa-cli merchants ${e} tools`),process.exit(1)),console.log(`
313
+ `)});async function u1(e,t,n){if(!t||t==="tools"){let r=n.indexOf("--category"),s=r!==-1?n[r+1]:void 0,o=n.includes("--verbose"),i=n.includes("--json");await Ad({category:s,verbose:o,json:i,merchant:e});return}if(t==="describe"){let r=n[0];r||(console.error(`Usage: visa-cli merchants ${e} describe <tool>`),process.exit(1));try{let s=pe(),o=await s.getPublicMerchantDiscover(e);if(o||(console.error(`Merchant not found: ${e}`),console.error("List merchants with: visa-cli merchants list"),process.exit(1)),!await s.catalogTool(r,"discover_tools")){let a=o.routes.find(c=>c.tool_id===r);a||(console.error(`Tool "${r}" not found for merchant "${e}"`),console.error(`Browse with: visa-cli merchants ${e} tools`),process.exit(1)),console.log(`
314
314
  ${r}
315
315
  `),a.description&&console.log(a.description),console.log(`
316
- Price`),console.log(` ${so(a.price_cents)}`),console.log(`
316
+ Price`),console.log(` ${oo(a.price_cents)}`),console.log(`
317
317
  Examples`),console.log(` visa-cli merchants run ${r} --json '${JSON.stringify(a.request?.body_example??{})}'`),console.log(` visa-cli merchants ${e} run ${r}
318
- `);return}await xd(r)}catch(s){console.error("Error:",s.message),process.exit(1)}return}if(t==="run"){let r=n[0];r||(console.error(`Usage: visa-cli merchants ${e} run <tool> [--json '{...}']`),process.exit(1));let s=i=>{let a=n.indexOf(i);return a!==-1?n[a+1]:void 0},o=n.includes("--yes");try{let i=s("--json"),a=x_(i,"--json"),c=s("--prompt");c&&(a.prompt=c),Bs({yes:o}),console.log(`Running ${r}`);let l=await Qa(r,a,`visa-cli merchants ${e} run ${r}`);za(l),Ja(l)}catch(i){console.error("Error:",i.message),process.exit(1)}return}console.error(`Unknown subcommand "${t}" for merchant "${e}"`),console.error("Available: tools, describe <tool>, run <tool>"),process.exit(1)}J.command("tools").description("List available merchant tools (alias for: merchants tools)").option("--category <category>","Filter by category (image, video, audio, 3d, llm)").option("--query <query>","Search by intent or keyword").option("--merchant <slug>","Scope to a single merchant (e.g. fal, openrouter)").option("--verbose","Show grouped cards with descriptions").option("--json","Print machine-readable JSON").option("--limit <n>",`Maximum tools to return (default ${hd}, max ${yd})`,Ka).option("--offset <n>","Pagination offset (default 0)",Ka).action(Td);J.command("describe <tool>").description("Show schema, price, and examples for a tool (alias for: merchants describe)").action(async e=>{await xd(e)});var Vo=J.command("generate").description("Generate media with merchant tools").addHelpCommand(!1).action(Lt);async function qo(e){Bs({yes:e.yes}),e.json||e.format&&ti(e.format)||(console.log(`
318
+ `);return}await Td(r)}catch(s){console.error("Error:",s.message),process.exit(1)}return}if(t==="run"){let r=n[0];r||(console.error(`Usage: visa-cli merchants ${e} run <tool> [--json '{...}']`),process.exit(1));let s=i=>{let a=n.indexOf(i);return a!==-1?n[a+1]:void 0},o=n.includes("--yes");try{let i=s("--json"),a=T_(i,"--json"),c=s("--prompt");c&&(a.prompt=c),Bs({yes:o}),console.log(`Running ${r}`);let l=await ec(r,a,`visa-cli merchants ${e} run ${r}`);Ja(l),Xa(l)}catch(i){console.error("Error:",i.message),process.exit(1)}return}console.error(`Unknown subcommand "${t}" for merchant "${e}"`),console.error("Available: tools, describe <tool>, run <tool>"),process.exit(1)}J.command("tools").description("List available merchant tools (alias for: merchants tools)").option("--category <category>","Filter by category (image, video, audio, 3d, llm)").option("--query <query>","Search by intent or keyword").option("--merchant <slug>","Scope to a single merchant (e.g. fal, openrouter)").option("--verbose","Show grouped cards with descriptions").option("--json","Print machine-readable JSON").option("--limit <n>",`Maximum tools to return (default ${yd}, max ${_d})`,Ga).option("--offset <n>","Pagination offset (default 0)",Ga).action(Ad);J.command("describe <tool>").description("Show schema, price, and examples for a tool (alias for: merchants describe)").action(async e=>{await Td(e)});var qo=J.command("generate").description("Generate media with merchant tools").addHelpCommand(!1).action(Lt);async function Ko(e){Bs({yes:e.yes}),e.json||e.format&&ni(e.format)||(console.log(`
319
319
  ${e.kind}
320
320
  `),console.log(`Using: ${e.toolId}`),console.log(`Prompt: ${e.prompt}
321
- `));let n=await Qa(e.toolId,e.params,`visa-cli generate ${e.kind.toLowerCase()}: ${e.prompt}`);za(n,{json:e.json,format:e.format,command:e.command??`generate.${e.kind.toLowerCase().replace(/\s+/g,"_")}`}),Ja(n)}var Wn=(e,t)=>n=>(t.includes(n)||J.error(`error: option '${e}' accepts ${t.map(r=>`'${r}'`).join(", ")} (got '${n}')`,{exitCode:2}),n);Vo.command("image [prompt]").description("Generate an image from a prompt (accepts stdin via `-` or --stdin)").option("--quality <quality>","Image quality: standard or high",Wn("--quality",["standard","high"]),"standard").option("--fast","Use the fast image tool").option("--tool <tool>","Exact tool id override").option("--image-ref <url>","Optional source image URL for edit/style-transfer tools").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Wn("--format",gn)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await Yn(e,t),r=t.tool??(t.fast||t.quality!=="high"?"fal-flux-pro":"fal-flux-pro-ultra"),s={prompt:n};t.imageRef&&(s.image_url=t.imageRef),await qo({kind:"Image generation",toolId:r,params:s,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.image"})}catch(n){$s("generate.image",n,{json:t.json,format:t.format})}});Vo.command("video [prompt]").description("Generate a video from a prompt (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--aspect-ratio <ratio>","Aspect ratio, when supported by the selected tool").option("--duration <seconds>","Duration in seconds, when supported by the selected tool").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Wn("--format",gn)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await Yn(e,t),r={prompt:n};t.aspectRatio&&(r.aspect_ratio=t.aspectRatio),t.duration&&(r.duration=Number(t.duration)),await qo({kind:"Video generation",toolId:t.tool??"fal-minimax-video",params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.video"})}catch(n){$s("generate.video",n,{json:t.json,format:t.format})}});Vo.command("music [prompt]").description("Generate music from a prompt (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--instrumental","Generate instrumental music").option("--duration <seconds>","Duration in seconds, when supported by the selected tool").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Wn("--format",gn)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await Yn(e,t),r={prompt:n};t.instrumental&&(r.instrumental=!0),t.duration&&(r.duration=Number(t.duration)),await qo({kind:"Music generation",toolId:t.tool??In("generate_music"),params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.music"})}catch(n){$s("generate.music",n,{json:t.json,format:t.format})}});Vo.command("speech [text]").description("Generate speech from text using a voice sample (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--audio-url <url>","Voice sample audio URL for voice cloning").option("--ref-audio-url <url>","Alias for --audio-url").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Wn("--format",gn)).option("--stdin","Read text from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=t.audioUrl??t.refAudioUrl;n||J.error("error: option '--audio-url <url>' is required for visa-cli generate speech",{exitCode:2});let r=await Yn(e,t),s={text:r,audio_url:n};await qo({kind:"Speech generation",toolId:t.tool??"fal-metavoice",params:s,prompt:r,json:t.json,format:t.format,yes:t.yes,command:"generate.speech"})}catch(n){$s("generate.speech",n,{json:t.json,format:t.format})}});Vo.command("3d [image-url]").alias("model").description("Generate a 3D model from an image URL (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Wn("--format",gn)).option("--stdin","Read image URL from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await Yn(e,t),r={image_url:n};await qo({kind:"3D generation",toolId:t.tool??In("generate_3d"),params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.3d"})}catch(n){$s("generate.3d",n,{json:t.json,format:t.format})}});var dd="reasoning",h_=Object.keys(lo.run_llm.tiers);J.command("run-llm [prompt]").description(`Run a chat-completion against an OpenRouter-backed LLM (default tier: ${dd})`).option("--tier <tier>",`LLM tier: ${h_.join(" | ")} (resolves to a catalog tool id via the run_llm meta-tool)`,Wn("--tier",h_),dd).option("--model <id>","Exact catalog tool id (e.g. or-claude-haiku, or-gemini-3-flash). Overrides --tier.").option("--system <prompt>","System prompt (inline string or @./path to a file)").option("--max-tokens <n>","Maximum completion tokens").option("--temperature <n>","Sampling temperature 0-2").option("--image-url <url>","Image URL for vision-capable models (or-gemini-nano-banana-pro, etc.)").option("--from-stdin <field>","Read upstream JSON envelope from stdin and bind .field to a flag value (e.g. --image-url --from-stdin .urls[0])").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Wn("--format",gn)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=t.imageUrl;if(t.fromStdin){let l=await pc(),u=JSON.parse(l),d=Kd(u,t.fromStdin);n=n??d}let r=await Yn(e,{stdin:t.stdin&&!t.fromStdin});Bs({yes:t.yes});let s={prompt:r},o=await Wd(t.system);o&&(s.system_prompt=o),t.maxTokens&&(s.max_tokens=Number(t.maxTokens)),t.temperature!==void 0&&(s.temperature=Number(t.temperature)),n&&(s.image_url=n);let i=t.tier??dd,a=t.model??In("run_llm",i),c=await Qa(a,s,"visa-cli run-llm");if(!t.json&&c?.success!==!1){console.log(`
321
+ `));let n=await ec(e.toolId,e.params,`visa-cli generate ${e.kind.toLowerCase()}: ${e.prompt}`);Ja(n,{json:e.json,format:e.format,command:e.command??`generate.${e.kind.toLowerCase().replace(/\s+/g,"_")}`}),Xa(n)}var Wn=(e,t)=>n=>(t.includes(n)||J.error(`error: option '${e}' accepts ${t.map(r=>`'${r}'`).join(", ")} (got '${n}')`,{exitCode:2}),n);qo.command("image [prompt]").description("Generate an image from a prompt (accepts stdin via `-` or --stdin)").option("--quality <quality>","Image quality: standard or high",Wn("--quality",["standard","high"]),"standard").option("--fast","Use the fast image tool").option("--tool <tool>","Exact tool id override").option("--image-ref <url>","Optional source image URL for edit/style-transfer tools").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Wn("--format",gn)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await Yn(e,t),r=t.tool??(t.fast||t.quality!=="high"?"fal-flux-pro":"fal-flux-pro-ultra"),s={prompt:n};t.imageRef&&(s.image_url=t.imageRef),await Ko({kind:"Image generation",toolId:r,params:s,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.image"})}catch(n){Ps("generate.image",n,{json:t.json,format:t.format})}});qo.command("video [prompt]").description("Generate a video from a prompt (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--aspect-ratio <ratio>","Aspect ratio, when supported by the selected tool").option("--duration <seconds>","Duration in seconds, when supported by the selected tool").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Wn("--format",gn)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await Yn(e,t),r={prompt:n};t.aspectRatio&&(r.aspect_ratio=t.aspectRatio),t.duration&&(r.duration=Number(t.duration)),await Ko({kind:"Video generation",toolId:t.tool??"fal-minimax-video",params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.video"})}catch(n){Ps("generate.video",n,{json:t.json,format:t.format})}});qo.command("music [prompt]").description("Generate music from a prompt (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--instrumental","Generate instrumental music").option("--duration <seconds>","Duration in seconds, when supported by the selected tool").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Wn("--format",gn)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await Yn(e,t),r={prompt:n};t.instrumental&&(r.instrumental=!0),t.duration&&(r.duration=Number(t.duration)),await Ko({kind:"Music generation",toolId:t.tool??In("generate_music"),params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.music"})}catch(n){Ps("generate.music",n,{json:t.json,format:t.format})}});qo.command("speech [text]").description("Generate speech from text using a voice sample (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--audio-url <url>","Voice sample audio URL for voice cloning").option("--ref-audio-url <url>","Alias for --audio-url").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Wn("--format",gn)).option("--stdin","Read text from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=t.audioUrl??t.refAudioUrl;n||J.error("error: option '--audio-url <url>' is required for visa-cli generate speech",{exitCode:2});let r=await Yn(e,t),s={text:r,audio_url:n};await Ko({kind:"Speech generation",toolId:t.tool??"fal-metavoice",params:s,prompt:r,json:t.json,format:t.format,yes:t.yes,command:"generate.speech"})}catch(n){Ps("generate.speech",n,{json:t.json,format:t.format})}});qo.command("3d [image-url]").alias("model").description("Generate a 3D model from an image URL (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Wn("--format",gn)).option("--stdin","Read image URL from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await Yn(e,t),r={image_url:n};await Ko({kind:"3D generation",toolId:t.tool??In("generate_3d"),params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.3d"})}catch(n){Ps("generate.3d",n,{json:t.json,format:t.format})}});var fd="reasoning",y_=Object.keys(uo.run_llm.tiers);J.command("run-llm [prompt]").description(`Run a chat-completion against an OpenRouter-backed LLM (default tier: ${fd})`).option("--tier <tier>",`LLM tier: ${y_.join(" | ")} (resolves to a catalog tool id via the run_llm meta-tool)`,Wn("--tier",y_),fd).option("--model <id>","Exact catalog tool id (e.g. or-claude-haiku, or-gemini-3-flash). Overrides --tier.").option("--system <prompt>","System prompt (inline string or @./path to a file)").option("--max-tokens <n>","Maximum completion tokens").option("--temperature <n>","Sampling temperature 0-2").option("--image-url <url>","Image URL for vision-capable models (or-gemini-nano-banana-pro, etc.)").option("--from-stdin <field>","Read upstream JSON envelope from stdin and bind .field to a flag value (e.g. --image-url --from-stdin .urls[0])").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Wn("--format",gn)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=t.imageUrl;if(t.fromStdin){let l=await gc(),u=JSON.parse(l),d=Gd(u,t.fromStdin);n=n??d}let r=await Yn(e,{stdin:t.stdin&&!t.fromStdin});Bs({yes:t.yes});let s={prompt:r},o=await Yd(t.system);o&&(s.system_prompt=o),t.maxTokens&&(s.max_tokens=Number(t.maxTokens)),t.temperature!==void 0&&(s.temperature=Number(t.temperature)),n&&(s.image_url=n);let i=t.tier??fd,a=t.model??In("run_llm",i),c=await ec(a,s,"visa-cli run-llm");if(!t.json&&c?.success!==!1){console.log(`
322
322
  LLM completion
323
323
  `),console.log(`Using: ${a}`);let l=r.length>200?`${r.slice(0,200)}\u2026`:r;console.log(`Prompt: ${l}
324
- `)}za(c,{json:t.json,format:t.format,command:"run-llm"}),Ja(c)}catch(n){$s("run-llm",n,{json:t.json,format:t.format})}});J.command("uninstall [client]").description("Remove MCP server from an AI client").option("--all","Remove from all clients").option("--scope <scope>","Uninstall scope: global or project","global").action(async(e,t)=>{try{let n=t.scope==="project"?"project":"global";if(t.all){let o=[];for(let i of ht)ad(i,n).removed&&o.push(i.displayName);o.length>0?console.log(`Removed visa-cli from: ${o.join(", ")}.`):console.log("visa-cli was not installed in any client.");return}e||(console.error("Usage: visa-cli uninstall <client>"),console.error(" visa-cli uninstall --all"),console.error(`
325
- Supported clients: ${ht.map(o=>o.id).join(", ")}`),process.exit(1));let r=rd(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${ht.map(o=>o.id).join(", ")}`),process.exit(1));let s=ad(r,n);s.removed?console.log(`Removed visa-cli from ${s.configPath}`):console.log(`visa-cli was not installed for ${r.displayName}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});J.hook("postAction",()=>{if(Fo){Fo=!1;return}Va&&jy(Va.lastSignals)});e_(J);n_(J);JC(["setup","install","status","cards","keys","balance","tools","describe","merchants","generate","run-llm","config","feedback","update","uninstall"]);A_(J);J.parseAsync().catch(async e=>{console.error("Error:",e instanceof Error?e.message:String(e));let{reportFatal:t}=await Promise.resolve().then(()=>(Ha(),Fa));await t(e)});process.on("uncaughtException",async e=>{console.error("Uncaught exception:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(Ha(),Fa));await t(e)});process.on("unhandledRejection",async e=>{console.error("Unhandled rejection:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(Ha(),Fa));await t(e)});0&&(module.exports={printGroupHelpAndExit});
324
+ `)}Ja(c,{json:t.json,format:t.format,command:"run-llm"}),Xa(c)}catch(n){Ps("run-llm",n,{json:t.json,format:t.format})}});J.command("uninstall [client]").description("Remove MCP server from an AI client").option("--all","Remove from all clients").option("--scope <scope>","Uninstall scope: global or project","global").action(async(e,t)=>{try{let n=t.scope==="project"?"project":"global";if(t.all){let o=[];for(let i of ht)cd(i,n).removed&&o.push(i.displayName);o.length>0?console.log(`Removed visa-cli from: ${o.join(", ")}.`):console.log("visa-cli was not installed in any client.");return}e||(console.error("Usage: visa-cli uninstall <client>"),console.error(" visa-cli uninstall --all"),console.error(`
325
+ Supported clients: ${ht.map(o=>o.id).join(", ")}`),process.exit(1));let r=sd(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${ht.map(o=>o.id).join(", ")}`),process.exit(1));let s=cd(r,n);s.removed?console.log(`Removed visa-cli from ${s.configPath}`):console.log(`visa-cli was not installed for ${r.displayName}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});J.hook("postAction",()=>{if(Ho){Ho=!1;return}qa&&By(qa.lastSignals)});t_(J);r_(J);XE(["setup","install","status","cards","keys","balance","tools","describe","merchants","generate","run-llm","config","feedback","update","uninstall"]);C_(J);J.parseAsync().catch(async e=>{console.error("Error:",e instanceof Error?e.message:String(e));let{reportFatal:t}=await Promise.resolve().then(()=>(Va(),Ha));await t(e)});process.on("uncaughtException",async e=>{console.error("Uncaught exception:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(Va(),Ha));await t(e)});process.on("unhandledRejection",async e=>{console.error("Unhandled rejection:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(Va(),Ha));await t(e)});0&&(module.exports={printGroupHelpAndExit});
326
326
  /*! Bundled license information:
327
327
 
328
328
  @noble/ed25519/index.js: