@visa/cli 4.0.0-rc.15 → 4.0.0-rc.16

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 $_=Object.create;var qo=Object.defineProperty;var P_=Object.getOwnPropertyDescriptor;var O_=Object.getOwnPropertyNames;var N_=Object.getPrototypeOf,M_=Object.prototype.hasOwnProperty;var rt=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Za=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},jr=(e,t)=>{for(var n in t)qo(e,n,{get:t[n],enumerable:!0})},Cd=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of O_(t))!M_.call(e,s)&&s!==n&&qo(e,s,{get:()=>t[s],enumerable:!(r=P_(t,s))||r.enumerable});return e};var I=(e,t,n)=>(n=e!=null?$_(N_(e)):{},Cd(t||!e||!e.__esModule?qo(n,"default",{value:e,enumerable:!0}):n,e)),L_=e=>Cd(qo({},"__esModule",{value:!0}),e);var Ms=Za((eT,z_)=>{z_.exports={name:"@visa/cli",version:"4.0.0-rc.15",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 && pnpm --filter @visa/identity build && pnpm --filter @visa/wallet build && pnpm --filter @visa/wallet-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/wallet":"workspace:*","@visa/wallet-tools":"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":"^26.1.0","@typescript-eslint/eslint-plugin":"^8.63.0","@typescript-eslint/parser":"^8.63.0","@types/express":"^5.0.0",esbuild:"^0.28.1",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.9.4","ts-jest":"^29.4.11",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","native/visa-keychain-win.cpp","native/build-win.bat","native/bin/win32-x64/visa-keychain-win.exe","server.json","README.md","LICENSE"]}});function _0(){Be.existsSync(Mc)||Be.mkdirSync(Mc,{recursive:!0,mode:448})}function b0(){if(!Nc){if(_0(),Be.existsSync(Xs)&&Be.statSync(Xs).size>y0){let t=Xs+".1";Be.existsSync(t)&&Be.unlinkSync(t),Be.renameSync(Xs,t)}Nc=Be.createWriteStream(Xs,{flags:"a"})}return Nc}function v0(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function _i(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
- `;v0(e)&&process.stderr.write(s),b0().write(s)}var Be,Lc,nm,Mc,Xs,y0,Nc,h,Ht=rt(()=>{"use strict";Be=I(require("fs")),Lc=I(require("path")),nm=I(require("os")),Mc=Lc.join(nm.homedir(),".visa-mcp"),Xs=Lc.join(Mc,"mcp-server.log"),y0=5*1024*1024,Nc=null;h={debug:(...e)=>_i("DEBUG",...e),info:(...e)=>_i("INFO",...e),warn:(...e)=>_i("WARN",...e),error:(...e)=>_i("ERROR",...e)}});var bi,im,am,Uc,Zs,cm=rt(()=>{"use strict";bi=I(require("fs")),im=I(require("path")),am=I(require("os")),Uc=im.join(am.homedir(),".visa-mcp"),Zs=class{static ensureConfigDir(){bi.existsSync(Uc)||bi.mkdirSync(Uc,{recursive:!0,mode:448})}static getConfigDir(){return Uc}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 lm(e){let t=um.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function Qs(){return dm.join(Zs.getConfigDir(),x0)}function fm(e){if((0,Bc.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function A0(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 fm(s)}function E0(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,Bc.isIP)(t);return n===4?fm(t):n===6?t==="::1"||A0(t):!1}function Dc(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:"&&E0(n.hostname)))throw new Error(`${t} ${C0}`)}function er(){let e=Qs();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:lm(e),reason:"not_object"}),{}):n}catch(t){return h.warn("settings:corrupt",{path:lm(e),error:t?.message||String(t)}),{}}}function jc(e){Zs.ensureConfigDir();let t=Qs(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
3
- `;wn.writeFileSync(n,r,{mode:384}),wn.renameSync(n,t)}function Hc(e){let t=er()[e];return typeof t=="string"?t:void 0}function wi(e){let t=er()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function Vc(e){let t=er()[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 Si(e,t){if(mm.some(o=>e.startsWith(o)))throw new Vt(e);if(e in vi)throw new vn(e);let n=tr[e];if(!n)throw new it(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=er();return s[e]=r,jc(s),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:Qs()}}function xi(e){if(mm.some(o=>e.startsWith(o)))throw new Vt(e);let t=tr[e];if(e in vi){let o=er(),i=e in o;return i&&(delete o[e],jc(o)),{key:e,removed:i,requiresRestart:!1,path:Qs()}}if(!t)throw new it(e);let r=er(),s=e in r;return s&&(delete r[e],jc(r)),{key:e,removed:s,requiresRestart:s&&!!t.requiresRestart,path:Qs()}}function pm(){let e=er();return Object.entries(vi).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}function R0(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function I0(){try{let e=Ms();return R0(e.version)}catch{return!1}}function $0(e){return e.envVar!==void 0&&e.envVar!==""?(Dc(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(Dc(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?T0:k0}function $e(){return $0({envVar:process.env.VISA_AUTH_URL,settingValue:Hc("auth.serverUrl"),isPrerelease:I0()})}function gm(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":wi("ui.suppressBrowser")??!1}function hm(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":wi("ui.suppressFeed")??!1}function ym(){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=Vc("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):Fc}var wn,Bc,um,dm,x0,C0,tr,Fc,vi,it,Vt,vn,mm,k0,T0,qt=rt(()=>{"use strict";wn=I(require("fs")),Bc=require("node:net"),um=I(require("os")),dm=I(require("path"));cm();Ht();x0="settings.json",C0="must use https unless it points at localhost/loopback for local development";tr={"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");Dc(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.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)")}}},Fc=500,vi={"tools.specific":"Legacy direct _card MCP tools are retired. Use discover_tools/execute_tool.","tools.meta":"Category meta-tools (generate_image, run_llm, ...) are removed. Use discover_tools/execute_tool.","credit.sessionMode":"The session-mode toggle is retired. Use start_session, close_session, and get_session_status."};it=class extends Error{constructor(t){let n=Object.keys(tr).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}\`. `+vi[t]),this.name="RetiredSettingKeyError"}},mm=["biometric.","spending.","account.","cards.","biometric"];k0="https://auth.visacli.sh",T0="https://auth-visa-code-preview.up.railway.app"});var np=Za(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.formatCents=tp;ct.formatUsd=Aw;ct.formatMicros=$i;ct.formatMicrosWire=Ew;ct.formatTxAmount=kw;ct.formatDate=Tw;ct.formatRelativeTime=Rw;ct.formatTime=Iw;ct.formatAge=$w;var ep=1e6,Cw=100;function tp(e,t={}){let n=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return n;let s=(e/Cw).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${s}`:s}function Aw(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 $i(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/ep).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??6});return t.showPlusSign&&r>0?`+${o}`:o}function Ew(e,t,n={}){return e&&/^-?\d+$/.test(e)?$i(e,n):t!=null&&Number.isFinite(t)?tp(t,n):n.fallback??"\u2014"}function kw(e,t={}){let n=Number(e.amount_micros);if(Number.isFinite(n)&&e.amount_micros!=null&&e.amount_micros!=="")return $i(n,t);let r=Number(String(e.amount).replace(/^\$/,""));return Number.isFinite(r)?$i(r*ep,t):t.fallback??"\u2014"}function Tw(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 Rw(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?ss(r,s,a,"minute"):c<24?ss(r,s,c,"hour"):l===1?s?"yesterday":"tomorrow":l<7?ss(r,s,l,"day"):u<4?ss(r,s,u,"week"):d<12?ss(r,s,d,"month"):ss(r,s,f,"year")}function ss(e,t,n,r){let s=n!==1?"s":"";return t?`${n} ${r}${s} ago`:`in ${n} ${r}${s}`}function Iw(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 $w(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 os=Za(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.formatAge=q.formatTime=q.formatRelativeTime=q.formatDate=q.formatTxAmount=q.formatMicrosWire=q.formatMicros=q.formatUsd=q.formatCents=void 0;q.micros=Pw;q.fromCents=Ow;q.fromUsdc=Nw;q.fromUsd=Mw;q.toCents=Lw;q.toCentsForAcquirer=Uw;q.toUsdc=Dw;q.toWire=jw;q.fromWire=Bw;q.toDisplay=Fw;q.toUsdRounded2dp=Hw;q.add=Vw;q.sub=qw;q.clampNonNegative=Kw;q.isNonNegative=Gw;q.max=Ww;q.min=Yw;var zt=10000n,rp=1000000n;function Pw(e){return e}function Ow(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 Nw(e){return e}function Mw(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function Lw(e){if(e>=0n)return Number(e/zt);let t=e/zt,n=e%zt;return Number(n===0n?t:t-1n)}function Uw(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/zt)}function Dw(e){return e}function jw(e){return e.toString()}function Bw(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 Fw(e,t={}){let n=t.decimals??2,r=t.symbol??"$",s=e<0n,o=s?-e:e,i=o/rp,a=o%rp,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 Hw(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 Vw(e,t){return e+t}function qw(e,t){return e-t}function Kw(e){return e<0n?0n:e}function Gw(e){return e>=0n}function Ww(e,t){return e>t?e:t}function Yw(e,t){return e<t?e:t}var Jt=np();Object.defineProperty(q,"formatCents",{enumerable:!0,get:function(){return Jt.formatCents}});Object.defineProperty(q,"formatUsd",{enumerable:!0,get:function(){return Jt.formatUsd}});Object.defineProperty(q,"formatMicros",{enumerable:!0,get:function(){return Jt.formatMicros}});Object.defineProperty(q,"formatMicrosWire",{enumerable:!0,get:function(){return Jt.formatMicrosWire}});Object.defineProperty(q,"formatTxAmount",{enumerable:!0,get:function(){return Jt.formatTxAmount}});Object.defineProperty(q,"formatDate",{enumerable:!0,get:function(){return Jt.formatDate}});Object.defineProperty(q,"formatRelativeTime",{enumerable:!0,get:function(){return Jt.formatRelativeTime}});Object.defineProperty(q,"formatTime",{enumerable:!0,get:function(){return Jt.formatTime}});Object.defineProperty(q,"formatAge",{enumerable:!0,get:function(){return Jt.formatAge}})});function Cl(e,t){switch(e){case"name_not_found":return new Gp(t);case"delivery_failed":return new Wp(t);case"timeout":return new ho(t);case"not_registered":return new Yp;case"register_failed":return new Yi(t);case"invalid_message":return new zp(t);case"rate_limited":return new Jp(t);default:return new Et(e,t)}}var Et,Gp,Wp,ho,Yp,Ne,zp,Yi,Jp,Al=rt(()=>{"use strict";Et=class extends Error{code;constructor(e,t){super(t),this.name="SubwayError",this.code=e}},Gp=class extends Et{constructor(e){super("name_not_found",`Agent not registered: ${e}`),this.name="NameNotFoundError"}},Wp=class extends Et{constructor(e){super("delivery_failed",e),this.name="DeliveryFailedError"}},ho=class extends Et{constructor(e="RPC call timed out"){super("timeout",e),this.name="TimeoutError"}},Yp=class extends Et{constructor(){super("not_registered","Client has not registered with the bridge"),this.name="NotRegisteredError"}},Ne=class extends Et{constructor(e){super("connection_failed",e),this.name="ConnectionError"}},zp=class extends Et{constructor(e){super("invalid_message",e),this.name="InvalidMessageError"}},Yi=class extends Et{constructor(e){super("register_failed",e),this.name="RegisterFailedError"}},Jp=class extends Et{constructor(e="Rate limited"){super("rate_limited",e),this.name="RateLimitedError"}}});var Xp,El=rt(()=>{"use strict";Xp=(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 kl(){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 wS(){if(typeof WebSocket<"u")return WebSocket;try{let e=Xp("ws");return e.default??e}catch{return}}function SS(e,t,n){return Math.min(Math.max(e,t),n)}function WS(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Lg(e,t,n=""){let r=WS(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 og(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 YS(e,t){Lg(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 yo(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function $l(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Tt(e,t){return e<<32-t|e>>>t}function Ug(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 zS(e,t,n){return e&t^~e&n}function JS(e,t,n){return e&t^e&n^t&n}function XS(e,t=!1){return t?{h:Number(e&zi),l:Number(e>>ig&zi)}:{h:Number(e>>ig&zi)|0,l:Number(e&zi)|0}}function ZS(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}=XS(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 px(e){return BS(e)}function gx(e,t){return VS(t,e)}function yx(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function vx(e){let t=hx(fx(e.payload)),n=`${e.messageId}
1
+ "use strict";var A_=Object.create;var Ko=Object.defineProperty;var k_=Object.getOwnPropertyDescriptor;var T_=Object.getOwnPropertyNames;var R_=Object.getPrototypeOf,I_=Object.prototype.hasOwnProperty;var st=(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}},Fr=(e,t)=>{for(var n in t)Ko(e,n,{get:t[n],enumerable:!0})},xd=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of T_(t))!I_.call(e,s)&&s!==n&&Ko(e,s,{get:()=>t[s],enumerable:!(r=k_(t,s))||r.enumerable});return e};var R=(e,t,n)=>(n=e!=null?A_(R_(e)):{},xd(t||!e||!e.__esModule?Ko(n,"default",{value:e,enumerable:!0}):n,e)),$_=e=>xd(Ko({},"__esModule",{value:!0}),e);var Ls=ec((Hk,q_)=>{q_.exports={name:"@visa/cli",version:"4.0.0-rc.16",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 && pnpm --filter @visa/identity build && pnpm --filter @visa/wallet build && pnpm --filter @visa/wallet-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/wallet":"workspace:*","@visa/wallet-tools":"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":"^26.1.0","@typescript-eslint/eslint-plugin":"^8.63.0","@typescript-eslint/parser":"^8.63.0","@types/express":"^5.0.0",esbuild:"^0.28.1",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.9.4","ts-jest":"^29.4.11",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","native/visa-keychain-win.cpp","native/build-win.bat","native/bin/win32-x64/visa-keychain-win.exe","server.json","README.md","LICENSE"]}});function m0(){Fe.existsSync(Uc)||Fe.mkdirSync(Uc,{recursive:!0,mode:448})}function p0(){if(!Lc){if(m0(),Fe.existsSync(Zs)&&Fe.statSync(Zs).size>f0){let t=Zs+".1";Fe.existsSync(t)&&Fe.unlinkSync(t),Fe.renameSync(Zs,t)}Lc=Fe.createWriteStream(Zs,{flags:"a"})}return Lc}function g0(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
+ `;g0(e)&&process.stderr.write(s),p0().write(s)}var Fe,Dc,tm,Uc,Zs,f0,Lc,g,qt=st(()=>{"use strict";Fe=R(require("fs")),Dc=R(require("path")),tm=R(require("os")),Uc=Dc.join(tm.homedir(),".visa-mcp"),Zs=Dc.join(Uc,"mcp-server.log"),f0=5*1024*1024,Lc=null;g={debug:(...e)=>bi("DEBUG",...e),info:(...e)=>bi("INFO",...e),warn:(...e)=>bi("WARN",...e),error:(...e)=>bi("ERROR",...e)}});var vi,om,im,jc,Qs,am=st(()=>{"use strict";vi=R(require("fs")),om=R(require("path")),im=R(require("os")),jc=om.join(im.homedir(),".visa-mcp"),Qs=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 cm(e){let t=lm.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function eo(){return um.join(Qs.getConfigDir(),_0)}function dm(e){if((0,Hc.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function v0(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 dm(s)}function w0(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,Hc.isIP)(t);return n===4?dm(t):n===6?t==="::1"||v0(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:"&&w0(n.hostname)))throw new Error(`${t} ${b0}`)}function er(){let e=eo();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)?(g.warn("settings:corrupt",{path:cm(e),reason:"not_object"}),{}):n}catch(t){return g.warn("settings:corrupt",{path:cm(e),error:t?.message||String(t)}),{}}}function Fc(e){Qs.ensureConfigDir();let t=eo(),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=er()[e];return typeof t=="string"?t:void 0}function Si(e){let t=er()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function Kc(e){let t=er()[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(fm.some(o=>e.startsWith(o)))throw new Kt(e);if(e in wi)throw new vn(e);let n=tr[e];if(!n)throw new at(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=er();return s[e]=r,Fc(s),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:eo()}}function Ci(e){if(fm.some(o=>e.startsWith(o)))throw new Kt(e);let t=tr[e];if(e in wi){let o=er(),i=e in o;return i&&(delete o[e],Fc(o)),{key:e,removed:i,requiresRestart:!1,path:eo()}}if(!t)throw new at(e);let r=er(),s=e in r;return s&&(delete r[e],Fc(r)),{key:e,removed:s,requiresRestart:s&&!!t.requiresRestart,path:eo()}}function mm(){let e=er();return Object.entries(wi).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}function C0(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function E0(){try{let e=Ls();return C0(e.version)}catch{return!1}}function A0(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?x0:S0}function Se(){return A0({envVar:process.env.VISA_AUTH_URL,settingValue:qc("auth.serverUrl"),isPrerelease:E0()})}function pm(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":Si("ui.suppressBrowser")??!1}function gm(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":Si("ui.suppressFeed")??!1}function hm(){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,lm,um,_0,b0,tr,Vc,wi,at,Kt,vn,fm,S0,x0,St=st(()=>{"use strict";wn=R(require("fs")),Hc=require("node:net"),lm=R(require("os")),um=R(require("path"));am();qt();_0="settings.json",b0="must use https unless it points at localhost/loopback for local development";tr={"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.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 discover_tools/execute_tool.","tools.meta":"Category meta-tools (generate_image, run_llm, ...) are removed. Use discover_tools/execute_tool.","credit.sessionMode":"The session-mode toggle is retired. Use start_session, close_session, and get_session_status."};at=class extends Error{constructor(t){let n=Object.keys(tr).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"}},Kt=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"}},fm=["biometric.","spending.","account.","cards.","biometric"];S0="https://auth.visacli.sh",x0="https://auth-visa-code-preview.up.railway.app"});var tp=ec(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.formatCents=ep;lt.formatUsd=vw;lt.formatMicros=Pi;lt.formatMicrosWire=ww;lt.formatTxAmount=Sw;lt.formatDate=xw;lt.formatRelativeTime=Cw;lt.formatTime=Ew;lt.formatAge=Aw;var Qm=1e6,bw=100;function ep(e,t={}){let n=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return n;let s=(e/bw).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${s}`:s}function vw(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/Qm).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??6});return t.showPlusSign&&r>0?`+${o}`:o}function ww(e,t,n={}){return e&&/^-?\d+$/.test(e)?Pi(e,n):t!=null&&Number.isFinite(t)?ep(t,n):n.fallback??"\u2014"}function Sw(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*Qm,t):t.fallback??"\u2014"}function xw(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 Cw(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 Ew(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 Aw(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(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.formatAge=q.formatTime=q.formatRelativeTime=q.formatDate=q.formatTxAmount=q.formatMicrosWire=q.formatMicros=q.formatUsd=q.formatCents=void 0;q.micros=kw;q.fromCents=Tw;q.fromUsdc=Rw;q.fromUsd=Iw;q.toCents=$w;q.toCentsForAcquirer=Pw;q.toUsdc=Ow;q.toWire=Nw;q.fromWire=Mw;q.toDisplay=Lw;q.toUsdRounded2dp=Uw;q.add=Dw;q.sub=jw;q.clampNonNegative=Bw;q.isNonNegative=Fw;q.max=Hw;q.min=Vw;var Jt=10000n,np=1000000n;function kw(e){return e}function Tw(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*Jt}function Rw(e){return e}function Iw(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function $w(e){if(e>=0n)return Number(e/Jt);let t=e/Jt,n=e%Jt;return Number(n===0n?t:t-1n)}function Pw(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/Jt)}function Ow(e){return e}function Nw(e){return e.toString()}function Mw(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 Lw(e,t={}){let n=t.decimals??2,r=t.symbol??"$",s=e<0n,o=s?-e:e,i=o/np,a=o%np,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 Uw(e){let t=e<0n,n=t?-e:e,r=n/Jt,o=n%Jt*2n,i;o<Jt?i=r:o>Jt?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function Dw(e,t){return e+t}function jw(e,t){return e-t}function Bw(e){return e<0n?0n:e}function Fw(e){return e>=0n}function Hw(e,t){return e>t?e:t}function Vw(e,t){return e<t?e:t}var Xt=tp();Object.defineProperty(q,"formatCents",{enumerable:!0,get:function(){return Xt.formatCents}});Object.defineProperty(q,"formatUsd",{enumerable:!0,get:function(){return Xt.formatUsd}});Object.defineProperty(q,"formatMicros",{enumerable:!0,get:function(){return Xt.formatMicros}});Object.defineProperty(q,"formatMicrosWire",{enumerable:!0,get:function(){return Xt.formatMicrosWire}});Object.defineProperty(q,"formatTxAmount",{enumerable:!0,get:function(){return Xt.formatTxAmount}});Object.defineProperty(q,"formatDate",{enumerable:!0,get:function(){return Xt.formatDate}});Object.defineProperty(q,"formatRelativeTime",{enumerable:!0,get:function(){return Xt.formatRelativeTime}});Object.defineProperty(q,"formatTime",{enumerable:!0,get:function(){return Xt.formatTime}});Object.defineProperty(q,"formatAge",{enumerable:!0,get:function(){return Xt.formatAge}})});function Al(e,t){switch(e){case"name_not_found":return new Kp(t);case"delivery_failed":return new Gp(t);case"timeout":return new yo(t);case"not_registered":return new Wp;case"register_failed":return new zi(t);case"invalid_message":return new Yp(t);case"rate_limited":return new zp(t);default:return new Tt(e,t)}}var Tt,Kp,Gp,yo,Wp,Ne,Yp,zi,zp,kl=st(()=>{"use strict";Tt=class extends Error{code;constructor(e,t){super(t),this.name="SubwayError",this.code=e}},Kp=class extends Tt{constructor(e){super("name_not_found",`Agent not registered: ${e}`),this.name="NameNotFoundError"}},Gp=class extends Tt{constructor(e){super("delivery_failed",e),this.name="DeliveryFailedError"}},yo=class extends Tt{constructor(e="RPC call timed out"){super("timeout",e),this.name="TimeoutError"}},Wp=class extends Tt{constructor(){super("not_registered","Client has not registered with the bridge"),this.name="NotRegisteredError"}},Ne=class extends Tt{constructor(e){super("connection_failed",e),this.name="ConnectionError"}},Yp=class extends Tt{constructor(e){super("invalid_message",e),this.name="InvalidMessageError"}},zi=class extends Tt{constructor(e){super("register_failed",e),this.name="RegisterFailedError"}},zp=class extends Tt{constructor(e="Rate limited"){super("rate_limited",e),this.name="RateLimitedError"}}});var Jp,Tl=st(()=>{"use strict";Jp=(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 Ar(e){return e.includes(".")?e:`${e}.relay`}function Rl(){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=Jp("ws");return e.default??e}catch{return}}function yS(e,t,n){return Math.min(Math.max(e,t),n)}function HS(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Mg(e,t,n=""){let r=HS(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 sg(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 VS(e,t){Mg(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 Ol(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function It(e,t){return e<<32-t|e>>>t}function Lg(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 qS(e,t,n){return e&t^~e&n}function KS(e,t,n){return e&t^e&n^t&n}function GS(e,t=!1){return t?{h:Number(e&Ji),l:Number(e>>og&Ji)}:{h:Number(e>>og&Ji)|0,l:Number(e&Ji)|0}}function WS(e,t=!1){let n=e.length,r=new Uint32Array(n),s=new Uint32Array(n);for(let o=0;o<n;o++){let{h:i,l:a}=GS(e[o],t);[r[o],s[o]]=[i,a]}return[r,s]}function tn(e,t,n,r){let s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}function lx(e){return MS(e)}function ux(e,t){return DS(t,e)}function fx(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function gx(e){let t=dx(ax(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 _x.encode(n)}function wx(e,t,n,r,s,o,i){return vx({messageId:e,senderPeerId:t,senderName:n,timestampMs:r,messageType:s,payload:o,nonce:i})}function Sx(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 Kx(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function eh(e,t,n=""){let r=Kx(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 yg(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){eh(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 Fl(...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 Wx(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 Jx(e,t=!1){return t?{h:Number(e&Zi),l:Number(e>>_g&Zi)}:{h:Number(e>>_g&Zi)|0,l:Number(e&Zi)|0}}function Xx(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}=Jx(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 lC(){return Fx.randomSecretKey()}function nh(e){return jx(e)}function uC(){let e=lC();return{secretKey:e,publicKey:nh(e)}}function dC(e){if((0,Bn.existsSync)(e)){let n=(0,Bn.readFileSync)(e),r=new Uint8Array(n.buffer.slice(n.byteOffset,n.byteOffset+32));return{secretKey:r,publicKey:nh(r)}}let t=uC();return(0,Bn.mkdirSync)((0,xg.dirname)(e),{recursive:!0}),(0,Bn.writeFileSync)(e,new Uint8Array(t.secretKey)),t}function fC(e){let{secretKey:t,publicKey:n}=dC(e);return{privateKey:t,publicKey:n}}async function mC(e,t,n,r,s,o,i,a){let c=wx(t,n,r,s,o,i,a);return{signature:await gx(e,c),signatureInput:bx.subwayAgentMsgV1}}function Sg(e){return yx(e)}var Bn,xg,xS,CS,AS,ES,kS,Cg,ra,ta,Zp,Qp,Tl,Rl,TS,la,RS,Ee,IS,$S,PS,rn,ua,Hl,Ag,Vl,Qt,eg,ql,Eg,OS,ds,NS,sa,Sr,oe,tg,$,kg,Tg,Rg,Ig,Il,Ll,_o,Rr,kr,$g,Pg,kt,MS,ng,LS,Ul,Kl,US,Og,DS,jS,BS,FS,HS,VS,Gl,Ng,oa,qS,Mg,Dl,KS,rg,sg,GS,Dg,jg,Nn,Me,zi,ig,ag,cg,as,cs,Ji,Xi,QS,ex,tx,nx,rx,sx,ox,Mn,ix,ax,Bg,cx,lx,Ln,Un,ux,dx,fx,mx,lg,hx,Fg,_x,bx,Hg,ia,na,ug,dg,Pl,Ol,xx,fs,Cx,ke,Ax,Ex,kx,Fn,da,Wl,Vg,qg,tn,fg,Kg,Gg,Tx,Yl,Rx,aa,Cr,ae,mg,P,Ix,$x,Wg,Yg,Nl,jl,bo,ms,Tr,Px,zg,Rt,Ox,pg,Nx,Mx,Lx,Ux,Jg,Dx,Xg,jx,Zg,Bx,Fx,ca,Hx,Qg,Bl,Vx,gg,hg,qx,Yx,zx,Le,Zi,_g,bg,vg,ls,us,Qi,ea,Zx,Qx,eC,tC,nC,rC,th,sC,oC,Dn,jn,iC,aC,cC,wg,pC,gC,rh,zl=rt(()=>{"use strict";Al();Al();El();Bn=require("fs"),xg=require("path");xS=1e3,CS=10,AS=3e4,ES=3e4,kS=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??xS,this.maxReconnectAttempts=e.maxReconnectAttempts??CS,this.pingInterval=e.pingInterval??AS}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=wS();if(!n){t(new Ne('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 Ne(`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 Ne("WebSocket closed before connection established")))},this.ws.onerror=()=>{r||(r=!0,t(new Ne(`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 Ne("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=SS(this.reconnectInterval*Math.pow(2,this.reconnectAttempt),this.reconnectInterval,ES);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)}}},Cg=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:ra,n:ta,Gx:Zp,Gy:Qp,a:Tl,d:Rl,h:TS}=Cg,la=32,RS=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},Ee=(e="")=>{let t=new Error(e);throw RS(t,Ee),t},IS=e=>typeof e=="bigint",$S=e=>typeof e=="string",PS=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=PS(e),s=e?.length,o=t!==void 0;if(!r||o&&s!==t){let i=n&&`"${n}" `,a=o?` of length ${t}`:"",c=r?`length=${s}`:`type=${typeof e}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):new TypeError(l)}return e},ua=e=>new Uint8Array(e),Hl=e=>Uint8Array.from(e),Ag=(e,t)=>e.toString(16).padStart(t,"0"),Vl=e=>Array.from(rn(e)).map(t=>Ag(t,2)).join(""),Qt={_0:48,_9:57,A:65,F:70,a:97,f:102},eg=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)},ql=e=>{let t="hex invalid";if(!$S(e))return Ee(t);let n=e.length,r=n/2;if(n%2)return Ee(t);let s=ua(r);for(let o=0,i=0;o<r;o++,i+=2){let a=eg(e.charCodeAt(i)),c=eg(e.charCodeAt(i+1));if(a===void 0||c===void 0)return Ee(t);s[o]=a*16+c}return s},Eg=()=>globalThis?.crypto,OS=()=>Eg()?.subtle??Ee("crypto.subtle must be defined, consider polyfill"),ds=(...e)=>{let t=0;for(let s of e)t+=rn(s).length;let n=ua(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},NS=(e=la)=>Eg().getRandomValues(ua(e)),sa=BigInt,Sr=(e,t,n,r="bad number: out of range")=>{if(!IS(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},oe=(e,t=ra)=>{let n=e%t;return n>=0n?n:t+n},tg=(1n<<255n)-1n,$=e=>{e<0n&&Ee("negative coordinate");let t=(e>>255n)*19n+(e&tg);return t=(t>>255n)*19n+(t&tg),t%ra},kg=e=>oe(e,ta),Tg=(e,t)=>{(e===0n||t<=0n)&&Ee("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):Ee("no inverse")},Rg=e=>{let t=Ng[e];return typeof t!="function"&&Ee("hashes."+e+" not set"),t},Ig=e=>rn(e,64,"digest"),Il=e=>e instanceof _o?e:Ee("Point expected"),Ll=2n**256n,_o=class xr{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=Ll;this.X=Sr(t,0n,o),this.Y=Sr(n,0n,o),this.Z=Sr(r,1n,o),this.T=Sr(s,0n,o),Object.freeze(this)}static CURVE(){return Cg}static fromAffine(t){return new xr(t.x,t.y,1n,$(t.x*t.y))}static fromBytes(t,n=!1){let r=Rl,s=Hl(rn(t,la)),o=t[31];s[31]=o&-129;let i=Pg(s);Sr(i,0n,n?Ll:ra);let c=$(i*i),l=oe(c-1n),u=$(r*c+1n),{isValid:d,value:f}=LS(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=oe(-f)),new xr(f,i,1n,$(f*i))}static fromHex(t,n){return xr.fromBytes(ql(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Tl,n=Rl,r=this;if(r.is0())return Ee("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 Ee("bad point: equation left != right (1)");let g=$(s*o),b=$(i*a);return g!==b?Ee("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=Il(t),c=$(n*a),l=$(o*s),u=$(r*a),d=$(i*s);return c===l&&u===d}is0(){return this.equals(kr)}negate(){return new xr(oe(-this.X),this.Y,this.Z,oe(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=Tl,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),b=$(u*m),A=$(f*d);return new xr(p,g,A,b)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=Il(t),u=Tl,d=Rl,f=$(n*i),m=$(r*a),p=$($(o*d)*l),g=$(s*c),b=oe($(oe(n+r)*oe(i+a))-f-m),A=oe(g-p),_=oe(g+p),v=oe(m-$(u*f)),w=$(b*A),T=$(_*v),E=$(b*v),y=$(A*_);return new xr(w,T,y,E)}subtract(t){return this.add(Il(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(Sr(t,1n,ta),!n&&this.is0()))return kr;if(t===1n)return this;if(this.equals(Rr))return GS(t).p;let r=kr,s=Rr;for(let o=this;t>0n;o=o.double(),t>>=1n)t&1n?r=r.add(o):n&&(s=s.add(o));return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(this.equals(kr))return{x:0n,y:1n};let s=Tg(r,ra);$(r*s)!==1n&&Ee("invalid inverse");let o=$(t*s),i=$(n*s);return{x:o,y:i}}toBytes(){let{x:t,y:n}=this.toAffine(),r=$g(n);return r[31]|=t&1n?128:0,r}toHex(){return Vl(this.toBytes())}clearCofactor(){return this.multiply(sa(TS),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(ta/2n,!1).double();return ta%2n&&(t=t.add(this)),t.is0()}},Rr=new _o(Zp,Qp,1n,oe(Zp*Qp)),kr=new _o(0n,1n,1n,0n);_o.BASE=Rr;_o.ZERO=kr;$g=e=>ql(Ag(Sr(e,0n,Ll),64)).reverse(),Pg=e=>sa("0x"+Vl(Hl(rn(e)).reverse())),kt=(e,t)=>{let n=e;for(;t-- >0n;)n=$(n*n);return n},MS=e=>{let t=$(e*e),n=$(t*e),r=$(kt(n,2n)*n),s=$(kt(r,1n)*e),o=$(kt(s,5n)*s),i=$(kt(o,10n)*o),a=$(kt(i,20n)*i),c=$(kt(a,40n)*a),l=$(kt(c,80n)*c),u=$(kt(l,80n)*c),d=$(kt(u,10n)*o);return{pow_p_5_8:$(kt(d,2n)*e),b2:n}},ng=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,LS=(e,t)=>{let n=$(t*$(t*t)),r=$($(n*n)*t),s=MS($(e*r)).pow_p_5_8,o=$(e*$(n*s)),i=$(t*$(o*o)),a=o,c=$(o*ng),l=i===e,u=i===oe(-e),d=i===oe(-e*ng);return l&&(o=a),(u||d)&&(o=c),(oe(o)&1n)===1n&&(o=oe(-o)),{isValid:l||u,value:o}},Ul=e=>kg(Pg(e)),Kl=(...e)=>Promise.resolve(Rg("sha512Async")(ds(...e))).then(Ig),US=(...e)=>Ig(Rg("sha512")(ds(...e))),Og=e=>{let t=Hl(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=Ul(n),o=Rr.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},DS=e=>Kl(rn(e,la)).then(Og),jS=e=>Og(US(rn(e,la))),BS=e=>jS(e).pointBytes,FS=e=>Kl(e.hashable).then(e.finish),HS=(e,t,n)=>{let{pointBytes:r,scalar:s}=e,o=Ul(t),i=Rr.multiply(o).toBytes();return{hashable:ds(i,r,n),finish:l=>{let u=kg(o+Ul(l)*s);return rn(ds(i,$g(u)),64)}}},VS=async(e,t)=>{let n=rn(e),r=await DS(t),s=await Kl(r.prefix,n);return FS(HS(r,s,n))},Gl=Object.freeze({bytesToHex:Vl,hexToBytes:ql,concatBytes:ds,mod:oe,invert:Tg,randomBytes:NS}),Ng={sha512Async:async e=>{let t=OS(),n=ds(e);return ua(await t.digest("SHA-512",n.buffer))},sha512:void 0},oa=8,qS=256,Mg=Math.ceil(qS/oa)+1,Dl=2**(oa-1),KS=()=>{let e=[],t=Rr,n=t;for(let r=0;r<Mg;r++){n=t,e.push(n);for(let s=1;s<Dl;s++)n=n.add(t),e.push(n);t=n.double()}return e},rg=void 0,sg=(e,t)=>{let n=t.negate();return e?n:t},GS=e=>{let t=rg||(rg=KS()),n=kr,r=Rr,s=2**oa,o=s,i=sa(s-1),a=sa(oa);for(let c=0;c<Mg;c++){let l=Number(e&i);e>>=a,l>Dl&&(l-=o,e+=1n);let u=c*Dl,d=u,f=u+Math.abs(l)-1,m=c%2!==0,p=l<0;l===0?r=r.add(sg(m,t[d])):n=n.add(sg(p,t[f]))}return e!==0n&&Ee("invalid wnaf"),{p:n,f:r}};Dg=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});jg=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=$l(this.buffer)}update(e){og(this),Lg(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=$l(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){og(this),YS(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,yo(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=$l(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]),Me=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),zi=BigInt(2**32-1),ig=BigInt(32);ag=(e,t,n)=>e>>>n,cg=(e,t,n)=>e<<32-n|t>>>n,as=(e,t,n)=>e>>>n|t<<32-n,cs=(e,t,n)=>e<<32-n|t>>>n,Ji=(e,t,n)=>e<<64-n|t>>>n-32,Xi=(e,t,n)=>e>>>n-32|t<<64-n;QS=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),ex=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,tx=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),nx=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,rx=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),sx=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,ox=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]),Mn=new Uint32Array(64),ix=class extends jg{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)Mn[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let d=Mn[u-15],f=Mn[u-2],m=Tt(d,7)^Tt(d,18)^d>>>3,p=Tt(f,17)^Tt(f,19)^f>>>10;Mn[u]=p+Mn[u-7]+m+Mn[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=Tt(i,6)^Tt(i,11)^Tt(i,25),f=l+d+zS(i,a,c)+ox[u]+Mn[u]|0,p=(Tt(n,2)^Tt(n,13)^Tt(n,22))+JS(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(){yo(Mn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),yo(this.buffer)}},ax=class extends ix{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)}},Bg=ZS(["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=Bg[0],lx=Bg[1],Ln=new Uint32Array(80),Un=new Uint32Array(80),ux=class extends jg{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 _=0;_<16;_++,t+=4)Ln[_]=e.getUint32(t),Un[_]=e.getUint32(t+=4);for(let _=16;_<80;_++){let v=Ln[_-15]|0,w=Un[_-15]|0,T=as(v,w,1)^as(v,w,8)^ag(v,w,7),E=cs(v,w,1)^cs(v,w,8)^cg(v,w,7),y=Ln[_-2]|0,x=Un[_-2]|0,Y=as(y,x,19)^Ji(y,x,61)^ag(y,x,6),X=cs(y,x,19)^Xi(y,x,61)^cg(y,x,6),K=tx(E,X,Un[_-7],Un[_-16]),be=nx(K,T,Y,Ln[_-7],Ln[_-16]);Ln[_]=be|0,Un[_]=K|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:b,Hl:A}=this;for(let _=0;_<80;_++){let v=as(u,d,14)^as(u,d,18)^Ji(u,d,41),w=cs(u,d,14)^cs(u,d,18)^Xi(u,d,41),T=u&f^~u&p,E=d&m^~d&g,y=rx(A,w,E,lx[_],Un[_]),x=sx(y,b,v,T,cx[_],Ln[_]),Y=y|0,X=as(n,r,28)^Ji(n,r,34)^Ji(n,r,39),K=cs(n,r,28)^Xi(n,r,34)^Xi(n,r,39),be=n&s^n&i^s&i,se=r&o^r&a^o&a;b=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,x|0,Y|0),c=i|0,l=a|0,i=s|0,a=o|0,s=n|0,o=r|0;let Z=QS(Y,K,se);n=ex(Z,x,X,be),r=Z|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:b,l:A}=en(this.Hh|0,this.Hl|0,b|0,A|0),this.set(n,r,s,o,i,a,c,l,u,d,f,m,p,g,b,A)}roundClean(){yo(Ln,Un)}destroy(){this.destroyed=!0,yo(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},dx=class extends ux{Ah=Me[0]|0;Al=Me[1]|0;Bh=Me[2]|0;Bl=Me[3]|0;Ch=Me[4]|0;Cl=Me[5]|0;Dh=Me[6]|0;Dl=Me[7]|0;Eh=Me[8]|0;El=Me[9]|0;Fh=Me[10]|0;Fl=Me[11]|0;Gh=Me[12]|0;Gl=Me[13]|0;Hh=Me[14]|0;Hl=Me[15]|0;constructor(){super(64)}},fx=Ug(()=>new ax,Dg(1)),mx=Ug(()=>new dx,Dg(3)),lg=Ng;lg.sha512||(lg.sha512=e=>mx(e));hx=Gl.bytesToHex,Fg=Gl.hexToBytes;Gl.concatBytes;_x=new TextEncoder,bx={subwayAgentMsgV1:"message_id;sender_peer_id;sender_name;timestamp_ms;message_type;payload_hash;nonce"};Fg("302e020100300506032b657004220420");Fg("302a300506032b6570032100");Hg=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:ia,n:na,Gx:ug,Gy:dg,a:Pl,d:Ol,h:xx}=Hg,fs=32,Cx=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},ke=(e="")=>{let t=new Error(e);throw Cx(t,ke),t},Ax=e=>typeof e=="bigint",Ex=e=>typeof e=="string",kx=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,Fn=(e,t,n="")=>{let r=kx(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},da=e=>new Uint8Array(e),Wl=e=>Uint8Array.from(e),Vg=(e,t)=>e.toString(16).padStart(t,"0"),qg=e=>Array.from(Fn(e)).map(t=>Vg(t,2)).join(""),tn={_0:48,_9:57,A:65,F:70,a:97,f:102},fg=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)},Kg=e=>{let t="hex invalid";if(!Ex(e))return ke(t);let n=e.length,r=n/2;if(n%2)return ke(t);let s=da(r);for(let o=0,i=0;o<r;o++,i+=2){let a=fg(e.charCodeAt(i)),c=fg(e.charCodeAt(i+1));if(a===void 0||c===void 0)return ke(t);s[o]=a*16+c}return s},Gg=()=>globalThis?.crypto,Tx=()=>Gg()?.subtle??ke("crypto.subtle must be defined, consider polyfill"),Yl=(...e)=>{let t=0;for(let s of e)t+=Fn(s).length;let n=da(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},Rx=(e=fs)=>Gg().getRandomValues(da(e)),aa=BigInt,Cr=(e,t,n,r="bad number: out of range")=>{if(!Ax(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},ae=(e,t=ia)=>{let n=e%t;return n>=0n?n:t+n},mg=(1n<<255n)-1n,P=e=>{e<0n&&ke("negative coordinate");let t=(e>>255n)*19n+(e&mg);return t=(t>>255n)*19n+(t&mg),t%ia},Ix=e=>ae(e,na),$x=(e,t)=>{(e===0n||t<=0n)&&ke("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):ke("no inverse")},Wg=e=>{let t=Zg[e];return typeof t!="function"&&ke("hashes."+e+" not set"),t},Yg=e=>Fn(e,64,"digest"),Nl=e=>e instanceof bo?e:ke("Point expected"),jl=2n**256n,bo=class Ar{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=jl;this.X=Cr(t,0n,o),this.Y=Cr(n,0n,o),this.Z=Cr(r,1n,o),this.T=Cr(s,0n,o),Object.freeze(this)}static CURVE(){return Hg}static fromAffine(t){return new Ar(t.x,t.y,1n,P(t.x*t.y))}static fromBytes(t,n=!1){let r=Ol,s=Wl(Fn(t,fs)),o=t[31];s[31]=o&-129;let i=zg(s);Cr(i,0n,n?jl:ia);let c=P(i*i),l=ae(c-1n),u=P(r*c+1n),{isValid:d,value:f}=Nx(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=ae(-f)),new Ar(f,i,1n,P(f*i))}static fromHex(t,n){return Ar.fromBytes(Kg(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Pl,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=ae(d+P(n*P(c*l)));if(m!==p)return ke("bad point: equation left != right (1)");let g=P(s*o),b=P(i*a);return g!==b?ke("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=Nl(t),c=P(n*a),l=P(o*s),u=P(r*a),d=P(i*s);return c===l&&u===d}is0(){return this.equals(Tr)}negate(){return new Ar(ae(-this.X),this.Y,this.Z,ae(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=Pl,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),b=P(u*m),A=P(f*d);return new Ar(p,g,A,b)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=Nl(t),u=Pl,d=Ol,f=P(n*i),m=P(r*a),p=P(P(o*d)*l),g=P(s*c),b=ae(P(ae(n+r)*ae(i+a))-f-m),A=ae(g-p),_=ae(g+p),v=ae(m-P(u*f)),w=P(b*A),T=P(_*v),E=P(b*v),y=P(A*_);return new Ar(w,T,y,E)}subtract(t){return this.add(Nl(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(Cr(t,1n,na),!n&&this.is0()))return Tr;if(t===1n)return this;if(this.equals(ms))return qx(t).p;let r=Tr,s=ms;for(let o=this;t>0n;o=o.double(),t>>=1n)t&1n?r=r.add(o):n&&(s=s.add(o));return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(this.equals(Tr))return{x:0n,y:1n};let s=$x(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=Px(n);return r[31]|=t&1n?128:0,r}toHex(){return qg(this.toBytes())}clearCofactor(){return this.multiply(aa(xx),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(na/2n,!1).double();return na%2n&&(t=t.add(this)),t.is0()}},ms=new bo(ug,dg,1n,ae(ug*dg)),Tr=new bo(0n,1n,1n,0n);bo.BASE=ms;bo.ZERO=Tr;Px=e=>Kg(Vg(Cr(e,0n,jl),64)).reverse(),zg=e=>aa("0x"+qg(Wl(Fn(e)).reverse())),Rt=(e,t)=>{let n=e;for(;t-- >0n;)n=P(n*n);return n},Ox=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}},pg=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,Nx=(e,t)=>{let n=P(t*P(t*t)),r=P(P(n*n)*t),s=Ox(P(e*r)).pow_p_5_8,o=P(e*P(n*s)),i=P(t*P(o*o)),a=o,c=P(o*pg),l=i===e,u=i===ae(-e),d=i===ae(-e*pg);return l&&(o=a),(u||d)&&(o=c),(ae(o)&1n)===1n&&(o=ae(-o)),{isValid:l||u,value:o}},Mx=e=>Ix(zg(e)),Lx=(...e)=>Promise.resolve(Wg("sha512Async")(Yl(...e))).then(Yg),Ux=(...e)=>Yg(Wg("sha512")(Yl(...e))),Jg=e=>{let t=Wl(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=Mx(n),o=ms.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},Dx=e=>Lx(Fn(e,fs)).then(Jg),Xg=e=>Jg(Ux(Fn(e,fs))),jx=e=>Xg(e).pointBytes,Zg={sha512Async:async e=>{let t=Tx(),n=Yl(e);return da(await t.digest("SHA-512",n.buffer))},sha512:void 0},Bx=e=>(e=e===void 0?Rx(fs):e,Fn(e,fs)),Fx=Object.freeze({getExtendedPublicKeyAsync:Dx,getExtendedPublicKey:Xg,randomSecretKey:Bx}),ca=8,Hx=256,Qg=Math.ceil(Hx/ca)+1,Bl=2**(ca-1),Vx=()=>{let e=[],t=ms,n=t;for(let r=0;r<Qg;r++){n=t,e.push(n);for(let s=1;s<Bl;s++)n=n.add(t),e.push(n);t=n.double()}return e},gg=void 0,hg=(e,t)=>{let n=t.negate();return e?n:t},qx=e=>{let t=gg||(gg=Vx()),n=Tr,r=ms,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>Bl&&(l-=o,e+=1n);let u=c*Bl,d=u,f=u+Math.abs(l)-1,m=c%2!==0,p=l<0;l===0?r=r.add(hg(m,t[d])):n=n.add(hg(p,t[f]))}return e!==0n&&ke("invalid wnaf"),{p:n,f:r}};Yx=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),zx=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){yg(this),eh(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){yg(this),Gx(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,Fl(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()}},Le=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Zi=BigInt(2**32-1),_g=BigInt(32);bg=(e,t,n)=>e>>>n,vg=(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;Zx=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Qx=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,eC=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),tC=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,nC=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),rC=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,th=Xx(["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))),sC=th[0],oC=th[1],Dn=new Uint32Array(80),jn=new Uint32Array(80),iC=class extends zx{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 _=0;_<16;_++,t+=4)Dn[_]=e.getUint32(t),jn[_]=e.getUint32(t+=4);for(let _=16;_<80;_++){let v=Dn[_-15]|0,w=jn[_-15]|0,T=ls(v,w,1)^ls(v,w,8)^bg(v,w,7),E=us(v,w,1)^us(v,w,8)^vg(v,w,7),y=Dn[_-2]|0,x=jn[_-2]|0,Y=ls(y,x,19)^Qi(y,x,61)^bg(y,x,6),X=us(y,x,19)^ea(y,x,61)^vg(y,x,6),K=eC(E,X,jn[_-7],jn[_-16]),be=tC(K,T,Y,Dn[_-7],Dn[_-16]);Dn[_]=be|0,jn[_]=K|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:b,Hl:A}=this;for(let _=0;_<80;_++){let v=ls(u,d,14)^ls(u,d,18)^Qi(u,d,41),w=us(u,d,14)^us(u,d,18)^ea(u,d,41),T=u&f^~u&p,E=d&m^~d&g,y=nC(A,w,E,oC[_],jn[_]),x=rC(y,b,v,T,sC[_],Dn[_]),Y=y|0,X=ls(n,r,28)^Qi(n,r,34)^Qi(n,r,39),K=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;b=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,x|0,Y|0),c=i|0,l=a|0,i=s|0,a=o|0,s=n|0,o=r|0;let Z=Zx(Y,K,se);n=Qx(Z,x,X,be),r=Z|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:b,l:A}=nn(this.Hh|0,this.Hl|0,b|0,A|0),this.set(n,r,s,o,i,a,c,l,u,d,f,m,p,g,b,A)}roundClean(){Fl(Dn,jn)}destroy(){this.destroyed=!0,Fl(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},aC=class extends iC{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)}},cC=Wx(()=>new aC,Yx(3)),wg=Zg;wg.sha512||(wg.sha512=e=>cC(e));pC="ws://localhost:9001/ws",gC=3e4,rh=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=fC(e.keyPath)}catch{}this.options={name:this._name,url:e.url??pC,relay:e.relay??"",autoReconnect:e.autoReconnect??!0,reconnectInterval:e.reconnectInterval??1e3,maxReconnectAttempts:e.maxReconnectAttempts??10,rpcTimeout:e.rpcTimeout??gC,pingInterval:e.pingInterval??3e4,binding:e.binding??""},this.transport=new kS({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=Sx(new Uint8Array(t));n&&(this._keypair={privateKey:n,publicKey:px(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=Sg(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 Ne(String(r)))}})}disconnect(){for(let[,e]of this.pendingCalls)clearTimeout(e.timer),e.reject(new Ne("Client disconnected"));this.pendingCalls.clear();for(let[,e]of this.pendingSend)e.reject(new Ne("Client disconnected"));this.pendingSend.clear();for(let[,e]of this.pendingResolve)e.reject(new Ne("Client disconnected"));this.pendingResolve.clear(),this.registerPromise&&(this.registerPromise.reject(new Ne("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=kl();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 Ne(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=kl(),i=Date.now(),a=Math.floor(Math.random()*2**32),c=new TextEncoder().encode(n),{signature:l,signatureInput:u}=await mC(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 Ne(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??kl(),i=r?.timeout??this.options.rpcTimeout;return new Promise((a,c)=>{let l=setTimeout(()=>{this.pendingCalls.delete(o),c(new ho(`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 Ne(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 Ne(String(s)))}setTimeout(()=>{this.pendingResolve.has(t)&&(this.pendingResolve.delete(t),r(new ho(`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=Cl(e.code,e.message);this.registerPromise&&e.code==="register_failed"&&(this.registerPromise.reject(new Yi(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=Sg(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 MC(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Rh(e,t,n=""){let r=MC(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 dh(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 LC(e,t){Rh(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 ru(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ql(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function UC(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 BC(e,t=!1){return t?{h:Number(e&fa),l:Number(e>>fh&fa)}:{h:Number(e>>fh&fa)|0,l:Number(e&fa)|0}}function FC(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}=BC(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 QC(){return $C.randomSecretKey()}function va(e){return EC(e)}function $h(){let e=QC();return{secretKey:e,publicKey:va(e)}}function wo(e,t){return RC(t,e)}function eA(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function tA(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 _s(e){return eA(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function nA(e){let t=e.length%4===0?0:4-e.length%4,n=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return tA(n)}function rA(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function Oh(e){let t=va(e);return{kty:"OKP",crv:"Ed25519",x:_s(t),d:_s(e)}}function Nh(e){return{kty:"OKP",crv:"Ed25519",x:_s(e)}}function So(e){if(rA(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return nA(e.d)}var hh,ha,ga,sh,oh,Jl,Xl,hC,hs,yC,Te,_C,bC,vC,$t,ba,su,yh,ou,sn,ih,iu,_h,wC,ys,bh,ya,Ir,ie,ah,O,vh,wh,Sh,xh,Zl,eu,vo,Or,Pr,Ch,Ah,It,SC,ch,xC,tu,CC,au,Eh,AC,cu,EC,kC,TC,RC,lu,kh,IC,$C,_a,PC,Th,nu,OC,lh,uh,NC,DC,jC,Ue,fa,fh,mh,ph,ps,gs,ma,pa,HC,VC,qC,KC,GC,WC,Ih,YC,zC,Hn,Vn,JC,XC,ZC,gh,k2,Ph,T2,R2,I2,$2,wa=rt(()=>{"use strict";hh=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:ha,n:ga,Gx:sh,Gy:oh,a:Jl,d:Xl,h:hC}=hh,hs=32,yC=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},Te=(e="")=>{let t=new Error(e);throw yC(t,Te),t},_C=e=>typeof e=="bigint",bC=e=>typeof e=="string",vC=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,$t=(e,t,n="")=>{let r=vC(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},ba=e=>new Uint8Array(e),su=e=>Uint8Array.from(e),yh=(e,t)=>e.toString(16).padStart(t,"0"),ou=e=>Array.from($t(e)).map(t=>yh(t,2)).join(""),sn={_0:48,_9:57,A:65,F:70,a:97,f:102},ih=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)},iu=e=>{let t="hex invalid";if(!bC(e))return Te(t);let n=e.length,r=n/2;if(n%2)return Te(t);let s=ba(r);for(let o=0,i=0;o<r;o++,i+=2){let a=ih(e.charCodeAt(i)),c=ih(e.charCodeAt(i+1));if(a===void 0||c===void 0)return Te(t);s[o]=a*16+c}return s},_h=()=>globalThis?.crypto,wC=()=>_h()?.subtle??Te("crypto.subtle must be defined, consider polyfill"),ys=(...e)=>{let t=0;for(let s of e)t+=$t(s).length;let n=ba(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},bh=(e=hs)=>_h().getRandomValues(ba(e)),ya=BigInt,Ir=(e,t,n,r="bad number: out of range")=>{if(!_C(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},ie=(e,t=ha)=>{let n=e%t;return n>=0n?n:t+n},ah=(1n<<255n)-1n,O=e=>{e<0n&&Te("negative coordinate");let t=(e>>255n)*19n+(e&ah);return t=(t>>255n)*19n+(t&ah),t%ha},vh=e=>ie(e,ga),wh=(e,t)=>{(e===0n||t<=0n)&&Te("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):Te("no inverse")},Sh=e=>{let t=kh[e];return typeof t!="function"&&Te("hashes."+e+" not set"),t},xh=e=>$t(e,64,"digest"),Zl=e=>e instanceof vo?e:Te("Point expected"),eu=2n**256n,vo=class $r{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=eu;this.X=Ir(t,0n,o),this.Y=Ir(n,0n,o),this.Z=Ir(r,1n,o),this.T=Ir(s,0n,o),Object.freeze(this)}static CURVE(){return hh}static fromAffine(t){return new $r(t.x,t.y,1n,O(t.x*t.y))}static fromBytes(t,n=!1){let r=Xl,s=su($t(t,hs)),o=t[31];s[31]=o&-129;let i=Ah(s);Ir(i,0n,n?eu:ha);let c=O(i*i),l=ie(c-1n),u=O(r*c+1n),{isValid:d,value:f}=xC(l,u);d||Te("bad point: y not sqrt");let m=(f&1n)===1n,p=(o&128)!==0;return!n&&f===0n&&p&&Te("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(iu(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Jl,n=Xl,r=this;if(r.is0())return Te("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 Te("bad point: equation left != right (1)");let g=O(s*o),b=O(i*a);return g!==b?Te("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=Zl(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(Pr)}negate(){return new $r(ie(-this.X),this.Y,this.Z,ie(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=Jl,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),b=O(u*m),A=O(f*d);return new $r(p,g,A,b)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=Zl(t),u=Jl,d=Xl,f=O(n*i),m=O(r*a),p=O(O(o*d)*l),g=O(s*c),b=ie(O(ie(n+r)*ie(i+a))-f-m),A=ie(g-p),_=ie(g+p),v=ie(m-O(u*f)),w=O(b*A),T=O(_*v),E=O(b*v),y=O(A*_);return new $r(w,T,y,E)}subtract(t){return this.add(Zl(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(Ir(t,1n,ga),!n&&this.is0()))return Pr;if(t===1n)return this;if(this.equals(Or))return NC(t).p;let r=Pr,s=Or;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(Pr))return{x:0n,y:1n};let s=wh(r,ha);O(r*s)!==1n&&Te("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=Ch(n);return r[31]|=t&1n?128:0,r}toHex(){return ou(this.toBytes())}clearCofactor(){return this.multiply(ya(hC),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(ga/2n,!1).double();return ga%2n&&(t=t.add(this)),t.is0()}},Or=new vo(sh,oh,1n,ie(sh*oh)),Pr=new vo(0n,1n,1n,0n);vo.BASE=Or;vo.ZERO=Pr;Ch=e=>iu(yh(Ir(e,0n,eu),64)).reverse(),Ah=e=>ya("0x"+ou(su($t(e)).reverse())),It=(e,t)=>{let n=e;for(;t-- >0n;)n=O(n*n);return n},SC=e=>{let t=O(e*e),n=O(t*e),r=O(It(n,2n)*n),s=O(It(r,1n)*e),o=O(It(s,5n)*s),i=O(It(o,10n)*o),a=O(It(i,20n)*i),c=O(It(a,40n)*a),l=O(It(c,80n)*c),u=O(It(l,80n)*c),d=O(It(u,10n)*o);return{pow_p_5_8:O(It(d,2n)*e),b2:n}},ch=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,xC=(e,t)=>{let n=O(t*O(t*t)),r=O(O(n*n)*t),s=SC(O(e*r)).pow_p_5_8,o=O(e*O(n*s)),i=O(t*O(o*o)),a=o,c=O(o*ch),l=i===e,u=i===ie(-e),d=i===ie(-e*ch);return l&&(o=a),(u||d)&&(o=c),(ie(o)&1n)===1n&&(o=ie(-o)),{isValid:l||u,value:o}},tu=e=>vh(Ah(e)),CC=(...e)=>Promise.resolve(Sh("sha512Async")(ys(...e))).then(xh),au=(...e)=>xh(Sh("sha512")(ys(...e))),Eh=e=>{let t=su(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=tu(n),o=Or.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},AC=e=>CC($t(e,hs)).then(Eh),cu=e=>Eh(au($t(e,hs))),EC=e=>cu(e).pointBytes,kC=e=>e.finish(au(e.hashable)),TC=(e,t,n)=>{let{pointBytes:r,scalar:s}=e,o=tu(t),i=Or.multiply(o).toBytes();return{hashable:ys(i,r,n),finish:l=>{let u=vh(o+tu(l)*s);return $t(ys(i,Ch(u)),64)}}},RC=(e,t)=>{let n=$t(e),r=cu(t),s=au(r.prefix,n);return kC(TC(r,s,n))},lu=Object.freeze({bytesToHex:ou,hexToBytes:iu,concatBytes:ys,mod:ie,invert:wh,randomBytes:bh}),kh={sha512Async:async e=>{let t=wC(),n=ys(e);return ba(await t.digest("SHA-512",n.buffer))},sha512:void 0},IC=e=>(e=e===void 0?bh(hs):e,$t(e,hs)),$C=Object.freeze({getExtendedPublicKeyAsync:AC,getExtendedPublicKey:cu,randomSecretKey:IC}),_a=8,PC=256,Th=Math.ceil(PC/_a)+1,nu=2**(_a-1),OC=()=>{let e=[],t=Or,n=t;for(let r=0;r<Th;r++){n=t,e.push(n);for(let s=1;s<nu;s++)n=n.add(t),e.push(n);t=n.double()}return e},lh=void 0,uh=(e,t)=>{let n=t.negate();return e?n:t},NC=e=>{let t=lh||(lh=OC()),n=Pr,r=Or,s=2**_a,o=s,i=ya(s-1),a=ya(_a);for(let c=0;c<Th;c++){let l=Number(e&i);e>>=a,l>nu&&(l-=o,e+=1n);let u=c*nu,d=u,f=u+Math.abs(l)-1,m=c%2!==0,p=l<0;l===0?r=r.add(uh(m,t[d])):n=n.add(uh(p,t[f]))}return e!==0n&&Te("invalid wnaf"),{p:n,f:r}};DC=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),jC=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=Ql(this.buffer)}update(e){dh(this),Rh(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=Ql(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){dh(this),LC(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,ru(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=Ql(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]),fa=BigInt(2**32-1),fh=BigInt(32);mh=(e,t,n)=>e>>>n,ph=(e,t,n)=>e<<32-n|t>>>n,ps=(e,t,n)=>e>>>n|t<<32-n,gs=(e,t,n)=>e<<32-n|t>>>n,ma=(e,t,n)=>e<<64-n|t>>>n-32,pa=(e,t,n)=>e>>>n-32|t<<64-n;HC=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),VC=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,qC=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),KC=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,GC=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),WC=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,Ih=FC(["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))),YC=Ih[0],zC=Ih[1],Hn=new Uint32Array(80),Vn=new Uint32Array(80),JC=class extends jC{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 _=0;_<16;_++,t+=4)Hn[_]=e.getUint32(t),Vn[_]=e.getUint32(t+=4);for(let _=16;_<80;_++){let v=Hn[_-15]|0,w=Vn[_-15]|0,T=ps(v,w,1)^ps(v,w,8)^mh(v,w,7),E=gs(v,w,1)^gs(v,w,8)^ph(v,w,7),y=Hn[_-2]|0,x=Vn[_-2]|0,Y=ps(y,x,19)^ma(y,x,61)^mh(y,x,6),X=gs(y,x,19)^pa(y,x,61)^ph(y,x,6),K=qC(E,X,Vn[_-7],Vn[_-16]),be=KC(K,T,Y,Hn[_-7],Hn[_-16]);Hn[_]=be|0,Vn[_]=K|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:b,Hl:A}=this;for(let _=0;_<80;_++){let v=ps(u,d,14)^ps(u,d,18)^ma(u,d,41),w=gs(u,d,14)^gs(u,d,18)^pa(u,d,41),T=u&f^~u&p,E=d&m^~d&g,y=GC(A,w,E,zC[_],Vn[_]),x=WC(y,b,v,T,YC[_],Hn[_]),Y=y|0,X=ps(n,r,28)^ma(n,r,34)^ma(n,r,39),K=gs(n,r,28)^pa(n,r,34)^pa(n,r,39),be=n&s^n&i^s&i,se=r&o^r&a^o&a;b=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,x|0,Y|0),c=i|0,l=a|0,i=s|0,a=o|0,s=n|0,o=r|0;let Z=HC(Y,K,se);n=VC(Z,x,X,be),r=Z|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:b,l:A}=on(this.Hh|0,this.Hl|0,b|0,A|0),this.set(n,r,s,o,i,a,c,l,u,d,f,m,p,g,b,A)}roundClean(){ru(Hn,Vn)}destroy(){this.destroyed=!0,ru(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},XC=class extends JC{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)}},ZC=UC(()=>new XC,DC(3)),gh=kh;gh.sha512||(gh.sha512=e=>ZC(e));k2=lu.bytesToHex,Ph=lu.hexToBytes,T2=lu.concatBytes;R2=new TextEncoder;I2=Ph("302e020100300506032b657004220420"),$2=Ph("302a300506032b6570032100");});var Bh={};jr(Bh,{CardRequiredError:()=>an,buildIssuanceRequest:()=>jh,enrollCardUrl:()=>Sa,jkt:()=>Uh,proofPayload:()=>Dh,readSeed:()=>xa,requestVisaBinding:()=>uu});function Uh(e){let t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return Mh.createHash("sha256").update(t,"utf8").digest("base64url")}function Dh(e,t,n){return`visa-agent-binding:v1:${e}:${t}:${n}`}function jh(e,t,n="visa",r=Math.floor(Date.now()/1e3)){let s=Nh(va(e)),o=Buffer.from(Dh(t,Uh(s),r),"utf8"),i=Buffer.from(wo(e,o)).toString("base64url");return{name:t,mesh:n,agent_pubkey:s,proof:{ts:r,sig:i}}}function Sa(e){try{return new URL("/enroll-card",e).toString()}catch{return"https://auth.visacli.sh/enroll-card"}}async function uu(e){let t=jh(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.",Sa(e.authUrl),"no_card"):new Error(`Visa binding issuance failed (${s.status})${o?`: ${o}`:""}`)}return await s.json()}function xa(e){return new Uint8Array(Lh.readFileSync(e))}var Mh,Lh,an,Ca=rt(()=>{"use strict";Mh=I(require("crypto")),Lh=I(require("fs"));wa();an=class extends Error{enrollUrl;reason;constructor(t,n,r){super(t),this.name="CardRequiredError",this.enrollUrl=n,this.reason=r}}});var yu={};jr(yu,{SUBWAY_PROTOCOL:()=>Xh,registerDirect:()=>hA,resolveDirect:()=>yA});function mu(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 pu(e,t){return e<<3|t}function xo(e,t,n){e.push(pu(t,2)),mu(e,n.length);for(let r of n)e.push(r)}function sA(e,t){let n=[];return xo(n,1,fu.encode(e)),t&&t.length>0&&xo(n,2,fu.encode(t)),Uint8Array.from(n)}function oA(e,t,n){let r=[];return n!==0n&&(r.push(pu(1,0)),mu(r,n)),xo(r,2,sA(e,t)),Uint8Array.from(r)}function iA(e){let t=[];return xo(t,1,fu.encode(e)),Uint8Array.from(t)}function aA(e,t){let n=[];return t!==0n&&(n.push(pu(1,0)),mu(n,t)),xo(n,3,iA(e)),Uint8Array.from(n)}function cA(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=zh.decode(e.subarray(l,u)),t=u}else t=gu(e,t,i)}return n}function lA(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=zh.decode(e.subarray(l,u)),t=u}else t=gu(e,t,i)}return n}function gu(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 Jh(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=cA(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=lA(e.subarray(l,u)),t=u}else t=gu(e,t,i)}return n}function uA(e){let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t}function hu(e){return new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1)}function dA(e){if(e.length<4)return{success:!1,error:"short reply (no length prefix)"};let t=hu(e.subarray(0,4));return e.length<4+t?{success:!1,error:`truncated frame (have ${e.length-4}, need ${t})`}:Jh(e.subarray(4,4+t)).registerNameResponse??{success:!1,error:"reply carried no register_name_response"}}function fA(e){if(e.length<4)return{peerId:new Uint8Array(0),error:"short reply (no length prefix)"};let t=hu(e.subarray(0,4));return e.length<4+t?{peerId:new Uint8Array(0),error:`truncated frame (have ${e.length-4}, need ${t})`}:Jh(e.subarray(4,4+t)).resolveNameResponse??{peerId:new Uint8Array(0),error:"reply carried no resolve_name_response"}}function du(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 gA(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>Fh)throw new Error("subway: reply exceeded max size");if(r<0&&n>=4&&(r=4+hu(du(t).subarray(0,4)),r>Fh))throw new Error("subway: declared frame exceeds max size");if(r>=0&&n>=r)return du(t).subarray(0,r)}return du(t)}async function Zh(e){return(0,Hh.createLibp2p)({...e?{privateKey:await(0,Gh.generateKeyPairFromSeed)("Ed25519",e)}:{},transports:[(0,Vh.tcp)()],connectionEncrypters:[(0,qh.noise)()],streamMuxers:[(0,Kh.yamux)()],connectionGater:{denyDialMultiaddr:async()=>!1}})}async function Qh(e,t,n){let r=await e.dialProtocol((0,Wh.multiaddr)(t),Xh,{signal:AbortSignal.timeout(mA)});r.send(uA(n));let s;return Promise.race([gA(r),new Promise((o,i)=>{s=setTimeout(()=>i(new Error("subway: request timed out")),pA)})]).finally(()=>clearTimeout(s))}async function hA(e){let t=await Zh(e.seed);try{let n=await Qh(t,e.relayMultiaddr,oA(e.name,e.binding,e.requestId??1n)),r=dA(n);return{success:r.success,error:r.error,peerId:t.peerId.toString()}}finally{await t.stop()}}async function yA(e){let t=await Zh(e.seed);try{let n=await Qh(t,e.relayMultiaddr,aA(e.name,e.requestId??1n)),r=fA(n);return r.peerId.length===0?{found:!1,peerId:"",error:r.error||"name not found"}:{found:!0,peerId:(0,Yh.toString)(r.peerId,"base58btc"),error:""}}finally{await t.stop()}}var Hh,Vh,qh,Kh,Gh,Wh,Yh,fu,zh,Xh,mA,pA,Fh,_u=rt(()=>{"use strict";El();Hh=require("libp2p"),Vh=require("@libp2p/tcp"),qh=require("@chainsafe/libp2p-noise"),Kh=require("@chainsafe/libp2p-yamux"),Gh=require("@libp2p/crypto/keys"),Wh=require("@multiformats/multiaddr"),Yh=require("uint8arrays/to-string"),fu=new TextEncoder,zh=new TextDecoder;Xh="/subway/p2p/1.0.0",mA=15e3,pA=15e3,Fh=1<<20});var Eo={};jr(Eo,{MESH:()=>Re,RELAY_URL:()=>Ao,connectOrThrow:()=>ws,ensureMailbox:()=>$u,isSubwayEnabled:()=>xu,listRegistered:()=>Iu,loadBindingFor:()=>Eu,loadRegistry:()=>Nr,makeClient:()=>vs,maybeMintVisaBinding:()=>ny,meshName:()=>dt,readInbox:()=>vA,registerName:()=>ku,resolveActingName:()=>ka,resolveMeshName:()=>Tu,seedSubwayKeyFromTapAgent:()=>ty,sendMessage:()=>Ru,sendVia:()=>wA,subwayKeyPath:()=>Ea});function dt(e){return e.includes(".")?e:`${e}.${Re}`}function xu(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 Au(){ve.mkdirSync(Cu,{recursive:!0,mode:448})}function _A(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function Ea(e){return bs.join(Cu,`${_A(e)}.key`)}function Nr(){if(!ve.existsSync(Su))return{};try{return JSON.parse(ve.readFileSync(Su,"utf8"))}catch{return{}}}function vu(e){Au(),ve.writeFileSync(Su,JSON.stringify(e,null,2),{mode:384})}function wu(){try{return Co.userInfo().username}catch{return"local"}}function ty(e){if(ve.existsSync(e)||!ve.existsSync(bu))return null;let t=ve.readdirSync(bu).filter(r=>r.endsWith(".json"));if(t.length===0)return null;let n=t.map(r=>bs.join(bu,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=So(r.private_key_jwk);return Au(),ve.writeFileSync(e,Buffer.from(s),{mode:384}),r.agent_id??null}catch{return null}}function vs(e,t={}){return new rh({name:dt(e),url:Ao,keyPath:Ea(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function Eu(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 ws(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 ka(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 ny(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.",Sa($e()),"no_key");try{return await uu({authUrl:$e(),apiKey:t,seed:xa(Ea(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 ku(e){let t=Ea(e),n=ty(t),r=dt(e);Re==="visa"&&!ve.existsSync(t)&&(Au(),ve.writeFileSync(t,(0,ey.randomBytes)(32),{mode:384}));let s=await ny(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(()=>(_u(),yu)),l=await c({relayMultiaddr:i,seed:xa(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:wu(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},vu(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:wu(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},vu(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=vs(e,{autoReconnect:!1,binding:s?.binding});try{await ws(a);let c=Nr();return c[e]={relayName:r,mesh:Re,peerId:a.peerId,owner:wu(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},vu(c),{relayName:r,mesh:Re,peerId:a.peerId,tapAgentId:n,...s?{binding:s.binding}:{}}}finally{a.disconnect()}}async function Tu(e){let t=dt(e),n=process.env.SUBWAY_RELAY_MULTIADDR;if(Re==="visa"&&n){let{resolveDirect:r}=await Promise.resolve().then(()=>(_u(),yu)),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 Ru(e,t,n){let r=vs(e,{autoReconnect:!1,binding:Eu(e)});try{await ws(r);let s=dt(t);return await r.sendSigned(s,"chat",n),{to:s,as:dt(e)}}finally{r.disconnect()}}function Iu(){let e=Nr();return Object.entries(e).map(([t,n])=>({name:t,...n}))}async function $u(e){let t=Aa.get(e);if(t)return{relayName:dt(e),peerId:t.client.peerId};let n=vs(e,{autoReconnect:!0,binding:Eu(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()}),Aa.set(e,{client:n,buffer:r}),await ws(n),{relayName:dt(e),peerId:n.peerId}}async function vA(e,t=20,n=!1){await $u(e);let r=Aa.get(e);if(!r)return[];let s=r.buffer.slice(-t);return n&&(r.buffer.length=0),s}async function wA(e,t,n){await $u(e);let r=Aa.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,Co,bs,ey,Re,Ao,Cu,Su,bu,Aa,bA,Ss=rt(()=>{"use strict";zl();wa();ve=I(require("fs")),Co=I(require("os")),bs=I(require("path")),ey=require("crypto");qt();Ca();Re=process.env.SUBWAY_MESH??"relay",Ao=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";Cu=bs.join(Co.homedir(),".visa-cli","subway"),Su=bs.join(Cu,"registry.json"),bu=bs.join(Co.homedir(),".visa-cli","agents");Aa=new Map,bA=200});var ja={};jr(ja,{initSentry:()=>nk,isSentryConfigured:()=>tk,reportFatal:()=>rk});function tk(){return!1}async function nk(){return null}async function rk(e,t){process.exit(t?.exitCode??1)}var Ba=rt(()=>{});var Wk={};jr(Wk,{printGroupHelpAndExit:()=>Mt});module.exports=L_(Wk);var u_=require("commander"),qa=I(require("crypto")),ce=I(require("fs")),re=I(require("os")),nt=I(require("path")),d_=require("child_process"),fd=require("node:readline/promises"),f_=require("util");var Wo=require("child_process"),Nd=require("util"),mn=I(require("fs")),Yo=I(require("os")),sc=I(require("path"));var Td=I(require("crypto"));var Ut="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";var Rd="VISA_ALLOW_INSECURE_MOCKS",Ad,Ed,kd;function Qa(e){return`${e}-${Td.randomBytes(24).toString("base64url")}`}function Id(e=process.env){return e.NODE_ENV==="test"||e[Rd]==="true"}function dn(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&Id(e)}function Br(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&Id(e)}function ec(){return`Set ${Rd}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function $d(){return Ad??=Qa("mock-session"),Ad}function Pd(e=process.env){return e.NODE_ENV==="test"?Ut:(Ed??=Qa("mock-rc"),Ed)}function Od(){return kd??=Qa("mock-signature"),kd}var ht=(0,Nd.promisify)(Wo.execFile),oc=sc.join(Yo.homedir(),".visa-mcp"),Ns=sc.join(oc,"session-token"),We="visa-cli",fn="session-token",Ko="rc-access",U_=5e3,Go=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function D_(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
10
- `)}function Md(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=D_(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function j_(){try{let{stdout:e}=await ht("security",["find-generic-password","-s",We,"-a",fn,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(Md(e))throw new Go("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 B_(e){try{try{await ht("security",["delete-generic-password","-s",We,"-a",fn],{timeout:5e3})}catch{}return await ht("security",["add-generic-password","-s",We,"-a",fn,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function F_(){try{await ht("security",["delete-generic-password","-s",We,"-a",fn],{timeout:5e3})}catch{}}async function H_(){if(!ic())return null;try{let{stdout:e}=await ht("secret-tool",["lookup","service",We,"account",fn],{timeout:5e3});return e.trim()||null}catch{return null}}async function V_(e){if(!ic())return!1;try{let t=(0,Wo.execFile)("secret-tool",["store","--label",`${We} ${fn}`,"service",We,"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"))},U_))]),!0):!1}catch{return!1}}async function q_(){if(ic())try{await ht("secret-tool",["clear","service",We,"account",fn],{timeout:5e3})}catch{}}function ic(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function K_(){try{let{stdout:e}=await ht("security",["find-generic-password","-s",We,"-a",Ko,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function G_(e){try{try{await ht("security",["delete-generic-password","-s",We,"-a",Ko],{timeout:5e3})}catch{}await ht("security",["add-generic-password","-s",We,"-a",Ko,"-w",e],{timeout:5e3})}catch{}}async function W_(){try{await ht("security",["delete-generic-password","-s",We,"-a",Ko],{timeout:5e3})}catch{}}function nc(){try{return mn.readFileSync(Ns,"utf-8").trim()||null}catch(e){if(Md(e))throw new Go(`Unable to read Visa CLI credentials from ${Ns}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function Ld(e){mn.mkdirSync(oc,{recursive:!0,mode:448}),mn.writeFileSync(Ns,e,{mode:384}),process.platform==="win32"&&Y_(Ns)}function rc(){try{mn.unlinkSync(Ns)}catch{}}function Y_(e){try{let t=Yo.userInfo().username;(0,Wo.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 tc(){switch(process.platform){case"darwin":return{get:j_,store:B_,delete:F_};case"linux":return{get:H_,store:V_,delete:q_};default:return{get:async()=>nc(),store:async e=>{try{return Ld(e),!0}catch{return!1}},delete:async()=>rc(),storesInSessionFile:!0}}}var G=class{static async getSessionToken(){if(dn())return Promise.resolve($d());let t=tc(),n=await t.get();if(n)return n;let r=nc();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(dn())return;let n=tc();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||rc();return}await n.delete()}if(Ld(t),nc()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${oc} is writable.`))}static async getRcAccessToken(){return dn()?Pd():K_()}static async saveRcAccessToken(t){dn()||await G_(t)}static async deleteSessionToken(){if(dn())return;await tc().delete(),rc()}static async clearAll(){await this.deleteSessionToken(),await W_()}};var zo=I(require("crypto")),Jo=I(require("tty")),Xo=I(require("fs"));function J_(e){return/-rc\.|-beta\./.test(e)}function ac(e){return zo.createHash("sha256").update(e.trim()).digest("hex")}function Ud(e){return Ut==="SKIP"?!0:zo.timingSafeEqual(Buffer.from(ac(e)),Buffer.from(Ut))}function X_(){try{let e=Xo.openSync("/dev/tty","r+"),t=new Jo.ReadStream(e),n=new Jo.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{Xo.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 Z_(e){return new Promise((t,n)=>{let r;try{r=X_()}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 mx.encode(n)}function hx(e,t,n,r,s,o,i){return gx({messageId:e,senderPeerId:t,senderName:n,timestampMs:r,messageType:s,payload:o,nonce:i})}function yx(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 Bx(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=Bx(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 hg(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 Fx(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 Vl(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ul(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Hx(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 Kx(e,t=!1){return t?{h:Number(e&Qi),l:Number(e>>yg&Qi)}:{h:Number(e>>yg&Qi)|0,l:Number(e&Qi)|0}}function Gx(e,t=!1){let n=e.length,r=new Uint32Array(n),s=new Uint32Array(n);for(let o=0;o<n;o++){let{h:i,l:a}=Kx(e[o],t);[r[o],s[o]]=[i,a]}return[r,s]}function rn(e,t,n,r){let s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}function sC(){return Lx.randomSecretKey()}function th(e){return Nx(e)}function oC(){let e=sC();return{secretKey:e,publicKey:th(e)}}function iC(e){if((0,Bn.existsSync)(e)){let n=(0,Bn.readFileSync)(e),r=new Uint8Array(n.buffer.slice(n.byteOffset,n.byteOffset+32));return{secretKey:r,publicKey:th(r)}}let t=oC();return(0,Bn.mkdirSync)((0,Sg.dirname)(e),{recursive:!0}),(0,Bn.writeFileSync)(e,new Uint8Array(t.secretKey)),t}function aC(e){let{secretKey:t,publicKey:n}=iC(e);return{privateKey:t,publicKey:n}}async function cC(e,t,n,r,s,o,i,a){let c=hx(t,n,r,s,o,i,a);return{signature:await ux(e,c),signatureInput:px.subwayAgentMsgV1}}function wg(e){return fx(e)}var Bn,Sg,_S,bS,vS,wS,SS,xg,sa,na,Xp,Zp,Il,$l,xS,ua,CS,ke,ES,AS,kS,sn,da,ql,Cg,Kl,en,Qp,Gl,Eg,TS,ms,RS,oa,Sr,oe,eg,$,Ag,kg,Tg,Rg,Pl,Dl,bo,Rr,kr,Ig,$g,Rt,IS,tg,$S,jl,Wl,PS,Pg,OS,NS,MS,LS,US,DS,Yl,Og,ia,jS,Ng,Bl,BS,ng,rg,FS,Ug,Dg,Nn,Me,Ji,og,ig,ag,ls,us,Xi,Zi,YS,zS,JS,XS,ZS,QS,ex,Mn,tx,nx,jg,rx,sx,Ln,Un,ox,ix,ax,cx,cg,dx,Bg,mx,px,Fg,aa,ra,lg,ug,Nl,Ml,_x,ps,bx,Te,vx,wx,Sx,Fn,fa,zl,Hg,Vg,nn,dg,qg,Kg,xx,Jl,Cx,ca,Cr,ae,fg,P,Ex,Ax,Gg,Wg,Ll,Fl,vo,gs,Tr,kx,Yg,$t,Tx,mg,Rx,Ix,$x,Px,zg,Ox,Jg,Nx,Xg,Mx,Lx,la,Ux,Zg,Hl,Dx,pg,gg,jx,Vx,qx,Le,Qi,yg,_g,bg,ds,fs,ea,ta,Wx,Yx,zx,Jx,Xx,Zx,eh,Qx,eC,Dn,jn,tC,nC,rC,vg,lC,uC,nh,Xl=st(()=>{"use strict";kl();kl();Tl();Bn=require("fs"),Sg=require("path");_S=1e3,bS=10,vS=3e4,wS=3e4,SS=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??_S,this.maxReconnectAttempts=e.maxReconnectAttempts??bS,this.pingInterval=e.pingInterval??vS}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 Ne('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 Ne(`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 Ne("WebSocket closed before connection established")))},this.ws.onerror=()=>{r||(r=!0,t(new Ne(`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 Ne("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=yS(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)}}},xg=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:sa,n:na,Gx:Xp,Gy:Zp,a:Il,d:$l,h:xS}=xg,ua=32,CS=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},ke=(e="")=>{let t=new Error(e);throw CS(t,ke),t},ES=e=>typeof e=="bigint",AS=e=>typeof e=="string",kS=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,sn=(e,t,n="")=>{let r=kS(e),s=e?.length,o=t!==void 0;if(!r||o&&s!==t){let i=n&&`"${n}" `,a=o?` of length ${t}`:"",c=r?`length=${s}`:`type=${typeof e}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):new TypeError(l)}return e},da=e=>new Uint8Array(e),ql=e=>Uint8Array.from(e),Cg=(e,t)=>e.toString(16).padStart(t,"0"),Kl=e=>Array.from(sn(e)).map(t=>Cg(t,2)).join(""),en={_0:48,_9:57,A:65,F:70,a:97,f:102},Qp=e=>{if(e>=en._0&&e<=en._9)return e-en._0;if(e>=en.A&&e<=en.F)return e-(en.A-10);if(e>=en.a&&e<=en.f)return e-(en.a-10)},Gl=e=>{let t="hex invalid";if(!AS(e))return ke(t);let n=e.length,r=n/2;if(n%2)return ke(t);let s=da(r);for(let o=0,i=0;o<r;o++,i+=2){let a=Qp(e.charCodeAt(i)),c=Qp(e.charCodeAt(i+1));if(a===void 0||c===void 0)return ke(t);s[o]=a*16+c}return s},Eg=()=>globalThis?.crypto,TS=()=>Eg()?.subtle??ke("crypto.subtle must be defined, consider polyfill"),ms=(...e)=>{let t=0;for(let s of e)t+=sn(s).length;let n=da(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},RS=(e=ua)=>Eg().getRandomValues(da(e)),oa=BigInt,Sr=(e,t,n,r="bad number: out of range")=>{if(!ES(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},oe=(e,t=sa)=>{let n=e%t;return n>=0n?n:t+n},eg=(1n<<255n)-1n,$=e=>{e<0n&&ke("negative coordinate");let t=(e>>255n)*19n+(e&eg);return t=(t>>255n)*19n+(t&eg),t%sa},Ag=e=>oe(e,na),kg=(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")},Tg=e=>{let t=Og[e];return typeof t!="function"&&ke("hashes."+e+" not set"),t},Rg=e=>sn(e,64,"digest"),Pl=e=>e instanceof bo?e:ke("Point expected"),Dl=2n**256n,bo=class xr{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=Dl;this.X=Sr(t,0n,o),this.Y=Sr(n,0n,o),this.Z=Sr(r,1n,o),this.T=Sr(s,0n,o),Object.freeze(this)}static CURVE(){return xg}static fromAffine(t){return new xr(t.x,t.y,1n,$(t.x*t.y))}static fromBytes(t,n=!1){let r=$l,s=ql(sn(t,ua)),o=t[31];s[31]=o&-129;let i=$g(s);Sr(i,0n,n?Dl:sa);let c=$(i*i),l=oe(c-1n),u=$(r*c+1n),{isValid:d,value:f}=$S(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 xr(f,i,1n,$(f*i))}static fromHex(t,n){return xr.fromBytes(Gl(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Il,n=$l,r=this;if(r.is0())return ke("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 ke("bad point: equation left != right (1)");let h=$(s*o),v=$(i*a);return h!==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}=Pl(t),c=$(n*a),l=$(o*s),u=$(r*a),d=$(i*s);return c===l&&u===d}is0(){return this.equals(kr)}negate(){return new xr(oe(-this.X),this.Y,this.Z,oe(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=Il,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),h=$(d*m),v=$(u*m),I=$(f*d);return new xr(p,h,I,v)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=Pl(t),u=Il,d=$l,f=$(n*i),m=$(r*a),p=$($(o*d)*l),h=$(s*c),v=oe($(oe(n+r)*oe(i+a))-f-m),I=oe(h-p),_=oe(h+p),b=oe(m-$(u*f)),w=$(v*I),T=$(_*b),A=$(v*b),y=$(I*_);return new xr(w,T,y,A)}subtract(t){return this.add(Pl(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(Sr(t,1n,na),!n&&this.is0()))return kr;if(t===1n)return this;if(this.equals(Rr))return FS(t).p;let r=kr,s=Rr;for(let o=this;t>0n;o=o.double(),t>>=1n)t&1n?r=r.add(o):n&&(s=s.add(o));return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(this.equals(kr))return{x:0n,y:1n};let s=kg(r,sa);$(r*s)!==1n&&ke("invalid inverse");let o=$(t*s),i=$(n*s);return{x:o,y:i}}toBytes(){let{x:t,y:n}=this.toAffine(),r=Ig(n);return r[31]|=t&1n?128:0,r}toHex(){return Kl(this.toBytes())}clearCofactor(){return this.multiply(oa(xS),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(na/2n,!1).double();return na%2n&&(t=t.add(this)),t.is0()}},Rr=new bo(Xp,Zp,1n,oe(Xp*Zp)),kr=new bo(0n,1n,1n,0n);bo.BASE=Rr;bo.ZERO=kr;Ig=e=>Gl(Cg(Sr(e,0n,Dl),64)).reverse(),$g=e=>oa("0x"+Kl(ql(sn(e)).reverse())),Rt=(e,t)=>{let n=e;for(;t-- >0n;)n=$(n*n);return n},IS=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}},tg=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,$S=(e,t)=>{let n=$(t*$(t*t)),r=$($(n*n)*t),s=IS($(e*r)).pow_p_5_8,o=$(e*$(n*s)),i=$(t*$(o*o)),a=o,c=$(o*tg),l=i===e,u=i===oe(-e),d=i===oe(-e*tg);return l&&(o=a),(u||d)&&(o=c),(oe(o)&1n)===1n&&(o=oe(-o)),{isValid:l||u,value:o}},jl=e=>Ag($g(e)),Wl=(...e)=>Promise.resolve(Tg("sha512Async")(ms(...e))).then(Rg),PS=(...e)=>Rg(Tg("sha512")(ms(...e))),Pg=e=>{let t=ql(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=jl(n),o=Rr.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},OS=e=>Wl(sn(e,ua)).then(Pg),NS=e=>Pg(PS(sn(e,ua))),MS=e=>NS(e).pointBytes,LS=e=>Wl(e.hashable).then(e.finish),US=(e,t,n)=>{let{pointBytes:r,scalar:s}=e,o=jl(t),i=Rr.multiply(o).toBytes();return{hashable:ms(i,r,n),finish:l=>{let u=Ag(o+jl(l)*s);return sn(ms(i,Ig(u)),64)}}},DS=async(e,t)=>{let n=sn(e),r=await OS(t),s=await Wl(r.prefix,n);return LS(US(r,s,n))},Yl=Object.freeze({bytesToHex:Kl,hexToBytes:Gl,concatBytes:ms,mod:oe,invert:kg,randomBytes:RS}),Og={sha512Async:async e=>{let t=TS(),n=ms(e);return da(await t.digest("SHA-512",n.buffer))},sha512:void 0},ia=8,jS=256,Ng=Math.ceil(jS/ia)+1,Bl=2**(ia-1),BS=()=>{let e=[],t=Rr,n=t;for(let r=0;r<Ng;r++){n=t,e.push(n);for(let s=1;s<Bl;s++)n=n.add(t),e.push(n);t=n.double()}return e},ng=void 0,rg=(e,t)=>{let n=t.negate();return e?n:t},FS=e=>{let t=ng||(ng=BS()),n=kr,r=Rr,s=2**ia,o=s,i=oa(s-1),a=oa(ia);for(let c=0;c<Ng;c++){let l=Number(e&i);e>>=a,l>Bl&&(l-=o,e+=1n);let u=c*Bl,d=u,f=u+Math.abs(l)-1,m=c%2!==0,p=l<0;l===0?r=r.add(rg(m,t[d])):n=n.add(rg(p,t[f]))}return e!==0n&&ke("invalid wnaf"),{p:n,f:r}};Ug=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});Dg=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=Ol(this.buffer)}update(e){sg(this),Mg(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=Ol(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){sg(this),VS(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=Ol(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]),Me=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Ji=BigInt(2**32-1),og=BigInt(32);ig=(e,t,n)=>e>>>n,ag=(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,Xi=(e,t,n)=>e<<64-n|t>>>n-32,Zi=(e,t,n)=>e>>>n-32|t<<64-n;YS=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),zS=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,JS=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),XS=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,ZS=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),QS=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,ex=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]),Mn=new Uint32Array(64),tx=class extends Dg{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)Mn[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let d=Mn[u-15],f=Mn[u-2],m=It(d,7)^It(d,18)^d>>>3,p=It(f,17)^It(f,19)^f>>>10;Mn[u]=p+Mn[u-7]+m+Mn[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+qS(i,a,c)+ex[u]+Mn[u]|0,p=(It(n,2)^It(n,13)^It(n,22))+KS(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(Mn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),_o(this.buffer)}},nx=class extends tx{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)}},jg=WS(["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=jg[0],sx=jg[1],Ln=new Uint32Array(80),Un=new Uint32Array(80),ox=class extends Dg{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:h}=this;return[e,t,n,r,s,o,i,a,c,l,u,d,f,m,p,h]}set(e,t,n,r,s,o,i,a,c,l,u,d,f,m,p,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=s|0,this.Cl=o|0,this.Dh=i|0,this.Dl=a|0,this.Eh=c|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=f|0,this.Gl=m|0,this.Hh=p|0,this.Hl=h|0}process(e,t){for(let _=0;_<16;_++,t+=4)Ln[_]=e.getUint32(t),Un[_]=e.getUint32(t+=4);for(let _=16;_<80;_++){let b=Ln[_-15]|0,w=Un[_-15]|0,T=ls(b,w,1)^ls(b,w,8)^ig(b,w,7),A=us(b,w,1)^us(b,w,8)^ag(b,w,7),y=Ln[_-2]|0,x=Un[_-2]|0,Y=ls(y,x,19)^Xi(y,x,61)^ig(y,x,6),X=us(y,x,19)^Zi(y,x,61)^ag(y,x,6),K=JS(A,X,Un[_-7],Un[_-16]),be=XS(K,T,Y,Ln[_-7],Ln[_-16]);Ln[_]=be|0,Un[_]=K|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:h,Hh:v,Hl:I}=this;for(let _=0;_<80;_++){let b=ls(u,d,14)^ls(u,d,18)^Xi(u,d,41),w=us(u,d,14)^us(u,d,18)^Zi(u,d,41),T=u&f^~u&p,A=d&m^~d&h,y=ZS(I,w,A,sx[_],Un[_]),x=QS(y,v,b,T,rx[_],Ln[_]),Y=y|0,X=ls(n,r,28)^Xi(n,r,34)^Xi(n,r,39),K=us(n,r,28)^Zi(n,r,34)^Zi(n,r,39),be=n&s^n&i^s&i,se=r&o^r&a^o&a;v=p|0,I=h|0,p=f|0,h=m|0,f=u|0,m=d|0,{h:u,l:d}=tn(c|0,l|0,x|0,Y|0),c=i|0,l=a|0,i=s|0,a=o|0,s=n|0,o=r|0;let Z=YS(Y,K,se);n=zS(Z,x,X,be),r=Z|0}({h:n,l:r}=tn(this.Ah|0,this.Al|0,n|0,r|0)),{h:s,l:o}=tn(this.Bh|0,this.Bl|0,s|0,o|0),{h:i,l:a}=tn(this.Ch|0,this.Cl|0,i|0,a|0),{h:c,l}=tn(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=tn(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:m}=tn(this.Fh|0,this.Fl|0,f|0,m|0),{h:p,l:h}=tn(this.Gh|0,this.Gl|0,p|0,h|0),{h:v,l:I}=tn(this.Hh|0,this.Hl|0,v|0,I|0),this.set(n,r,s,o,i,a,c,l,u,d,f,m,p,h,v,I)}roundClean(){_o(Ln,Un)}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)}},ix=class extends ox{Ah=Me[0]|0;Al=Me[1]|0;Bh=Me[2]|0;Bl=Me[3]|0;Ch=Me[4]|0;Cl=Me[5]|0;Dh=Me[6]|0;Dl=Me[7]|0;Eh=Me[8]|0;El=Me[9]|0;Fh=Me[10]|0;Fl=Me[11]|0;Gh=Me[12]|0;Gl=Me[13]|0;Hh=Me[14]|0;Hl=Me[15]|0;constructor(){super(64)}},ax=Lg(()=>new nx,Ug(1)),cx=Lg(()=>new ix,Ug(3)),cg=Og;cg.sha512||(cg.sha512=e=>cx(e));dx=Yl.bytesToHex,Bg=Yl.hexToBytes;Yl.concatBytes;mx=new TextEncoder,px={subwayAgentMsgV1:"message_id;sender_peer_id;sender_name;timestamp_ms;message_type;payload_hash;nonce"};Bg("302e020100300506032b657004220420");Bg("302a300506032b6570032100");Fg=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:aa,n:ra,Gx:lg,Gy:ug,a:Nl,d:Ml,h:_x}=Fg,ps=32,bx=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},Te=(e="")=>{let t=new Error(e);throw bx(t,Te),t},vx=e=>typeof e=="bigint",wx=e=>typeof e=="string",Sx=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,Fn=(e,t,n="")=>{let r=Sx(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),zl=e=>Uint8Array.from(e),Hg=(e,t)=>e.toString(16).padStart(t,"0"),Vg=e=>Array.from(Fn(e)).map(t=>Hg(t,2)).join(""),nn={_0:48,_9:57,A:65,F:70,a:97,f:102},dg=e=>{if(e>=nn._0&&e<=nn._9)return e-nn._0;if(e>=nn.A&&e<=nn.F)return e-(nn.A-10);if(e>=nn.a&&e<=nn.f)return e-(nn.a-10)},qg=e=>{let t="hex invalid";if(!wx(e))return Te(t);let n=e.length,r=n/2;if(n%2)return Te(t);let s=fa(r);for(let o=0,i=0;o<r;o++,i+=2){let a=dg(e.charCodeAt(i)),c=dg(e.charCodeAt(i+1));if(a===void 0||c===void 0)return Te(t);s[o]=a*16+c}return s},Kg=()=>globalThis?.crypto,xx=()=>Kg()?.subtle??Te("crypto.subtle must be defined, consider polyfill"),Jl=(...e)=>{let t=0;for(let s of e)t+=Fn(s).length;let n=fa(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},Cx=(e=ps)=>Kg().getRandomValues(fa(e)),ca=BigInt,Cr=(e,t,n,r="bad number: out of range")=>{if(!vx(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},ae=(e,t=aa)=>{let n=e%t;return n>=0n?n:t+n},fg=(1n<<255n)-1n,P=e=>{e<0n&&Te("negative coordinate");let t=(e>>255n)*19n+(e&fg);return t=(t>>255n)*19n+(t&fg),t%aa},Ex=e=>ae(e,ra),Ax=(e,t)=>{(e===0n||t<=0n)&&Te("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):Te("no inverse")},Gg=e=>{let t=Xg[e];return typeof t!="function"&&Te("hashes."+e+" not set"),t},Wg=e=>Fn(e,64,"digest"),Ll=e=>e instanceof vo?e:Te("Point expected"),Fl=2n**256n,vo=class Er{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=Fl;this.X=Cr(t,0n,o),this.Y=Cr(n,0n,o),this.Z=Cr(r,1n,o),this.T=Cr(s,0n,o),Object.freeze(this)}static CURVE(){return Fg}static fromAffine(t){return new Er(t.x,t.y,1n,P(t.x*t.y))}static fromBytes(t,n=!1){let r=Ml,s=zl(Fn(t,ps)),o=t[31];s[31]=o&-129;let i=Yg(s);Cr(i,0n,n?Fl:aa);let c=P(i*i),l=ae(c-1n),u=P(r*c+1n),{isValid:d,value:f}=Rx(l,u);d||Te("bad point: y not sqrt");let m=(f&1n)===1n,p=(o&128)!==0;return!n&&f===0n&&p&&Te("bad point: x==0, isLastByteOdd"),p!==m&&(f=ae(-f)),new Er(f,i,1n,P(f*i))}static fromHex(t,n){return Er.fromBytes(qg(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Nl,n=Ml,r=this;if(r.is0())return Te("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 Te("bad point: equation left != right (1)");let h=P(s*o),v=P(i*a);return h!==v?Te("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=Ll(t),c=P(n*a),l=P(o*s),u=P(r*a),d=P(i*s);return c===l&&u===d}is0(){return this.equals(Tr)}negate(){return new Er(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),h=P(d*m),v=P(u*m),I=P(f*d);return new Er(p,h,I,v)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=Ll(t),u=Nl,d=Ml,f=P(n*i),m=P(r*a),p=P(P(o*d)*l),h=P(s*c),v=ae(P(ae(n+r)*ae(i+a))-f-m),I=ae(h-p),_=ae(h+p),b=ae(m-P(u*f)),w=P(v*I),T=P(_*b),A=P(v*b),y=P(I*_);return new Er(w,T,y,A)}subtract(t){return this.add(Ll(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(Cr(t,1n,ra),!n&&this.is0()))return Tr;if(t===1n)return this;if(this.equals(gs))return jx(t).p;let r=Tr,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(Tr))return{x:0n,y:1n};let s=Ax(r,aa);P(r*s)!==1n&&Te("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=kx(n);return r[31]|=t&1n?128:0,r}toHex(){return Vg(this.toBytes())}clearCofactor(){return this.multiply(ca(_x),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(ra/2n,!1).double();return ra%2n&&(t=t.add(this)),t.is0()}},gs=new vo(lg,ug,1n,ae(lg*ug)),Tr=new vo(0n,1n,1n,0n);vo.BASE=gs;vo.ZERO=Tr;kx=e=>qg(Hg(Cr(e,0n,Fl),64)).reverse(),Yg=e=>ca("0x"+Vg(zl(Fn(e)).reverse())),$t=(e,t)=>{let n=e;for(;t-- >0n;)n=P(n*n);return n},Tx=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}},mg=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,Rx=(e,t)=>{let n=P(t*P(t*t)),r=P(P(n*n)*t),s=Tx(P(e*r)).pow_p_5_8,o=P(e*P(n*s)),i=P(t*P(o*o)),a=o,c=P(o*mg),l=i===e,u=i===ae(-e),d=i===ae(-e*mg);return l&&(o=a),(u||d)&&(o=c),(ae(o)&1n)===1n&&(o=ae(-o)),{isValid:l||u,value:o}},Ix=e=>Ex(Yg(e)),$x=(...e)=>Promise.resolve(Gg("sha512Async")(Jl(...e))).then(Wg),Px=(...e)=>Wg(Gg("sha512")(Jl(...e))),zg=e=>{let t=zl(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=Ix(n),o=gs.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},Ox=e=>$x(Fn(e,ps)).then(zg),Jg=e=>zg(Px(Fn(e,ps))),Nx=e=>Jg(e).pointBytes,Xg={sha512Async:async e=>{let t=xx(),n=Jl(e);return fa(await t.digest("SHA-512",n.buffer))},sha512:void 0},Mx=e=>(e=e===void 0?Cx(ps):e,Fn(e,ps)),Lx=Object.freeze({getExtendedPublicKeyAsync:Ox,getExtendedPublicKey:Jg,randomSecretKey:Mx}),la=8,Ux=256,Zg=Math.ceil(Ux/la)+1,Hl=2**(la-1),Dx=()=>{let e=[],t=gs,n=t;for(let r=0;r<Zg;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},pg=void 0,gg=(e,t)=>{let n=t.negate();return e?n:t},jx=e=>{let t=pg||(pg=Dx()),n=Tr,r=gs,s=2**la,o=s,i=ca(s-1),a=ca(la);for(let c=0;c<Zg;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(gg(m,t[d])):n=n.add(gg(p,t[f]))}return e!==0n&&Te("invalid wnaf"),{p:n,f:r}};Vx=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),qx=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=Ul(this.buffer)}update(e){hg(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=Ul(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){hg(this),Fx(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,Vl(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let u=o;u<r;u++)t[u]=0;n.setBigUint64(r-8,BigInt(this.length*8),s),this.process(n,0);let i=Ul(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]),Qi=BigInt(2**32-1),yg=BigInt(32);_g=(e,t,n)=>e>>>n,bg=(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,ea=(e,t,n)=>e<<64-n|t>>>n-32,ta=(e,t,n)=>e>>>n-32|t<<64-n;Wx=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Yx=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,zx=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Jx=(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),Zx=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,eh=Gx(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),Qx=eh[0],eC=eh[1],Dn=new Uint32Array(80),jn=new Uint32Array(80),tC=class extends qx{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:h}=this;return[e,t,n,r,s,o,i,a,c,l,u,d,f,m,p,h]}set(e,t,n,r,s,o,i,a,c,l,u,d,f,m,p,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=s|0,this.Cl=o|0,this.Dh=i|0,this.Dl=a|0,this.Eh=c|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=f|0,this.Gl=m|0,this.Hh=p|0,this.Hl=h|0}process(e,t){for(let _=0;_<16;_++,t+=4)Dn[_]=e.getUint32(t),jn[_]=e.getUint32(t+=4);for(let _=16;_<80;_++){let b=Dn[_-15]|0,w=jn[_-15]|0,T=ds(b,w,1)^ds(b,w,8)^_g(b,w,7),A=fs(b,w,1)^fs(b,w,8)^bg(b,w,7),y=Dn[_-2]|0,x=jn[_-2]|0,Y=ds(y,x,19)^ea(y,x,61)^_g(y,x,6),X=fs(y,x,19)^ta(y,x,61)^bg(y,x,6),K=zx(A,X,jn[_-7],jn[_-16]),be=Jx(K,T,Y,Dn[_-7],Dn[_-16]);Dn[_]=be|0,jn[_]=K|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:h,Hh:v,Hl:I}=this;for(let _=0;_<80;_++){let b=ds(u,d,14)^ds(u,d,18)^ea(u,d,41),w=fs(u,d,14)^fs(u,d,18)^ta(u,d,41),T=u&f^~u&p,A=d&m^~d&h,y=Xx(I,w,A,eC[_],jn[_]),x=Zx(y,v,b,T,Qx[_],Dn[_]),Y=y|0,X=ds(n,r,28)^ea(n,r,34)^ea(n,r,39),K=fs(n,r,28)^ta(n,r,34)^ta(n,r,39),be=n&s^n&i^s&i,se=r&o^r&a^o&a;v=p|0,I=h|0,p=f|0,h=m|0,f=u|0,m=d|0,{h:u,l:d}=rn(c|0,l|0,x|0,Y|0),c=i|0,l=a|0,i=s|0,a=o|0,s=n|0,o=r|0;let Z=Wx(Y,K,se);n=Yx(Z,x,X,be),r=Z|0}({h:n,l:r}=rn(this.Ah|0,this.Al|0,n|0,r|0)),{h:s,l:o}=rn(this.Bh|0,this.Bl|0,s|0,o|0),{h:i,l:a}=rn(this.Ch|0,this.Cl|0,i|0,a|0),{h:c,l}=rn(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=rn(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:m}=rn(this.Fh|0,this.Fl|0,f|0,m|0),{h:p,l:h}=rn(this.Gh|0,this.Gl|0,p|0,h|0),{h:v,l:I}=rn(this.Hh|0,this.Hl|0,v|0,I|0),this.set(n,r,s,o,i,a,c,l,u,d,f,m,p,h,v,I)}roundClean(){Vl(Dn,jn)}destroy(){this.destroyed=!0,Vl(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},nC=class extends tC{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)}},rC=Hx(()=>new nC,Vx(3)),vg=Xg;vg.sha512||(vg.sha512=e=>rC(e));lC="ws://localhost:9001/ws",uC=3e4,nh=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=Ar(e.name),e.keyPath)try{this._keypair=aC(e.keyPath)}catch{}this.options={name:this._name,url:e.url??lC,relay:e.relay??"",autoReconnect:e.autoReconnect??!0,reconnectInterval:e.reconnectInterval??1e3,maxReconnectAttempts:e.maxReconnectAttempts??10,rpcTimeout:e.rpcTimeout??uC,pingInterval:e.pingInterval??3e4,binding:e.binding??""},this.transport=new SS({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=yx(new Uint8Array(t));n&&(this._keypair={privateKey:n,publicKey:lx(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=wg(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 Ne(String(r)))}})}disconnect(){for(let[,e]of this.pendingCalls)clearTimeout(e.timer),e.reject(new Ne("Client disconnected"));this.pendingCalls.clear();for(let[,e]of this.pendingSend)e.reject(new Ne("Client disconnected"));this.pendingSend.clear();for(let[,e]of this.pendingResolve)e.reject(new Ne("Client disconnected"));this.pendingResolve.clear(),this.registerPromise&&(this.registerPromise.reject(new Ne("Client disconnected")),this.registerPromise=null),this.transport.disconnect(),this._peerId=null,this.hasConnectedOnce=!1}async send(e,t,n,r){let s=Ar(e),o=Rl();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 Ne(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=Ar(e),o=Rl(),i=Date.now(),a=Math.floor(Math.random()*2**32),c=new TextEncoder().encode(n),{signature:l,signatureInput:u}=await cC(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 Ne(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=Ar(e),o=r?.correlationId??Rl(),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 Ne(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=Ar(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 Ne(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=Al(e.code,e.message);this.registerPromise&&e.code==="register_failed"&&(this.registerPromise.reject(new zi(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=wg(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 IC(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Th(e,t,n=""){let r=IC(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 uh(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 $C(e,t){Th(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 ou(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function tu(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function PC(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 MC(e,t=!1){return t?{h:Number(e&ma),l:Number(e>>dh&ma)}:{h:Number(e>>dh&ma)|0,l:Number(e&ma)|0}}function LC(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}=MC(e[o],t);[r[o],s[o]]=[i,a]}return[r,s]}function an(e,t,n,r){let s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}function YC(){return AC.randomSecretKey()}function wa(e){return wC(e)}function Ih(){let e=YC();return{secretKey:e,publicKey:wa(e)}}function $h(e,t){return CC(t,e)}function zC(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function JC(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 iu(e){return zC(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function XC(e){let t=e.length%4===0?0:4-e.length%4,n=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return JC(n)}function ZC(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function Oh(e){let t=wa(e);return{kty:"OKP",crv:"Ed25519",x:iu(t),d:iu(e)}}function Nh(e){return{kty:"OKP",crv:"Ed25519",x:iu(e)}}function Sa(e){if(ZC(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return XC(e.d)}var gh,ya,ha,rh,sh,Zl,Ql,dC,_s,fC,Re,mC,pC,gC,Ot,va,au,hh,cu,on,oh,lu,yh,hC,bs,_h,_a,Ir,ie,ih,O,bh,vh,wh,Sh,eu,nu,wo,Or,Pr,xh,Ch,Pt,yC,ah,_C,ru,bC,uu,Eh,vC,du,wC,SC,xC,CC,fu,Ah,EC,AC,ba,kC,kh,su,TC,ch,lh,RC,OC,NC,Ue,ma,dh,fh,mh,hs,ys,pa,ga,UC,DC,jC,BC,FC,HC,Rh,VC,qC,Hn,Vn,KC,GC,WC,ph,g2,Ph,h2,y2,_2,b2,xa=st(()=>{"use strict";gh=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:ya,n:ha,Gx:rh,Gy:sh,a:Zl,d:Ql,h:dC}=gh,_s=32,fC=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},Re=(e="")=>{let t=new Error(e);throw fC(t,Re),t},mC=e=>typeof e=="bigint",pC=e=>typeof e=="string",gC=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=gC(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},va=e=>new Uint8Array(e),au=e=>Uint8Array.from(e),hh=(e,t)=>e.toString(16).padStart(t,"0"),cu=e=>Array.from(Ot(e)).map(t=>hh(t,2)).join(""),on={_0:48,_9:57,A:65,F:70,a:97,f:102},oh=e=>{if(e>=on._0&&e<=on._9)return e-on._0;if(e>=on.A&&e<=on.F)return e-(on.A-10);if(e>=on.a&&e<=on.f)return e-(on.a-10)},lu=e=>{let t="hex invalid";if(!pC(e))return Re(t);let n=e.length,r=n/2;if(n%2)return Re(t);let s=va(r);for(let o=0,i=0;o<r;o++,i+=2){let a=oh(e.charCodeAt(i)),c=oh(e.charCodeAt(i+1));if(a===void 0||c===void 0)return Re(t);s[o]=a*16+c}return s},yh=()=>globalThis?.crypto,hC=()=>yh()?.subtle??Re("crypto.subtle must be defined, consider polyfill"),bs=(...e)=>{let t=0;for(let s of e)t+=Ot(s).length;let n=va(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},_h=(e=_s)=>yh().getRandomValues(va(e)),_a=BigInt,Ir=(e,t,n,r="bad number: out of range")=>{if(!mC(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},ie=(e,t=ya)=>{let n=e%t;return n>=0n?n:t+n},ih=(1n<<255n)-1n,O=e=>{e<0n&&Re("negative coordinate");let t=(e>>255n)*19n+(e&ih);return t=(t>>255n)*19n+(t&ih),t%ya},bh=e=>ie(e,ha),vh=(e,t)=>{(e===0n||t<=0n)&&Re("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):Re("no inverse")},wh=e=>{let t=Ah[e];return typeof t!="function"&&Re("hashes."+e+" not set"),t},Sh=e=>Ot(e,64,"digest"),eu=e=>e instanceof wo?e:Re("Point expected"),nu=2n**256n,wo=class $r{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=nu;this.X=Ir(t,0n,o),this.Y=Ir(n,0n,o),this.Z=Ir(r,1n,o),this.T=Ir(s,0n,o),Object.freeze(this)}static CURVE(){return gh}static fromAffine(t){return new $r(t.x,t.y,1n,O(t.x*t.y))}static fromBytes(t,n=!1){let r=Ql,s=au(Ot(t,_s)),o=t[31];s[31]=o&-129;let i=Ch(s);Ir(i,0n,n?nu:ya);let c=O(i*i),l=ie(c-1n),u=O(r*c+1n),{isValid:d,value:f}=_C(l,u);d||Re("bad point: y not sqrt");let m=(f&1n)===1n,p=(o&128)!==0;return!n&&f===0n&&p&&Re("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(lu(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Zl,n=Ql,r=this;if(r.is0())return Re("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 Re("bad point: equation left != right (1)");let h=O(s*o),v=O(i*a);return h!==v?Re("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=eu(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(Pr)}negate(){return new $r(ie(-this.X),this.Y,this.Z,ie(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=Zl,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),h=O(d*m),v=O(u*m),I=O(f*d);return new $r(p,h,I,v)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=eu(t),u=Zl,d=Ql,f=O(n*i),m=O(r*a),p=O(O(o*d)*l),h=O(s*c),v=ie(O(ie(n+r)*ie(i+a))-f-m),I=ie(h-p),_=ie(h+p),b=ie(m-O(u*f)),w=O(v*I),T=O(_*b),A=O(v*b),y=O(I*_);return new $r(w,T,y,A)}subtract(t){return this.add(eu(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(Ir(t,1n,ha),!n&&this.is0()))return Pr;if(t===1n)return this;if(this.equals(Or))return RC(t).p;let r=Pr,s=Or;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(Pr))return{x:0n,y:1n};let s=vh(r,ya);O(r*s)!==1n&&Re("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=xh(n);return r[31]|=t&1n?128:0,r}toHex(){return cu(this.toBytes())}clearCofactor(){return this.multiply(_a(dC),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(ha/2n,!1).double();return ha%2n&&(t=t.add(this)),t.is0()}},Or=new wo(rh,sh,1n,ie(rh*sh)),Pr=new wo(0n,1n,1n,0n);wo.BASE=Or;wo.ZERO=Pr;xh=e=>lu(hh(Ir(e,0n,nu),64)).reverse(),Ch=e=>_a("0x"+cu(au(Ot(e)).reverse())),Pt=(e,t)=>{let n=e;for(;t-- >0n;)n=O(n*n);return n},yC=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}},ah=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,_C=(e,t)=>{let n=O(t*O(t*t)),r=O(O(n*n)*t),s=yC(O(e*r)).pow_p_5_8,o=O(e*O(n*s)),i=O(t*O(o*o)),a=o,c=O(o*ah),l=i===e,u=i===ie(-e),d=i===ie(-e*ah);return l&&(o=a),(u||d)&&(o=c),(ie(o)&1n)===1n&&(o=ie(-o)),{isValid:l||u,value:o}},ru=e=>bh(Ch(e)),bC=(...e)=>Promise.resolve(wh("sha512Async")(bs(...e))).then(Sh),uu=(...e)=>Sh(wh("sha512")(bs(...e))),Eh=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=ru(n),o=Or.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},vC=e=>bC(Ot(e,_s)).then(Eh),du=e=>Eh(uu(Ot(e,_s))),wC=e=>du(e).pointBytes,SC=e=>e.finish(uu(e.hashable)),xC=(e,t,n)=>{let{pointBytes:r,scalar:s}=e,o=ru(t),i=Or.multiply(o).toBytes();return{hashable:bs(i,r,n),finish:l=>{let u=bh(o+ru(l)*s);return Ot(bs(i,xh(u)),64)}}},CC=(e,t)=>{let n=Ot(e),r=du(t),s=uu(r.prefix,n);return SC(xC(r,s,n))},fu=Object.freeze({bytesToHex:cu,hexToBytes:lu,concatBytes:bs,mod:ie,invert:vh,randomBytes:_h}),Ah={sha512Async:async e=>{let t=hC(),n=bs(e);return va(await t.digest("SHA-512",n.buffer))},sha512:void 0},EC=e=>(e=e===void 0?_h(_s):e,Ot(e,_s)),AC=Object.freeze({getExtendedPublicKeyAsync:vC,getExtendedPublicKey:du,randomSecretKey:EC}),ba=8,kC=256,kh=Math.ceil(kC/ba)+1,su=2**(ba-1),TC=()=>{let e=[],t=Or,n=t;for(let r=0;r<kh;r++){n=t,e.push(n);for(let s=1;s<su;s++)n=n.add(t),e.push(n);t=n.double()}return e},ch=void 0,lh=(e,t)=>{let n=t.negate();return e?n:t},RC=e=>{let t=ch||(ch=TC()),n=Pr,r=Or,s=2**ba,o=s,i=_a(s-1),a=_a(ba);for(let c=0;c<kh;c++){let l=Number(e&i);e>>=a,l>su&&(l-=o,e+=1n);let u=c*su,d=u,f=u+Math.abs(l)-1,m=c%2!==0,p=l<0;l===0?r=r.add(lh(m,t[d])):n=n.add(lh(p,t[f]))}return e!==0n&&Re("invalid wnaf"),{p:n,f:r}};OC=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),NC=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=tu(this.buffer)}update(e){uh(this),Th(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=tu(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){uh(this),$C(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,ou(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=tu(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]),ma=BigInt(2**32-1),dh=BigInt(32);fh=(e,t,n)=>e>>>n,mh=(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,pa=(e,t,n)=>e<<64-n|t>>>n-32,ga=(e,t,n)=>e>>>n-32|t<<64-n;UC=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),DC=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,jC=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),BC=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,FC=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),HC=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,Rh=LC(["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))),VC=Rh[0],qC=Rh[1],Hn=new Uint32Array(80),Vn=new Uint32Array(80),KC=class extends NC{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:h}=this;return[e,t,n,r,s,o,i,a,c,l,u,d,f,m,p,h]}set(e,t,n,r,s,o,i,a,c,l,u,d,f,m,p,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=s|0,this.Cl=o|0,this.Dh=i|0,this.Dl=a|0,this.Eh=c|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=f|0,this.Gl=m|0,this.Hh=p|0,this.Hl=h|0}process(e,t){for(let _=0;_<16;_++,t+=4)Hn[_]=e.getUint32(t),Vn[_]=e.getUint32(t+=4);for(let _=16;_<80;_++){let b=Hn[_-15]|0,w=Vn[_-15]|0,T=hs(b,w,1)^hs(b,w,8)^fh(b,w,7),A=ys(b,w,1)^ys(b,w,8)^mh(b,w,7),y=Hn[_-2]|0,x=Vn[_-2]|0,Y=hs(y,x,19)^pa(y,x,61)^fh(y,x,6),X=ys(y,x,19)^ga(y,x,61)^mh(y,x,6),K=jC(A,X,Vn[_-7],Vn[_-16]),be=BC(K,T,Y,Hn[_-7],Hn[_-16]);Hn[_]=be|0,Vn[_]=K|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:h,Hh:v,Hl:I}=this;for(let _=0;_<80;_++){let b=hs(u,d,14)^hs(u,d,18)^pa(u,d,41),w=ys(u,d,14)^ys(u,d,18)^ga(u,d,41),T=u&f^~u&p,A=d&m^~d&h,y=FC(I,w,A,qC[_],Vn[_]),x=HC(y,v,b,T,VC[_],Hn[_]),Y=y|0,X=hs(n,r,28)^pa(n,r,34)^pa(n,r,39),K=ys(n,r,28)^ga(n,r,34)^ga(n,r,39),be=n&s^n&i^s&i,se=r&o^r&a^o&a;v=p|0,I=h|0,p=f|0,h=m|0,f=u|0,m=d|0,{h:u,l:d}=an(c|0,l|0,x|0,Y|0),c=i|0,l=a|0,i=s|0,a=o|0,s=n|0,o=r|0;let Z=UC(Y,K,se);n=DC(Z,x,X,be),r=Z|0}({h:n,l:r}=an(this.Ah|0,this.Al|0,n|0,r|0)),{h:s,l:o}=an(this.Bh|0,this.Bl|0,s|0,o|0),{h:i,l:a}=an(this.Ch|0,this.Cl|0,i|0,a|0),{h:c,l}=an(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=an(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:m}=an(this.Fh|0,this.Fl|0,f|0,m|0),{h:p,l:h}=an(this.Gh|0,this.Gl|0,p|0,h|0),{h:v,l:I}=an(this.Hh|0,this.Hl|0,v|0,I|0),this.set(n,r,s,o,i,a,c,l,u,d,f,m,p,h,v,I)}roundClean(){ou(Hn,Vn)}destroy(){this.destroyed=!0,ou(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},GC=class extends KC{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)}},WC=PC(()=>new GC,OC(3)),ph=Ah;ph.sha512||(ph.sha512=e=>WC(e));g2=fu.bytesToHex,Ph=fu.hexToBytes,h2=fu.concatBytes;y2=new TextEncoder;_2=Ph("302e020100300506032b657004220420"),b2=Ph("302a300506032b6570032100");});var jh={};Fr(jh,{BindingIssuanceError:()=>Nr,CardRequiredError:()=>Ze,buildIssuanceRequest:()=>Dh,enrollCardUrl:()=>Ea,jkt:()=>Ca,proofPayload:()=>Uh,readSeed:()=>Aa,requestVisaBinding:()=>So});function Ca(e){let t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return Mh.createHash("sha256").update(t,"utf8").digest("base64url")}function Uh(e,t,n){return`visa-agent-binding:v1:${e}:${t}:${n}`}function Dh(e,t,n="visa",r=Math.floor(Date.now()/1e3)){let s=Nh(wa(e)),o=Buffer.from(Uh(t,Ca(s),r),"utf8"),i=Buffer.from($h(e,o)).toString("base64url");return{name:t,mesh:n,mode:"card",agent_pubkey:s,proof:{ts:r,sig:i}}}function Ea(e){try{return new URL("/enroll-card",e).toString()}catch{return"https://auth.visacli.sh/enroll-card"}}async function So(e){let t=Dh(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,"x-source":"cli"},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 Ze("No card on file \u2014 enroll a card to register on the trusted .visa mesh.",Ea(e.authUrl),"no_card"):new Nr(`Visa binding issuance failed (${s.status})${o?`: ${o}`:""}`,s.status,i||void 0)}return await s.json()}function Aa(e){return new Uint8Array(Lh.readFileSync(e))}var Mh,Lh,Ze,Nr,xo=st(()=>{"use strict";Mh=R(require("crypto")),Lh=R(require("fs"));xa();Ze=class extends Error{enrollUrl;reason;constructor(t,n,r){super(t),this.name="CardRequiredError",this.enrollUrl=n,this.reason=r}},Nr=class extends Error{status;code;constructor(t,n,r){super(t),this.name="BindingIssuanceError",this.status=n,this.code=r}}});var bu={};Fr(bu,{SUBWAY_PROTOCOL:()=>Jh,registerDirect:()=>dE,resolveDirect:()=>fE});function gu(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 Qe(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 hu(e,t){return e<<3|t}function Co(e,t,n){e.push(hu(t,2)),gu(e,n.length);for(let r of n)e.push(r)}function QC(e,t){let n=[];return Co(n,1,pu.encode(e)),t&&t.length>0&&Co(n,2,pu.encode(t)),Uint8Array.from(n)}function eE(e,t,n){let r=[];return n!==0n&&(r.push(hu(1,0)),gu(r,n)),Co(r,2,QC(e,t)),Uint8Array.from(r)}function tE(e){let t=[];return Co(t,1,pu.encode(e)),Uint8Array.from(t)}function nE(e,t){let n=[];return t!==0n&&(n.push(hu(1,0)),gu(n,t)),Co(n,3,tE(e)),Uint8Array.from(n)}function rE(e){let t=0,n={success:!1,error:""};for(;t<e.length;){let[r,s]=Qe(e,t);t=s;let o=Number(r)>>3,i=Number(r)&7;if(o===1&&i===0){let[a,c]=Qe(e,t);t=c,n.success=a!==0n}else if(o===2&&i===2){let[a,c]=Qe(e,t),l=c,u=l+Number(a);n.error=Yh.decode(e.subarray(l,u)),t=u}else t=yu(e,t,i)}return n}function sE(e){let t=0,n={peerId:new Uint8Array(0),error:""};for(;t<e.length;){let[r,s]=Qe(e,t);t=s;let o=Number(r)>>3,i=Number(r)&7;if(o===1&&i===2){let[a,c]=Qe(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]=Qe(e,t),l=c,u=l+Number(a);n.error=Yh.decode(e.subarray(l,u)),t=u}else t=yu(e,t,i)}return n}function yu(e,t,n){if(n===0)return Qe(e,t)[1];if(n===2){let[r,s]=Qe(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 zh(e){let t=0,n={requestId:0n};for(;t<e.length;){let[r,s]=Qe(e,t);t=s;let o=Number(r)>>3,i=Number(r)&7;if(o===1&&i===0){let[a,c]=Qe(e,t);t=c,n.requestId=a}else if(o===13&&i===2){let[a,c]=Qe(e,t),l=c,u=l+Number(a);n.registerNameResponse=rE(e.subarray(l,u)),t=u}else if(o===14&&i===2){let[a,c]=Qe(e,t),l=c,u=l+Number(a);n.resolveNameResponse=sE(e.subarray(l,u)),t=u}else t=yu(e,t,i)}return n}function oE(e){let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t}function _u(e){return new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1)}function iE(e){if(e.length<4)return{success:!1,error:"short reply (no length prefix)"};let t=_u(e.subarray(0,4));return e.length<4+t?{success:!1,error:`truncated frame (have ${e.length-4}, need ${t})`}:zh(e.subarray(4,4+t)).registerNameResponse??{success:!1,error:"reply carried no register_name_response"}}function aE(e){if(e.length<4)return{peerId:new Uint8Array(0),error:"short reply (no length prefix)"};let t=_u(e.subarray(0,4));return e.length<4+t?{peerId:new Uint8Array(0),error:`truncated frame (have ${e.length-4}, need ${t})`}:zh(e.subarray(4,4+t)).resolveNameResponse??{peerId:new Uint8Array(0),error:"reply carried no resolve_name_response"}}function mu(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 uE(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>Bh)throw new Error("subway: reply exceeded max size");if(r<0&&n>=4&&(r=4+_u(mu(t).subarray(0,4)),r>Bh))throw new Error("subway: declared frame exceeds max size");if(r>=0&&n>=r)return mu(t).subarray(0,r)}return mu(t)}async function Xh(e){return(0,Fh.createLibp2p)({...e?{privateKey:await(0,Kh.generateKeyPairFromSeed)("Ed25519",e)}:{},transports:[(0,Hh.tcp)()],connectionEncrypters:[(0,Vh.noise)()],streamMuxers:[(0,qh.yamux)()],connectionGater:{denyDialMultiaddr:async()=>!1}})}async function Zh(e,t,n){let r=await e.dialProtocol((0,Gh.multiaddr)(t),Jh,{signal:AbortSignal.timeout(cE)});r.send(oE(n));let s;return Promise.race([uE(r),new Promise((o,i)=>{s=setTimeout(()=>i(new Error("subway: request timed out")),lE)})]).finally(()=>clearTimeout(s))}async function dE(e){let t=await Xh(e.seed);try{let n=await Zh(t,e.relayMultiaddr,eE(e.name,e.binding,e.requestId??1n)),r=iE(n);return{success:r.success,error:r.error,peerId:t.peerId.toString()}}finally{await t.stop()}}async function fE(e){let t=await Xh(e.seed);try{let n=await Zh(t,e.relayMultiaddr,nE(e.name,e.requestId??1n)),r=aE(n);return r.peerId.length===0?{found:!1,peerId:"",error:r.error||"name not found"}:{found:!0,peerId:(0,Wh.toString)(r.peerId,"base58btc"),error:""}}finally{await t.stop()}}var Fh,Hh,Vh,qh,Kh,Gh,Wh,pu,Yh,Jh,cE,lE,Bh,vu=st(()=>{"use strict";Tl();Fh=require("libp2p"),Hh=require("@libp2p/tcp"),Vh=require("@chainsafe/libp2p-noise"),qh=require("@chainsafe/libp2p-yamux"),Kh=require("@libp2p/crypto/keys"),Gh=require("@multiformats/multiaddr"),Wh=require("uint8arrays/to-string"),pu=new TextEncoder,Yh=new TextDecoder;Jh="/subway/p2p/1.0.0",cE=15e3,lE=15e3,Bh=1<<20});var ko={};Fr(ko,{MESH:()=>Ie,RELAY_URL:()=>Ao,connectOrThrow:()=>Ss,ensureMailbox:()=>Ou,isSubwayEnabled:()=>Eu,listRegistered:()=>Pu,loadBindingFor:()=>Tu,loadRegistry:()=>Mr,makeClient:()=>ws,maybeMintVisaBinding:()=>ty,meshName:()=>ft,readInbox:()=>gE,registerName:()=>Ru,resolveActingName:()=>Ra,resolveMeshName:()=>Iu,seedSubwayKeyFromTapAgent:()=>ey,sendMessage:()=>$u,sendVia:()=>hE,subwayKeyPath:()=>Ta});function ft(e){return e.includes(".")?e:`${e}.${Ie}`}function Eu(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 ku(){ve.mkdirSync(Au,{recursive:!0,mode:448})}function mE(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function Ta(e){return vs.join(Au,`${mE(e)}.key`)}function Mr(){if(!ve.existsSync(Cu))return{};try{return JSON.parse(ve.readFileSync(Cu,"utf8"))}catch{return{}}}function Su(e){ku(),ve.writeFileSync(Cu,JSON.stringify(e,null,2),{mode:384})}function xu(){try{return Eo.userInfo().username}catch{return"local"}}function ey(e){if(ve.existsSync(e)||!ve.existsSync(wu))return null;let t=ve.readdirSync(wu).filter(r=>r.endsWith(".json"));if(t.length===0)return null;let n=t.map(r=>vs.join(wu,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=Sa(r.private_key_jwk);return ku(),ve.writeFileSync(e,Buffer.from(s),{mode:384}),r.agent_id??null}catch{return null}}function ws(e,t={}){return new nh({name:ft(e),url:Ao,keyPath:Ta(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function Tu(e){if(Ie!=="visa")return;let t=Mr()[e];if(t?.binding&&!(t.bindingExpiresAt&&Date.parse(t.bindingExpiresAt)<=Date.now()))return t.binding}async function Ss(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(Mr());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 ty(e){if(Ie!=="visa")return null;let t=process.env.VISA_CLI_API_KEY?.trim();if(!t)throw new Ze("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.",Ea(Se()),"no_key");try{return await So({authUrl:Se(),apiKey:t,seed:Aa(Ta(e)),name:ft(e)})}catch(n){if(n instanceof Ze)throw n;return console.warn(`[subway] Visa binding not minted: ${n instanceof Error?n.message:String(n)}`),null}}async function Ru(e){let t=Ta(e),n=ey(t),r=ft(e);Ie==="visa"&&!ve.existsSync(t)&&(ku(),ve.writeFileSync(t,(0,Qh.randomBytes)(32),{mode:384}));let s=await ty(e),o=s?{binding:s.binding,bindingExpiresAt:new Date(Date.now()+s.expires_in*1e3).toISOString()}:{},i=process.env.SUBWAY_RELAY_MULTIADDR;if(Ie==="visa"&&i){let{registerDirect:c}=await Promise.resolve().then(()=>(vu(),bu)),l=await c({relayMultiaddr:i,seed:Aa(t),name:r,binding:s?.binding});if(!l.success)throw new Error(`.visa relay admission failed: ${l.error||"unknown"}`);let u=Mr();return u[e]={relayName:r,mesh:Ie,peerId:l.peerId,owner:xu(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},Su(u),{relayName:r,mesh:Ie,peerId:l.peerId,tapAgentId:n,...s?{binding:s.binding}:{}}}if(Ie==="visa"&&!process.env.SUBWAY_RELAY){let c=Mr();return c[e]={relayName:r,mesh:Ie,peerId:null,owner:xu(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},Su(c),{relayName:r,mesh:Ie,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=ws(e,{autoReconnect:!1,binding:s?.binding});try{await Ss(a);let c=Mr();return c[e]={relayName:r,mesh:Ie,peerId:a.peerId,owner:xu(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},Su(c),{relayName:r,mesh:Ie,peerId:a.peerId,tapAgentId:n,...s?{binding:s.binding}:{}}}finally{a.disconnect()}}async function Iu(e){let t=ft(e),n=process.env.SUBWAY_RELAY_MULTIADDR;if(Ie==="visa"&&n){let{resolveDirect:r}=await Promise.resolve().then(()=>(vu(),bu)),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 $u(e,t,n){let r=ws(e,{autoReconnect:!1,binding:Tu(e)});try{await Ss(r);let s=ft(t);return await r.sendSigned(s,"chat",n),{to:s,as:ft(e)}}finally{r.disconnect()}}function Pu(){let e=Mr();return Object.entries(e).map(([t,n])=>({name:t,...n}))}async function Ou(e){let t=ka.get(e);if(t)return{relayName:ft(e),peerId:t.client.peerId};let n=ws(e,{autoReconnect:!0,binding:Tu(e)}),r=[];return n.onMessage(s=>{r.push({from:s.fromName,text:s.payload,ts:s.timestampMs,verified:!!s.verified}),r.length>pE&&r.shift()}),ka.set(e,{client:n,buffer:r}),await Ss(n),{relayName:ft(e),peerId:n.peerId}}async function gE(e,t=20,n=!1){await Ou(e);let r=ka.get(e);if(!r)return[];let s=r.buffer.slice(-t);return n&&(r.buffer.length=0),s}async function hE(e,t,n){await Ou(e);let r=ka.get(e);if(!r)throw new Error(`mailbox for ${e} unavailable`);let s=ft(t);return await r.client.sendSigned(s,"chat",n),{to:s,as:ft(e)}}var ve,Eo,vs,Qh,Ie,Ao,Au,Cu,wu,ka,pE,xs=st(()=>{"use strict";Xl();xa();ve=R(require("fs")),Eo=R(require("os")),vs=R(require("path")),Qh=require("crypto");St();xo();Ie=process.env.SUBWAY_MESH??"relay",Ao=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";Au=vs.join(Eo.homedir(),".visa-cli","subway"),Cu=vs.join(Au,"registry.json"),wu=vs.join(Eo.homedir(),".visa-cli","agents");ka=new Map,pE=200});var Fa={};Fr(Fa,{initSentry:()=>q1,isSentryConfigured:()=>V1,reportFatal:()=>K1});function V1(){return!1}async function q1(){return null}async function K1(e,t){process.exit(t?.exitCode??1)}var Ha=st(()=>{});var Mk={};Fr(Mk,{printGroupHelpAndExit:()=>Ut});module.exports=$_(Mk);var o_=require("commander"),Ga=R(require("crypto")),ce=R(require("fs")),re=R(require("os")),rt=R(require("path")),i_=require("child_process"),dd=require("node:readline/promises"),a_=require("util");var Yo=require("child_process"),Od=require("util"),mn=R(require("fs")),zo=R(require("os")),ic=R(require("path"));var kd=R(require("crypto"));var jt="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";var Td="VISA_ALLOW_INSECURE_MOCKS",Cd,Ed,Ad;function tc(e){return`${e}-${kd.randomBytes(24).toString("base64url")}`}function Rd(e=process.env){return e.NODE_ENV==="test"||e[Td]==="true"}function dn(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&Rd(e)}function Hr(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&Rd(e)}function nc(){return`Set ${Td}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function Id(){return Cd??=tc("mock-session"),Cd}function $d(e=process.env){return e.NODE_ENV==="test"?jt:(Ed??=tc("mock-rc"),Ed)}function Pd(){return Ad??=tc("mock-signature"),Ad}var yt=(0,Od.promisify)(Yo.execFile),ac=ic.join(zo.homedir(),".visa-mcp"),Ms=ic.join(ac,"session-token"),We="visa-cli",fn="session-token",Go="rc-access",P_=5e3,Wo=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function O_(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
10
+ `)}function Nd(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")}async function N_(){try{let{stdout:e}=await yt("security",["find-generic-password","-s",We,"-a",fn,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(Nd(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 M_(e){try{try{await yt("security",["delete-generic-password","-s",We,"-a",fn],{timeout:5e3})}catch{}return await yt("security",["add-generic-password","-s",We,"-a",fn,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function L_(){try{await yt("security",["delete-generic-password","-s",We,"-a",fn],{timeout:5e3})}catch{}}async function U_(){if(!cc())return null;try{let{stdout:e}=await yt("secret-tool",["lookup","service",We,"account",fn],{timeout:5e3});return e.trim()||null}catch{return null}}async function D_(e){if(!cc())return!1;try{let t=(0,Yo.execFile)("secret-tool",["store","--label",`${We} ${fn}`,"service",We,"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"))},P_))]),!0):!1}catch{return!1}}async function j_(){if(cc())try{await yt("secret-tool",["clear","service",We,"account",fn],{timeout:5e3})}catch{}}function cc(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function B_(){try{let{stdout:e}=await yt("security",["find-generic-password","-s",We,"-a",Go,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function F_(e){try{try{await yt("security",["delete-generic-password","-s",We,"-a",Go],{timeout:5e3})}catch{}await yt("security",["add-generic-password","-s",We,"-a",Go,"-w",e],{timeout:5e3})}catch{}}async function H_(){try{await yt("security",["delete-generic-password","-s",We,"-a",Go],{timeout:5e3})}catch{}}function sc(){try{return mn.readFileSync(Ms,"utf-8").trim()||null}catch(e){if(Nd(e))throw new Wo(`Unable to read Visa CLI credentials from ${Ms}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function Md(e){mn.mkdirSync(ac,{recursive:!0,mode:448}),mn.writeFileSync(Ms,e,{mode:384}),process.platform==="win32"&&V_(Ms)}function oc(){try{mn.unlinkSync(Ms)}catch{}}function V_(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:N_,store:M_,delete:L_};case"linux":return{get:U_,store:D_,delete:j_};default:return{get:async()=>sc(),store:async e=>{try{return Md(e),!0}catch{return!1}},delete:async()=>oc(),storesInSessionFile:!0}}}var G=class{static async getSessionToken(){if(dn())return Promise.resolve(Id());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(Md(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()?$d():B_()}static async saveRcAccessToken(t){dn()||await F_(t)}static async deleteSessionToken(){if(dn())return;await rc().delete(),oc()}static async clearAll(){await this.deleteSessionToken(),await H_()}};var Jo=R(require("crypto")),Xo=R(require("tty")),Zo=R(require("fs"));function K_(e){return/-rc\.|-beta\./.test(e)}function lc(e){return Jo.createHash("sha256").update(e.trim()).digest("hex")}function Ld(e){return jt==="SKIP"?!0:Jo.timingSafeEqual(Buffer.from(lc(e)),Buffer.from(jt))}function G_(){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 W_(e){return new Promise((t,n)=>{let r;try{r=G_()}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 Q_=`
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 Y_=`
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 _x.encode(n)}function wx(e,t,n,r,s,o,i){return vx({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 Dd(e={}){let t=e.version??Ms().version;if(!J_(t))return;let n=process.env.VISA_RC_CODE;if(n&&Ud(n)){await G.saveRcAccessToken(ac(n));return}if(e.isMcp??!1){let i=await G.getRcAccessToken();if(i&&(Ut==="SKIP"||i===Ut))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&&(Ut==="SKIP"||s===Ut))return;console.log(Q_);let o=3;for(let i=1;i<=o;i++){let a;try{a=await Z_(" Enter RC access code: ")}catch{process.exit(1)}if(Ud(a)){await G.saveRcAccessToken(ac(a)),console.log(`
22
+ `;async function Ud(e={}){let t=e.version??Ls().version;if(!K_(t))return;let n=process.env.VISA_RC_CODE;if(n&&Ld(n)){await G.saveRcAccessToken(lc(n));return}if(e.isMcp??!1){let i=await G.getRcAccessToken();if(i&&(jt==="SKIP"||i===jt))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&&(jt==="SKIP"||s===jt))return;console.log(Y_);let o=3;for(let i=1;i<=o;i++){let a;try{a=await W_(" Enter RC access code: ")}catch{process.exit(1)}if(Ld(a)){await G.saveRcAccessToken(lc(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 Zo=I(require("fs")),jd=I(require("os")),cc=I(require("path")),eb=[{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"}}],tb=/^data:(image\/(png|jpeg|jpg|gif|webp));base64,([A-Za-z0-9+/=]+)$/;function Fr(e){if(typeof e!="string"||e.length===0)return null;let t=e.trim(),n=tb.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 eb)if(r.startsWith(s))return{base64:r,sig:o};return null}function Ls(e,t={}){let n=t.outputDir??cc.join(jd.tmpdir(),"visa-cli");Zo.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=cc.join(n,`${r}-${s}.${e.sig.ext}`),i=Buffer.from(e.base64,"base64");return Zo.writeFileSync(o,i,{mode:384}),{filePath:o,bytes:i.length,mime:e.sig.mime}}function Bd(e){return typeof e?.status=="string"&&(e.status==="IN_QUEUE"||e.status==="PENDING")}function lc(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 nb(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 Us(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 uc(e,t){if(!t||typeof t!="object")return Us(e,"No result payload from tool");let n=t;if(n.success===!1)return Us(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 nb(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 dc=require("process");async function fc(){let e="";dc.stdin.setEncoding("utf8");for await(let t of dc.stdin)e+=t;return e.endsWith(`
30
- `)?e.slice(0,-1):e}async function Wn(e,t){if(e==="-"||t.stdin===!0&&!e){let s=(await fc()).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 Ds(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 qd=I(require("fs")),Qo=I(require("path"));var pn=class extends Error{constructor(t){super(t),this.name="FromStdinFieldError"}},Fd=new Set;function rb(e){Fd.add(e)}function Hd(e){return Fd.has(e)}function Vd(e,t){if(!t.startsWith("."))throw new pn(`--from-stdin path must start with "." (got: "${t}")`);let n=sb(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 rb(s),s}function sb(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 mc=class extends Error{constructor(t){super(t),this.name="FileShorthandStdinSourceError"}};async function Kd(e){if(e===void 0)return;if(!e.startsWith("@"))return e;if(Hd(e))throw new mc("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("~")?Qo.join(process.env.HOME??"",t.slice(1)):Qo.resolve(process.cwd(),t),r=await qd.promises.readFile(n,"utf8");return r.endsWith(`
31
- `)?r.slice(0,-1):r}var js=require("process"),gn=["json","yaml","tsv","table"];function ei(e){return gn.includes(e)}function Bs(e,t){switch(t){case"json":js.stdout.write(JSON.stringify(e)+`
32
- `);return;case"yaml":js.stdout.write(ob(e)+`
33
- `);return;case"tsv":js.stdout.write(ib(e)+`
34
- `);return;case"table":js.stdout.write(ab(e)+`
35
- `);return}}function ob(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(` - ${Gd(s)}`)}else r!==null&&typeof r=="object"?t.push(`${n}: ${JSON.stringify(r)}`):t.push(`${n}: ${Gd(r)}`);return t.join(`
36
- `)}function Gd(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 ib(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 ab(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 Yd=require("child_process");function pc(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 cb(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 Fs(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=Fs(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 Jd(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 Xd(e,t=process.platform){let n=Fs(e);return n?Jd(n,t):null}function Wd(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function gc(e,t={}){let n=t.log??(l=>console.log(l)),r=t.env??process.env,s=t.platform??process.platform,o=Fs(e),i=t.spawn??((l,u,d)=>{(0,Yd.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 cb(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=pc(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=Jd(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?Wd(n,d):(n(" Opened browser. Waiting for you to sign in..."),n("")),l()};try{i(c.cmd,c.args,u)}catch(d){Wd(n,d instanceof Error?d:new Error(String(d))),l()}})}function lb(e){return new Promise(t=>setTimeout(t,e))}function Zd(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 Qd(e){return!Number.isFinite(e)||e===null||e<=0?1e3:Math.min(Math.max(Math.ceil(e),1e3),3e4)}async function ub(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=Zd(e.headers?.get("Retry-After"));if(r!==null)return n(Qd(r));if(typeof e.json=="function")try{let s=await e.json();return n(Qd(Zd(s?.retryAfter)))}catch{return n(1e3)}return n(1e3)}async function hn(e,t){let n=await ub(e);return t?.(n),await lb(n),n}var bf=I(require("crypto")),vf=require("child_process"),we=I(require("fs")),wf=I(require("os")),De=I(require("path"));var z=I(require("fs")),Jn=I(require("os")),Q=I(require("path")),af=require("child_process"),_c=require("crypto");var Vr=I(require("fs")),ti=I(require("tty"));function tf(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 nf(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 rf(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 ef(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 db=80,fb="/dev/tty";function mb(e=fb){if(process.platform==="win32")return null;let t,n;try{t=Vr.openSync(e,"r"),n=Vr.openSync(e,"w");let r=new ti.ReadStream(t),s=new ti.WriteStream(n);return{stdin:r,stdout:s,close:()=>{try{r.destroy?.()}catch{}try{s.destroy?.()}catch{}}}}catch{try{t!==void 0&&Vr.closeSync(t)}catch{}try{n!==void 0&&Vr.closeSync(n)}catch{}return null}}function pb(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??mb)(e.ttyPath);return o?.stdout.isTTY&&o.stdin.isTTY&&typeof o.stdin.setRawMode=="function"?o:(o?.close?.(),null)}async function gb(e={}){let t=pb(e);if(!t)return null;let{stdin:n,stdout:r}=t,s=e.timeoutMs??db,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 b=ef(l),A=l.includes("\x07")||l.includes("\x1B\\");b!==null&&A&&m(b>.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=ef(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 Yn,Hs;function hb(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=rf(e.COLORFGBG);return n||"dark"}function ni(e=process.env){return Yn!==void 0||(Yn=hb(e)),Yn}function Ie(e=process.env){if(Hs!==void 0)return Hs;let t=ni(e),n=tf(e);return Hs=nf(t==="light"?"light":"dark",n),Hs}function ri(e=process.env){return ni(e)==="no-color"}async function hc(e={}){if(Yn!==void 0)return Yn;let t=e.env??process.env;if((t.NO_COLOR??"")!=="")return Hr("no-color",t);let n=(t.VISA_CLI_HUD_THEME??"").toLowerCase().trim();if(n==="light")return Hr("light",t);if(n==="dark")return Hr("dark",t);let r=rf(t.COLORFGBG);if(r)return Hr(r,t);let s=await gb(e);return Hr(s||"dark",t)}function Hr(e,t){Yn=e;let n=tf(t);return Hs=nf(e==="light"?"light":"dark",n),e}var yb=2,si="# >>> visa-cli shell hud v2 >>>",oi="# <<< visa-cli shell hud v2 <<<",_b="# >>> visa-cli shell hud >>>",bb="# <<< visa-cli shell hud <<<",cf=3e4,vb=6e4,wb="VISA | HUD not ready \u2014 run: visa-cli config hud doctor",Sb={currentVersion:"0.0.0"},xb=15e3;function bc(){try{return Q.join(Sc(),".visa-cli")}catch{return Q.join(Jn.tmpdir(),".visa-cli")}}function yn(){return Q.join(bc(),"shell-hud.json")}function Vs(){return Q.join(bc(),"shell-hud.line")}function lf(){return Q.join(bc(),"shell-hud.lock")}function Gr(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 qs(e){let t=Sc();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 uf(e,t){let n=t??Sc(),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 Cb(e){let t="$HOME/.visa-cli/shell-hud.line",n=Hb(e),r=Vb(e);if(e==="zsh")return`${si}
29
+ `),process.exit(1)}var Qo=R(require("fs")),Dd=R(require("os")),uc=R(require("path")),z_=[{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"}}],J_=/^data:(image\/(png|jpeg|jpg|gif|webp));base64,([A-Za-z0-9+/=]+)$/;function Vr(e){if(typeof e!="string"||e.length===0)return null;let t=e.trim(),n=J_.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 z_)if(r.startsWith(s))return{base64:r,sig:o};return null}function Us(e,t={}){let n=t.outputDir??uc.join(Dd.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 jd(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 X_(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 Ds(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 Ds(e,"No result payload from tool");let n=t;if(n.success===!1)return Ds(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 X_(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 Wn(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 js(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 Vd=R(require("fs")),ei=R(require("path"));var pn=class extends Error{constructor(t){super(t),this.name="FromStdinFieldError"}},Bd=new Set;function Z_(e){Bd.add(e)}function Fd(e){return Bd.has(e)}function Hd(e,t){if(!t.startsWith("."))throw new pn(`--from-stdin path must start with "." (got: "${t}")`);let n=Q_(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 Z_(s),s}function Q_(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 qd(e){if(e===void 0)return;if(!e.startsWith("@"))return e;if(Fd(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 Vd.promises.readFile(n,"utf8");return r.endsWith(`
31
+ `)?r.slice(0,-1):r}var Bs=require("process"),gn=["json","yaml","tsv","table"];function ti(e){return gn.includes(e)}function Fs(e,t){switch(t){case"json":Bs.stdout.write(JSON.stringify(e)+`
32
+ `);return;case"yaml":Bs.stdout.write(eb(e)+`
33
+ `);return;case"tsv":Bs.stdout.write(tb(e)+`
34
+ `);return;case"table":Bs.stdout.write(nb(e)+`
35
+ `);return}}function eb(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(` - ${Kd(s)}`)}else r!==null&&typeof r=="object"?t.push(`${n}: ${JSON.stringify(r)}`):t.push(`${n}: ${Kd(r)}`);return t.join(`
36
+ `)}function Kd(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 tb(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 nb(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 Wd=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 rb(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 Hs(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 Yd(e,t){let n=Hs(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 Jd(e,t=process.platform){let n=Hs(e);return n?zd(n,t):null}function Gd(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=Hs(e),i=t.spawn??((l,u,d)=>{(0,Wd.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 rb(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?Gd(n,d):(n(" Opened browser. Waiting for you to sign in..."),n("")),l()};try{i(c.cmd,c.args,u)}catch(d){Gd(n,d instanceof Error?d:new Error(String(d))),l()}})}function sb(e){return new Promise(t=>setTimeout(t,e))}function Xd(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 Zd(e){return!Number.isFinite(e)||e===null||e<=0?1e3:Math.min(Math.max(Math.ceil(e),1e3),3e4)}async function ob(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=Xd(e.headers?.get("Retry-After"));if(r!==null)return n(Zd(r));if(typeof e.json=="function")try{let s=await e.json();return n(Zd(Xd(s?.retryAfter)))}catch{return n(1e3)}return n(1e3)}async function hn(e,t){let n=await ob(e);return t?.(n),await sb(n),n}var _f=R(require("crypto")),bf=require("child_process"),we=R(require("fs")),vf=R(require("os")),De=R(require("path"));var z=R(require("fs")),Jn=R(require("os")),Q=R(require("path")),of=require("child_process"),vc=require("crypto");var Kr=R(require("fs")),ni=R(require("tty"));function ef(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 tf(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 nf(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 Qd(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 ib=80,ab="/dev/tty";function cb(e=ab){if(process.platform==="win32")return null;let t,n;try{t=Kr.openSync(e,"r"),n=Kr.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&&Kr.closeSync(t)}catch{}try{n!==void 0&&Kr.closeSync(n)}catch{}return null}}function lb(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??cb)(e.ttyPath);return o?.stdout.isTTY&&o.stdin.isTTY&&typeof o.stdin.setRawMode=="function"?o:(o?.close?.(),null)}async function ub(e={}){let t=lb(e);if(!t)return null;let{stdin:n,stdout:r}=t,s=e.timeoutMs??ib,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=h=>{l+=typeof h=="string"?h:h.toString("utf-8");let v=Qd(l),I=l.includes("\x07")||l.includes("\x1B\\");v!==null&&I&&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=h=>{c||(c=!0,f(),a(h))},p=o(()=>{let h=Qd(l);m(h!==null?h>.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 Yn,Vs;function db(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=nf(e.COLORFGBG);return n||"dark"}function ri(e=process.env){return Yn!==void 0||(Yn=db(e)),Yn}function $e(e=process.env){if(Vs!==void 0)return Vs;let t=ri(e),n=ef(e);return Vs=tf(t==="light"?"light":"dark",n),Vs}function si(e=process.env){return ri(e)==="no-color"}async function _c(e={}){if(Yn!==void 0)return Yn;let t=e.env??process.env;if((t.NO_COLOR??"")!=="")return qr("no-color",t);let n=(t.VISA_CLI_HUD_THEME??"").toLowerCase().trim();if(n==="light")return qr("light",t);if(n==="dark")return qr("dark",t);let r=nf(t.COLORFGBG);if(r)return qr(r,t);let s=await ub(e);return qr(s||"dark",t)}function qr(e,t){Yn=e;let n=ef(t);return Vs=tf(e==="light"?"light":"dark",n),e}var fb=2,oi="# >>> visa-cli shell hud v2 >>>",ii="# <<< visa-cli shell hud v2 <<<",mb="# >>> visa-cli shell hud >>>",pb="# <<< visa-cli shell hud <<<",af=3e4,gb=6e4,hb="VISA | HUD not ready \u2014 run: visa-cli config hud doctor",yb={currentVersion:"0.0.0"},_b=15e3;function wc(){try{return Q.join(Cc(),".visa-cli")}catch{return Q.join(Jn.tmpdir(),".visa-cli")}}function yn(){return Q.join(wc(),"shell-hud.json")}function qs(){return Q.join(wc(),"shell-hud.line")}function cf(){return Q.join(wc(),"shell-hud.lock")}function Yr(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 Ks(e){let t=Cc();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 lf(e,t){let n=t??Cc(),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 bb(e){let t="$HOME/.visa-cli/shell-hud.line",n=Ub(e),r=Db(e);if(e==="zsh")return`${oi}
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
- ${oi}`;if(e==="powershell"){let s="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${si}
57
+ ${ii}`;if(e==="powershell"){let s="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${oi}
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
- ${oi}`}return`${si}
76
+ ${ii}`}return`${oi}
77
77
  __visa_cli_shell_hud_precmd() {
78
78
  if [ -f "${t}" ]; then
79
79
  cat "${t}"
@@ -90,129 +90,122 @@ 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
- ${oi}`}function Ab(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 Eb(e,t,n){let r=new RegExp(`(^|\\n)([ \\t]*${of(t)}[ \\t]*\\r?\\n)([\\s\\S]*?)(\\r?\\n[ \\t]*${of(n)}[ \\t]*)(?=\\r?\\n|$)(\\r?\\n)?`,"g");return e.replace(r,(s,o,i,a,c,l,u)=>{if(!Ab(a))return s;let d=u>0?e[u-1]:"";return o===`
93
+ ${ii}`}function vb(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 wb(e,t,n){let r=new RegExp(`(^|\\n)([ \\t]*${sf(t)}[ \\t]*\\r?\\n)([\\s\\S]*?)(\\r?\\n[ \\t]*${sf(n)}[ \\t]*)(?=\\r?\\n|$)(\\r?\\n)?`,"g");return e.replace(r,(s,o,i,a,c,l,u)=>{if(!vb(a))return s;let d=u>0?e[u-1]:"";return o===`
94
94
  `&&d!==`
95
95
  `?`
96
- `:""})}function Ks(e){let t=e;for(let[n,r]of[[si,oi],[_b,bb]])t=Eb(t,n,r);return t.trimEnd()}function df(e){return Ks(e)!==e.trimEnd()}function kb(e,t){let n=Ks(e).trimEnd(),r=Cb(t);return n.length>0?`${n}
96
+ `:""})}function Gs(e){let t=e;for(let[n,r]of[[oi,ii],[mb,pb]])t=wb(t,n,r);return t.trimEnd()}function uf(e){return Gs(e)!==e.trimEnd()}function Sb(e,t){let n=Gs(e).trimEnd(),r=bb(t);return n.length>0?`${n}
97
97
 
98
98
  ${r}
99
99
  `:`${r}
100
- `}function ii(e=Gr()){if(!e)return!1;try{let t=qs(e),n=z.readFileSync(t,"utf-8");return df(n)}catch{return!1}}function Xn(e=Jn.homedir()){let t=[],n=Tb(e);for(let r of n)try{if(!z.existsSync(r))continue;let s=z.readFileSync(r,"utf-8");df(s)&&t.push(r)}catch{}return t}function Tb(e){return uf(null,e).map(t=>t.rcPath)}function ai(e=Gr()){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=qs(e);let n=z.existsSync(t)?z.readFileSync(t,"utf-8"):"",r=kb(n,e),s=r!==n;return s&&Kr(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}: ${yc(n)}`}}}function Dt(e=Gr(),t){let n=[],r=[],s=[];try{for(let o of uf(e,t))if(r.push(o.rcPath),!!z.existsSync(o.rcPath))try{let i=z.readFileSync(o.rcPath,"utf-8"),a=Ks(i);if(a===i.trimEnd())continue;Kr(o.rcPath,a.length>0?`${a}
101
- `:""),n.push(o.rcPath)}catch(i){s.push(`${o.rcPath}: ${yc(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: ${yc(o)}`}}}function vc(e,t){let n=t??Sb,r=n.currentVersion==="0.0.0"&&e.version?e.version:n.currentVersion,s=_n(r),o=` ${te("\u2502",ee.chrome)} `,i=ff(n),a=Ob(n,i),c=n.updateCheckDisabled?"":i,l=Pb(s,c);if(!e.enrolled)return[l,te("setup needed",ee.visaGold),a].filter(Boolean).join(o);let u=Fb(e),d=$b(e),f=_n(Jn.hostname().split(".")[0]),m=[l,f?te(f,ee.muted):"",te(u,ee.visaGold),a].filter(Boolean).join(o),p=[d,Rb(e)].filter(Boolean),g=p.length>0?p.join(o):"";return g?`${m}
102
- ${g}`:m}function Rb(e){let t=` ${te("\u2502",ee.chrome)} `,n=[];if(typeof e.spentToday=="number"&&Number.isFinite(e.spentToday)&&n.push(te(`spent today ${qr(Math.max(0,e.spentToday))}`,ee.muted)),e.lastService&&typeof e.lastService.toolName=="string"&&e.lastService.toolName.length>0){let r=Bb(_n(e.lastService.toolName)),s=Ib(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 Ib(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 $b(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`${jb(l)} ${te(`${qr(a/100)} in session`,ee.green)} ${te(`(${qr(c/100)}/${qr(i/100)} cap)`,ee.muted)} ${te("\xB7",ee.chrome)} ${te(`${qr(r)} balance`,ee.muted)}`}let s=10,o=`balance ${qr(r)}`;return t>=s?te(o,ee.green):te(`${o} \u2014 top up via buy_credits`,ee.visaGold)}function Pb(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 Ob(e,t){return t&&!e.updateCheckDisabled?te("run: visa-cli update",ee.visaGold):t?null:Nb(e)}function ff(e){return e.latestVersion?_n(e.latestVersion):""}function Nb(e){let t=ff(e);return t?te(`update ready v${t}`,ee.visaGold):null}function mf(){let e=Gs();return!(!e||Date.now()-e.renderedAt>cf||e.cwd&&e.cwd!==process.cwd())}function ci(){let e=Gs(),t=Date.now();if(e&&t-e.renderedAt<=cf||(Lb(),e?.line))return sf(e.line,e,t);try{let n=Vs();if(z.existsSync(n)){let r=z.readFileSync(n,"utf-8").trimEnd();if(r&&!li(r))return r}}catch{}return wb}function sf(e,t,n){let r=n-t.renderedAt,s=typeof t.refreshFailedAt=="number"&&t.refreshFailedAt>t.renderedAt,o=[];if(r>=vb&&o.push(`stale ${Mb(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 ai(e=Yr()){if(!e)return!1;try{let t=Ks(e),n=z.readFileSync(t,"utf-8");return uf(n)}catch{return!1}}function Xn(e=Jn.homedir()){let t=[],n=xb(e);for(let r of n)try{if(!z.existsSync(r))continue;let s=z.readFileSync(r,"utf-8");uf(s)&&t.push(r)}catch{}return t}function xb(e){return lf(null,e).map(t=>t.rcPath)}function ci(e=Yr()){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=Ks(e);let n=z.existsSync(t)?z.readFileSync(t,"utf-8"):"",r=Sb(n,e),s=r!==n;return s&&Wr(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 Bt(e=Yr(),t){let n=[],r=[],s=[];try{for(let o of lf(e,t))if(r.push(o.rcPath),!!z.existsSync(o.rcPath))try{let i=z.readFileSync(o.rcPath,"utf-8"),a=Gs(i);if(a===i.trimEnd())continue;Wr(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??yb,r=n.currentVersion==="0.0.0"&&e.version?e.version:n.currentVersion,s=_n(r),o=` ${te("\u2502",ee.chrome)} `,i=df(n),a=Tb(n,i),c=n.updateCheckDisabled?"":i,l=kb(s,c);if(!e.enrolled)return[l,te("setup needed",ee.visaGold),a].filter(Boolean).join(o);let u=Lb(e),d=Ab(e),f=_n(Jn.hostname().split(".")[0]),m=[l,f?te(f,ee.muted):"",te(u,ee.visaGold),a].filter(Boolean).join(o),p=[d,Cb(e)].filter(Boolean),h=p.length>0?p.join(o):"";return h?`${m}
102
+ ${h}`:m}function Cb(e){let t=` ${te("\u2502",ee.chrome)} `,n=[];if(typeof e.spentToday=="number"&&Number.isFinite(e.spentToday)&&n.push(te(`spent today ${Gr(Math.max(0,e.spentToday))}`,ee.muted)),e.lastService&&typeof e.lastService.toolName=="string"&&e.lastService.toolName.length>0){let r=Mb(_n(e.lastService.toolName)),s=Eb(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 Eb(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 Ab(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`${Nb(l)} ${te(`${Gr(a/100)} in session`,ee.green)} ${te(`(${Gr(c/100)}/${Gr(i/100)} cap)`,ee.muted)} ${te("\xB7",ee.chrome)} ${te(`${Gr(r)} balance`,ee.muted)}`}let s=10,o=`balance ${Gr(r)}`;return t>=s?te(o,ee.green):te(`${o} \u2014 top up via buy_credits`,ee.visaGold)}function kb(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 Tb(e,t){return t&&!e.updateCheckDisabled?te("run: visa-cli update",ee.visaGold):t?null:Rb(e)}function df(e){return e.latestVersion?_n(e.latestVersion):""}function Rb(e){let t=df(e);return t?te(`update ready v${t}`,ee.visaGold):null}function ff(){let e=Ws();return!(!e||Date.now()-e.renderedAt>af||e.cwd&&e.cwd!==process.cwd())}function li(){let e=Ws(),t=Date.now();if(e&&t-e.renderedAt<=af||($b(),e?.line))return rf(e.line,e,t);try{let n=qs();if(z.existsSync(n)){let r=z.readFileSync(n,"utf-8").trimEnd();if(r&&!ui(r))return r}}catch{}return hb}function rf(e,t,n){let r=n-t.renderedAt,s=typeof t.refreshFailedAt=="number"&&t.refreshFailedAt>t.renderedAt,o=[];if(r>=gb&&o.push(`stale ${Ib(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 Mb(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 wc(e,t){try{let n=Q.dirname(yn());z.mkdirSync(n,{recursive:!0});let r=e.split(`
105
- `).map(o=>Db(o)).filter(o=>o.length>0).join(`
106
- `),s={hudVersion:yb,renderedAt:Date.now(),line:r,cwd:process.cwd(),status:t};Kr(yn(),JSON.stringify(s)+`
107
- `),Kr(Vs(),r+`
108
- `)}catch{}}function pf(e){try{let t=Gs();if(!t)return;let n=Math.max(Date.now(),t.renderedAt+1),r={...t,refreshFailedAt:n,refreshErrorReason:_n(e).slice(0,200)};Kr(yn(),JSON.stringify(r)+`
109
- `)}catch{}}function gf(){try{let e=Gs();if(!e)return;let t={...e,renderedAt:0};Kr(yn(),JSON.stringify(t)+`
110
- `)}catch{}}function zn(){try{z.unlinkSync(lf())}catch{}}function Gs(){let e=yn();if(!z.existsSync(e))return null;try{let t=JSON.parse(z.readFileSync(e,"utf-8"));return typeof t?.line=="string"&&li(t.line)?null:t}catch{return null}}function li(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 hf(){return Gs()?.status??null}function Lb(){if(process.env.JEST_WORKER_ID)return;let e=lf();try{if(z.mkdirSync(Q.dirname(e),{recursive:!0}),!qb(e))return;let t=process.argv[1]?Q.resolve(process.argv[1]):"";if(!t){zn();return}let n=ni(),r=(process.env.VISA_CLI_HUD_THEME??"").toLowerCase().trim(),s=n==="no-color"||r==="light"||r==="dark"?{}:{VISA_CLI_HUD_THEME:n},o=(0,af.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,...s,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});o.once("error",zn),o.unref()}catch{zn()}}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 Ub=/^\u001B\[(?:0|38;2;\d{1,3};\d{1,3};\d{1,3}|38;5;\d{1,3})m$/;function Db(e){let t=[],n=`__VISA_CLI_HUD_SGR_${(0,_c.randomBytes)(8).toString("hex")}_`,r=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,o=>{if(!Ub.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 jb(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 qr(e){return`$${e.toFixed(2)}`}function Bb(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 Fb(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||ri()?e:`${t}${e}${ee.reset}`}function of(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Sc(){let e=Jn.homedir();if(!e||!Q.isAbsolute(e))throw new Error("unable to determine a valid home directory");return Q.resolve(e)}function Hb(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function Vb(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function qb(e){for(let t=0;t<2;t+=1){let n;try{return n=z.openSync(e,"wx"),z.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=z.statSync(e);if(Date.now()-s.mtimeMs<=xb)return!1;z.unlinkSync(e)}catch{}}finally{n!==void 0&&z.closeSync(n)}}return!1}function yc(e){return e instanceof Error?e.message:"unknown file system error"}function Kr(e,t){z.mkdirSync(Q.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${(0,_c.randomBytes)(8).toString("hex")}.tmp`;try{z.writeFileSync(n,t),z.renameSync(n,e)}catch(r){try{z.unlinkSync(n)}catch{}throw r}}var Kb=1440*60*1e3;function di(e,t){we.mkdirSync(De.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${bf.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 yf(e){return`'${e.replace(/'/g,"'\\''")}'`}var Cc="# visa-cli-hud-v1";function fi(e,t){if(!e&&!t&&Gb())return`visa-cli config statusline ${Cc}`;let n=e??process.execPath,r=t??process.argv[1]??"",s=r?De.resolve(r):"";return`${s?`${yf(n)} ${yf(s)} config statusline`:"visa-cli config statusline"} ${Cc}`}function Gb(){try{return(0,vf.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 Wb(){return"4.0.0-rc.15"}function mi(e){let t=De.dirname(De.resolve(e));return De.basename(t)===".claude"?De.dirname(t):wf.homedir()}function ui(e,t){let n=De.relative(t,e);return!n.startsWith("..")&&!De.isAbsolute(n)?`~/${n}`:e}function Yb(e){return De.join(mi(e),".visa-cli","hud-self-heal.json")}function zb(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 xc(e,t,n){try{di(e,{version:t,checkedAt:n})}catch{}}function Jb(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function Ac(e,t={}){let n=t.now??Date.now(),r=t.version??Wb(),s=t.stampPath??Yb(e),o=t.minIntervalMs??Kb,i=[],a=!1,c=!1;if(!t.force&&zb(s,r,n,o))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:i,skippedReason:"recently checked"};try{if(!we.existsSync(e))return xc(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 xc(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let f=(t.getCommand??fi)();if(d!==f&&(l.statusLine=Jb(u,f),di(e,l),a=!0,i.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!pi()){let m=mi(e);if(Xn(m).length>0){let g=Dt(null,m);if(g.removed&&g.rcPaths&&g.rcPaths.length>0){let b=g.rcPaths.map(A=>ui(A,m)).join(", ");c=!0,i.push(`Cleaned legacy shell-prompt HUD block from ${b}.`)}}}return xc(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 Xb(e,t){let n=mi(t),r=Xn(n);if(r.length===0)return e;let s=r.map(o=>ui(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 pi(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 _f(e,t){let n=mi(t),r=Xn(n);if(r.length===0)return e;let s=r.map(i=>ui(i,n)).join(", ");if(pi())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=Dt(null,n);if(o.removed&&o.rcPaths&&o.rcPaths.length>0){let i=o.rcPaths.map(a=>ui(a,n)).join(", ");return`${e}
104
+ `);return`${e}${i}`}function Ib(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());z.mkdirSync(n,{recursive:!0});let r=e.split(`
105
+ `).map(o=>Ob(o)).filter(o=>o.length>0).join(`
106
+ `),s={hudVersion:fb,renderedAt:Date.now(),line:r,cwd:process.cwd(),status:t};Wr(yn(),JSON.stringify(s)+`
107
+ `),Wr(qs(),r+`
108
+ `)}catch{}}function mf(e){try{let t=Ws();if(!t)return;let n=Math.max(Date.now(),t.renderedAt+1),r={...t,refreshFailedAt:n,refreshErrorReason:_n(e).slice(0,200)};Wr(yn(),JSON.stringify(r)+`
109
+ `)}catch{}}function pf(){try{let e=Ws();if(!e)return;let t={...e,renderedAt:0};Wr(yn(),JSON.stringify(t)+`
110
+ `)}catch{}}function zn(){try{z.unlinkSync(cf())}catch{}}function Ws(){let e=yn();if(!z.existsSync(e))return null;try{let t=JSON.parse(z.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 gf(){return Ws()?.status??null}function $b(){if(process.env.JEST_WORKER_ID)return;let e=cf();try{if(z.mkdirSync(Q.dirname(e),{recursive:!0}),!jb(e))return;let t=process.argv[1]?Q.resolve(process.argv[1]):"";if(!t){zn();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,of.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,...s,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});o.once("error",zn),o.unref()}catch{zn()}}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 Pb=/^\u001B\[(?:0|38;2;\d{1,3};\d{1,3};\d{1,3}|38;5;\d{1,3})m$/;function Ob(e){let t=[],n=`__VISA_CLI_HUD_SGR_${(0,vc.randomBytes)(8).toString("hex")}_`,r=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,o=>{if(!Pb.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 Nb(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 Gr(e){return`$${e.toFixed(2)}`}function Mb(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 Lb(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 $e().reset},get visaBlue(){return $e().visaBlue},get visaBlueSoft(){return $e().visaBlueSoft},get visaGold(){return $e().visaGold},get green(){return $e().green},get muted(){return $e().muted},get chrome(){return $e().chrome}};function te(e,t){return e.length===0||process.env.NO_COLOR||si()?e:`${t}${e}${ee.reset}`}function sf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Cc(){let e=Jn.homedir();if(!e||!Q.isAbsolute(e))throw new Error("unable to determine a valid home directory");return Q.resolve(e)}function Ub(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function Db(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=z.openSync(e,"wx"),z.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=z.statSync(e);if(Date.now()-s.mtimeMs<=_b)return!1;z.unlinkSync(e)}catch{}}finally{n!==void 0&&z.closeSync(n)}}return!1}function bc(e){return e instanceof Error?e.message:"unknown file system error"}function Wr(e,t){z.mkdirSync(Q.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${(0,vc.randomBytes)(8).toString("hex")}.tmp`;try{z.writeFileSync(n,t),z.renameSync(n,e)}catch(r){try{z.unlinkSync(n)}catch{}throw r}}var Bb=1440*60*1e3;function fi(e,t){we.mkdirSync(De.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${_f.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 hf(e){return`'${e.replace(/'/g,"'\\''")}'`}var Ac="# visa-cli-hud-v1";function mi(e,t){if(!e&&!t&&Fb())return`visa-cli config statusline ${Ac}`;let n=e??process.execPath,r=t??process.argv[1]??"",s=r?De.resolve(r):"";return`${s?`${hf(n)} ${hf(s)} config statusline`:"visa-cli config statusline"} ${Ac}`}function Fb(){try{return(0,bf.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 Hb(){return"4.0.0-rc.16"}function pi(e){let t=De.dirname(De.resolve(e));return De.basename(t)===".claude"?De.dirname(t):vf.homedir()}function di(e,t){let n=De.relative(t,e);return!n.startsWith("..")&&!De.isAbsolute(n)?`~/${n}`:e}function Vb(e){return De.join(pi(e),".visa-cli","hud-self-heal.json")}function qb(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 Ec(e,t,n){try{fi(e,{version:t,checkedAt:n})}catch{}}function Kb(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function kc(e,t={}){let n=t.now??Date.now(),r=t.version??Hb(),s=t.stampPath??Vb(e),o=t.minIntervalMs??Bb,i=[],a=!1,c=!1;if(!t.force&&qb(s,r,n,o))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:i,skippedReason:"recently checked"};try{if(!we.existsSync(e))return Ec(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 Ec(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let f=(t.getCommand??mi)();if(d!==f&&(l.statusLine=Kb(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(Xn(m).length>0){let h=Bt(null,m);if(h.removed&&h.rcPaths&&h.rcPaths.length>0){let v=h.rcPaths.map(I=>di(I,m)).join(", ");c=!0,i.push(`Cleaned legacy shell-prompt HUD block from ${v}.`)}}}return Ec(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 Gb(e,t){let n=pi(t),r=Xn(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 yf(e,t){let n=pi(t),r=Xn(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=Bt(null,n);if(o.removed&&o.rcPaths&&o.rcPaths.length>0){let i=o.rcPaths.map(a=>di(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 Ws(e,t=fi){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:_f("Visa HUD already registered in ~/.claude/settings.json.",e)}:{installed:"other-hud-present",message:Xb("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()},di(e,n),{installed:"new",message:_f(`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 Ec(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{di(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 Sf=I(require("os")),xf=I(require("path"));function jt(e=Sf.homedir()){return xf.join(e,".claude","settings.json")}var Bt=I(require("fs")),yt=I(require("path"));var Zb=1,Zn={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},Qb=["terminal","claude","claude-code","all"];function hi(e){let t=e.toLowerCase();return Qb.includes(t)?t:null}var e0=50,t0=64*1024,Cf=10,kc=80,M={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||ri()?e:`${t}${e}${M.reset}`}function Af(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function Rf(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)},e0);e.on("data",i),e.on("end",a),e.on("error",c)})}function Ys(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||"",M.visaBlueSoft)}${L(s||"",M.chrome)}`}function zs(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 n0(e){if(jf(e))return s0(e);let t=` ${L("\u2502",M.chrome)} `,n=gi(e)||"claude",r=e.cwd?ge(yt.basename(e.cwd)):"",s=yi(e.workspace),o=r||s,i=s&&s!==o?` ${L(`@${s}`,M.visaBlueSoft)}`:"",a=[L(`[${n}]`,M.visaBlueSoft)];o&&a.push(`${L(o,M.visaGold)}${i}`);let c=ge(e.git_branch??e.branch??"");c&&a.push(`${L("git:(",M.muted)}${L(c,M.visaBlueSoft)}${L(")",M.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(E=>typeof E=="number"&&Number.isFinite(E)),p=m.length>0?m.reduce((E,y)=>E+y,0):null,g=Number(e.context_window?.total_input_tokens??p??f?.input_tokens??0),b=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(b*u):g,_;if(u>0||d!==null){let E=`${String(Math.round(b*100)).padStart(2," ")}%`,y=u>0?` ${L(`(${zs(A)}/${zs(u)})`,M.muted)}`:"";_=`${L("Context",M.muted)} ${Ys(b)} ${L(E,M.green)}${y}`}else _=`${L("Context",M.muted)} ${L("-",M.muted)}`;let v=If(e.rate_limits),w=[_];v&&w.push(v);let T=w.join(t);return`${l}
118
- ${T}`}function r0(e){if(jf(e))return null;let t=` ${L("\u2502",M.chrome)} `,n=gi(e)||"claude",r=e.cwd?ge(yt.basename(e.cwd)):"",s=yi(e.workspace),o=r||s,i=s&&s!==o?` ${L(`@${s}`,M.visaBlueSoft)}`:"",a=[L(`[${n}]`,M.visaBlueSoft)];o&&a.push(`${L(o,M.visaGold)}${i}`);let c=ge(e.git_branch??e.branch??"");c&&a.push(`${L("git:(",M.muted)}${L(c,M.visaBlueSoft)}${L(")",M.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(w=>typeof w=="number"&&Number.isFinite(w)),m=f.length>0?f.reduce((w,T)=>w+T,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,b=u!==null&&l>0?Math.round(g*l):p,A;if(l>0||u!==null){let w=`${String(Math.round(g*100)).padStart(2," ")}%`,T=l>0?` ${L(`(${zs(b)}/${zs(l)})`,M.muted)}`:"";A=`${L("Context",M.muted)} ${Ys(g)} ${L(w,M.green)}${T}`}else A=`${L("Context",M.muted)} ${L("-",M.muted)}`;let _=If(e.rate_limits),v=[A];return _&&v.push(_),{identity:a.join(t),metrics:v.join(t)}}function s0(e){let t=` ${L("\u2502",M.chrome)} `,n=Bf(e),r=n.model||"codex",s=[L(`[${r}]`,M.visaBlueSoft)];n.project&&s.push(L(n.project,M.visaGold)),n.gitBranch&&s.push(`${L("git",M.muted)} ${L(n.gitBranch,M.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",M.muted)} ${Ys(c)} ${L(`${Math.round(n.contextUsedPercent)}%`,M.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",M.muted)} ${Ys(l)} ${L(`${Math.round(c)}%`,M.green)}`)}typeof n.usedTokens=="number"&&i.push(`${L("Tokens",M.muted)} ${zs(n.usedTokens)}`),n.status&&i.push(`${L("Status",M.muted)} ${L(n.status,M.visaBlueSoft)}`),n.threadTitle&&i.push(`${L("Thread",M.muted)} ${L(n.threadTitle,M.visaBlueSoft)}`);let a=i.length>0?i.join(t):`${L("Context",M.muted)} ${L("-",M.muted)}`;return`${o}
119
- ${a}`}function o0(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 Ef(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=Ys(r),o=n>=90?"\x1B[38;5;196m":n>=70?M.visaGold:M.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=o0(e.resets_at),c=a?` ${L(`(${a} / ${t})`,M.muted)}`:` ${L(`(${t})`,M.muted)}`;return`${s} ${L(i,o)}${c}`}function If(e){if(!e)return null;let t=Ef(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?Ef(e.seven_day,"7d"):null;if(!t&&!r)return null;let s=` ${L("\u2502",M.chrome)} `,o=[t,r].filter(Boolean);return`${L("Usage",M.muted)} ${o.join(s)}`}function $f(e){let t;try{let n=Bt.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let s=Math.min(r,t0),o=r-s;t=Bt.openSync(e,"r");let i=Buffer.alloc(s);Bt.readSync(t,i,0,s,o);let a=i.toString("utf-8");if(o>0){let c=Buffer.alloc(1);if(Bt.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{Bt.closeSync(t)}catch{}}}function i0(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=yt.basename(yt.dirname(s)),i=yt.basename(s);return o&&o!=="."&&o!=="/"?`${o}/${i}`:i}return s}}}function a0(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:i0(d.input),running:m})}}}return n.reverse(),n.slice(Math.max(0,n.length-Cf))}function c0(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 l0(e){let t=e.running?L("\u25D0",M.visaGold):L("\u2713",M.green),n=e.running?M.visaGold:M.visaBlueSoft,r=L(ge(e.name),n),s=e.target?ge(e.target):"",o=s?`${L(":",M.chrome)} ${L(s,M.muted)}`:"",i=e.count>1?` ${L(`\xD7${e.count}`,M.muted)}`:"";return o?`${t} ${r}${o}${i}`:`${t} ${r}${i}`}function u0(e){let t=` ${L("\u2502",M.chrome)} `,n=Af(t),r=e.slice();for(;r.length>0;){let c=r.join(t);if(Af(c)<=kc)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>kc-n-1?i.slice(0,kc-n-1)+s:i;return`${L(s,M.muted)}${t}${a}`}async function kf(e){if(!e||typeof e!="string")return null;let t=$f(e);if(!t)return null;let n;try{n=a0(t)}catch{return null}if(n.length===0)return null;let s=c0(n).map(l0);return u0(s)||null}async function Pf(e,t,n){return(await Nf(e,t,n)).join(`
122
- `)}function Of(e,t,n){let r=!!t?.activeSession||e.includes("in session"),s=n?f0(n):!1;return{isActive:r||s,hasSession:r,hasToolActivity:s}}async function Nf(e,t,n){let{isActive:r}=Of(e,n,t?.transcript_path),s=e.split(`
123
- `).filter(a=>a.length>0),i=t&&!r?s.map(a=>L(Tc(a),M.muted)):[...s];if(t){let a=r0(t);if(a){if(i.push(a.identity),t.transcript_path){let c=await kf(t.transcript_path);c&&i.push(...c.split(`
124
- `))}i.push(a.metrics)}else{let c=n0(t);if(c&&i.push(...c.split(`
125
- `)),t.transcript_path){let l=await kf(t.transcript_path);l&&i.push(...l.split(`
126
- `))}}}return i}var d0=["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 f0(e){let t=$f(e);if(!t)return!1;let n=t.slice(-16384).toLowerCase();return d0.some(r=>n.includes(`"${r}"`))}async function Mf(e,t,n){let r=await Nf(e,t,n),s=r.join(`
127
- `),{isActive:o}=Of(e,n,t?.transcript_path);return{schemaVersion:Zb,client:t?Df(t):Zn.UNKNOWN,rendered:s,lines:r.map(Tc),visa:{spendLine:Tc(e),balanceCents:n?.balanceCents,balanceMicros:n?.balanceMicros,balanceUsd:n?.amountUsd,sessionMode:n?.sessionMode,activeSession:n?.activeSession,isVisaActive:o},context:t?Bf(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 yi(e){if(typeof e=="string")return ge(yt.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?yt.basename(t):e.name)}function Lf(e){return ge(e.app_name??e.appName??e.app??e.client)}function gi(e){return ge(e.model?.display_name??e.model?.id??e.model_name??e.modelName)}function Uf(e){return ge(e.cwd??e.current_dir??e.project_root)}function Tf(e){let t=ge(e.project);if(t)return t;let n=Uf(e);if(n)return ge(yt.basename(n));let r=yi(e.workspace);return r||""}function st(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function Df(e){let t=Lf(e).toLowerCase();return t.includes("codex")?Zn.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?Zn.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||st(e.context_used)!==void 0?Zn.CODEX:Zn.UNKNOWN}function jf(e){return Df(e)===Zn.CODEX}function Bf(e){let t=Lf(e),n=Uf(e),r=yi(e.workspace),s=st(e.context_used)??st(e.context_window?.used_percentage??void 0),o=st(e.context_remaining)??st(e.context_window?.remaining_percentage??void 0);return{...t?{app:t}:{},...gi(e)?{model:gi(e)}:{},...Tf(e)?{project:Tf(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}:{},...st(e.used_tokens)!==void 0?{usedTokens:st(e.used_tokens)}:{},...st(e.total_input_tokens)!==void 0?{totalInputTokens:st(e.total_input_tokens)}:{},...st(e.total_output_tokens)!==void 0?{totalOutputTokens:st(e.total_output_tokens)}:{}}}function Tc(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}var Hf=I(require("path"));function Ff(e){return e instanceof Error?e.message:String(e)}function Rc(e,t){let n=[],r=[],s=e??"claude",o=hi(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: ${Ff(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=Hf.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: ${Ff(c)}`)}}return{ok:i,messages:n,errors:r}}function Vf(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 qf=I(require("os")),Kf=require("node:readline/promises"),Js={card:"default VISA ****7242",balance:"balance $6.38",spentToday:"spent today $0.62",lastActivity:"last Visa tool 38m",model:"Opus 4.6"};async function Ic(e,t=!1){if(!process.stdin.isTTY)return t;let n=t?"[Y/n]":"[y/N]",r,s;try{r=(0,Kf.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 m0(e,t){return e.replace(/[\x00-\x1F\x7F\u202A-\u202E\u2066-\u2069]/g,"").trim()||t}function Gf(e=qf.hostname()){let t=Ms().version,n=m0(e,"this-machine");return[" Preview if installed (sample):",` VISA CLI v${t} | ${n} | ${Js.card}`,` ${Js.balance} | ${Js.spentToday} | ${Js.lastActivity}`,` [${Js.model}] | you`," Activity live"].join(`
128
- `)}function Wf(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 $c(e){return`$${(e/100).toFixed(2)}`}function Yf(e){return typeof e=="number"?$c(e):"no cap"}function zf(e){return e.length>0?e.join(", "):"all tools"}var p0=[" \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 g0(){return[...Wf(null),...p0].join(`
129
- `)}var Jf="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 h0(e){let t=Math.max(5,...e.map(([o])=>o.length)),n=Math.max(5,...e.map(([,o])=>o.length)),r=`+-${"-".repeat(t)}-+-${"-".repeat(n)}-+`,s=(o,i)=>`| ${o.padEnd(t)} | ${i.padEnd(n)} |`;return[r,s("Field","Value"),r,...e.map(([o,i])=>s(o,i)),r]}function Xf(e,t={}){let n=t.authUrl??"https://auth.visacli.sh",r=[...g0().split(`
130
- `),"","Visa Key active","Scoped agent spend credential ready for apps and agents","",...h0([["Key",e.key],["Label",e.label],["Owner",e.owner],["Daily cap",`${$c(e.daily_cap_cents)}/day`],["Total cap",Yf(e.total_cap_cents)],["Allowed tools",zf(e.allowed_tools)]]),"","Guardrails",`- Spend: ${$c(e.daily_cap_cents)}/day, ${Yf(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("",Jf,`Server warning: ${e.biometric_warning}`):e.biometric_enabled&&r.push("",Jf),`${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 Ys(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:yf("Visa HUD already registered in ~/.claude/settings.json.",e)}:{installed:"other-hud-present",message:Gb("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:yf(`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 Tc(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 wf=R(require("os")),Sf=R(require("path"));function Ft(e=wf.homedir()){return Sf.join(e,".claude","settings.json")}var Ht=R(require("fs")),_t=R(require("path"));var Wb=1,Zn={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},Yb=["terminal","claude","claude-code","all"];function yi(e){let t=e.toLowerCase();return Yb.includes(t)?t:null}var zb=50,Jb=64*1024,xf=10,Rc=80,M={get reset(){return $e().reset},get visaBlue(){return $e().visaBlue},get visaBlueSoft(){return $e().visaBlueSoft},get visaGold(){return $e().visaGold},get green(){return $e().green},get muted(){return $e().muted},get chrome(){return $e().chrome}};function L(e,t){return e.length===0||process.env.NO_COLOR||si()?e:`${t}${e}${M.reset}`}function Cf(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function Tf(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)},zb);e.on("data",i),e.on("end",a),e.on("error",c)})}function zs(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||"",M.visaBlueSoft)}${L(s||"",M.chrome)}`}function Js(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 Xb(e){if(Df(e))return Qb(e);let t=` ${L("\u2502",M.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}`,M.visaBlueSoft)}`:"",a=[L(`[${n}]`,M.visaBlueSoft)];o&&a.push(`${L(o,M.visaGold)}${i}`);let c=ge(e.git_branch??e.branch??"");c&&a.push(`${L("git:(",M.muted)}${L(c,M.visaBlueSoft)}${L(")",M.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(A=>typeof A=="number"&&Number.isFinite(A)),p=m.length>0?m.reduce((A,y)=>A+y,0):null,h=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,h/u)):0,I=d!==null&&u>0?Math.round(v*u):h,_;if(u>0||d!==null){let A=`${String(Math.round(v*100)).padStart(2," ")}%`,y=u>0?` ${L(`(${Js(I)}/${Js(u)})`,M.muted)}`:"";_=`${L("Context",M.muted)} ${zs(v)} ${L(A,M.green)}${y}`}else _=`${L("Context",M.muted)} ${L("-",M.muted)}`;let b=Rf(e.rate_limits),w=[_];b&&w.push(b);let T=w.join(t);return`${l}
118
+ ${T}`}function Zb(e){if(Df(e))return null;let t=` ${L("\u2502",M.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}`,M.visaBlueSoft)}`:"",a=[L(`[${n}]`,M.visaBlueSoft)];o&&a.push(`${L(o,M.visaGold)}${i}`);let c=ge(e.git_branch??e.branch??"");c&&a.push(`${L("git:(",M.muted)}${L(c,M.visaBlueSoft)}${L(")",M.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(w=>typeof w=="number"&&Number.isFinite(w)),m=f.length>0?f.reduce((w,T)=>w+T,0):null,p=Number(e.context_window?.total_input_tokens??m??d?.input_tokens??0),h=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(h*l):p,I;if(l>0||u!==null){let w=`${String(Math.round(h*100)).padStart(2," ")}%`,T=l>0?` ${L(`(${Js(v)}/${Js(l)})`,M.muted)}`:"";I=`${L("Context",M.muted)} ${zs(h)} ${L(w,M.green)}${T}`}else I=`${L("Context",M.muted)} ${L("-",M.muted)}`;let _=Rf(e.rate_limits),b=[I];return _&&b.push(_),{identity:a.join(t),metrics:b.join(t)}}function Qb(e){let t=` ${L("\u2502",M.chrome)} `,n=jf(e),r=n.model||"codex",s=[L(`[${r}]`,M.visaBlueSoft)];n.project&&s.push(L(n.project,M.visaGold)),n.gitBranch&&s.push(`${L("git",M.muted)} ${L(n.gitBranch,M.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",M.muted)} ${zs(c)} ${L(`${Math.round(n.contextUsedPercent)}%`,M.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",M.muted)} ${zs(l)} ${L(`${Math.round(c)}%`,M.green)}`)}typeof n.usedTokens=="number"&&i.push(`${L("Tokens",M.muted)} ${Js(n.usedTokens)}`),n.status&&i.push(`${L("Status",M.muted)} ${L(n.status,M.visaBlueSoft)}`),n.threadTitle&&i.push(`${L("Thread",M.muted)} ${L(n.threadTitle,M.visaBlueSoft)}`);let a=i.length>0?i.join(t):`${L("Context",M.muted)} ${L("-",M.muted)}`;return`${o}
119
+ ${a}`}function e0(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 Ef(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=zs(r),o=n>=90?"\x1B[38;5;196m":n>=70?M.visaGold:M.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=e0(e.resets_at),c=a?` ${L(`(${a} / ${t})`,M.muted)}`:` ${L(`(${t})`,M.muted)}`;return`${s} ${L(i,o)}${c}`}function Rf(e){if(!e)return null;let t=Ef(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?Ef(e.seven_day,"7d"):null;if(!t&&!r)return null;let s=` ${L("\u2502",M.chrome)} `,o=[t,r].filter(Boolean);return`${L("Usage",M.muted)} ${o.join(s)}`}function If(e){let t;try{let n=Ht.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let s=Math.min(r,Jb),o=r-s;t=Ht.openSync(e,"r");let i=Buffer.alloc(s);Ht.readSync(t,i,0,s,o);let a=i.toString("utf-8");if(o>0){let c=Buffer.alloc(1);if(Ht.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{Ht.closeSync(t)}catch{}}}function t0(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 n0(e){let t=e.split(`
121
+ `),n=[],r=new Set;for(let s=t.length-1;s>=0&&n.length<xf*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:t0(d.input),running:m})}}}return n.reverse(),n.slice(Math.max(0,n.length-xf))}function r0(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 s0(e){let t=e.running?L("\u25D0",M.visaGold):L("\u2713",M.green),n=e.running?M.visaGold:M.visaBlueSoft,r=L(ge(e.name),n),s=e.target?ge(e.target):"",o=s?`${L(":",M.chrome)} ${L(s,M.muted)}`:"",i=e.count>1?` ${L(`\xD7${e.count}`,M.muted)}`:"";return o?`${t} ${r}${o}${i}`:`${t} ${r}${i}`}function o0(e){let t=` ${L("\u2502",M.chrome)} `,n=Cf(t),r=e.slice();for(;r.length>0;){let c=r.join(t);if(Cf(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,M.muted)}${t}${a}`}async function Af(e){if(!e||typeof e!="string")return null;let t=If(e);if(!t)return null;let n;try{n=n0(t)}catch{return null}if(n.length===0)return null;let s=r0(n).map(s0);return o0(s)||null}async function $f(e,t,n){return(await Of(e,t,n)).join(`
122
+ `)}function Pf(e,t,n){let r=!!t?.activeSession||e.includes("in session"),s=n?a0(n):!1;return{isActive:r||s,hasSession:r,hasToolActivity:s}}async function Of(e,t,n){let{isActive:r}=Pf(e,n,t?.transcript_path),s=e.split(`
123
+ `).filter(a=>a.length>0),i=t&&!r?s.map(a=>L(Ic(a),M.muted)):[...s];if(t){let a=Zb(t);if(a){if(i.push(a.identity),t.transcript_path){let c=await Af(t.transcript_path);c&&i.push(...c.split(`
124
+ `))}i.push(a.metrics)}else{let c=Xb(t);if(c&&i.push(...c.split(`
125
+ `)),t.transcript_path){let l=await Af(t.transcript_path);l&&i.push(...l.split(`
126
+ `))}}}return i}var i0=["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 a0(e){let t=If(e);if(!t)return!1;let n=t.slice(-16384).toLowerCase();return i0.some(r=>n.includes(`"${r}"`))}async function Nf(e,t,n){let r=await Of(e,t,n),s=r.join(`
127
+ `),{isActive:o}=Pf(e,n,t?.transcript_path);return{schemaVersion:Wb,client:t?Uf(t):Zn.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?jf(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 Mf(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 Lf(e){return ge(e.cwd??e.current_dir??e.project_root)}function kf(e){let t=ge(e.project);if(t)return t;let n=Lf(e);if(n)return ge(_t.basename(n));let r=_i(e.workspace);return r||""}function ot(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function Uf(e){let t=Mf(e).toLowerCase();return t.includes("codex")?Zn.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?Zn.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||ot(e.context_used)!==void 0?Zn.CODEX:Zn.UNKNOWN}function Df(e){return Uf(e)===Zn.CODEX}function jf(e){let t=Mf(e),n=Lf(e),r=_i(e.workspace),s=ot(e.context_used)??ot(e.context_window?.used_percentage??void 0),o=ot(e.context_remaining)??ot(e.context_window?.remaining_percentage??void 0);return{...t?{app:t}:{},...hi(e)?{model:hi(e)}:{},...kf(e)?{project:kf(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}:{},...ot(e.used_tokens)!==void 0?{usedTokens:ot(e.used_tokens)}:{},...ot(e.total_input_tokens)!==void 0?{totalInputTokens:ot(e.total_input_tokens)}:{},...ot(e.total_output_tokens)!==void 0?{totalOutputTokens:ot(e.total_output_tokens)}:{}}}function Ic(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}var Ff=R(require("path"));function Bf(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: ${Bf(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=Ff.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: ${Bf(c)}`)}}return{ok:i,messages:n,errors:r}}function Hf(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 Vf=R(require("os")),qf=require("node:readline/promises"),Xs={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,qf.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 c0(e,t){return e.replace(/[\x00-\x1F\x7F\u202A-\u202E\u2066-\u2069]/g,"").trim()||t}function Kf(e=Vf.hostname()){let t=Ls().version,n=c0(e,"this-machine");return[" Preview if installed (sample):",` VISA CLI v${t} | ${n} | ${Xs.card}`,` ${Xs.balance} | ${Xs.spentToday} | ${Xs.lastActivity}`,` [${Xs.model}] | you`," Activity live"].join(`
128
+ `)}function Gf(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 Wf(e){return typeof e=="number"?Oc(e):"no cap"}function Yf(e){return e.length>0?e.join(", "):"all tools"}var l0=[" \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 u0(){return[...Gf(null),...l0].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 d0(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 Jf(e,t={}){let n=t.authUrl??"https://auth.visacli.sh",r=[...u0().split(`
130
+ `),"","Visa Key active","Scoped agent spend credential ready for apps and agents","",...d0([["Key",e.key],["Label",e.label],["Owner",e.owner],["Daily cap",`${Oc(e.daily_cap_cents)}/day`],["Total cap",Wf(e.total_cap_cents)],["Allowed tools",Yf(e.allowed_tools)]]),"","Guardrails",`- Spend: ${Oc(e.daily_cap_cents)}/day, ${Wf(e.total_cap_cents)} total`,`- Tools: ${Yf(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(`
131
131
  `)}
132
- `}function Zf(e){return e.json===!0||e.isTTY!==!0}function Pc(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 Oc(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 Qf(e,t){let n=Pc(e);if(n!==void 0)return n;if(Zf(t))return 500}function em(e,t){let n=Oc(e);if(n!==void 0)return n;if(Zf(t)||t.recommendedCapsAccepted===!0)return 2500}async function _t(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 Qn=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},Wr=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}},Ft=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}},bt=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}},ot=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 tm={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 Yr(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&&tm[n]?tm[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.`}Ht();var w0=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function sm(e,t){let n=rm(e),r=rm(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:S0(n.pre,r.pre)>0}function rm(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(w0);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function S0(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 vt(){return!!(om(process.env.VISA_CLI_NO_UPDATE_CHECK)||om(process.env.CI)||process.env.NODE_ENV==="test")}function om(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}qt();var P0="CARD_REENROLLMENT_REQUIRED",O0="https://auth.visacli.sh/enroll-card";function N0(){try{return new URL("/enroll-card",$e()).toString()}catch{return O0}}function M0(e){let t=N0();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="4.0.0-rc.15",L0=/^(?:VisaKey_[A-Za-z0-9_-]{16,128}|visakey_[A-Za-z0-9_-]{16,128}|vk_[A-Za-z0-9_-]{32,128})$/;async function eo(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 to(e,t){let n=typeof t?.error=="string"&&t.error||typeof t?.message=="string"&&t.message||"";return n?new Error(n):e>=500||e===408||e===425||e===429?new Error(`Request failed (${e}). Try again.`):e===404?new Error(`Request failed (${e}) \u2014 not found; check the identifier or slug.`):new Error(`Request failed (${e}).`)}function U0(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 qc(e){return e==="TOPUP_CHARGE_AMBIGUOUS"||e==="TOPUP_RECONCILIATION_REQUIRED"?e:null}var D0="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function zr(e){return typeof e=="string"?e.trim():""}function no(e){let t=e&&typeof e=="object"?e:{},n=zr(t.error)||zr(t.message);if(!n)return D0;let r=zr(t.error_code),s=[["surface",zr(t.disabled_surface)],["flag",zr(t.flag)],["correlation_id",zr(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?L0.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={},!vt()){let r=t.headers.get("X-Latest-Version");r&&sm(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 Qn(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 _t(`${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(Yr(d))}if(this.parseServerSignals(l),l.status===401)throw await eo(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===P0){let f=typeof u?.last4=="string"?u.last4:"",m=typeof u?.brand=="string"?u.brand:"card",p=M0(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=qc(u?.error_code);if(d)throw new ot(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 to(l.status,u)}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 _t(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(p){throw new Error(Yr(p))}if(this.parseServerSignals(d),d.status===401)throw await eo(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 b=Number(d.headers.get("Retry-After"))||1;throw new Ft(m?.message||m?.error||"Session budget is being modified by another request. Retry shortly.",b,d.status)}throw new Error(no(m))}let p=U0(m?.error_code);if(p||d.status===410){let b=p??"BUDGET_CLOSED";throw new Wr(m?.message||m?.error||"Your session was invalidated by the server.",b,{budgetId:n.session_budget_id,status:d.status})}if(m?.declined){let b=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(b)&&b>0?b:void 0)}let g=qc(m?.error_code);throw g?new ot(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}):to(d.status,m)}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 _t(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(p){throw new Error(Yr(p))}if(this.parseServerSignals(d),d.status===401)throw await eo(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 bt("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 bt(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 b=Number(d.headers.get("Retry-After"))||1;throw new Ft(m?.message||m?.error||"Session budget is being modified by another request. Retry shortly.",b,d.status)}throw new Error(no(m))}if(m?.declined){let b=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(b)&&b>0?b:void 0)}let g=qc(m?.error_code);throw g?new ot(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}):to(d.status,m)}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 _t(`${this.baseUrl}${n}`,{method:"POST",headers:s,body:JSON.stringify(o),timeoutMs:void 0})}catch(u){throw new Error(Yr(u))}if(this.parseServerSignals(i),i.status===401)throw await eo(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 bt("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 bt(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 to(i.status,a)}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 _t(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(p){throw new Error(Yr(p))}if(this.parseServerSignals(d),d.status===401)throw await eo(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 Ft(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 to(d.status,m)}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 _t(`${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 _t(`${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 bm(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 _m(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function j0(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 B0(e){return Math.max(4,e.reduce((t,n)=>Math.max(t,n.id.length),0))}function F0(e){return Math.max(8,Math.min(14,e.reduce((t,n)=>Math.max(t,(n.category||"").length),0)))}function H0(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 vm(e){let t=B0(e),n=7,r=F0(e),s=H0(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)} ${_m(o.category||"other",r).padEnd(r)} ${_m(bm(o),s)}`)}function wm(e){console.log(`
132
+ `}function Xf(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 Mc(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 Zf(e,t){let n=Nc(e);if(n!==void 0)return n;if(Xf(t))return 500}function Qf(e,t){let n=Mc(e);if(n!==void 0)return n;if(Xf(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 Qn=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},zr=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}},Vt=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}},it=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 em={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 Jr(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&&em[n]?em[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.`}qt();var h0=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function rm(e,t){let n=nm(e),r=nm(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:y0(n.pre,r.pre)>0}function nm(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(h0);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function y0(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 wt(){return!!(sm(process.env.VISA_CLI_NO_UPDATE_CHECK)||sm(process.env.CI)||process.env.NODE_ENV==="test")}function sm(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}St();var k0="CARD_REENROLLMENT_REQUIRED",T0="https://auth.visacli.sh/enroll-card";function R0(){try{return new URL("/enroll-card",Se()).toString()}catch{return T0}}function I0(e){let t=R0();if(typeof e!="string")return t;try{let n=new URL(e),r=new URL(t);if(n.origin===r.origin&&n.pathname==="/enroll-card")return n.toString()}catch{}return g.warn("card-reenroll:reenroll_url_rejected_fallback",{reason:"untrusted_or_malformed_reenroll_url",fallbackPath:"/enroll-card"}),t}var Sn="4.0.0-rc.16",$0=/^(?:VisaKey_[A-Za-z0-9_-]{16,128}|visakey_[A-Za-z0-9_-]{16,128}|vk_[A-Za-z0-9_-]{32,128})$/;async function to(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 no(e,t){let n=typeof t?.error=="string"&&t.error||typeof t?.message=="string"&&t.message||"";return n?new Error(n):e>=500||e===408||e===425||e===429?new Error(`Request failed (${e}). Try again.`):e===404?new Error(`Request failed (${e}) \u2014 not found; check the identifier or slug.`):new Error(`Request failed (${e}).`)}function P0(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 O0="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function Xr(e){return typeof e=="string"?e.trim():""}function ro(e){let t=e&&typeof e=="object"?e:{},n=Xr(t.error)||Xr(t.message);if(!n)return O0;let r=Xr(t.error_code),s=[["surface",Xr(t.disabled_surface)],["flag",Xr(t.flag)],["correlation_id",Xr(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?$0.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 Ke=class{constructor(t){this.getSessionToken=t;this.baseUrl=Se()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!wt()){let r=t.headers.get("X-Latest-Version");r&&rm(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 Qn(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(Jr(d))}if(this.parseServerSignals(l),l.status===401)throw await to(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===k0){let f=typeof u?.last4=="string"?u.last4:"",m=typeof u?.brand=="string"?u.brand:"card",p=I0(u?.reenroll_url),h=f?`${m} ending in ${f}`:"your card";throw new Error(`Please re-add ${h} to keep payments running. Open: ${p}`)}let d=Gc(u?.error_code);if(d)throw new it(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 no(l.status,u)}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(Jr(p))}if(this.parseServerSignals(d),d.status===401)throw await to(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 Vt(m?.message||m?.error||"Session budget is being modified by another request. Retry shortly.",v,d.status)}throw new Error(ro(m))}let p=P0(m?.error_code);if(p||d.status===410){let v=p??"BUDGET_CLOSED";throw new zr(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 h=Gc(m?.error_code);throw h?new it(m?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",h,{transactionId:typeof m?.transactionId=="string"?m.transactionId:void 0,retryable:!!m?.retryable,reconciliationRequired:m?.reconciliation_required!==!1}):no(d.status,m)}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(Jr(p))}if(this.parseServerSignals(d),d.status===401)throw await to(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 Vt(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 h=Gc(m?.error_code);throw h?new it(m?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",h,{transactionId:typeof m?.transactionId=="string"?m.transactionId:void 0,retryable:!!m?.retryable,reconciliationRequired:m?.reconciliation_required!==!1}):no(d.status,m)}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(Jr(u))}if(this.parseServerSignals(i),i.status===401)throw await to(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 no(i.status,a)}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(Jr(p))}if(this.parseServerSignals(d),d.status===401)throw await to(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 Vt(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 no(d.status,m)}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 merchantDirectorySearch(t,n){let r=new URLSearchParams({provider:t.provider,q:t.q,protocol:t.protocol,max_price_usd:t.maxPriceUsd,limit:String(t.limit),offset:String(t.offset)});return this.request("GET",`/v1/merchant-directory/search?${r.toString()}`,void 0,void 0,n)}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 _m(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 ym(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function N0(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 M0(e){return Math.max(4,e.reduce((t,n)=>Math.max(t,n.id.length),0))}function L0(e){return Math.max(8,Math.min(14,e.reduce((t,n)=>Math.max(t,(n.category||"").length),0)))}function U0(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 bm(e){let t=M0(e),n=7,r=L0(e),s=U0(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)} ${ym(o.category||"other",r).padEnd(r)} ${ym(_m(o),s)}`)}function vm(e){console.log(`
134
134
  Merchant tools
135
- `),vm(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 Kc(e){console.log(`
135
+ `),bm(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(`
136
136
  Merchant tools
137
- `);for(let[t,n]of j0(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: ${bm(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 Sm(e,t){console.log(`
137
+ `);for(let[t,n]of N0(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: ${_m(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 wm(e,t){console.log(`
139
139
  ${e} tools
140
- `),vm(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 Gc(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 C={};jr(C,{BRAND:()=>pv,DIRTY:()=>nr,EMPTY_PATH:()=>G0,INVALID:()=>D,NEVER:()=>Zv,OK:()=>Pe,ParseStatus:()=>Ae,Schema:()=>H,ZodAny:()=>An,ZodArray:()=>Yt,ZodBigInt:()=>sr,ZodBoolean:()=>or,ZodBranded:()=>io,ZodCatch:()=>hr,ZodDate:()=>ir,ZodDefault:()=>gr,ZodDiscriminatedUnion:()=>Ei,ZodEffects:()=>Je,ZodEnum:()=>mr,ZodError:()=>Fe,ZodFirstPartyTypeKind:()=>j,ZodFunction:()=>Ti,ZodIntersection:()=>ur,ZodIssueCode:()=>S,ZodLazy:()=>dr,ZodLiteral:()=>fr,ZodMap:()=>ts,ZodNaN:()=>rs,ZodNativeEnum:()=>pr,ZodNever:()=>at,ZodNull:()=>cr,ZodNullable:()=>xt,ZodNumber:()=>rr,ZodObject:()=>He,ZodOptional:()=>Ye,ZodParsedType:()=>R,ZodPipeline:()=>ao,ZodPromise:()=>En,ZodReadonly:()=>yr,ZodRecord:()=>ki,ZodSchema:()=>H,ZodSet:()=>ns,ZodString:()=>Cn,ZodSymbol:()=>Qr,ZodTransformer:()=>Je,ZodTuple:()=>St,ZodType:()=>H,ZodUndefined:()=>ar,ZodUnion:()=>lr,ZodUnknown:()=>Wt,ZodVoid:()=>es,addIssueToContext:()=>k,any:()=>xv,array:()=>kv,bigint:()=>_v,boolean:()=>Om,coerce:()=>Xv,custom:()=>Im,date:()=>bv,datetimeRegex:()=>Tm,defaultErrorMap:()=>Kt,discriminatedUnion:()=>$v,effect:()=>Vv,enum:()=>Bv,function:()=>Uv,getErrorMap:()=>Jr,getParsedType:()=>wt,instanceof:()=>hv,intersection:()=>Pv,isAborted:()=>Ci,isAsync:()=>Xr,isDirty:()=>Ai,isValid:()=>xn,late:()=>gv,lazy:()=>Dv,literal:()=>jv,makeIssue:()=>oo,map:()=>Mv,nan:()=>yv,nativeEnum:()=>Fv,never:()=>Av,null:()=>Sv,nullable:()=>Kv,number:()=>Pm,object:()=>Tv,objectUtil:()=>Wc,oboolean:()=>Jv,onumber:()=>zv,optional:()=>qv,ostring:()=>Yv,pipeline:()=>Wv,preprocess:()=>Gv,promise:()=>Hv,quotelessJson:()=>V0,record:()=>Nv,set:()=>Lv,setErrorMap:()=>K0,strictObject:()=>Rv,string:()=>$m,symbol:()=>vv,transformer:()=>Vv,tuple:()=>Ov,undefined:()=>wv,union:()=>Iv,unknown:()=>Cv,util:()=>V,void:()=>Ev});var V;(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})(V||(V={}));var Wc;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Wc||(Wc={}));var R=V.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),wt=e=>{switch(typeof e){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(e)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(e)?R.array:e===null?R.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?R.promise:typeof Map<"u"&&e instanceof Map?R.map:typeof Set<"u"&&e instanceof Set?R.set:typeof Date<"u"&&e instanceof Date?R.date:R.object;default:return R.unknown}};var S=V.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"]),V0=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,V.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 q0=(e,t)=>{let n;switch(e.code){case S.invalid_type:e.received===R.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case S.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,V.jsonStringifyReplacer)}`;break;case S.unrecognized_keys:n=`Unrecognized key(s) in object: ${V.joinValues(e.keys,", ")}`;break;case S.invalid_union:n="Invalid input";break;case S.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${V.joinValues(e.options)}`;break;case S.invalid_enum_value:n=`Invalid enum value. Expected ${V.joinValues(e.options)}, received '${e.received}'`;break;case S.invalid_arguments:n="Invalid function arguments";break;case S.invalid_return_type:n="Invalid function return type";break;case S.invalid_date:n="Invalid date";break;case S.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}"`:V.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case S.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 S.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 S.custom:n="Invalid input";break;case S.invalid_intersection_types:n="Intersection results could not be merged";break;case S.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case S.not_finite:n="Number must be finite";break;default:n=t.defaultError,V.assertNever(e)}return{message:n}},Kt=q0;var xm=Kt;function K0(e){xm=e}function Jr(){return xm}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}},G0=[];function k(e,t){let n=Jr(),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 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"}),nr=e=>({status:"dirty",value:e}),Pe=e=>({status:"valid",value:e}),Ci=e=>e.status==="aborted",Ai=e=>e.status==="dirty",xn=e=>e.status==="valid",Xr=e=>typeof Promise<"u"&&e instanceof Promise;var N;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(N||(N={}));var ze=class{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},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 H=class{get description(){return this._def.description}_getType(t){return wt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:wt(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:wt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Xr(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:wt(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:wt(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:wt(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(Xr(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:S.custom,...r(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new Je({schema:this,typeName:j.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Ye.create(this,this._def)}nullable(){return xt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yt.create(this)}promise(){return En.create(this,this._def)}or(t){return lr.create([this,t],this._def)}and(t){return ur.create(this,t,this._def)}transform(t){return new Je({...B(this._def),schema:this,typeName:j.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new gr({...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 hr({...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 yr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},W0=/^c[^\s-]{8,}$/i,Y0=/^[0-9a-z]+$/,z0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,J0=/^[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,X0=/^[a-z0-9_-]{21}$/i,Z0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Q0=/^[-+]?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)?)??$/,ev=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,tv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Yc,nv=/^(?:(?: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])$/,rv=/^(?:(?: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])$/,sv=/^(([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]))$/,ov=/^(([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])$/,iv=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,av=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Em="((\\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])))",cv=new RegExp(`^${Em}$`);function km(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 lv(e){return new RegExp(`^${km(e)}$`)}function Tm(e){let t=`${Em}T${km(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 uv(e,t){return!!((t==="v4"||!t)&&nv.test(e)||(t==="v6"||!t)&&sv.test(e))}function dv(e,t){if(!Z0.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 fv(e,t){return!!((t==="v4"||!t)&&rv.test(e)||(t==="v6"||!t)&&ov.test(e))}var Cn=class e extends H{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==R.string){let o=this._getOrReturnCtx(t);return k(o,{code:S.invalid_type,expected:R.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:S.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:S.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:S.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&k(s,{code:S.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")ev.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"email",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")Yc||(Yc=new RegExp(tv,"u")),Yc.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"emoji",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")J0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"uuid",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")X0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"nanoid",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")W0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"cuid",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")Y0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"cuid2",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")z0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"ulid",code:S.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:S.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:S.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:S.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:S.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:S.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?Tm(o).test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{code:S.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?cv.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{code:S.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?lv(o).test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{code:S.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?Q0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"duration",code:S.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?uv(t.data,o.version)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"ip",code:S.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?dv(t.data,o.alg)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"jwt",code:S.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?fv(t.data,o.version)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"cidr",code:S.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?iv.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"base64",code:S.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?av.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"base64url",code:S.invalid_string,message:o.message}),r.dirty()):V.assertNever(o);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:S.invalid_string,...N.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...N.errToObj(t)})}url(t){return this._addCheck({kind:"url",...N.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...N.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...N.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...N.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...N.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...N.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...N.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...N.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...N.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...N.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...N.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...N.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,...N.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,...N.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...N.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...N.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...N.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...N.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...N.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...N.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...N.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...N.errToObj(n)})}nonempty(t){return this.min(1,N.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}};Cn.create=e=>new Cn({checks:[],typeName:j.ZodString,coerce:e?.coerce??!1,...B(e)});function mv(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 rr=class e extends H{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)!==R.number){let o=this._getOrReturnCtx(t);return k(o,{code:S.invalid_type,expected:R.number,received:o.parsedType}),D}let r,s=new Ae;for(let o of this._def.checks)o.kind==="int"?V.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),k(r,{code:S.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:S.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:S.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?mv(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),k(r,{code:S.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:S.not_finite,message:o.message}),s.dirty()):V.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,N.toString(n))}gt(t,n){return this.setLimit("min",t,!1,N.toString(n))}lte(t,n){return this.setLimit("max",t,!0,N.toString(n))}lt(t,n){return this.setLimit("max",t,!1,N.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:N.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:N.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:N.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:N.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.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"&&V.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)}};rr.create=e=>new rr({checks:[],typeName:j.ZodNumber,coerce:e?.coerce||!1,...B(e)});var sr=class e extends H{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)!==R.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:S.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:S.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:S.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):V.assertNever(o);return{status:s.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return k(n,{code:S.invalid_type,expected:R.bigint,received:n.parsedType}),D}gte(t,n){return this.setLimit("min",t,!0,N.toString(n))}gt(t,n){return this.setLimit("min",t,!1,N.toString(n))}lte(t,n){return this.setLimit("max",t,!0,N.toString(n))}lt(t,n){return this.setLimit("max",t,!1,N.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:N.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:N.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:N.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}};sr.create=e=>new sr({checks:[],typeName:j.ZodBigInt,coerce:e?.coerce??!1,...B(e)});var or=class extends H{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==R.boolean){let r=this._getOrReturnCtx(t);return k(r,{code:S.invalid_type,expected:R.boolean,received:r.parsedType}),D}return Pe(t.data)}};or.create=e=>new or({typeName:j.ZodBoolean,coerce:e?.coerce||!1,...B(e)});var ir=class e extends H{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==R.date){let o=this._getOrReturnCtx(t);return k(o,{code:S.invalid_type,expected:R.date,received:o.parsedType}),D}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return k(o,{code:S.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:S.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:S.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):V.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:N.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:N.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}};ir.create=e=>new ir({checks:[],coerce:e?.coerce||!1,typeName:j.ZodDate,...B(e)});var Qr=class extends H{_parse(t){if(this._getType(t)!==R.symbol){let r=this._getOrReturnCtx(t);return k(r,{code:S.invalid_type,expected:R.symbol,received:r.parsedType}),D}return Pe(t.data)}};Qr.create=e=>new Qr({typeName:j.ZodSymbol,...B(e)});var ar=class extends H{_parse(t){if(this._getType(t)!==R.undefined){let r=this._getOrReturnCtx(t);return k(r,{code:S.invalid_type,expected:R.undefined,received:r.parsedType}),D}return Pe(t.data)}};ar.create=e=>new ar({typeName:j.ZodUndefined,...B(e)});var cr=class extends H{_parse(t){if(this._getType(t)!==R.null){let r=this._getOrReturnCtx(t);return k(r,{code:S.invalid_type,expected:R.null,received:r.parsedType}),D}return Pe(t.data)}};cr.create=e=>new cr({typeName:j.ZodNull,...B(e)});var An=class extends H{constructor(){super(...arguments),this._any=!0}_parse(t){return Pe(t.data)}};An.create=e=>new An({typeName:j.ZodAny,...B(e)});var Wt=class extends H{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Pe(t.data)}};Wt.create=e=>new Wt({typeName:j.ZodUnknown,...B(e)});var at=class extends H{_parse(t){let n=this._getOrReturnCtx(t);return k(n,{code:S.invalid_type,expected:R.never,received:n.parsedType}),D}};at.create=e=>new at({typeName:j.ZodNever,...B(e)});var es=class extends H{_parse(t){if(this._getType(t)!==R.undefined){let r=this._getOrReturnCtx(t);return k(r,{code:S.invalid_type,expected:R.void,received:r.parsedType}),D}return Pe(t.data)}};es.create=e=>new es({typeName:j.ZodVoid,...B(e)});var Yt=class e extends H{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==R.array)return k(n,{code:S.invalid_type,expected:R.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?S.too_big:S.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:S.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:S.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>s.type._parseAsync(new ze(n,i,n.path,a)))).then(i=>Ae.mergeArray(r,i));let o=[...n.data].map((i,a)=>s.type._parseSync(new ze(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:N.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:N.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:N.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 Zr(e){if(e instanceof He){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Ye.create(Zr(r))}return new He({...e._def,shape:()=>t})}else return e instanceof Yt?new Yt({...e._def,type:Zr(e.element)}):e instanceof Ye?Ye.create(Zr(e.unwrap())):e instanceof xt?xt.create(Zr(e.unwrap())):e instanceof St?St.create(e.items.map(t=>Zr(t))):e}var He=class e extends H{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=V.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==R.object){let l=this._getOrReturnCtx(t);return k(l,{code:S.invalid_type,expected:R.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 at&&this._def.unknownKeys==="strip"))for(let l in s.data)i.includes(l)||a.push(l);let c=[];for(let l of i){let u=o[l],d=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new ze(s,d,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof at){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:S.unrecognized_keys,keys:a}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let d=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new ze(s,d,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,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 N.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:N.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 V.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 V.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return Zr(this)}partial(t){let n={};for(let r of V.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 V.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof Ye;)o=o._def.innerType;n[r]=o}return new e({...this._def,shape:()=>n})}keyof(){return Rm(V.objectKeys(this.shape))}};He.create=(e,t)=>new He({shape:()=>e,unknownKeys:"strip",catchall:at.create(),typeName:j.ZodObject,...B(t)});He.strictCreate=(e,t)=>new He({shape:()=>e,unknownKeys:"strict",catchall:at.create(),typeName:j.ZodObject,...B(t)});He.lazycreate=(e,t)=>new He({shape:e,unknownKeys:"strip",catchall:at.create(),typeName:j.ZodObject,...B(t)});var lr=class extends H{_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:S.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:S.invalid_union,unionErrors:a}),D}}get options(){return this._def.options}};lr.create=(e,t)=>new lr({options:e,typeName:j.ZodUnion,...B(t)});var Gt=e=>e instanceof dr?Gt(e.schema):e instanceof Je?Gt(e.innerType()):e instanceof fr?[e.value]:e instanceof mr?e.options:e instanceof pr?V.objectValues(e.enum):e instanceof gr?Gt(e._def.innerType):e instanceof ar?[void 0]:e instanceof cr?[null]:e instanceof Ye?[void 0,...Gt(e.unwrap())]:e instanceof xt?[null,...Gt(e.unwrap())]:e instanceof io||e instanceof yr?Gt(e.unwrap()):e instanceof hr?Gt(e._def.innerType):[],Ei=class e extends H{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==R.object)return k(n,{code:S.invalid_type,expected:R.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:S.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=wt(e),r=wt(t);if(e===t)return{valid:!0,data:e};if(n===R.object&&r===R.object){let s=V.objectKeys(t),o=V.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===R.array&&r===R.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===R.date&&r===R.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var ur=class extends H{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=(o,i)=>{if(Ci(o)||Ci(i))return D;let a=zc(o.value,i.value);return a.valid?((Ai(o)||Ai(i))&&n.dirty(),{status:n.value,value:a.data}):(k(r,{code:S.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}))}};ur.create=(e,t,n)=>new ur({left:e,right:t,typeName:j.ZodIntersection,...B(n)});var St=class e extends H{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==R.array)return k(r,{code:S.invalid_type,expected:R.array,received:r.parsedType}),D;if(r.data.length<this._def.items.length)return k(r,{code:S.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:S.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...r.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new ze(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>Ae.mergeArray(n,i)):Ae.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};St.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new St({items:e,typeName:j.ZodTuple,rest:null,...B(t)})};var ki=class e extends H{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!==R.object)return k(r,{code:S.invalid_type,expected:R.object,received:r.parsedType}),D;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in r.data)s.push({key:o._parse(new ze(r,a,r.path,a)),value:i._parse(new ze(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?Ae.mergeObjectAsync(n,s):Ae.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof H?new e({keyType:t,valueType:n,typeName:j.ZodRecord,...B(r)}):new e({keyType:Cn.create(),valueType:t,typeName:j.ZodRecord,...B(n)})}},ts=class extends H{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!==R.map)return k(r,{code:S.invalid_type,expected:R.map,received:r.parsedType}),D;let s=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([a,c],l)=>({key:s._parse(new ze(r,a,r.path,[l,"key"])),value:o._parse(new ze(r,c,r.path,[l,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return D;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let c of i){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return D;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}}}};ts.create=(e,t,n)=>new ts({valueType:t,keyType:e,typeName:j.ZodMap,...B(n)});var ns=class e extends H{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==R.set)return k(r,{code:S.invalid_type,expected:R.set,received:r.parsedType}),D;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(k(r,{code:S.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:S.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let o=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return D;u.status==="dirty"&&n.dirty(),l.add(u.value)}return{status:n.value,value:l}}let a=[...r.data.values()].map((c,l)=>o._parse(new ze(r,c,r.path,l)));return r.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(t,n){return new e({...this._def,minSize:{value:t,message:N.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:N.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};ns.create=(e,t)=>new ns({valueType:e,minSize:null,maxSize:null,typeName:j.ZodSet,...B(t)});var Ti=class e extends H{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==R.function)return k(n,{code:S.invalid_type,expected:R.function,received:n.parsedType}),D;function r(a,c){return oo({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Jr(),Kt].filter(l=>!!l),issueData:{code:S.invalid_arguments,argumentsError:c}})}function s(a,c){return oo({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Jr(),Kt].filter(l=>!!l),issueData:{code:S.invalid_return_type,returnTypeError:c}})}let o={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof En){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:St.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||St.create([]).rest(Wt.create()),returns:n||Wt.create(),typeName:j.ZodFunction,...B(r)})}},dr=class extends H{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})}};dr.create=(e,t)=>new dr({getter:e,typeName:j.ZodLazy,...B(t)});var fr=class extends H{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return k(n,{received:n.data,code:S.invalid_literal,expected:this._def.value}),D}return{status:"valid",value:t.data}}get value(){return this._def.value}};fr.create=(e,t)=>new fr({value:e,typeName:j.ZodLiteral,...B(t)});function Rm(e,t){return new mr({values:e,typeName:j.ZodEnum,...B(t)})}var mr=class e extends H{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return k(n,{expected:V.joinValues(r),received:n.parsedType,code:S.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:S.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})}};mr.create=Rm;var pr=class extends H{_parse(t){let n=V.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==R.string&&r.parsedType!==R.number){let s=V.objectValues(n);return k(r,{expected:V.joinValues(s),received:r.parsedType,code:S.invalid_type}),D}if(this._cache||(this._cache=new Set(V.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let s=V.objectValues(n);return k(r,{received:r.data,code:S.invalid_enum_value,options:s}),D}return Pe(t.data)}get enum(){return this._def.values}};pr.create=(e,t)=>new pr({values:e,typeName:j.ZodNativeEnum,...B(t)});var En=class extends H{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==R.promise&&n.common.async===!1)return k(n,{code:S.invalid_type,expected:R.promise,received:n.parsedType}),D;let r=n.parsedType===R.promise?n.data:Promise.resolve(n.data);return Pe(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};En.create=(e,t)=>new En({type:e,typeName:j.ZodPromise,...B(t)});var Je=class extends H{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"?nr(c.value):n.value==="dirty"?nr(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"?nr(a.value):n.value==="dirty"?nr(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);V.assertNever(s)}};Je.create=(e,t,n)=>new Je({schema:e,typeName:j.ZodEffects,effect:t,...B(n)});Je.createWithPreprocess=(e,t,n)=>new Je({schema:t,effect:{type:"preprocess",transform:e},typeName:j.ZodEffects,...B(n)});var Ye=class extends H{_parse(t){return this._getType(t)===R.undefined?Pe(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ye.create=(e,t)=>new Ye({innerType:e,typeName:j.ZodOptional,...B(t)});var xt=class extends H{_parse(t){return this._getType(t)===R.null?Pe(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};xt.create=(e,t)=>new xt({innerType:e,typeName:j.ZodNullable,...B(t)});var gr=class extends H{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===R.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};gr.create=(e,t)=>new gr({innerType:e,typeName:j.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...B(t)});var hr=class extends H{_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 Xr(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}};hr.create=(e,t)=>new hr({innerType:e,typeName:j.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...B(t)});var rs=class extends H{_parse(t){if(this._getType(t)!==R.nan){let r=this._getOrReturnCtx(t);return k(r,{code:S.invalid_type,expected:R.nan,received:r.parsedType}),D}return{status:"valid",value:t.data}}};rs.create=e=>new rs({typeName:j.ZodNaN,...B(e)});var pv=Symbol("zod_brand"),io=class extends H{_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 H{_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(),nr(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})}},yr=class extends H{_parse(t){let n=this._def.innerType._parse(t),r=s=>(xn(s)&&(s.value=Object.freeze(s.value)),s);return Xr(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};yr.create=(e,t)=>new yr({innerType:e,typeName:j.ZodReadonly,...B(t)});function Am(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Im(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=Am(t,r),c=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=Am(t,r),a=i.fatal??n??!0;s.addIssue({code:"custom",...i,fatal:a})}}):An.create()}var gv={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 hv=(e,t={message:`Input not instance of ${e.name}`})=>Im(n=>n instanceof e,t),$m=Cn.create,Pm=rr.create,yv=rs.create,_v=sr.create,Om=or.create,bv=ir.create,vv=Qr.create,wv=ar.create,Sv=cr.create,xv=An.create,Cv=Wt.create,Av=at.create,Ev=es.create,kv=Yt.create,Tv=He.create,Rv=He.strictCreate,Iv=lr.create,$v=Ei.create,Pv=ur.create,Ov=St.create,Nv=ki.create,Mv=ts.create,Lv=ns.create,Uv=Ti.create,Dv=dr.create,jv=fr.create,Bv=mr.create,Fv=pr.create,Hv=En.create,Vv=Je.create,qv=Ye.create,Kv=xt.create,Gv=Je.createWithPreprocess,Wv=ao.create,Yv=()=>$m().optional(),zv=()=>Pm().optional(),Jv=()=>Om().optional(),Xv={string:(e=>Cn.create({...e,coerce:!0})),number:(e=>rr.create({...e,coerce:!0})),boolean:(e=>or.create({...e,coerce:!0})),bigint:(e=>sr.create({...e,coerce:!0})),date:(e=>ir.create({...e,coerce:!0}))};var Zv=D;var Qv=/^[A-Za-z0-9._-]+$/,ew=/^[A-Za-z0-9._-]+(\|[A-Za-z0-9._-]+)*$/,Nm=new Set([".",".."]),je=class extends Error{pattern;constructor(t,n){super(`Invalid freeReadPathPattern ${JSON.stringify(n)}: ${t}`),this.pattern=n,this.name="FreePathPatternError"}};function tw(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(!ew.test(s))throw new je(`malformed alternation segment ${JSON.stringify(e)}`,t);let o=s.split("|");if(o.some(i=>Nm.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(Qv.test(e)){if(Nm.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 nw(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=>tw(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 Jc(e){nw(e)}var Mm=["tempo","mpp_self","merchant_self"],Lm=["catalog_static","fal_direct","fal_queue","openrouter_chat","openrouter_image","platform_proxy","tempo_gateway","x402_gateway"],Um=["image","audio","queued_audio","video","queued_video","model_3d","llm","transcription","utility"],Dm=["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 Zc=C.object({inputPerMillion:C.number().positive(),outputPerMillion:C.number().positive(),contextWindow:C.number().int().positive().optional(),maxOutput:C.number().int().positive().optional(),perRequestFeeCents:C.number().nonnegative().optional()}),rw=C.object({strategy:C.enum(["flat","token","band"]).optional(),pricingModel:C.enum(["per-call","per-token","band"]).optional(),priceCents:C.number().nonnegative().optional(),currency:C.string().optional(),display:C.string().optional(),estimate:C.boolean().optional(),source:C.string().optional(),priceBand:C.record(C.unknown()).optional(),tokenPricing:Zc.optional()}).passthrough(),Qc=C.discriminatedUnion("type",[C.object({type:C.literal("shortcut"),routedPath:C.string().min(1).startsWith("/")}),C.object({type:C.literal("custom"),merchantSlug:C.string().min(1),subPath:C.string().optional()}),C.object({type:C.literal("local"),fn:C.string().min(1)}),C.object({type:C.literal("read")})]),el=C.object({amount:C.number().nonnegative(),currency:C.string().length(3).optional(),display:C.string().optional(),free:C.boolean().optional(),batchDiscount:C.number().min(0).max(100).optional()}),jm=C.object({attestation:C.boolean().optional(),rateLimitMs:C.number().positive().optional()}),Bm=C.object({displayName:C.string().optional(),feedbackEligible:C.boolean().optional(),suggestionEligible:C.boolean().optional(),batchable:C.boolean().optional()}),Fm=C.object({enabled:C.boolean().optional(),gatewayPath:C.string().min(1).startsWith("/").optional(),method:C.enum(["GET","POST","PUT","PATCH","DELETE"]).optional(),timeoutMs:C.number().int().positive().max(12e4).optional()}).strict(),sw=C.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),ow=120,iw=120,aw=1200,cw=/^[^\u0000-\u001F\u007F]+$/;function Xc(e,t){return C.string().min(1).max(e).regex(cw,`${t} must not contain control characters`)}var tl={id:C.string().min(1),name:Xc(ow,"name"),description:Xc(aw,"description"),provider:C.string().min(1),model:C.string().min(1),category:sw,priceCents:C.number().nonnegative(),inputSchema:C.record(C.unknown()),gatewayUrl:C.string().min(1),merchantName:Xc(iw,"merchantName"),isAsync:C.boolean().optional(),pollUrl:C.string().optional(),pollInterval:C.number().positive().optional(),pollTimeout:C.number().positive().optional(),tags:C.array(C.string()).optional(),tokenPricing:Zc.optional(),priceDisplay:C.string().optional(),pricingModel:C.enum(["per-call","per-token","band"]).optional(),pricingInfo:rw.optional(),status:C.enum(["available","unavailable"]).optional(),handler:Qc.optional(),pricing:el.optional(),security:jm.optional(),engagement:Bm.optional(),gatewayConfig:Fm.optional(),freeReadPathPattern:C.string().optional().superRefine((e,t)=>{if(e!==void 0)try{Jc(e)}catch(n){t.addIssue({code:C.ZodIssueCode.custom,message:n instanceof Error?n.message:String(n)})}}),enabled:C.boolean().optional(),beta:C.boolean().optional(),deprecated:C.boolean().optional(),internal:C.boolean().optional(),employeeOnly:C.boolean().optional(),employeeOnlyRolloutFlag:C.string().min(1).max(100).optional(),replacementTool:C.string().optional(),minCliVersion:C.string().optional(),sunsetAt:C.string().optional(),rail:C.enum(Mm).optional(),executionKind:C.enum(Lm).optional(),resultKind:C.enum(Um).optional(),extractionMode:C.enum(Dm).optional(),pricingStrategy:C.enum(["flat","token","band"]).optional()},Hm=C.object({...tl,dispatch:C.literal("routed"),routedPath:C.string().min(1).startsWith("/")}).strict(),Vm=C.object({...tl,dispatch:C.literal("enveloped")}).strict(),qm=C.object({...tl,handler:Qc,pricing:el}).strict(),Km=C.union([C.discriminatedUnion("dispatch",[Hm,Vm]),qm]);var dw="https://fal.run",zm="https://openrouter.mpp.tempo.xyz",rl=1024,Ii=8192,fw=4096,mw=10;function pw(e){return e>=mw?fw:Ii}function Jm(e,t){let n=typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):rl;return Math.min(n,t)}var gw=["num_images","num_outputs","num_samples","num_videos","batch_size","n"];function Xm(e){for(let t of gw)delete e[t];return e}function hw(e){let{attestation:t,tool_id:n,...r}=e;return Xm(r)}var Gm={"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 Ri(e){let{attestation:t,tool_id:n,aspect_ratio:r,image_size:s,...o}=e,i=Xm({...o});return typeof s=="string"&&s.length>0?(i.image_size=s,i):(typeof r=="string"&&Gm[r]&&(i.image_size=Gm[r]),i)}function yw(e){let{attestation:t,tool_id:n,...r}=e;return r}function Wm(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 _w(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 bw(e,t,n,r,s,o,i,a){return _w(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:`${dw}/${r}`,merchantName:"fal.ai",buildBody:hw,tags:[],...a}}function Zm(e,t=Ii){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:Jm(c??l,t),usage:{include:!0}}}}function Qm(e,t=Ii){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,b=[{type:"text",text:o}];return typeof i=="string"&&i.length>0&&b.push({type:"image_url",image_url:{url:i}}),{messages:Array.isArray(f)?f:[{role:"user",content:b}],temperature:p??.7,...g,model:e,...typeof a=="string"&&a.length>0?{image_config:{aspect_ratio:a}}:{},max_tokens:Jm(c??l,t),usage:{include:!0}}}}function le(e,t,n,r,s,o,i){let a=i?.maxOutputTokens??pw(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: ${rl}); 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:Zm(r,a),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:s,outputPerMillion:o,...c>0?{perRequestFeeCents:c}:{}},...p}}function nl(e,t,n,r,s,o){let i=o?.maxOutputTokens??Ii,{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: ${rl}); 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:Qm(r,i),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...c}}var sl=[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:Ri}),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:Ri}),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:Ri}),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"]}),nl("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),nl("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}}),nl("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"]}),bw("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:Wm,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:yw,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=>Ri({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:Wm,tags:["onchain","prices","allium","crypto","legacy"]}];function co(e){return sl.find(t=>t.id===e)}var Sw=[{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 xw(e,t){let r=(Array.isArray(t.type)?t.type:t.type!==void 0?[t.type]:[]).flatMap(o=>Sw.filter(i=>i.type===o)),s=new Set(r.filter(o=>o.matches(e)).map(o=>o.type));return{declared:r,matched:s}}function ol(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}=xw(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 $a=I(os());var Mi=require("child_process"),mp=require("util"),pp=I(require("crypto")),ne=I(require("fs")),gp=I(require("os")),Oe=I(require("path"));Ht();var lt=(0,mp.promisify)(Mi.execFile),zw=6e4,Jw=()=>process.platform==="darwin",kn=()=>process.platform==="win32",Tn=Oe.join(gp.homedir(),".visa-mcp","bin"),_r=Oe.join(Tn,"Visa CLI"),Xt=Oe.join(Tn,"visa-keychain-win.exe"),hp=Oe.join(__dirname,"..","native"),sp="6",op=Oe.join(Tn,"visa-keychain.version"),ip=Oe.join(Tn,"visa-keychain.sha256"),ap="1",cp=Oe.join(Tn,"visa-keychain-win.version"),lp=Oe.join(Tn,"visa-keychain-win.sha256"),yp=[Oe.join(hp,"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 Pi(e){let t=ne.readFileSync(e);return pp.createHash("sha256").update(t).digest("hex")}function Xw(e){let t=e.trim();if(t.startsWith("OK:"))return t.slice(3);if(t==="OK")return;let n=t.startsWith("ERROR:")?t.slice(6):"Unknown error";throw new Error(n)}function up(e){let t=typeof e?.message=="string"?e.message:"";return e?.code==="ETIMEDOUT"||e?.killed===!0||/timed out|timeout/i.test(t)}function dp(e){let t=Math.max(1,Math.round(e/1e3));return new Error(`Timed out waiting for Touch ID/device approval after ${t}s.`)}async function il(){try{if(ne.readFileSync(op,"utf-8").trim()===sp&&ne.existsSync(_r)){let r=ne.readFileSync(ip,"utf-8").trim();if(Pi(_r)!==r)h.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),ne.unlinkSync(_r);else return _r}}catch{}let e=Oe.join(hp,"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(Tn,{recursive:!0,mode:448});try{await lt("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",_r,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=Pi(_r);return ne.writeFileSync(ip,t,{mode:384}),ne.writeFileSync(op,sp,{mode:384}),_r}function _p(){for(let e of yp)if(ne.existsSync(e))return e;return null}async function is(){try{if(ne.readFileSync(cp,"utf-8").trim()===ap&&ne.existsSync(Xt)){let r=ne.readFileSync(lp,"utf-8").trim();if(Pi(Xt)!==r)h.warn("binary:hash-mismatch:win32",{message:"Windows binary hash mismatch. Redeploying."}),ne.unlinkSync(Xt);else return Xt}}catch{}let e=_p();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(Tn,{recursive:!0}),ne.copyFileSync(e,Xt);let t=Pi(Xt);return ne.writeFileSync(lp,t,{mode:384}),ne.writeFileSync(cp,ap,{mode:384}),Xt}async function Zw(){return kn()?is():il()}var Oi="visa-cli",Ni="attestation-key";async function Qw(e){try{await lt("security",["delete-generic-password","-s",Oi,"-a",Ni],{timeout:5e3})}catch{}await lt("security",["add-generic-password","-s",Oi,"-a",Ni,"-w",e],{timeout:5e3})}function eS(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 tS(){try{let{stdout:e}=await lt("security",["find-generic-password","-s",Oi,"-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:eS(e)}}}async function al(){let e=await tS();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 bp(e){let t=await Zw(),n;try{n=(await lt(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?.toString().trim()||r.message||"Unknown error")}return Xw(n)}var fp=!1;function nS(){if(!kn())return!1;try{return ne.existsSync(Xt)||_p()!==null?!0:(fp||(fp=!0,h.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:Xt,searchedPrebuiltPaths:yp})),!1)}catch{return!1}}function de(){return Br()||Jw()?!0:kn()?nS():!1}async function Li(){if(kn()){let s=await is(),{stdout:o}=await lt(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 bp(["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 Qw(n),r}async function Ui(){if(kn())try{let e=await is(),{stdout:t}=await lt(e,["public-key"],{timeout:1e4});return t.trim().startsWith("OK:")}catch{return!1}return await al()!==null}async function vp(){if(Br())return"mock-public-key-spki";if(kn()){let n=await is(),{stdout:r}=await lt(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 al();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await il();return new Promise((n,r)=>{let s=(0,Mi.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?.toString().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(Br())return Promise.resolve(Od());let r=n.timeoutMs??zw;if(kn()){let a=await is(),c=["sign",e];t&&c.push(t);let l;try{l=(await lt(a,c,{timeout:r})).stdout}catch(d){throw up(d)?dp(r):d}let u=l.trim();if(u.startsWith("OK:"))return u.slice(3);throw new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error")}let s=await al();if(!s)throw new Error("Attestation key not found. Run setup to generate a new key.");let o=await il(),i=["sign",e];return t&&i.push(t),new Promise((a,c)=>{let l=(0,Mi.execFile)(o,i,{timeout:r},(u,d)=>{let f=(d||"").trim();if(u){f.startsWith("ERROR:")?c(new Error(f.slice(6))):up(u)?c(dp(r)):c(new Error(u.stderr?.toString().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 Di(){if(kn()){try{let e=await is();await lt(e,["delete-key"],{timeout:1e4})}catch{}return}try{await lt("security",["delete-generic-password","-s",Oi,"-a",Ni],{timeout:5e3})}catch{}try{await bp(["delete-key"])}catch{}}Ht();var rS=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],sS=[...rS.map(e=>({id:`legacy.${e}`,toolId:e,targetToolId:e,rail:"tempo",reason:"Preserve legacy Tempo _card target while the top-level MCP surface is opt-in."}))];function cl(e,t=sS){for(let n of t)if(n.toolId===e.requestedTool)return n.targetToolId;return null}function ll(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function wp(e=process.env){return ll(e)!==null}var oS=new Set(["false","0","no","off","disable","disabled"]),iS=new Set(["true","1","yes","on","enable","enabled"]);function Sp(e){let t=(e??"").trim().toLowerCase();return t?oS.has(t)?!1:!!iS.has(t):!0}function xp(e=process.env){return Sp(e.VISA_CLI_PARENTLESS_SINGLE_CALL)}function Cp(e=process.env){return Sp(e.VISA_CLI_PARENTLESS_BATCH)}var hy=require("child_process"),xe=I(require("crypto")),mt=I(require("fs")),Io=I(require("os")),Pa=I(require("path"));function Ct(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"?Fr(s):null,i=Array.isArray(n.urls)?n.urls[0]:void 0,c=typeof i=="string"&&i.startsWith("data:")?Fr(i):null;if(!o&&!c)return e;let l=o??c,u=o?"content":"urls",d;try{d=Ls(l,{tag:aS(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 aS(e,t){let n=typeof t.transactionId=="string"?t.transactionId:typeof t.transaction_id=="string"?t.transaction_id:null;return n?`${e}-${n}`:e}Ht();var ul=!1;async function br(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(ul)throw h.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;ul=!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 Li();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 ul=!1,a}catch(o){throw h.error("attestation:recovery-failure",{error:o.message}),r}}throw r}}function At(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}async function ji(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 Ui())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 At(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 Ap="4.0.0-rc.15";function dl(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function fl(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=wi(t);return s!==void 0?{value:s,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function Xe(e){return e==null?"\u2014":e?"yes":"no"}function Bi(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function cS(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function lS(){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=Vc("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:Fc,source:{kind:"default"}}}async function uo(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(E){n=E?.message||"unknown error"}let r=[],s=process.env.VISA_AUTH_URL,o=Hc("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:Xe(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:Xe(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:Xe(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:de(),formatted:Xe(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:Bi(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:Bi(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:Bi(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:Bi(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(E=>E.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=lS();r.push({key:"credit.sessionCapCents",value:m.value,formatted:cS(m.value),source:m.source});let p=pm();p.length>0&&r.push({key:"settings.retired",value:p.map(E=>E.key),formatted:p.map(E=>E.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${p.map(E=>`visa-cli config unset ${E.key}`).join(" && ")}`});let g=fl("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:g.value,formatted:Xe(g.value),source:g.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let b=fl("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:b.value,formatted:Xe(b.value),source:b.source});let A=vt(),_;process.env.VISA_CLI_NO_UPDATE_CHECK?_={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?_={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?_={kind:"env",var:"NODE_ENV"}:_={kind:"default"},r.push({key:"ui.updateCheck",value:!A,formatted:Xe(!A),source:_});let v=fl("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:v.value,formatted:Xe(v.value),source:v.source});let w=process.env.VISA_DRY_RUN,T=wp();if(r.push({key:"tools.dryRun",value:T,formatted:Xe(T),source:w===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:Ap,formatted:Ap,source:{kind:"default"}}),e.includeDev){let E=process.env.VISA_MOCK_KEYCHAIN,y=dn();r.push({key:"dev.mockKeychain",value:y,formatted:Xe(y),source:dl("VISA_MOCK_KEYCHAIN",!!E),hint:ec()});let x=process.env.VISA_MOCK_TOUCHID,Y=Br();r.push({key:"dev.mockTouchid",value:Y,formatted:Xe(Y),source:dl("VISA_MOCK_TOUCHID",!!x),hint:ec()});let X=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!X,formatted:Xe(!!X),source:dl("VISA_CLI_DEBUG",!!X)})}return{entries:r,statusError:n}}function uS(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 Ep(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}(${uS(o.source)})`),t.verbose&&o.hint&&s.push(` ${"\u21B3".padStart(n)} ${o.hint}`)}return s.join(`
144
- `)}function kp(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 Tp(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/1)} images. Try something now, or save them for later.`,balanceUsd:t,examples:[{tool:"fal-flux-schnell",cost:"$0.01",what:"an AI image"},{tool:"or-gpt-4o-mini",cost:"token-priced",what:"a quick model call"},{tool:"fal-ace-step-music",cost:"$0.02",what:"a music track"}]}}}qt();Ht();var In=require("fs"),Ip=require("os"),ml=require("path"),dS=(0,ml.join)((0,Ip.homedir)(),".visa-mcp"),Rp=(0,ml.join)(dS,"mcp-session-budget.json");function Fi(){try{(0,In.existsSync)(Rp)&&(0,In.unlinkSync)(Rp)}catch{}}var gl=require("crypto"),ut=I(os()),wr=null,Ke=0,Pn=0,Ve=0,$n=null,hl=null,yl=null,vr=Promise.resolve();function fS(e){return Number((0,ut.fromCents)(e))}function Pp(e){return(0,ut.toCents)((0,ut.micros)(BigInt(e)))}function $p(e){return(0,ut.toWire)((0,ut.fromCents)(e))}function pl(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Hi(e){return typeof e=="string"&&/^\d+$/.test(e)}var mS=43,pS=new RegExp(`^[A-Za-z0-9_-]{${mS}}$`);function gS(e){return typeof e=="string"&&pS.test(e)}function hS(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||wr&&e.session_id!==wr||typeof e.nonce!="string"||e.nonce.length===0||!gS(e.server_signature)||!pl(e.cumulative)||!pl(e.remaining)||!pl(e.delta)||e.cumulative<Ke||Ve>0&&e.cumulative>Ve||Ve>0&&e.remaining>Ve||e.cumulative_micros!==void 0&&!Hi(e.cumulative_micros)||e.remaining_micros!==void 0&&!Hi(e.remaining_micros)||e.delta_micros!==void 0&&!Hi(e.delta_micros)||e.reserved_micros!==void 0&&!Hi(e.reserved_micros))}function Zt(e){wr=e,Ke=0,Pn=0,Ve=0,$n=null,hl=null,yl=null,vr=Promise.resolve()}function fo(e){Ve=Math.max(0,Math.floor(e))}function _l(){return wr}function bl(e){if(!wr)return null;let t=Ke+Pn;return Ve>0&&t>Ve&&(t=Ve),{session_budget_id:wr,cumulative_micros:fS(t),nonce:(0,gl.randomUUID)(),idempotency_key:e||(0,gl.randomUUID)()}}function mo(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 hS(r)?(Ke=Math.max(Ke,r.cumulative),Pn=0,$n=r,r):null}function Op(){return $n}function vl(e){let t=Pp(e.cumulative_micros);Ke=Math.max(Ke,t),Pn=0;let n={status:"accepted",session_id:e.session_budget_id,cumulative:Ke,remaining:Math.max(0,Ve-Ke),delta:0,cumulative_micros:$p(Ke),remaining_micros:$p(Math.max(0,Ve-Ke)),delta_micros:"0",nonce:e.nonce};return $n=n,n}function po(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;hl=t;let s=e,o=typeof s.session_id=="string"?s.session_id:wr??"";$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 Np(e){let t=e.receipt??null;yl={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:Pp(e.voucher.cumulative_micros),estimatedCumulativeCents:Vi(),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 Mp(){return yl}function Lp(){return Ke}function Up(){return hl}function Vi(){let e=Ke+Pn;return Ve>0&&e>Ve&&(e=Ve),e}function wl(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return vr=vr.then(()=>{Pn+=t}),vr}function go(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return vr=vr.then(()=>{Pn=Math.max(0,Pn-t)}),vr}var yS=10,_S=1,fe=null,Dp=Promise.resolve();function Sl(e){let t=Dp.catch(()=>{}).then(e);return Dp=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 xl(e,t,n){return Sl(()=>jp(e,t,n))}async function jp(e,t,n){if(Fi(),fe&&new Date(fe.expiresAt).getTime()>Date.now())return _l()!==fe.budgetId&&(Zt(fe.budgetId),fo(fe.totalCents)),h.info("mcp-session:active-hit",{budgetId:fe.budgetId,tool:n.toolName,remainingEstimatedCents:fe.totalCents-Vi()}),{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"?_S:yS,i=Math.max(o,Math.ceil(n.minRequiredCents??o));if(r.balanceCents<i)throw new Se(r.balanceCents,i);let a=n.capCentsOverride??ym(),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),fo(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 Bp(e,t,n){return Sl(async()=>{let s=On()?await Fp(e):null,o=await jp(e,t,n);return{budgetId:o.budgetId,totalCents:o.totalCents,closedPrevious:s,requestedCapCents:o.requestedCapCents,appliedCapCents:o.appliedCapCents,clampedReason:o.clampedReason}})}async function Fp(e){let n=On()?.budgetId??_l(),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 Fi(),fe=null,Zt(null),{closedServerSide:r,budgetId:n,finalCumulativeCents:s,finalCumulativeMicros:o}}async function qi(e){return Sl(()=>Fp(e))}function On(){return Fi(),fe?new Date(fe.expiresAt).getTime()<=Date.now()?(fe=null,Zt(null),null):{budgetId:fe.budgetId,totalCents:fe.totalCents,lastReceiptCumulative:Lp(),lastReceiptCumulativeMicros:Op()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:Up(),estimatedCumulative:Vi(),lastToolSpend:Mp(),expiresAt:fe.expiresAt}:null}var Vp=I(os()),Hp=10000n;function bS(e){return e<=0n?0:Number((e+Hp-1n)/Hp)}function qp(e){return bS((0,Vp.fromUsd)(e))}var Ki=I(os()),vS=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;function Gi(e){if(typeof e!="string"||!vS.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,Ki.toDisplay)((0,Ki.fromCents)(s),{symbol:""})}}var Wi="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.",Kp="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 ry=Promise.resolve();function SA(e,t){if(e)try{let n=(0,$a.fromWire)(e),r=n%10000n===0n?2:6;return(0,$a.toDisplay)(n,{decimals:r})}catch{}return`$${(t/100).toFixed(2)}`}var sy=!1,oy=!1,iy=!1;function Oa(e){let t=ry.catch(()=>{}).then(e);return ry=t.then(()=>{},()=>{}),t}async function yy(e){let t=await Ce(()=>xl(U,tt,{toolName:e.toolId,userContext:e.userContext}));await wl(e.estimatedAmountCents);let n=bl(e.idempotencyKey);if(!n)throw await go(e.estimatedAmountCents),new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await PA(),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 Ft){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 go(e.estimatedAmountCents),u instanceof Wr){if(h.warn("mcp-session:server-invalidated-budget",{code:u.code,budgetId:u.budgetId??t.budgetId,tool:e.toolId}),await qi(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 iy||(iy=!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}),_y(e)}throw u instanceof Ft?(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=mo(o)??(n?vl(n):null);if(po(s?.receipt_v2),Np({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),Uu(s))return Ct(s);let c=await Lu();if(e.idempotencyKey&&Du(s,c,e.idempotencyKey))return Ct(s);let l=c?To(c):null;return Ct(ju(s,r,l))}function Qe(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function Ta(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(Ta).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${Ta(r)}`).join(",")}}`}function Mu(e,t,n,r){let s=xe.createHash("sha256").update(`${n}:${Ta(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${s}`}function xA(e,t){return`${e}:${t}`}function CA(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 Ra(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=CA(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),c=i!=null?String(i):a;return{batch_id:e,item_id:xA(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 _y(e){return Ce(()=>EA(e))}async function by(e,t,n){if(Uu(e))return Ct(e);let r=await Lu();if(n&&Du(e,r,n))return Ct(e);let s=r?To(r):null;return Ct(ju(e,t,s))}async function AA(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 tt("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 mo(i),po(o?.receipt_v2),h.info("parentless-single-call:completed",{tool:e.toolId}),by(o,e.beforeBalanceMicros,e.idempotencyKey)}async function EA(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=To(n);if(xp()&&!sy){let u=e.idempotencyKey??xe.randomUUID();try{return await AA({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 bt)sy=!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 tt("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),fo(a.budget.totalCents),h.info("on-demand-session:opened",{budgetId:c,capCents:a.budget.totalCents,tool:e.toolId});let l=!1;try{await wl(e.estimatedAmountCents);let u=bl(e.idempotencyKey);if(!u)throw await go(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(mo(f)||vl(u),l=!0,po(d?.receipt_v2),Uu(d))return Ct(d);let m=await Lu();if(e.idempotencyKey&&Du(d,m,e.idempotencyKey))return Ct(d);let p=m?To(m):null;return Ct(ju(d,s,p))}catch(u){throw l||await go(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 Kn(e){return Oa(async()=>On()?yy(e):_y(e))}function Na(){return $e()}var kA="https://v4-verify-web-visa-code-preview.up.railway.app";function TA(e=Bu){return/^\d+\.\d+\.\d+$/.test(e)&&e!=="0.0.0"}function vy(e=process.env,t=Bu){return e.VISA_VERIFY_WEB_URL?e.VISA_VERIFY_WEB_URL:TA(t)?null:kA}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 To(e){return ft(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function RA(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 IA(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 ko(e,t="INVALID_TOOL_PARAMS",n){return{success:!1,error_code:t,code:t,error:e,message:e,...n??{}}}function $A(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 PA(){try{let e=await U.getBalance();return e.success?To(e):null}catch{return null}}async function Lu(){try{let e=await U.getBalance();return e.success?e:null}catch{return null}}function Uu(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 Du(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 ju(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 Bu="4.0.0-rc.15",m$=["","","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 et(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=Fs(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(gm())return{opened:!1,url:t,blockedReason:"suppressed"};let n=pc();if(n.headless)return h.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let s=[Na(),vy()].filter(i=>!!i).map(i=>zd(t,i)).find(Boolean)??null;if(!s)return h.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let o=Xd(s);return o?((0,hy.execFile)(o.cmd,o.args,i=>{i&&h.warn(`Browser open failed: ${i.message}. URL: ${s}`)}),{opened:!0,url:s}):(h.info(`No browser command for platform "${Io.platform()}". URL: ${s}`),{opened:!1,url:s,blockedReason:"unsupported_platform"})}async function Ce(e){return br(U,e,Ry)}var wy="get_cards",Sy="set_default_card";function OA(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 '${wy}' to see enrolled cards and '${Sy}' to switch, then retry the original request.`}function NA(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 '${wy}' to see enrolled cards and '${Sy}' to switch. Do not retry automatically.`}function pt(e,t){let n=e.retryable?OA(e.code,e.retryAfter):NA(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 MA(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 Cs=null,LA=3e4;function xy(){Cs=null}var qn=class extends Error{constructor(n){super(`${Ia()} attestation is required for this action, but it is not available in this MCP process. `+Fu());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function Ma(e,t){return{success:!1,error:e.code,message:e.message,action:t,agent_guidance:`Biometric attestation is required for ${t}, but this MCP process cannot create a local attestation. `+Fu()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function UA(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:Wi,agent_guidance:Kp}}function Ia(){return process.platform==="darwin"?"Touch ID":"local biometric"}function Fu(){return process.platform==="darwin"?"Run the action from an interactive terminal with Touch ID access, or 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 DA(e){let t=Date.now();if(Cs&&Cs.expiresAt>t)return{required:Cs.required,hasRegisteredKey:Cs.hasRegisteredKey};try{let n=await U.getStatus(e),r=At(n),s=n.attestationRequired!==!1;return Cs={required:s,hasRegisteredKey:r,expiresAt:t+LA},{required:s,hasRegisteredKey:r}}catch{return{required:!0,hasRegisteredKey:!0}}}async function tt(e,t,n,r,s,o){if(!o?.forceRequired){let i=await DA(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 qn(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 ay="[dry-run] https://placeholder.visa-cli.dev/image.png",jA=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"]),BA=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 FA(e){return e.startsWith("or-")?"llm":jA.has(e)?"image":BA.has(e)?"video":HA(e)?"media":null}function HA(e){let t=co(e);return t?!La(t):!1}function VA(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function qA(e){return e==="llm"?"OpenRouter":"fal.ai"}function As(e,t,n,r){let s={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:qA(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${VA(n)}`;return{...s,content:i,data:{content:i,model:t,dry_run:!0}}}return{...s,urls:[ay],data:{[e==="video"?"videoUrl":e==="image"?"imageUrl":"url"]:ay,metadata:{dry_run:!0}}}}async function Pu(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 KA="https://openrouter.ai/api/v1/chat/completions",GA="openrouter/free",WA=50,YA=15e3;function zA(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 JA(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:As("llm",e,t,n),degraded:!0,resolvedModel:null};let s=zA(t),o;try{o=await _t(KA,{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:GA,messages:[{role:"user",content:s}],max_tokens:WA}),timeoutMs:YA})}catch(u){return h.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:As("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:As("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:As("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 $o(e,t,n,r){let s=ll();if(!s)return null;let o=FA(e);if(!o)return null;let i=Date.now();if(s==="mock"){let l=As(o,e,t,r);return await Pu({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=As(o,e,t,r);return await Pu({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 JA(e,t,r);return await Pu({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 XA(e,t,n){return n.has(e.resolvedTool)?0:Math.max(1,ln(t[e.resolvedTool]))}function ZA(){return Pa.join(Io.homedir(),".visa-mcp","allium-results")}var p$=16*1024,g$=50*1024*1024;function QA(){let e=ZA();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(Pa.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 cy=3600*1e3,Ou=0;function eE(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function Po(e){if(!hm()&&!(Date.now()<Ou))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(eE(t)){let n=Ou===0;Ou=Date.now()+cy,n&&h.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:cy});return}h.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function tE(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 Ce(async()=>{let l=await tt("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}),pt(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 nE(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 $o("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 Ce(async()=>{let o;try{o=await Kn({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=>et(i)),Po({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}),pt(o,r);throw un(o,{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName}),o}}async function rE(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 $o("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 Ce(async()=>{let o;try{o=await Kn({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=>et(i)),Po({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}),pt(o,r);throw un(o,{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName}),o}}async function sE(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 $o("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 Ce(async()=>{let o;try{o=await Kn({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=>et(i)),Po({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}),pt(o,r);throw un(o,{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName}),o}}async function oE(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 Ce(async()=>{let s;try{s=await Kn({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=>et(o)),Po({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}),pt(s,n);throw un(s,{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName}),s}}async function iE(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 Ce(async()=>{let s;try{s=await Kn({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=>et(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}),pt(s,n);throw un(s,{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName}),s}}async function aE(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 Ce(async()=>{let s;try{s=await Kn({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}),pt(s,n);throw un(s,{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName}),s}}var cE=["generate_music_tempo_card"],xs=10,ly=5,uy=new Map;function dy(e){let t=uy.get(e);if(t!==void 0)return t;let r=co(e)?.isAsync===!0||cE.includes(e);return uy.set(e,r),r}var lE=36e4,uE=18e4,dE=15e3,fE=12e4,mE=2e3;function Nu(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}function pE(e,t){return xe.createHash("sha256").update(`${e}:${Ta(t)}`).digest("hex")}function gE(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,...Ra(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=>et(d)),{deltaCharged:l,deltaMicros:u}}function hE(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,b=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:b,mode:d,batchId:u}),{success:m>0,outcome:b,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 yE(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,b=await U.getBalance();if(!b.success)throw new Error(`Could not read balance: ${b.error||"unknown error"}`);if(b.balanceCents<g)throw new Se(b.balanceCents,g);let A=`batch-${m}`,_=`spend up to $${(g/100).toFixed(2)} across a batch of ${t.length}`,{batchParentId:v}=await Ce(async()=>{let y=await tt("batch_open",g,A,_,p,{forceRequired:!0}),x=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:Y}=await U.batchOpen({...y?{attestation:y}:{},nonce:x,approved_total_cents:g,batch_id:m});return{batchParentId:Y}});h.info("parentless-batch:opened",{batchTool:l,count:t.length,batchParentId:v});let w=[],T=0,E=0n;try{for(let y=0;y<t.length;y+=1){let x=t[y],Y=n[x.resolvedTool],X=r.has(x.resolvedTool);try{let K;if(X)K=await U.shortcut(x.resolvedTool,x.params,f,p,"batch");else{let{data:Z,voucherReceiptHeader:Ps}=await U.shortcutParentlessBatchItem(x.resolvedTool,{batch_parent_id:v,batch_id:m,batch_index:y,batch_request_hash:pE(x.resolvedTool,x.params),item_ceiling_cents:o[y],idempotency_key:Mu(m,y,x.resolvedTool,x.params)},x.params,f,p,"batch");mo(Ps),po(Z?.receipt_v2),K=await by(Z,null,Mu(m,y,x.resolvedTool,x.params))}let{deltaCharged:be,deltaMicros:se}=gE({results:w,batchId:m,index:y,item:x,itemResult:K,preview:Y,isFree:X,catalogName:s[x.resolvedTool]?.name});T+=be,E+=se}catch(K){if(K instanceof Se&&w.length===0)return Qe(K);h.warn("payment:batch-item-failed",{tool:x.resolvedTool,index:y,error:K?.message||String(K)}),w.push({success:!1,tool:x.resolvedTool,...Ra(m,y),error:K?.message||String(K)})}}return hE({results:w,resolvedItems:t,uniqueTools:a,isHomogeneous:c,primaryTool:l,merchantNames:u,totalAmount:d,totalCharged:T,totalChargedMicros:E,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}),pt(y,{amount:d,merchantName:u});throw un(y,{tool:"batch",batchTool:l,count:t.length,totalAmount:d,merchant:u}),y}}async function _E(e,t){let n;if(Array.isArray(e.requests)&&e.requests.length>xs)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${xs} items. Please split into smaller batches.`};if(e.requests?.some(y=>y.tool||y.tool_id)&&e.requests)n=e.requests.map(y=>{let x=y.tool||y.tool_id||e.tool;if(!x)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let Y=cl({requestedTool:x})??x,{tool:X,tool_id:K,tier:be,params:se,...Z}=y,Ps=se&&typeof se=="object"?{...se,...Z}:Z;return{resolvedTool:Y,params:Ps}});else if(e.tool){let y=cl({requestedTool:e.tool})??e.tool;if(e.count!==void 0){if(!Number.isSafeInteger(e.count)||e.count<1)return Nu("BATCH_INVALID_COUNT","Batch count must be a positive integer.");if(e.count>xs)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${xs} items. Please split into smaller batches.`}}n=(e.requests||(e.count!==void 0&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(Y=>({resolvedTool:y,params:Y}))}else return Nu("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return Nu("BATCH_EMPTY","Batch requires at least one item.");if(n.length>xs)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${xs} items. Please split into smaller batches.`};if([...new Set(n.map(y=>y.resolvedTool))].some(dy)&&n.length>ly)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${ly} 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 Iy(y);let l=new Set(i.filter(y=>c[y]&&La(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=>XA(y,u,l)),m=f.reduce((y,x)=>y+x,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 b=n.some(y=>dy(y.resolvedTool)),A=n.some(y=>y.resolvedTool.startsWith("or-")||y.resolvedTool==="run_llm"||y.resolvedTool==="execute_tool"),_=b?lE:A?uE+n.length*dE:fE+n.length*mE,v=xe.randomUUID(),w=[],T=0,E=0n;return Oa(async()=>{let y=!On();if(Cp()&&!oy&&y&&m>0)try{return await yE({resolvedItems:n,previews:u,freeTools:l,catalogEntries:c,itemCeilingCents:f,batchCeilingCents:m,uniqueTools:i,isHomogeneous:a,primaryTool:g,merchantNames:p,totalAmount:d,timeoutMs:_,batchId:v,userContext:t})}catch(x){if(x instanceof bt)oy=!0,h.info("parentless-batch:falling-back-to-session",{batchTool:g,count:n.length,status:x.status,serverErrorCode:x.serverErrorCode});else{if(x instanceof Se)return Qe(x);throw x}}if(y&&m>0)try{let x=m;await Ce(()=>xl(U,tt,{toolName:"batch",userContext:t,sessionKind:"one_shot",minRequiredCents:x,capCentsOverride:x}))}catch(x){return x instanceof Se?Qe(x):(h.warn("payment:batch-prewarm-failed",{batchTool:g,count:n.length,error:x?.message||String(x)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:x?.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 Z=n[se],Ps=u[Z.resolvedTool];try{let ue=l.has(Z.resolvedTool)?await U.shortcut(Z.resolvedTool,Z.params,_,t,"batch"):await yy({toolId:Z.resolvedTool,toolParams:Z.params,estimatedAmountCents:f[se],userContext:t,metaTool:"batch",timeoutMs:_,idempotencyKey:Mu(v,se,Z.resolvedTool,Z.params)});if(l.has(Z.resolvedTool)&&ue&&typeof ue=="object"&&!Array.isArray(ue)&&ue.merchantName==null&&(ue.merchantName=c[Z.resolvedTool]?.name??Z.resolvedTool),w.push({success:ue?.success!==!1,tool:Z.resolvedTool,...ue,...Ra(v,se,ue)}),ue?.success!==!1){let Os=ft(ue?.amountMicros??ue?.amount_micros),xd=typeof ue?.amount=="number"?ue.amount:Ps?.amount??0;Os!==null&&Os>0n?E+=Os:E+=BigInt(Math.round(xd*1e6)),T+=xd}ue?.urls&&ue.urls.forEach(Os=>et(Os))}catch(ue){if(ue instanceof Se&&w.length===0)return Qe(ue);h.warn("payment:batch-item-failed",{tool:Z.resolvedTool,index:se,error:ue?.message||String(ue)}),w.push({success:!1,tool:Z.resolvedTool,...Ra(v,se),error:ue?.message||String(ue)})}}let x=w.filter(se=>se?.success===!1).length,Y=w.length-x,X=w.flatMap(se=>Array.isArray(se?.urls)?se.urls:[]),K=E>0n?Number(E)/1e6:Math.round((T+Number.EPSILON)*100)/100,be=Y===0?"failure":x===0?"success":"partial";return h.info("payment:success",{tool:"batch",batchTool:g,count:n.length,totalAmount:d,totalCharged:K,merchant:p,successCount:Y,failedCount:x,outcome:be,mode:"session",batchId:v}),{success:Y>0,outcome:be,batch_id:v,tool:a?i[0]:g,count:n.length,successCount:Y,failedCount:x,totalCharged:K,...E>0n?{totalChargedMicros:E.toString(),amountMicros:E.toString(),amount_micros:E.toString()}:{},merchantName:p,results:w,...X.length?{urls:X}:{}}}catch(x){if(x instanceof he)return h.warn("payment:declined",{tool:"batch",batchTool:g,count:n.length,totalAmount:d,merchant:p,code:x.code,retryable:x.retryable}),pt(x,{amount:d,merchantName:p});throw un(x,{tool:"batch",batchTool:g,count:n.length,totalAmount:d,merchant:p}),x}finally{if(y){let x=await qi(U);h.info("batch-session:closed",{budgetId:x.budgetId,closedServerSide:x.closedServerSide})}}})}function bE(){let e=!1,t;try{let r=Pa.join(Io.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=ii();return n||(t="visa-cli config hud enable"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function vE(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=QA();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=bE(),!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=Bu,Array.isArray(t.cards)&&(t.cards=t.cards.map(o=>({...o,displayName:Hu(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=On();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 Hu(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 Cy(e,t){try{let r=((await U.getStatus(t)).cards||[]).find(s=>s?.id===e);if(r)return Hu(r)}catch(n){h.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function wE(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:Hu(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 SE(e,t){return await U.getTransactions({limit:e.limit,offset:e.offset},t)}async function xE(e,t){return await U.feedback(e.message,e.transaction_id,t)}async function CE(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Mr("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=Gi(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 Ce(async()=>{let i=await tt("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=SA(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 qn)return UA();if(i instanceof ot)return h.warn("buy_credits:ambiguous",{amountCents:r,code:i.code,transactionId:i.transactionId}),MA(i);throw h.error("buy_credits:failure",{amountCents:r,error:i.message}),i}}function Mr(e,t){return{success:!1,error:t,code:e,message:t}}async function AE(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Mr("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 Mr("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 Mr("INVALID_VALUE","dailyLimit must be at least $1");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return Mr("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");h.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await Ce(async()=>{let n=await tt("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 qn)return Ma(n,"update_spending_controls");if(String(n?.message||n).includes("Attestation required"))return Mr("ATTESTATION_REQUIRED","Changing spending controls requires local attestation, even when payment biometric prompts are disabled.");throw n}}async function EE(e){let t=await uo({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 Vu=new Set(["auth.serverUrl"]);function Ro(){return Object.keys(tr).filter(e=>!Vu.has(e)).sort()}function Ay(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:Ro()}}async function kE(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(Vu.has(e.key))return h.warn("config:set:rejected:mcp-forbidden",{key:e.key}),Ay(e.key,"set");h.info("config:set",{key:e.key});try{let t=Si(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 it?"UNKNOWN_KEY":t instanceof Vt?"SERVER_CONTROLLED":t instanceof vn?"RETIRED_KEY":"INVALID_VALUE",r=t instanceof it?`Unknown setting "${e.key}". MCP-settable keys: ${Ro().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:Ro()}}}async function TE(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(Vu.has(e.key))return h.warn("config:unset:rejected:mcp-forbidden",{key:e.key}),Ay(e.key,"unset");h.info("config:unset",{key:e.key});try{let t=xi(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 it?"UNKNOWN_KEY":t instanceof Vt?"SERVER_CONTROLLED":t instanceof vn?"RETIRED_KEY":"INVALID_VALUE",r=t instanceof it?`Unknown setting "${e.key}". MCP-settable keys: ${Ro().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:Ro()}}}async function RE(e){let t=await U.getStatus(e),n=t.attestationRequired!==!1,r=At(t),s=de(),o=n?r?s?`${Ia()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${Ia()} is not available in this process. ${Fu()}`:"Biometric attestation is enabled on the account, but no attestation key is registered. Payments on this device proceed without a biometric signature; processor declines such as INVALID_OR_MISSING_CONFIG are card/account configuration issues, not something biometric setup fixes.":"Biometric attestation is NOT required for payments. Payments will proceed without biometric confirmation.";return{required:n,hasAttestationKey:!!t.hasAttestationKey,hasTelegramAttestationKey:!!t.hasTelegramAttestationKey,hasAnyAttestationKey:r,touchIdAvailable:s,platform:process.platform,effectiveRequiredOnThisDevice:n&&r&&s,canDisableFromThisDevice:!n||!r||s,message:o}}async function IE(e){h.info("biometric:on");let t=await ji(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?(xy(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:n.error||"unknown error"}}async function $E(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Mr("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 Ce(async()=>{let n=await U.getStatus(t),r;if(At(n)&&(r=await tt("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${Ia()} 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 xy(),{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 qn)return Ma(n,"biometric_off");throw n}}var fy=3e4,PE=3e5;async function Ey(e,t,n="login"){let r=xe.randomUUID(),s=`${e}${e.includes("?")?"&":"?"}state=${r}`,o=et(s);return!o.opened&&o.blockedReason!=="non_internal_host"&&o.blockedReason!=="invalid_url"?ky(s,o,n):o.opened?{...await Ty(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 ky(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 Ty(e,t,n="login"){let r=Date.now()+PE;for(;Date.now()<r;)try{let o=await fetch(`${Na()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:fy,...t&&{user_context:t}}),signal:AbortSignal.timeout(fy+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=Tp(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 Ry(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=et(n.recoveryUrl);return!r.opened&&r.blockedReason!=="non_internal_host"&&r.blockedReason!=="invalid_url"?ky(n.recoveryUrl,r,"attestation-recovery"):r.opened?{...await Ty(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 OE(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 Cy(n,t)}`;try{return await Ce(async()=>{let o=await tt(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 qn)return Ma(o,"remove_card");throw o}}async function NE(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 Cy(n,t)} as default`;try{return await Ce(async()=>{let o=await tt(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 qn)return Ma(o,"set_default_card");throw o}}async function ME(e){return h.info("auth:login_attempt"),Ey(`${Na()}/login`,e)}async function LE(e=vy()){if(!e)return{success:!1,message:"The Visa Verified Agent enrollment flow is not yet publicly available in stable builds. Set VISA_VERIFY_WEB_URL to a deployment URL to use enroll_agent."};h.info("agent:enroll_open",{url:e});let t=et(e),n="sign in \u2192 pick your .visa name \u2192 wallet \u2192 card (secure fields) \u2192 bank verification with passkey \u2192 mint";return t.opened?{success:!0,opened:!0,browserUrl:t.url,message:`Opened the Visa Verified Agent enrollment in your browser (${n}). Access is currently tester-gated \u2014 if sign-in shows "private testing", ask for the v4_verify_web_access flag.`}:{success:!0,opened:!1,requiresBrowser:!0,browserUrl:t.url??e,message:`Open this URL in a browser to enroll your agent (${n}): ${t.url??e}`}}function UE(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 DE(e={},t){let n;try{n=UE(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return Oa(async()=>{let r=await Ce(()=>Bp(U,tt,{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 jE(){let e=On();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 BE(){return Oa(async()=>{let e=On();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 qi(U);h.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=IA(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 ${RA(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 FE(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 Ey(`${Na()}/enroll-card?code=${encodeURIComponent(n)}`,e,"enrollment")}async function my(){if(await G.clearAll(),de())try{await Di()}catch{}}async function HE(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 my(),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&&At(r)){let s=await Ry(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 my(),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 VE(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
+ `),bm(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 C={};Fr(C,{BRAND:()=>lv,DIRTY:()=>nr,EMPTY_PATH:()=>F0,INVALID:()=>D,NEVER:()=>Wv,OK:()=>Pe,ParseStatus:()=>Ae,Schema:()=>H,ZodAny:()=>En,ZodArray:()=>zt,ZodBigInt:()=>sr,ZodBoolean:()=>or,ZodBranded:()=>ao,ZodCatch:()=>hr,ZodDate:()=>ir,ZodDefault:()=>gr,ZodDiscriminatedUnion:()=>ki,ZodEffects:()=>Je,ZodEnum:()=>mr,ZodError:()=>He,ZodFirstPartyTypeKind:()=>j,ZodFunction:()=>Ri,ZodIntersection:()=>ur,ZodIssueCode:()=>S,ZodLazy:()=>dr,ZodLiteral:()=>fr,ZodMap:()=>rs,ZodNaN:()=>os,ZodNativeEnum:()=>pr,ZodNever:()=>ct,ZodNull:()=>cr,ZodNullable:()=>Et,ZodNumber:()=>rr,ZodObject:()=>Ve,ZodOptional:()=>Ye,ZodParsedType:()=>k,ZodPipeline:()=>co,ZodPromise:()=>An,ZodReadonly:()=>yr,ZodRecord:()=>Ti,ZodSchema:()=>H,ZodSet:()=>ss,ZodString:()=>Cn,ZodSymbol:()=>ts,ZodTransformer:()=>Je,ZodTuple:()=>Ct,ZodType:()=>H,ZodUndefined:()=>ar,ZodUnion:()=>lr,ZodUnknown:()=>Yt,ZodVoid:()=>ns,addIssueToContext:()=>E,any:()=>_v,array:()=>Sv,bigint:()=>mv,boolean:()=>Pm,coerce:()=>Gv,custom:()=>Rm,date:()=>pv,datetimeRegex:()=>km,defaultErrorMap:()=>Gt,discriminatedUnion:()=>Av,effect:()=>Dv,enum:()=>Mv,function:()=>Pv,getErrorMap:()=>Zr,getParsedType:()=>xt,instanceof:()=>dv,intersection:()=>kv,isAborted:()=>Ei,isAsync:()=>Qr,isDirty:()=>Ai,isValid:()=>xn,late:()=>uv,lazy:()=>Ov,literal:()=>Nv,makeIssue:()=>io,map:()=>Iv,nan:()=>fv,nativeEnum:()=>Lv,never:()=>vv,null:()=>yv,nullable:()=>Bv,number:()=>$m,object:()=>xv,objectUtil:()=>zc,oboolean:()=>Kv,onumber:()=>qv,optional:()=>jv,ostring:()=>Vv,pipeline:()=>Hv,preprocess:()=>Fv,promise:()=>Uv,quotelessJson:()=>D0,record:()=>Rv,set:()=>$v,setErrorMap:()=>B0,strictObject:()=>Cv,string:()=>Im,symbol:()=>gv,transformer:()=>Dv,tuple:()=>Tv,undefined:()=>hv,union:()=>Ev,unknown:()=>bv,util:()=>V,void:()=>wv});var V;(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})(V||(V={}));var zc;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(zc||(zc={}));var k=V.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 k.undefined;case"string":return k.string;case"number":return Number.isNaN(e)?k.nan:k.number;case"boolean":return k.boolean;case"function":return k.function;case"bigint":return k.bigint;case"symbol":return k.symbol;case"object":return Array.isArray(e)?k.array:e===null?k.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?k.promise:typeof Map<"u"&&e instanceof Map?k.map:typeof Set<"u"&&e instanceof Set?k.set:typeof Date<"u"&&e instanceof Date?k.date:k.object;default:return k.unknown}};var S=V.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"]),D0=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),He=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,V.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()}};He.create=e=>new He(e);var j0=(e,t)=>{let n;switch(e.code){case S.invalid_type:e.received===k.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case S.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,V.jsonStringifyReplacer)}`;break;case S.unrecognized_keys:n=`Unrecognized key(s) in object: ${V.joinValues(e.keys,", ")}`;break;case S.invalid_union:n="Invalid input";break;case S.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${V.joinValues(e.options)}`;break;case S.invalid_enum_value:n=`Invalid enum value. Expected ${V.joinValues(e.options)}, received '${e.received}'`;break;case S.invalid_arguments:n="Invalid function arguments";break;case S.invalid_return_type:n="Invalid function return type";break;case S.invalid_date:n="Invalid date";break;case S.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}"`:V.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case S.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 S.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 S.custom:n="Invalid input";break;case S.invalid_intersection_types:n="Intersection results could not be merged";break;case S.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case S.not_finite:n="Number must be finite";break;default:n=t.defaultError,V.assertNever(e)}return{message:n}},Gt=j0;var Sm=Gt;function B0(e){Sm=e}function Zr(){return Sm}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}},F0=[];function E(e,t){let n=Zr(),r=io({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Gt?void 0:Gt].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"}),nr=e=>({status:"dirty",value:e}),Pe=e=>({status:"valid",value:e}),Ei=e=>e.status==="aborted",Ai=e=>e.status==="dirty",xn=e=>e.status==="valid",Qr=e=>typeof Promise<"u"&&e instanceof Promise;var N;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(N||(N={}));var ze=class{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},xm=(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 He(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 H=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(Qr(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 xm(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(Qr(s)?s:Promise.resolve(s));return xm(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:S.custom,...r(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new Je({schema:this,typeName:j.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Ye.create(this,this._def)}nullable(){return Et.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return zt.create(this)}promise(){return An.create(this,this._def)}or(t){return lr.create([this,t],this._def)}and(t){return ur.create(this,t,this._def)}transform(t){return new Je({...B(this._def),schema:this,typeName:j.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new gr({...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 hr({...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 yr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},H0=/^c[^\s-]{8,}$/i,V0=/^[0-9a-z]+$/,q0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,K0=/^[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,G0=/^[a-z0-9_-]{21}$/i,W0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Y0=/^[-+]?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)?)??$/,z0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,J0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Jc,X0=/^(?:(?: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])$/,Z0=/^(?:(?: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])$/,Q0=/^(([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]))$/,ev=/^(([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])$/,tv=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nv=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Em="((\\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])))",rv=new RegExp(`^${Em}$`);function Am(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 sv(e){return new RegExp(`^${Am(e)}$`)}function km(e){let t=`${Em}T${Am(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 ov(e,t){return!!((t==="v4"||!t)&&X0.test(e)||(t==="v6"||!t)&&Q0.test(e))}function iv(e,t){if(!W0.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 av(e,t){return!!((t==="v4"||!t)&&Z0.test(e)||(t==="v6"||!t)&&ev.test(e))}var Cn=class e extends H{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==k.string){let o=this._getOrReturnCtx(t);return E(o,{code:S.invalid_type,expected:k.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),E(s,{code:S.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),E(s,{code:S.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?E(s,{code:S.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&E(s,{code:S.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")z0.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"email",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")Jc||(Jc=new RegExp(J0,"u")),Jc.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"emoji",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")K0.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"uuid",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")G0.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"nanoid",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")H0.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"cuid",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")V0.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"cuid2",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")q0.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"ulid",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),E(s,{validation:"url",code:S.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),E(s,{validation:"regex",code:S.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),E(s,{code:S.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),E(s,{code:S.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(s=this._getOrReturnCtx(t,s),E(s,{code:S.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?km(o).test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{code:S.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?rv.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{code:S.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?sv(o).test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{code:S.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?Y0.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"duration",code:S.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?ov(t.data,o.version)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"ip",code:S.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?iv(t.data,o.alg)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"jwt",code:S.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?av(t.data,o.version)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"cidr",code:S.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?tv.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"base64",code:S.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?nv.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"base64url",code:S.invalid_string,message:o.message}),r.dirty()):V.assertNever(o);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:S.invalid_string,...N.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...N.errToObj(t)})}url(t){return this._addCheck({kind:"url",...N.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...N.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...N.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...N.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...N.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...N.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...N.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...N.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...N.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...N.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...N.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...N.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,...N.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,...N.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...N.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...N.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...N.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...N.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...N.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...N.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...N.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...N.errToObj(n)})}nonempty(t){return this.min(1,N.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}};Cn.create=e=>new Cn({checks:[],typeName:j.ZodString,coerce:e?.coerce??!1,...B(e)});function cv(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 rr=class e extends H{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)!==k.number){let o=this._getOrReturnCtx(t);return E(o,{code:S.invalid_type,expected:k.number,received:o.parsedType}),D}let r,s=new Ae;for(let o of this._def.checks)o.kind==="int"?V.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),E(r,{code:S.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),E(r,{code:S.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),E(r,{code:S.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?cv(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),E(r,{code:S.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),E(r,{code:S.not_finite,message:o.message}),s.dirty()):V.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,N.toString(n))}gt(t,n){return this.setLimit("min",t,!1,N.toString(n))}lte(t,n){return this.setLimit("max",t,!0,N.toString(n))}lt(t,n){return this.setLimit("max",t,!1,N.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:N.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:N.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:N.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:N.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.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"&&V.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)}};rr.create=e=>new rr({checks:[],typeName:j.ZodNumber,coerce:e?.coerce||!1,...B(e)});var sr=class e extends H{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)!==k.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),E(r,{code:S.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),E(r,{code:S.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),E(r,{code:S.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):V.assertNever(o);return{status:s.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return E(n,{code:S.invalid_type,expected:k.bigint,received:n.parsedType}),D}gte(t,n){return this.setLimit("min",t,!0,N.toString(n))}gt(t,n){return this.setLimit("min",t,!1,N.toString(n))}lte(t,n){return this.setLimit("max",t,!0,N.toString(n))}lt(t,n){return this.setLimit("max",t,!1,N.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:N.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:N.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:N.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}};sr.create=e=>new sr({checks:[],typeName:j.ZodBigInt,coerce:e?.coerce??!1,...B(e)});var or=class extends H{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==k.boolean){let r=this._getOrReturnCtx(t);return E(r,{code:S.invalid_type,expected:k.boolean,received:r.parsedType}),D}return Pe(t.data)}};or.create=e=>new or({typeName:j.ZodBoolean,coerce:e?.coerce||!1,...B(e)});var ir=class e extends H{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==k.date){let o=this._getOrReturnCtx(t);return E(o,{code:S.invalid_type,expected:k.date,received:o.parsedType}),D}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return E(o,{code:S.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),E(s,{code:S.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),E(s,{code:S.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):V.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:N.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:N.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}};ir.create=e=>new ir({checks:[],coerce:e?.coerce||!1,typeName:j.ZodDate,...B(e)});var ts=class extends H{_parse(t){if(this._getType(t)!==k.symbol){let r=this._getOrReturnCtx(t);return E(r,{code:S.invalid_type,expected:k.symbol,received:r.parsedType}),D}return Pe(t.data)}};ts.create=e=>new ts({typeName:j.ZodSymbol,...B(e)});var ar=class extends H{_parse(t){if(this._getType(t)!==k.undefined){let r=this._getOrReturnCtx(t);return E(r,{code:S.invalid_type,expected:k.undefined,received:r.parsedType}),D}return Pe(t.data)}};ar.create=e=>new ar({typeName:j.ZodUndefined,...B(e)});var cr=class extends H{_parse(t){if(this._getType(t)!==k.null){let r=this._getOrReturnCtx(t);return E(r,{code:S.invalid_type,expected:k.null,received:r.parsedType}),D}return Pe(t.data)}};cr.create=e=>new cr({typeName:j.ZodNull,...B(e)});var En=class extends H{constructor(){super(...arguments),this._any=!0}_parse(t){return Pe(t.data)}};En.create=e=>new En({typeName:j.ZodAny,...B(e)});var Yt=class extends H{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Pe(t.data)}};Yt.create=e=>new Yt({typeName:j.ZodUnknown,...B(e)});var ct=class extends H{_parse(t){let n=this._getOrReturnCtx(t);return E(n,{code:S.invalid_type,expected:k.never,received:n.parsedType}),D}};ct.create=e=>new ct({typeName:j.ZodNever,...B(e)});var ns=class extends H{_parse(t){if(this._getType(t)!==k.undefined){let r=this._getOrReturnCtx(t);return E(r,{code:S.invalid_type,expected:k.void,received:r.parsedType}),D}return Pe(t.data)}};ns.create=e=>new ns({typeName:j.ZodVoid,...B(e)});var zt=class e extends H{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==k.array)return E(n,{code:S.invalid_type,expected:k.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)&&(E(n,{code:i?S.too_big:S.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&&(E(n,{code:S.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&&(E(n,{code:S.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>s.type._parseAsync(new ze(n,i,n.path,a)))).then(i=>Ae.mergeArray(r,i));let o=[...n.data].map((i,a)=>s.type._parseSync(new ze(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:N.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:N.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:N.toString(n)}})}nonempty(t){return this.min(1,t)}};zt.create=(e,t)=>new zt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:j.ZodArray,...B(t)});function es(e){if(e instanceof Ve){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Ye.create(es(r))}return new Ve({...e._def,shape:()=>t})}else return e instanceof zt?new zt({...e._def,type:es(e.element)}):e instanceof Ye?Ye.create(es(e.unwrap())):e instanceof Et?Et.create(es(e.unwrap())):e instanceof Ct?Ct.create(e.items.map(t=>es(t))):e}var Ve=class e extends H{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=V.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==k.object){let l=this._getOrReturnCtx(t);return E(l,{code:S.invalid_type,expected:k.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 ct&&this._def.unknownKeys==="strip"))for(let l in s.data)i.includes(l)||a.push(l);let c=[];for(let l of i){let u=o[l],d=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new ze(s,d,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof ct){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&&(E(s,{code:S.unrecognized_keys,keys:a}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let d=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new ze(s,d,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,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 N.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:N.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 V.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 V.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return es(this)}partial(t){let n={};for(let r of V.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 V.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof Ye;)o=o._def.innerType;n[r]=o}return new e({...this._def,shape:()=>n})}keyof(){return Tm(V.objectKeys(this.shape))}};Ve.create=(e,t)=>new Ve({shape:()=>e,unknownKeys:"strip",catchall:ct.create(),typeName:j.ZodObject,...B(t)});Ve.strictCreate=(e,t)=>new Ve({shape:()=>e,unknownKeys:"strict",catchall:ct.create(),typeName:j.ZodObject,...B(t)});Ve.lazycreate=(e,t)=>new Ve({shape:e,unknownKeys:"strip",catchall:ct.create(),typeName:j.ZodObject,...B(t)});var lr=class extends H{_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 He(a.ctx.common.issues));return E(n,{code:S.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 He(c));return E(n,{code:S.invalid_union,unionErrors:a}),D}}get options(){return this._def.options}};lr.create=(e,t)=>new lr({options:e,typeName:j.ZodUnion,...B(t)});var Wt=e=>e instanceof dr?Wt(e.schema):e instanceof Je?Wt(e.innerType()):e instanceof fr?[e.value]:e instanceof mr?e.options:e instanceof pr?V.objectValues(e.enum):e instanceof gr?Wt(e._def.innerType):e instanceof ar?[void 0]:e instanceof cr?[null]:e instanceof Ye?[void 0,...Wt(e.unwrap())]:e instanceof Et?[null,...Wt(e.unwrap())]:e instanceof ao||e instanceof yr?Wt(e.unwrap()):e instanceof hr?Wt(e._def.innerType):[],ki=class e extends H{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==k.object)return E(n,{code:S.invalid_type,expected:k.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}):(E(n,{code:S.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=Wt(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===k.object&&r===k.object){let s=V.objectKeys(t),o=V.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===k.array&&r===k.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===k.date&&r===k.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var ur=class extends H{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=(o,i)=>{if(Ei(o)||Ei(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}):(E(r,{code:S.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}))}};ur.create=(e,t,n)=>new ur({left:e,right:t,typeName:j.ZodIntersection,...B(n)});var Ct=class e extends H{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==k.array)return E(r,{code:S.invalid_type,expected:k.array,received:r.parsedType}),D;if(r.data.length<this._def.items.length)return E(r,{code:S.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),D;!this._def.rest&&r.data.length>this._def.items.length&&(E(r,{code:S.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...r.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new ze(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>Ae.mergeArray(n,i)):Ae.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ct.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ct({items:e,typeName:j.ZodTuple,rest:null,...B(t)})};var Ti=class e extends H{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!==k.object)return E(r,{code:S.invalid_type,expected:k.object,received:r.parsedType}),D;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in r.data)s.push({key:o._parse(new ze(r,a,r.path,a)),value:i._parse(new ze(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?Ae.mergeObjectAsync(n,s):Ae.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof H?new e({keyType:t,valueType:n,typeName:j.ZodRecord,...B(r)}):new e({keyType:Cn.create(),valueType:t,typeName:j.ZodRecord,...B(n)})}},rs=class extends H{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!==k.map)return E(r,{code:S.invalid_type,expected:k.map,received:r.parsedType}),D;let s=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([a,c],l)=>({key:s._parse(new ze(r,a,r.path,[l,"key"])),value:o._parse(new ze(r,c,r.path,[l,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return D;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let c of i){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return D;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}}}};rs.create=(e,t,n)=>new rs({valueType:t,keyType:e,typeName:j.ZodMap,...B(n)});var ss=class e extends H{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==k.set)return E(r,{code:S.invalid_type,expected:k.set,received:r.parsedType}),D;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(E(r,{code:S.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&&(E(r,{code:S.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let o=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return D;u.status==="dirty"&&n.dirty(),l.add(u.value)}return{status:n.value,value:l}}let a=[...r.data.values()].map((c,l)=>o._parse(new ze(r,c,r.path,l)));return r.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(t,n){return new e({...this._def,minSize:{value:t,message:N.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:N.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};ss.create=(e,t)=>new ss({valueType:e,minSize:null,maxSize:null,typeName:j.ZodSet,...B(t)});var Ri=class e extends H{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==k.function)return E(n,{code:S.invalid_type,expected:k.function,received:n.parsedType}),D;function r(a,c){return io({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Zr(),Gt].filter(l=>!!l),issueData:{code:S.invalid_arguments,argumentsError:c}})}function s(a,c){return io({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Zr(),Gt].filter(l=>!!l),issueData:{code:S.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 He([]),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 He([r(c,l.error)]);let u=Reflect.apply(i,this,l.data),d=a._def.returns.safeParse(u,o);if(!d.success)throw new He([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:Ct.create(t).rest(Yt.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||Ct.create([]).rest(Yt.create()),returns:n||Yt.create(),typeName:j.ZodFunction,...B(r)})}},dr=class extends H{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})}};dr.create=(e,t)=>new dr({getter:e,typeName:j.ZodLazy,...B(t)});var fr=class extends H{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return E(n,{received:n.data,code:S.invalid_literal,expected:this._def.value}),D}return{status:"valid",value:t.data}}get value(){return this._def.value}};fr.create=(e,t)=>new fr({value:e,typeName:j.ZodLiteral,...B(t)});function Tm(e,t){return new mr({values:e,typeName:j.ZodEnum,...B(t)})}var mr=class e extends H{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return E(n,{expected:V.joinValues(r),received:n.parsedType,code:S.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 E(n,{received:n.data,code:S.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})}};mr.create=Tm;var pr=class extends H{_parse(t){let n=V.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==k.string&&r.parsedType!==k.number){let s=V.objectValues(n);return E(r,{expected:V.joinValues(s),received:r.parsedType,code:S.invalid_type}),D}if(this._cache||(this._cache=new Set(V.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let s=V.objectValues(n);return E(r,{received:r.data,code:S.invalid_enum_value,options:s}),D}return Pe(t.data)}get enum(){return this._def.values}};pr.create=(e,t)=>new pr({values:e,typeName:j.ZodNativeEnum,...B(t)});var An=class extends H{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==k.promise&&n.common.async===!1)return E(n,{code:S.invalid_type,expected:k.promise,received:n.parsedType}),D;let r=n.parsedType===k.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 Je=class extends H{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=>{E(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"?nr(c.value):n.value==="dirty"?nr(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"?nr(a.value):n.value==="dirty"?nr(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);V.assertNever(s)}};Je.create=(e,t,n)=>new Je({schema:e,typeName:j.ZodEffects,effect:t,...B(n)});Je.createWithPreprocess=(e,t,n)=>new Je({schema:t,effect:{type:"preprocess",transform:e},typeName:j.ZodEffects,...B(n)});var Ye=class extends H{_parse(t){return this._getType(t)===k.undefined?Pe(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ye.create=(e,t)=>new Ye({innerType:e,typeName:j.ZodOptional,...B(t)});var Et=class extends H{_parse(t){return this._getType(t)===k.null?Pe(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Et.create=(e,t)=>new Et({innerType:e,typeName:j.ZodNullable,...B(t)});var gr=class extends H{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===k.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};gr.create=(e,t)=>new gr({innerType:e,typeName:j.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...B(t)});var hr=class extends H{_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 Qr(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new He(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new He(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};hr.create=(e,t)=>new hr({innerType:e,typeName:j.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...B(t)});var os=class extends H{_parse(t){if(this._getType(t)!==k.nan){let r=this._getOrReturnCtx(t);return E(r,{code:S.invalid_type,expected:k.nan,received:r.parsedType}),D}return{status:"valid",value:t.data}}};os.create=e=>new os({typeName:j.ZodNaN,...B(e)});var lv=Symbol("zod_brand"),ao=class extends H{_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 H{_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(),nr(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})}},yr=class extends H{_parse(t){let n=this._def.innerType._parse(t),r=s=>(xn(s)&&(s.value=Object.freeze(s.value)),s);return Qr(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};yr.create=(e,t)=>new yr({innerType:e,typeName:j.ZodReadonly,...B(t)});function Cm(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Rm(e,t={},n){return e?En.create().superRefine((r,s)=>{let o=e(r);if(o instanceof Promise)return o.then(i=>{if(!i){let a=Cm(t,r),c=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=Cm(t,r),a=i.fatal??n??!0;s.addIssue({code:"custom",...i,fatal:a})}}):En.create()}var uv={object:Ve.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 dv=(e,t={message:`Input not instance of ${e.name}`})=>Rm(n=>n instanceof e,t),Im=Cn.create,$m=rr.create,fv=os.create,mv=sr.create,Pm=or.create,pv=ir.create,gv=ts.create,hv=ar.create,yv=cr.create,_v=En.create,bv=Yt.create,vv=ct.create,wv=ns.create,Sv=zt.create,xv=Ve.create,Cv=Ve.strictCreate,Ev=lr.create,Av=ki.create,kv=ur.create,Tv=Ct.create,Rv=Ti.create,Iv=rs.create,$v=ss.create,Pv=Ri.create,Ov=dr.create,Nv=fr.create,Mv=mr.create,Lv=pr.create,Uv=An.create,Dv=Je.create,jv=Ye.create,Bv=Et.create,Fv=Je.createWithPreprocess,Hv=co.create,Vv=()=>Im().optional(),qv=()=>$m().optional(),Kv=()=>Pm().optional(),Gv={string:(e=>Cn.create({...e,coerce:!0})),number:(e=>rr.create({...e,coerce:!0})),boolean:(e=>or.create({...e,coerce:!0})),bigint:(e=>sr.create({...e,coerce:!0})),date:(e=>ir.create({...e,coerce:!0}))};var Wv=D;var Yv=/^[A-Za-z0-9._-]+$/,zv=/^[A-Za-z0-9._-]+(\|[A-Za-z0-9._-]+)*$/,Om=new Set([".",".."]),je=class extends Error{pattern;constructor(t,n){super(`Invalid freeReadPathPattern ${JSON.stringify(n)}: ${t}`),this.pattern=n,this.name="FreePathPatternError"}};function Jv(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(!zv.test(s))throw new je(`malformed alternation segment ${JSON.stringify(e)}`,t);let o=s.split("|");if(o.some(i=>Om.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(Yv.test(e)){if(Om.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 Xv(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=>Jv(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){Xv(e)}var Nm=["tempo","mpp_self","merchant_self"],Mm=["catalog_static","fal_direct","fal_queue","openrouter_chat","openrouter_image","platform_proxy","tempo_gateway","x402_gateway"],Lm=["image","audio","queued_audio","video","queued_video","model_3d","llm","transcription","utility"],Um=["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=C.object({inputPerMillion:C.number().positive(),outputPerMillion:C.number().positive(),contextWindow:C.number().int().positive().optional(),maxOutput:C.number().int().positive().optional(),perRequestFeeCents:C.number().nonnegative().optional()}),Zv=C.object({strategy:C.enum(["flat","token","band"]).optional(),pricingModel:C.enum(["per-call","per-token","band"]).optional(),priceCents:C.number().nonnegative().optional(),currency:C.string().optional(),display:C.string().optional(),estimate:C.boolean().optional(),source:C.string().optional(),priceBand:C.record(C.unknown()).optional(),tokenPricing:el.optional()}).passthrough(),tl=C.discriminatedUnion("type",[C.object({type:C.literal("shortcut"),routedPath:C.string().min(1).startsWith("/")}),C.object({type:C.literal("custom"),merchantSlug:C.string().min(1),subPath:C.string().optional()}),C.object({type:C.literal("local"),fn:C.string().min(1)}),C.object({type:C.literal("read")})]),nl=C.object({amount:C.number().nonnegative(),currency:C.string().length(3).optional(),display:C.string().optional(),free:C.boolean().optional(),batchDiscount:C.number().min(0).max(100).optional()}),Dm=C.object({attestation:C.boolean().optional(),rateLimitMs:C.number().positive().optional()}),jm=C.object({displayName:C.string().optional(),feedbackEligible:C.boolean().optional(),suggestionEligible:C.boolean().optional(),batchable:C.boolean().optional()}),Bm=C.object({enabled:C.boolean().optional(),gatewayPath:C.string().min(1).startsWith("/").optional(),method:C.enum(["GET","POST","PUT","PATCH","DELETE"]).optional(),timeoutMs:C.number().int().positive().max(12e4).optional()}).strict(),Qv=C.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),ew=120,tw=120,nw=1200,rw=/^[^\u0000-\u001F\u007F]+$/;function Qc(e,t){return C.string().min(1).max(e).regex(rw,`${t} must not contain control characters`)}var rl={id:C.string().min(1),name:Qc(ew,"name"),description:Qc(nw,"description"),provider:C.string().min(1),model:C.string().min(1),category:Qv,priceCents:C.number().nonnegative(),inputSchema:C.record(C.unknown()),gatewayUrl:C.string().min(1),merchantName:Qc(tw,"merchantName"),isAsync:C.boolean().optional(),pollUrl:C.string().optional(),pollInterval:C.number().positive().optional(),pollTimeout:C.number().positive().optional(),tags:C.array(C.string()).optional(),tokenPricing:el.optional(),priceDisplay:C.string().optional(),pricingModel:C.enum(["per-call","per-token","band"]).optional(),pricingInfo:Zv.optional(),status:C.enum(["available","unavailable"]).optional(),handler:tl.optional(),pricing:nl.optional(),security:Dm.optional(),engagement:jm.optional(),gatewayConfig:Bm.optional(),freeReadPathPattern:C.string().optional().superRefine((e,t)=>{if(e!==void 0)try{Zc(e)}catch(n){t.addIssue({code:C.ZodIssueCode.custom,message:n instanceof Error?n.message:String(n)})}}),enabled:C.boolean().optional(),beta:C.boolean().optional(),deprecated:C.boolean().optional(),internal:C.boolean().optional(),employeeOnly:C.boolean().optional(),employeeOnlyRolloutFlag:C.string().min(1).max(100).optional(),replacementTool:C.string().optional(),minCliVersion:C.string().optional(),sunsetAt:C.string().optional(),rail:C.enum(Nm).optional(),executionKind:C.enum(Mm).optional(),resultKind:C.enum(Lm).optional(),extractionMode:C.enum(Um).optional(),pricingStrategy:C.enum(["flat","token","band"]).optional()},Fm=C.object({...rl,dispatch:C.literal("routed"),routedPath:C.string().min(1).startsWith("/")}).strict(),Hm=C.object({...rl,dispatch:C.literal("enveloped")}).strict(),Vm=C.object({...rl,handler:tl,pricing:nl}).strict(),qm=C.union([C.discriminatedUnion("dispatch",[Fm,Hm]),Vm]);var iw="https://fal.run",Ym="https://openrouter.mpp.tempo.xyz",ol=1024,$i=8192,aw=4096,cw=10;function lw(e){return e>=cw?aw:$i}function zm(e,t){let n=typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):ol;return Math.min(n,t)}var uw=["num_images","num_outputs","num_samples","num_videos","batch_size","n"];function Jm(e){for(let t of uw)delete e[t];return e}function dw(e){let{attestation:t,tool_id:n,...r}=e;return Jm(r)}var Km={"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=Jm({...o});return typeof s=="string"&&s.length>0?(i.image_size=s,i):(typeof r=="string"&&Km[r]&&(i.image_size=Km[r]),i)}function fw(e){let{attestation:t,tool_id:n,...r}=e;return r}function Gm(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 mw(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 pw(e,t,n,r,s,o,i,a){return mw(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:`${iw}/${r}`,merchantName:"fal.ai",buildBody:dw,tags:[],...a}}function Xm(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),usage:{include:!0}}}}function Zm(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,...h}=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,...h,model:e,...typeof a=="string"&&a.length>0?{image_config:{aspect_ratio:a}}:{},max_tokens:zm(c??l,t),usage:{include:!0}}}}function le(e,t,n,r,s,o,i){let a=i?.maxOutputTokens??lw(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: ${ol}); 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:`${Ym}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:Xm(r,a),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:s,outputPerMillion:o,...c>0?{perRequestFeeCents:c}:{}},...p}}function sl(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: ${ol}); 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:`${Ym}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:Zm(r,i),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...c}}var il=[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"]}),sl("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),sl("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}}),sl("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"]}),pw("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:Gm,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:fw,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:Gm,tags:["onchain","prices","allium","crypto","legacy"]}];function lo(e){return il.find(t=>t.id===e)}var yw=[{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 _w(e,t){let r=(Array.isArray(t.type)?t.type:t.type!==void 0?[t.type]:[]).flatMap(o=>yw.filter(i=>i.type===o)),s=new Set(r.filter(o=>o.matches(e)).map(o=>o.type));return{declared:r,matched:s}}function al(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}=_w(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"),fp=require("util"),mp=R(require("crypto")),ne=R(require("fs")),pp=R(require("os")),Oe=R(require("path"));qt();var ut=(0,fp.promisify)(Li.execFile),qw=6e4,Kw=()=>process.platform==="darwin",kn=()=>process.platform==="win32",Tn=Oe.join(pp.homedir(),".visa-mcp","bin"),_r=Oe.join(Tn,"Visa CLI"),Zt=Oe.join(Tn,"visa-keychain-win.exe"),gp=Oe.join(__dirname,"..","native"),rp="6",sp=Oe.join(Tn,"visa-keychain.version"),op=Oe.join(Tn,"visa-keychain.sha256"),ip="1",ap=Oe.join(Tn,"visa-keychain-win.version"),cp=Oe.join(Tn,"visa-keychain-win.sha256"),hp=[Oe.join(gp,"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 mp.createHash("sha256").update(t).digest("hex")}function Gw(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 lp(e){let t=typeof e?.message=="string"?e.message:"";return e?.code==="ETIMEDOUT"||e?.killed===!0||/timed out|timeout/i.test(t)}function up(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 cl(){try{if(ne.readFileSync(sp,"utf-8").trim()===rp&&ne.existsSync(_r)){let r=ne.readFileSync(op,"utf-8").trim();if(Oi(_r)!==r)g.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),ne.unlinkSync(_r);else return _r}}catch{}let e=Oe.join(gp,"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(Tn,{recursive:!0,mode:448});try{await ut("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",_r,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=Oi(_r);return ne.writeFileSync(op,t,{mode:384}),ne.writeFileSync(sp,rp,{mode:384}),_r}function yp(){for(let e of hp)if(ne.existsSync(e))return e;return null}async function cs(){try{if(ne.readFileSync(ap,"utf-8").trim()===ip&&ne.existsSync(Zt)){let r=ne.readFileSync(cp,"utf-8").trim();if(Oi(Zt)!==r)g.warn("binary:hash-mismatch:win32",{message:"Windows binary hash mismatch. Redeploying."}),ne.unlinkSync(Zt);else return Zt}}catch{}let e=yp();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(Tn,{recursive:!0}),ne.copyFileSync(e,Zt);let t=Oi(Zt);return ne.writeFileSync(cp,t,{mode:384}),ne.writeFileSync(ap,ip,{mode:384}),Zt}async function Ww(){return kn()?cs():cl()}var Ni="visa-cli",Mi="attestation-key";async function Yw(e){try{await ut("security",["delete-generic-password","-s",Ni,"-a",Mi],{timeout:5e3})}catch{}await ut("security",["add-generic-password","-s",Ni,"-a",Mi,"-w",e],{timeout:5e3})}function zw(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 Jw(){try{let{stdout:e}=await ut("security",["find-generic-password","-s",Ni,"-a",Mi,"-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:zw(e)}}}async function ll(){let e=await Jw();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 _p(e){let t=await Ww(),n;try{n=(await ut(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?.toString().trim()||r.message||"Unknown error")}return Gw(n)}var dp=!1;function Xw(){if(!kn())return!1;try{return ne.existsSync(Zt)||yp()!==null?!0:(dp||(dp=!0,g.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:Zt,searchedPrebuiltPaths:hp})),!1)}catch{return!1}}function de(){return Hr()||Kw()?!0:kn()?Xw():!1}async function Ui(){if(kn()){let s=await cs(),{stdout:o}=await ut(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 _p(["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 Yw(n),r}async function Di(){if(kn())try{let e=await cs(),{stdout:t}=await ut(e,["public-key"],{timeout:1e4});return t.trim().startsWith("OK:")}catch{return!1}return await ll()!==null}async function bp(){if(Hr())return"mock-public-key-spki";if(kn()){let n=await cs(),{stdout:r}=await ut(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 ll();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await cl();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?.toString().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(Hr())return Promise.resolve(Pd());let r=n.timeoutMs??qw;if(kn()){let a=await cs(),c=["sign",e];t&&c.push(t);let l;try{l=(await ut(a,c,{timeout:r})).stdout}catch(d){throw lp(d)?up(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 ll();if(!s)throw new Error("Attestation key not found. Run setup to generate a new key.");let o=await cl(),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))):lp(u)?c(up(r)):c(new Error(u.stderr?.toString().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(kn()){try{let e=await cs();await ut(e,["delete-key"],{timeout:1e4})}catch{}return}try{await ut("security",["delete-generic-password","-s",Ni,"-a",Mi],{timeout:5e3})}catch{}try{await _p(["delete-key"])}catch{}}qt();var Zw=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],Qw=[...Zw.map(e=>({id:`legacy.${e}`,toolId:e,targetToolId:e,rail:"tempo",reason:"Preserve legacy Tempo _card target while the top-level MCP surface is opt-in."}))];function ul(e,t=Qw){for(let n of t)if(n.toolId===e.requestedTool)return n.targetToolId;return null}function dl(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function vp(e=process.env){return dl(e)!==null}var eS=new Set(["false","0","no","off","disable","disabled"]),tS=new Set(["true","1","yes","on","enable","enabled"]);function wp(e){let t=(e??"").trim().toLowerCase();return t?eS.has(t)?!1:!!tS.has(t):!0}function Sp(e=process.env){return wp(e.VISA_CLI_PARENTLESS_SINGLE_CALL)}function xp(e=process.env){return wp(e.VISA_CLI_PARENTLESS_BATCH)}var gy=require("child_process"),Ce=R(require("crypto")),pt=R(require("fs")),$o=R(require("os")),Na=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"?Vr(s):null,i=Array.isArray(n.urls)?n.urls[0]:void 0,c=typeof i=="string"&&i.startsWith("data:")?Vr(i):null;if(!o&&!c)return e;let l=o??c,u=o?"content":"urls",d;try{d=Us(l,{tag:nS(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 nS(e,t){let n=typeof t.transactionId=="string"?t.transactionId:typeof t.transaction_id=="string"?t.transaction_id:null;return n?`${e}-${n}`:e}qt();var fl=!1;async function br(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(g.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(fl)throw g.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;fl=!0,g.info("attestation:starting-browser-recovery");try{let o=await n();if(!o.success)throw g.error("attestation:browser-recovery-failed",{message:o.message}),r;let i=await Ui();await e.registerAttestationKey(i),await e.setBiometricPreference({required:!0}),g.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),g.info("attestation:key-reregistered-after-recovery");let a=await t();return fl=!1,a}catch(o){throw g.error("attestation:recovery-failure",{error:o.message}),r}}throw r}}function kt(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 kt(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."}}St();var Cp="4.0.0-rc.16";function ml(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function pl(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 Xe(e){return e==null?"\u2014":e?"yes":"no"}function Fi(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function rS(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function sS(){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(A){n=A?.message||"unknown error"}let r=[],s=process.env.VISA_AUTH_URL,o=qc("auth.serverUrl"),i=Se(),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:Xe(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:Xe(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:Xe(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:de(),formatted:Xe(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:Fi(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:Fi(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:Fi(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:Fi(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(A=>A.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=sS();r.push({key:"credit.sessionCapCents",value:m.value,formatted:rS(m.value),source:m.source});let p=mm();p.length>0&&r.push({key:"settings.retired",value:p.map(A=>A.key),formatted:p.map(A=>A.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${p.map(A=>`visa-cli config unset ${A.key}`).join(" && ")}`});let h=pl("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:h.value,formatted:Xe(h.value),source:h.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let v=pl("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:v.value,formatted:Xe(v.value),source:v.source});let I=wt(),_;process.env.VISA_CLI_NO_UPDATE_CHECK?_={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?_={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?_={kind:"env",var:"NODE_ENV"}:_={kind:"default"},r.push({key:"ui.updateCheck",value:!I,formatted:Xe(!I),source:_});let b=pl("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:b.value,formatted:Xe(b.value),source:b.source});let w=process.env.VISA_DRY_RUN,T=vp();if(r.push({key:"tools.dryRun",value:T,formatted:Xe(T),source:w===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:Cp,formatted:Cp,source:{kind:"default"}}),e.includeDev){let A=process.env.VISA_MOCK_KEYCHAIN,y=dn();r.push({key:"dev.mockKeychain",value:y,formatted:Xe(y),source:ml("VISA_MOCK_KEYCHAIN",!!A),hint:nc()});let x=process.env.VISA_MOCK_TOUCHID,Y=Hr();r.push({key:"dev.mockTouchid",value:Y,formatted:Xe(Y),source:ml("VISA_MOCK_TOUCHID",!!x),hint:nc()});let X=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!X,formatted:Xe(!!X),source:ml("VISA_CLI_DEBUG",!!X)})}return{entries:r,statusError:n}}function oS(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 Ep(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}(${oS(o.source)})`),t.verbose&&o.hint&&s.push(` ${"\u21B3".padStart(n)} ${o.hint}`)}return s.join(`
144
+ `)}function Ap(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 kp(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/1)} images. Try something now, or save them for later.`,balanceUsd:t,examples:[{tool:"fal-flux-schnell",cost:"$0.01",what:"an AI image"},{tool:"or-gpt-4o-mini",cost:"token-priced",what:"a quick model call"},{tool:"fal-ace-step-music",cost:"$0.02",what:"a music track"}]}}}St();qt();var In=require("fs"),Rp=require("os"),gl=require("path"),iS=(0,gl.join)((0,Rp.homedir)(),".visa-mcp"),Tp=(0,gl.join)(iS,"mcp-session-budget.json");function Hi(){try{(0,In.existsSync)(Tp)&&(0,In.unlinkSync)(Tp)}catch{}}var yl=require("crypto"),dt=R(as()),wr=null,Ge=0,Pn=0,qe=0,$n=null,_l=null,bl=null,vr=Promise.resolve();function aS(e){return Number((0,dt.fromCents)(e))}function $p(e){return(0,dt.toCents)((0,dt.micros)(BigInt(e)))}function Ip(e){return(0,dt.toWire)((0,dt.fromCents)(e))}function hl(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Vi(e){return typeof e=="string"&&/^\d+$/.test(e)}var cS=43,lS=new RegExp(`^[A-Za-z0-9_-]{${cS}}$`);function uS(e){return typeof e=="string"&&lS.test(e)}function dS(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||wr&&e.session_id!==wr||typeof e.nonce!="string"||e.nonce.length===0||!uS(e.server_signature)||!hl(e.cumulative)||!hl(e.remaining)||!hl(e.delta)||e.cumulative<Ge||qe>0&&e.cumulative>qe||qe>0&&e.remaining>qe||e.cumulative_micros!==void 0&&!Vi(e.cumulative_micros)||e.remaining_micros!==void 0&&!Vi(e.remaining_micros)||e.delta_micros!==void 0&&!Vi(e.delta_micros)||e.reserved_micros!==void 0&&!Vi(e.reserved_micros))}function Qt(e){wr=e,Ge=0,Pn=0,qe=0,$n=null,_l=null,bl=null,vr=Promise.resolve()}function mo(e){qe=Math.max(0,Math.floor(e))}function vl(){return wr}function wl(e){if(!wr)return null;let t=Ge+Pn;return qe>0&&t>qe&&(t=qe),{session_budget_id:wr,cumulative_micros:aS(t),nonce:(0,yl.randomUUID)(),idempotency_key:e||(0,yl.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 dS(r)?(Ge=Math.max(Ge,r.cumulative),Pn=0,$n=r,r):null}function Pp(){return $n}function Sl(e){let t=$p(e.cumulative_micros);Ge=Math.max(Ge,t),Pn=0;let n={status:"accepted",session_id:e.session_budget_id,cumulative:Ge,remaining:Math.max(0,qe-Ge),delta:0,cumulative_micros:Ip(Ge),remaining_micros:Ip(Math.max(0,qe-Ge)),delta_micros:"0",nonce:e.nonce};return $n=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,dt.toCents)((0,dt.micros)(n));if(!Number.isFinite(r)||r<0)return;_l=t;let s=e,o=typeof s.session_id=="string"?s.session_id:wr??"";$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 Op(e){let t=e.receipt??null;bl={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:$p(e.voucher.cumulative_micros),estimatedCumulativeCents:qi(),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 Np(){return bl}function Mp(){return Ge}function Lp(){return _l}function qi(){let e=Ge+Pn;return qe>0&&e>qe&&(e=qe),e}function xl(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return vr=vr.then(()=>{Pn+=t}),vr}function ho(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return vr=vr.then(()=>{Pn=Math.max(0,Pn-t)}),vr}var fS=10,mS=1,fe=null,Up=Promise.resolve();function Cl(e){let t=Up.catch(()=>{}).then(e);return Up=t.then(()=>{},()=>{}),t}var xe=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 El(e,t,n){return Cl(()=>Dp(e,t,n))}async function Dp(e,t,n){if(Hi(),fe&&new Date(fe.expiresAt).getTime()>Date.now())return vl()!==fe.budgetId&&(Qt(fe.budgetId),mo(fe.totalCents)),g.info("mcp-session:active-hit",{budgetId:fe.budgetId,tool:n.toolName,remainingEstimatedCents:fe.totalCents-qi()}),{budgetId:fe.budgetId,isFresh:!1,totalCents:fe.totalCents,requestedCapCents:fe.totalCents,appliedCapCents:fe.totalCents,clampedReason:null};fe&&(fe=null,Qt(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"?mS:fS,i=Math.max(o,Math.ceil(n.minRequiredCents??o));if(r.balanceCents<i)throw new xe(r.balanceCents,i);let a=n.capCentsOverride??hm(),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,Qt(f.budgetId),mo(f.totalCents),g.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 jp(e,t,n){return Cl(async()=>{let s=On()?await Bp(e):null,o=await Dp(e,t,n);return{budgetId:o.budgetId,totalCents:o.totalCents,closedPrevious:s,requestedCapCents:o.requestedCapCents,appliedCapCents:o.appliedCapCents,clampedReason:o.clampedReason}})}async function Bp(e){let n=On()?.budgetId??vl(),r=!1,s,o;if(n)try{let i=await e.closeSession(n);r=!!i?.success,typeof i?.finalCumulativeCents=="number"&&(s=i.finalCumulativeCents),typeof i?.finalCumulativeMicros=="string"&&(o=i.finalCumulativeMicros)}catch(i){g.warn("mcp-session:close-server-failed",{budgetId:n,error:i?.message||String(i)})}return Hi(),fe=null,Qt(null),{closedServerSide:r,budgetId:n,finalCumulativeCents:s,finalCumulativeMicros:o}}async function Ki(e){return Cl(()=>Bp(e))}function On(){return Hi(),fe?new Date(fe.expiresAt).getTime()<=Date.now()?(fe=null,Qt(null),null):{budgetId:fe.budgetId,totalCents:fe.totalCents,lastReceiptCumulative:Mp(),lastReceiptCumulativeMicros:Pp()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:Lp(),estimatedCumulative:qi(),lastToolSpend:Np(),expiresAt:fe.expiresAt}:null}var Hp=R(as()),Fp=10000n;function pS(e){return e<=0n?0:Number((e+Fp-1n)/Fp)}function Vp(e){return pS((0,Hp.fromUsd)(e))}var Gi=R(as()),gS=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;function Wi(e){if(typeof e!="string"||!gS.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,Gi.toDisplay)((0,Gi.fromCents)(s),{symbol:""})}}var Yi="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.";St();var ny=Promise.resolve();function yE(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 ry=!1,sy=!1,oy=!1;function Ma(e){let t=ny.catch(()=>{}).then(e);return ny=t.then(()=>{},()=>{}),t}async function hy(e){let t=await Ee(()=>El(U,nt,{toolName:e.toolId,userContext:e.userContext}));await xl(e.estimatedAmountCents);let n=wl(e.idempotencyKey);if(!n)throw await ho(e.estimatedAmountCents),new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await kE(),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 Vt){let d=Math.min(Math.max(u.retryAfterSecs,0),5)*1e3;g.warn("mcp-session:lock-contended-retrying",{tool:e.toolId,retryAfterSecs:u.retryAfterSecs}),await new Promise(f=>setTimeout(f,d)),{data:s,voucherReceiptHeader:o}=await i()}else throw u}}catch(u){if(await ho(e.estimatedAmountCents),u instanceof zr){if(g.warn("mcp-session:server-invalidated-budget",{code:u.code,budgetId:u.budgetId??t.budgetId,tool:e.toolId}),await Ki(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 oy||(oy=!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.`)),g.info("mcp-session:falling-back-to-payg",{code:u.code,tool:e.toolId}),yy(e)}throw u instanceof Vt?(g.warn("mcp-session:lock-contended-give-up",{tool:e.toolId}),new Error("Another paid call is currently in progress on this session. Wait a moment and try again.")):u}let a=po(o)??(n?Sl(n):null);if(go(s?.receipt_v2),Op({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),ju(s))return At(s);let c=await Du();if(e.idempotencyKey&&Bu(s,c,e.idempotencyKey))return At(s);let l=c?Ro(c):null;return At(Fu(s,r,l))}function et(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 Uu(e,t,n,r){let s=Ce.createHash("sha256").update(`${n}:${Ia(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${s}`}function _E(e,t){return`${e}:${t}`}function bE(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=mt(r),o=s!==null?s.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=bE(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),c=i!=null?String(i):a;return{batch_id:e,item_id:_E(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 yy(e){return Ee(()=>wE(e))}async function _y(e,t,n){if(ju(e))return At(e);let r=await Du();if(n&&Bu(e,r,n))return At(e);let s=r?Ro(r):null;return At(Fu(e,t,s))}async function vE(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 nt("shortcut_call",t,e.toolId,n,e.userContext);g.info("parentless-single-call:attempt",{tool:e.toolId,approvedMaxCents:t,attested:!!r});let s=r?.nonce??(await U.getAttestationChallenge()).nonce,{data:o,voucherReceiptHeader:i}=await U.shortcutParentless(e.toolId,{...r?{attestation:r}:{},nonce:s,approved_max_cents:t,idempotency_key:e.idempotencyKey},e.toolParams,e.timeoutMs,e.userContext,e.metaTool);return po(i),go(o?.receipt_v2),g.info("parentless-single-call:completed",{tool:e.toolId}),_y(o,e.beforeBalanceMicros,e.idempotencyKey)}async function wE(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 xe(n.balanceCents,t);let r=t,s=Ro(n);if(Sp()&&!ry){let u=e.idempotencyKey??Ce.randomUUID();try{return await vE({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)ry=!0,g.info("parentless-single-call:falling-back-to-session",{tool:e.toolId,status:d.status,serverErrorCode:d.serverErrorCode});else throw d}}let o=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(r/100).toFixed(2)})`,i=await nt("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;Qt(c),mo(a.budget.totalCents),g.info("on-demand-session:opened",{budgetId:c,capCents:a.budget.totalCents,tool:e.toolId});let l=!1;try{await xl(e.estimatedAmountCents);let u=wl(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)||Sl(u),l=!0,go(d?.receipt_v2),ju(d))return At(d);let m=await Du();if(e.idempotencyKey&&Bu(d,m,e.idempotencyKey))return At(d);let p=m?Ro(m):null;return At(Fu(d,s,p))}catch(u){throw l||await ho(e.estimatedAmountCents),u}finally{try{await U.closeSession(c)}catch(u){g.warn("on-demand-session:close-failed",{budgetId:c,error:u?.message||String(u)})}Qt(null),g.info("on-demand-session:closed",{budgetId:c,tool:e.toolId})}}async function Kn(e){return Ma(async()=>On()?hy(e):yy(e))}function La(){return Se()}var SE="https://v4-verify-web-visa-code-preview.up.railway.app";function xE(e=Hu){return/^\d+\.\d+\.\d+$/.test(e)&&e!=="0.0.0"}function by(e=process.env,t=Hu){return e.VISA_VERIFY_WEB_URL?e.VISA_VERIFY_WEB_URL:xE(t)?null:SE}var U=new Ke(()=>G.getSessionToken());function mt(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function Ro(e){return mt(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function CE(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 EE(e){let t=mt(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=mt(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=mt(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function To(e,t="INVALID_TOOL_PARAMS",n){return{success:!1,error_code:t,code:t,error:e,message:e,...n??{}}}function AE(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 kE(){try{let e=await U.getBalance();return e.success?Ro(e):null}catch{return null}}async function Du(){try{let e=await U.getBalance();return e.success?e:null}catch{return null}}function ju(e){if(!e||e.success===!1)return!1;let t=mt(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=mt(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 Bu(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=mt(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 Fu(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 Hu="4.0.0-rc.16",t$=["","","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 tt(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=Hs(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(pm())return{opened:!1,url:t,blockedReason:"suppressed"};let n=hc();if(n.headless)return g.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let s=[La(),by()].filter(i=>!!i).map(i=>Yd(t,i)).find(Boolean)??null;if(!s)return g.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let o=Jd(s);return o?((0,gy.execFile)(o.cmd,o.args,i=>{i&&g.warn(`Browser open failed: ${i.message}. URL: ${s}`)}),{opened:!0,url:s}):(g.info(`No browser command for platform "${$o.platform()}". URL: ${s}`),{opened:!1,url:s,blockedReason:"unsupported_platform"})}async function Ee(e){return br(U,e,Ty)}var vy="get_cards",wy="set_default_card";function TE(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 '${vy}' to see enrolled cards and '${wy}' to switch, then retry the original request.`}function RE(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 '${vy}' to see enrolled cards and '${wy}' to switch. Do not retry automatically.`}function gt(e,t){let n=e.retryable?TE(e.code,e.retryAfter):RE(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 IE(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 Es=null,$E=3e4;function Sy(){Es=null}var qn=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 PE(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:Yi,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 OE(e){let t=Date.now();if(Es&&Es.expiresAt>t)return{required:Es.required,hasRegisteredKey:Es.hasRegisteredKey};try{let n=await U.getStatus(e),r=kt(n),s=n.attestationRequired!==!1;return Es={required:s,hasRegisteredKey:r,expiresAt:t+$E},{required:s,hasRegisteredKey:r}}catch{return{required:!0,hasRegisteredKey:!0}}}async function nt(e,t,n,r,s,o){if(!o?.forceRequired){let i=await OE(s);if(!i.required){g.info("attestation:skipped-by-server-policy",{context:e});return}if(!i.hasRegisteredKey){g.info("attestation:skipped-no-registered-key",{context:e});return}}if(!de())throw g.warn("attestation:unavailable",{context:e}),new qn(e);g.info("attestation:attempt",{context:e,amount:t,merchant:n});try{let{nonce:i}=await U.getAttestationChallenge(),a=Buffer.from(JSON.stringify({nonce:i,amount:t,merchant:n,context:e})).toString("base64");g.info("touchid:prompt",{context:e,amount:t,merchant:n});let c=await Rn(a,r);return g.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??"")?(g.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.")):(g.error("attestation:failure",{context:e,amount:t,merchant:n,error:i.message}),i)}}var iy="[dry-run] https://placeholder.visa-cli.dev/image.png",NE=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"]),ME=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 LE(e){return e.startsWith("or-")?"llm":NE.has(e)?"image":ME.has(e)?"video":UE(e)?"media":null}function UE(e){let t=lo(e);return t?!Da(t):!1}function DE(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function jE(e){return e==="llm"?"OpenRouter":"fal.ai"}function As(e,t,n,r){let s={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:jE(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${DE(n)}`;return{...s,content:i,data:{content:i,model:t,dry_run:!0}}}return{...s,urls:[iy],data:{[e==="video"?"videoUrl":e==="image"?"imageUrl":"url"]:iy,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:Ce.randomUUID(),timestamp:new Date().toISOString(),tool_name:e.toolName,user_prompt:e.userContext??"",tool_params:JSON.stringify(e.toolParams),result_success:!0,result_error:null,result_json:JSON.stringify(e.result),payment_rail:r,payment_amount:0,payment_currency:"USD",merchant_name:e.result.merchantName,transaction_id:e.result.transactionId,tx_hash:null,protocol:null,http_status:200,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",event_kind:"mcp_tool",endpoint:n,resolved_model:e.resolvedModel,session_budget_id:null}])}catch(s){g.warn("dry_run:telemetry_failed",{tool:e.toolName,error:s?.message||String(s),mode:t})}}var BE="https://openrouter.ai/api/v1/chat/completions",FE="openrouter/free",HE=50,VE=15e3;function qE(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 KE(e,t,n){let r=process.env.OPENROUTER_API_KEY;if(!r)return g.warn("preflight:no_openrouter_key_falling_back_to_mock",{tool:e}),{result:As("llm",e,t,n),degraded:!0,resolvedModel:null};let s=qE(t),o;try{o=await bt(BE,{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:FE,messages:[{role:"user",content:s}],max_tokens:HE}),timeoutMs:VE})}catch(u){return g.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:As("llm",e,t,n),degraded:!0,resolvedModel:null}}if(!o.ok){let u=await o.text().catch(()=>"");return g.warn("preflight:openrouter_http_error_falling_back_to_mock",{tool:e,status:o.status,bodyExcerpt:u.slice(0,200)}),{result:As("llm",e,t,n),degraded:!0,resolvedModel:null}}let i;try{i=await o.json()}catch(u){return g.warn("preflight:openrouter_invalid_json_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:As("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=dl();if(!s)return null;let o=LE(e);if(!o)return null;let i=Date.now();if(s==="mock"){let l=As(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"}),g.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:o,mode:s}),l}if(o!=="llm"){g.warn("preflight:not_supported_for_kind_falling_back_to_mock",{tool:e,kind:o});let l=As(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 KE(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"}),g.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 Vp(e.amount)}function GE(e,t,n){return n.has(e.resolvedTool)?0:Math.max(1,ln(t[e.resolvedTool]))}function WE(){return Na.join($o.homedir(),".visa-mcp","allium-results")}var n$=16*1024,r$=50*1024*1024;function YE(){let e=WE();try{if(!pt.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=pt.readdirSync(e),n=0,r=0;for(let s of t)try{let o=pt.statSync(Na.join(e,s));o.isFile()&&(n+=o.size,r++)}catch{}return{file_count:r,size_bytes:n,path:e}}catch(t){return g.warn("allium:disk_usage_error",{error:t.message}),{file_count:0,size_bytes:0,path:e}}}var ay=3600*1e3,Mu=0;function zE(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function Oo(e){if(!gm()&&!(Date.now()<Mu))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}}),g.info("feed:submitted",{tool:e.tool,mediaType:e.mediaType,transactionId:e.transactionId})}catch(t){if(zE(t)){let n=Mu===0;Mu=Date.now()+ay,n&&g.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:ay});return}g.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function JE(e,t){let n=(e.state||"").trim().toUpperCase(),r=(e.county||"").trim(),s=(e.start_date||"").trim(),o=(e.end_date||s).trim();if(!/^[A-Z]{2}$/.test(n))throw new Error('state must be a 2-letter US state code (e.g. "VA").');if(!r)throw new Error("county is required.");if(!/^\d{4}-\d{2}$/.test(s))throw new Error('start_date must be YYYY-MM (e.g. "2025-08").');if(o&&!/^\d{4}-\d{2}$/.test(o))throw new Error("end_date must be YYYY-MM.");let i="Visa SMI",a=.1,c=`Pay $0.10 to ${i} for SMI data (${n} / ${r})`;g.info("payment:attempt",{tool:"get_visa_smi",amount:a,merchant:i});try{return await Ee(async()=>{let l=await nt("get_visa_smi",a,i,c),u=await U.getVisaSmi({state:n,county:r,start_date:s,end_date:o,attestation:l,idempotencyKey:Ce.randomUUID()},t);return u.success?g.info("payment:success",{tool:"get_visa_smi",merchant:i,charged_cents:u.charged_cents}):g.warn("payment:declined",{tool:"get_visa_smi",merchant:i,message:u.error}),u})}catch(l){if(l instanceof he)return g.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 g.error("payment:failure",{tool:"get_visa_smi",merchant:i,error:l.message}),l}}async function XE(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=Ce.randomUUID();g.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await Ee(async()=>{let o;try{o=await Kn({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:ln(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof xe)return et(i);throw i}return g.info("payment:success",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>tt(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})):g.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof he)return g.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 ZE(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=Ce.randomUUID();g.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await Ee(async()=>{let o;try{o=await Kn({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:ln(r),userContext:t,timeoutMs:6e4,idempotencyKey:s})}catch(i){if(i instanceof xe)return et(i);throw i}return g.info("payment:success",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>tt(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})):g.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof he)return g.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 QE(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=Ce.randomUUID();g.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await Ee(async()=>{let o;try{o=await Kn({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:ln(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof xe)return et(i);throw i}return g.info("payment:success",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>tt(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})):g.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof he)return g.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 eA(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=Ce.randomUUID();g.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await Ee(async()=>{let s;try{s=await Kn({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:ln(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(o){if(o instanceof xe)return et(o);throw o}return g.info("payment:success",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),s.urls?.length&&s.status!=="processing"?(s.urls.forEach(o=>tt(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,g.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):g.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof he)return g.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 tA(e,t){let n=await cn("check_music_status_tempo_card",void 0,t),r=Ce.randomUUID();g.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await Ee(async()=>{let s;try{s=await Kn({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:ln(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof xe)return et(o);throw o}return g.info("payment:success",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),s.urls?.length&&s.urls.forEach(o=>tt(o)),s})}catch(s){if(s instanceof he)return g.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 nA(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=Ce.randomUUID();g.info("payment:attempt",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName});try{return await Ee(async()=>{let s;try{s=await Kn({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:ln(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof xe)return et(o);throw o}if(g.info("payment:success",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,mode:"session"}),Array.isArray(s?.data))s.data=s.data.map(o=>{if("mint"in o&&!("address"in o)){let{mint:i,...a}=o;return{address:i,...a}}return o});else if(s&&"mint"in s&&!("address"in s)){let{mint:o,...i}=s;return{address:o,...i}}return s})}catch(s){if(s instanceof he)return g.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 rA=["generate_music_tempo_card"],Cs=10,cy=5,ly=new Map;function uy(e){let t=ly.get(e);if(t!==void 0)return t;let r=lo(e)?.isAsync===!0||rA.includes(e);return ly.set(e,r),r}var sA=36e4,oA=18e4,iA=15e3,aA=12e4,cA=2e3;function Lu(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}function lA(e,t){return Ce.createHash("sha256").update(`${e}:${Ia(t)}`).digest("hex")}function uA(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=mt(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=>tt(d)),{deltaCharged:l,deltaMicros:u}}function dA(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(I=>I?.success===!1).length,m=t.length-f,p=t.flatMap(I=>Array.isArray(I?.urls)?I.urls:[]),h=l>0n?Number(l)/1e6:Math.round((c+Number.EPSILON)*100)/100,v=m===0?"failure":f===0?"success":"partial";return g.info("payment:success",{tool:"batch",batchTool:o,count:n.length,totalAmount:a,totalCharged:h,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:h,...l>0n?{totalChargedMicros:l.toString(),amountMicros:l.toString(),amount_micros:l.toString()}:{},merchantName:i,results:t,...p.length?{urls:p}:{}}}async function fA(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,h=i,v=await U.getBalance();if(!v.success)throw new Error(`Could not read balance: ${v.error||"unknown error"}`);if(v.balanceCents<h)throw new xe(v.balanceCents,h);let I=`batch-${m}`,_=`spend up to $${(h/100).toFixed(2)} across a batch of ${t.length}`,{batchParentId:b}=await Ee(async()=>{let y=await nt("batch_open",h,I,_,p,{forceRequired:!0}),x=y?.nonce??(await U.getAttestationChallenge()).nonce;g.info("parentless-batch:open-attempt",{batchTool:l,count:t.length,approvedTotalCents:h,attested:!!y});let{batch_parent_id:Y}=await U.batchOpen({...y?{attestation:y}:{},nonce:x,approved_total_cents:h,batch_id:m});return{batchParentId:Y}});g.info("parentless-batch:opened",{batchTool:l,count:t.length,batchParentId:b});let w=[],T=0,A=0n;try{for(let y=0;y<t.length;y+=1){let x=t[y],Y=n[x.resolvedTool],X=r.has(x.resolvedTool);try{let K;if(X)K=await U.shortcut(x.resolvedTool,x.params,f,p,"batch");else{let{data:Z,voucherReceiptHeader:Os}=await U.shortcutParentlessBatchItem(x.resolvedTool,{batch_parent_id:b,batch_id:m,batch_index:y,batch_request_hash:lA(x.resolvedTool,x.params),item_ceiling_cents:o[y],idempotency_key:Uu(m,y,x.resolvedTool,x.params)},x.params,f,p,"batch");po(Os),go(Z?.receipt_v2),K=await _y(Z,null,Uu(m,y,x.resolvedTool,x.params))}let{deltaCharged:be,deltaMicros:se}=uA({results:w,batchId:m,index:y,item:x,itemResult:K,preview:Y,isFree:X,catalogName:s[x.resolvedTool]?.name});T+=be,A+=se}catch(K){if(K instanceof xe&&w.length===0)return et(K);g.warn("payment:batch-item-failed",{tool:x.resolvedTool,index:y,error:K?.message||String(K)}),w.push({success:!1,tool:x.resolvedTool,...$a(m,y),error:K?.message||String(K)})}}return dA({results:w,resolvedItems:t,uniqueTools:a,isHomogeneous:c,primaryTool:l,merchantNames:u,totalAmount:d,totalCharged:T,totalChargedMicros:A,batchId:m,mode:"parentless"})}catch(y){if(y instanceof he)return g.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 mA(e,t){let n;if(Array.isArray(e.requests)&&e.requests.length>Cs)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${Cs} items. Please split into smaller batches.`};if(e.requests?.some(y=>y.tool||y.tool_id)&&e.requests)n=e.requests.map(y=>{let x=y.tool||y.tool_id||e.tool;if(!x)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let Y=ul({requestedTool:x})??x,{tool:X,tool_id:K,tier:be,params:se,...Z}=y,Os=se&&typeof se=="object"?{...se,...Z}:Z;return{resolvedTool:Y,params:Os}});else if(e.tool){let y=ul({requestedTool:e.tool})??e.tool;if(e.count!==void 0){if(!Number.isSafeInteger(e.count)||e.count<1)return Lu("BATCH_INVALID_COUNT","Batch count must be a positive integer.");if(e.count>Cs)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${Cs} items. Please split into smaller batches.`}}n=(e.requests||(e.count!==void 0&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(Y=>({resolvedTool:y,params:Y}))}else return Lu("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return Lu("BATCH_EMPTY","Batch requires at least one item.");if(n.length>Cs)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${Cs} items. Please split into smaller batches.`};if([...new Set(n.map(y=>y.resolvedTool))].some(uy)&&n.length>cy)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${cy} 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 Ry(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=>GE(y,u,l)),m=f.reduce((y,x)=>y+x,0),p=[...new Set([...Object.values(u).map(y=>y.merchantName),...i.filter(y=>l.has(y)).map(y=>c[y]?.name??y)])].join(", "),h=a?i[0]:"mixed";g.info("payment:attempt",{tool:"batch",batchTool:h,count:n.length,totalAmount:d,merchant:p,heterogeneous:!a});let v=n.some(y=>uy(y.resolvedTool)),I=n.some(y=>y.resolvedTool.startsWith("or-")||y.resolvedTool==="run_llm"||y.resolvedTool==="execute_tool"),_=v?sA:I?oA+n.length*iA:aA+n.length*cA,b=Ce.randomUUID(),w=[],T=0,A=0n;return Ma(async()=>{let y=!On();if(xp()&&!sy&&y&&m>0)try{return await fA({resolvedItems:n,previews:u,freeTools:l,catalogEntries:c,itemCeilingCents:f,batchCeilingCents:m,uniqueTools:i,isHomogeneous:a,primaryTool:h,merchantNames:p,totalAmount:d,timeoutMs:_,batchId:b,userContext:t})}catch(x){if(x instanceof vt)sy=!0,g.info("parentless-batch:falling-back-to-session",{batchTool:h,count:n.length,status:x.status,serverErrorCode:x.serverErrorCode});else{if(x instanceof xe)return et(x);throw x}}if(y&&m>0)try{let x=m;await Ee(()=>El(U,nt,{toolName:"batch",userContext:t,sessionKind:"one_shot",minRequiredCents:x,capCentsOverride:x}))}catch(x){return x instanceof xe?et(x):(g.warn("payment:batch-prewarm-failed",{batchTool:h,count:n.length,error:x?.message||String(x)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:x?.message||"Failed to authenticate batch session",tool:h,count:n.length,failedCount:n.length,results:[]})}try{for(let se=0;se<n.length;se+=1){let Z=n[se],Os=u[Z.resolvedTool];try{let ue=l.has(Z.resolvedTool)?await U.shortcut(Z.resolvedTool,Z.params,_,t,"batch"):await hy({toolId:Z.resolvedTool,toolParams:Z.params,estimatedAmountCents:f[se],userContext:t,metaTool:"batch",timeoutMs:_,idempotencyKey:Uu(b,se,Z.resolvedTool,Z.params)});if(l.has(Z.resolvedTool)&&ue&&typeof ue=="object"&&!Array.isArray(ue)&&ue.merchantName==null&&(ue.merchantName=c[Z.resolvedTool]?.name??Z.resolvedTool),w.push({success:ue?.success!==!1,tool:Z.resolvedTool,...ue,...$a(b,se,ue)}),ue?.success!==!1){let Ns=mt(ue?.amountMicros??ue?.amount_micros),Sd=typeof ue?.amount=="number"?ue.amount:Os?.amount??0;Ns!==null&&Ns>0n?A+=Ns:A+=BigInt(Math.round(Sd*1e6)),T+=Sd}ue?.urls&&ue.urls.forEach(Ns=>tt(Ns))}catch(ue){if(ue instanceof xe&&w.length===0)return et(ue);g.warn("payment:batch-item-failed",{tool:Z.resolvedTool,index:se,error:ue?.message||String(ue)}),w.push({success:!1,tool:Z.resolvedTool,...$a(b,se),error:ue?.message||String(ue)})}}let x=w.filter(se=>se?.success===!1).length,Y=w.length-x,X=w.flatMap(se=>Array.isArray(se?.urls)?se.urls:[]),K=A>0n?Number(A)/1e6:Math.round((T+Number.EPSILON)*100)/100,be=Y===0?"failure":x===0?"success":"partial";return g.info("payment:success",{tool:"batch",batchTool:h,count:n.length,totalAmount:d,totalCharged:K,merchant:p,successCount:Y,failedCount:x,outcome:be,mode:"session",batchId:b}),{success:Y>0,outcome:be,batch_id:b,tool:a?i[0]:h,count:n.length,successCount:Y,failedCount:x,totalCharged:K,...A>0n?{totalChargedMicros:A.toString(),amountMicros:A.toString(),amount_micros:A.toString()}:{},merchantName:p,results:w,...X.length?{urls:X}:{}}}catch(x){if(x instanceof he)return g.warn("payment:declined",{tool:"batch",batchTool:h,count:n.length,totalAmount:d,merchant:p,code:x.code,retryable:x.retryable}),gt(x,{amount:d,merchantName:p});throw un(x,{tool:"batch",batchTool:h,count:n.length,totalAmount:d,merchant:p}),x}finally{if(y){let x=await Ki(U);g.info("batch-session:closed",{budgetId:x.budgetId,closedServerSide:x.closedServerSide})}}})}function pA(){let e=!1,t;try{let r=Na.join($o.homedir(),".claude","settings.json");if(pt.existsSync(r)){let s=JSON.parse(pt.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 gA(e){let[t,n]=await Promise.all([U.getStatus(e),U.getBalance().catch(o=>(g.warn("get_status:balance_fetch_failed",{error:o?.message||String(o)}),null))]);typeof t?.dailyRemaining=="number"&&(t.dailyRemaining=Math.round(t.dailyRemaining*100)/100);let r=YE();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=pA(),!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=Hu,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=On();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 xy(e,t){try{let r=((await U.getStatus(t)).cards||[]).find(s=>s?.id===e);if(r)return qu(r)}catch(n){g.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function hA(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 yA(e,t){return await U.getTransactions({limit:e.limit,offset:e.offset},t)}async function _A(e,t){return await U.feedback(e.message,e.transaction_id,t)}async function bA(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=Wi(String(e.amount));if(n.ok===!1)return{success:!1,error:n.error};let r=n.cents,s=r/100,o=Ce.randomUUID();g.info("buy_credits:attempt",{amountCents:r});try{return await Ee(async()=>{let i=await nt("balance-topup",s,"Visa CLI Balance",`top up balance with $${n.displayUsd}`,t,{forceRequired:!0}),a=await U.topupBalance({amount_cents:r,idempotency_key:o,attestation:i});if(a.success){g.info("buy_credits:success",{amountCents:r,balanceCents:a.balanceCents,balanceMicros:a.balanceMicros});let c=yE(a.balanceMicros,a.balanceCents??0),l=(r/100).toFixed(2);return{...a,amount:r/100,amountMicros:String(r*1e4),merchantName:"Visa CLI Balance",message:`Added $${l} \u2014 balance is now ${c}`}}return g.warn("buy_credits:failed",{amountCents:r,error:a.error}),a})}catch(i){if(i instanceof qn)return PE();if(i instanceof it)return g.warn("buy_credits:ambiguous",{amountCents:r,code:i.code,transactionId:i.transactionId}),IE(i);throw g.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 vA(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");g.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await Ee(async()=>{let n=await nt("spending-controls",0,"","update spending controls"),r=await U.updateSpendingControls({maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit,confirm:!0,attestation:n},t);return g.info("spending_controls:success",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit}),r})}catch(n){if(g.error("spending_controls:failure",{error:n.message}),n instanceof qn)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 wA(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(tr).filter(e=>!Ku.has(e)).sort()}function Cy(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 SA(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 g.warn("config:set:rejected:mcp-forbidden",{key:e.key}),Cy(e.key,"set");g.info("config:set",{key:e.key});try{let t=xi(e.key,e.value);return g.info("config:set:success",{key:t.key,requiresRestart:t.requiresRestart}),{success:!0,key:t.key,value:t.value,requiresRestart:t.requiresRestart,path:t.path,message:t.requiresRestart?`Saved ${t.key}. Restart Claude Code for the change to take effect.`:`Saved ${t.key}.`}}catch(t){let n=t instanceof at?"UNKNOWN_KEY":t instanceof Kt?"SERVER_CONTROLLED":t instanceof vn?"RETIRED_KEY":"INVALID_VALUE",r=t instanceof at?`Unknown setting "${e.key}". MCP-settable keys: ${Io().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return g.warn("config:set:rejected",{key:e.key,code:n,error:r}),{success:!1,error:r,code:n,settableKeys:Io()}}}async function xA(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 g.warn("config:unset:rejected:mcp-forbidden",{key:e.key}),Cy(e.key,"unset");g.info("config:unset",{key:e.key});try{let t=Ci(e.key);return g.info("config:unset:success",{key:t.key,removed:t.removed}),{success:!0,key:t.key,removed:t.removed,requiresRestart:t.requiresRestart,path:t.path,message:t.removed?t.requiresRestart?`Removed ${t.key}. Restart Claude Code for the change to take effect.`:`Removed ${t.key}.`:`${t.key} was not set in settings.json \u2014 nothing to remove.`}}catch(t){let n=t instanceof at?"UNKNOWN_KEY":t instanceof Kt?"SERVER_CONTROLLED":t instanceof vn?"RETIRED_KEY":"INVALID_VALUE",r=t instanceof at?`Unknown setting "${e.key}". MCP-settable keys: ${Io().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return g.warn("config:unset:rejected",{key:e.key,code:n,error:r}),{success:!1,error:r,code:n,settableKeys:Io()}}}async function CA(e){let t=await U.getStatus(e),n=t.attestationRequired!==!1,r=kt(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 EA(e){g.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?(Sy(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:n.error||"unknown error"}}async function AA(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.");g.info("biometric:off");try{return await Ee(async()=>{let n=await U.getStatus(t),r;if(kt(n)&&(r=await nt("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 Sy(),{success:!0,required:!1,message:"Touch ID is no longer required for payments."}})}catch(n){if(g.error("biometric:off:failure",{error:n.message}),n instanceof qn)return Ua(n,"biometric_off");throw n}}var dy=3e4,kA=3e5;async function Ey(e,t,n="login"){let r=Ce.randomUUID(),s=`${e}${e.includes("?")?"&":"?"}state=${r}`,o=tt(s);return!o.opened&&o.blockedReason!=="non_internal_host"&&o.blockedReason!=="invalid_url"?Ay(s,o,n):o.opened?{...await ky(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 Ay(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 ky(e,t,n="login"){let r=Date.now()+kA;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:dy,...t&&{user_context:t}}),signal:AbortSignal.timeout(dy+5e3)});if(!o.ok){await hn(o,a=>{g.warn("auth_status:retry_after_http_error",{status:o.status,delayMs:a})});continue}let i=await o.json();if(i.status==="pending")continue;if(i.status==="expired")return{success:!1,message:"Session expired. Please try again."};if(i.status==="error")return{success:!1,message:i.error||"Authentication failed. Please try again."};if(i.status==="complete"){if(n==="attestation-recovery"||i.attestationCleared)return g.info("auth:attestation_recovery_complete",{user:i.user||""}),{success:!0,message:"Server-side biometric state cleared. Run visa-cli setup to register a fresh key before reenabling Touch ID."};let a=i.welcomeBonusCents??0,c=kp(a);if(n!=="enrollment"&&i.sessionToken){await G.saveSessionToken(i.sessionToken);let u=i.user||"",d=i.last4||"****";return g.info("auth:login_complete",{user:u,last4:d,bonusCents:a}),{success:!0,message:`Signed in as ${u}. Card ending in ${d} enrolled and ready for payments.`,...c||{}}}let l=i.last4||"****";return g.info("auth:card_added",{last4:l,bonusCents:a}),{success:!0,message:`Card ending in ${l} enrolled and ready for payments.`,...c||{}}}}catch{await hn(void 0,o=>{g.warn("auth_status:retry_after_network_error",{delayMs:o})})}return{success:!1,message:n==="enrollment"?"Card enrollment timed out. Please try again.":n==="attestation-recovery"?"Biometric reset timed out. Please try reset again.":"Login timed out. Please try again."}}async function Ty(e){let t=Ce.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=tt(n.recoveryUrl);return!r.opened&&r.blockedReason!=="non_internal_host"&&r.blockedReason!=="invalid_url"?Ay(n.recoveryUrl,r,"attestation-recovery"):r.opened?{...await ky(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 TA(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to remove this card."};let n=e.cardId;if(!Number.isInteger(n)||n<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to get the opaque cardId for the card you want to remove."};g.info("cards:remove_attempt",{cardId:n});let r=`remove-card:${n}`,s=`remove ${await xy(n,t)}`;try{return await Ee(async()=>{let o=await nt(r,0,"",s,t,{forceRequired:!0}),i=await U.removeCard(n,{attestation:o},t);return g.info("cards:remove_success",{cardId:n,promotedId:i?.promotedId??null}),i})}catch(o){if(g.error("cards:remove_failure",{cardId:n,error:o.message}),o instanceof qn)return Ua(o,"remove_card");throw o}}async function RA(e,t){let n=e.cardId;if(!Number.isInteger(n)||n<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to get the opaque cardId for the card you want to make default."};g.info("cards:set_default_attempt",{cardId:n});let r=`set-default-card:${n}`,s=`set ${await xy(n,t)} as default`;try{return await Ee(async()=>{let o=await nt(r,0,"",s,t,{forceRequired:!0}),i=await U.setDefaultCard(n,{attestation:o},t);return g.info("cards:set_default_success",{cardId:n}),i})}catch(o){if(g.error("cards:set_default_failure",{cardId:n,error:o.message}),o instanceof qn)return Ua(o,"set_default_card");throw o}}async function IA(e){return g.info("auth:login_attempt"),Ey(`${La()}/login`,e)}async function $A(e=by()){if(!e)return{success:!1,message:"The Visa Verified Agent enrollment flow is not yet publicly available in stable builds. Set VISA_VERIFY_WEB_URL to a deployment URL to use enroll_agent."};g.info("agent:enroll_open",{url:e});let t=tt(e),n="sign in \u2192 pick your .visa name \u2192 wallet \u2192 card (secure fields) \u2192 bank verification with passkey \u2192 mint";return t.opened?{success:!0,opened:!0,browserUrl:t.url,message:`Opened the Visa Verified Agent enrollment in your browser (${n}). Access is currently tester-gated \u2014 if sign-in shows "private testing", ask for the v4_verify_web_access flag.`}:{success:!0,opened:!1,requiresBrowser:!0,browserUrl:t.url??e,message:`Open this URL in a browser to enroll your agent (${n}): ${t.url??e}`}}function PA(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 OA(e={},t){let n;try{n=PA(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return Ma(async()=>{let r=await Ee(()=>jp(U,nt,{toolName:"start_session",userContext:t,capCentsOverride:n}));g.info("session:started",{budgetId:r.budgetId,totalCents:r.totalCents,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious});let s=(r.appliedCapCents/100).toFixed(2),o=(r.requestedCapCents/100).toFixed(2),i=`Session started with a $${s} cap. Paid calls will use this approval window until you close it, it expires, or this MCP process restarts.`,a=r.clampedReason==="balance"?`${i} Note: requested cap of $${o} was clamped to your prepaid balance of $${s}. Run buy_credits to top up if you need a larger session.`:i;return{success:!0,budgetId:r.budgetId,totalCents:r.totalCents,amountUsd:r.totalCents/100,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious,message:a}})}async function NA(){let e=On();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 MA(){return Ma(async()=>{let e=On();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 Ki(U);g.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=EE(e),r=mt(t.finalCumulativeMicros),s=r??(typeof t.finalCumulativeCents=="number"?BigInt(Math.max(0,t.finalCumulativeCents))*10000n:n.micros),o=Number(s/10000n);return g.info("session:closed:final-spend",{budgetId:t.budgetId,closedServerSide:t.closedServerSide,finalSpendMicros:s.toString(),finalSpendCents:o,finalSpendSource:r!==null?"server.finalCumulativeMicros":typeof t.finalCumulativeCents=="number"?"server.finalCumulativeCents":n.source,totalCents:e.totalCents}),{success:!0,closed:!0,closedServerSide:t.closedServerSide,budgetId:t.budgetId,finalEstimatedCumulativeCents:o,finalEstimatedCumulativeMicros:s.toString(),totalCents:e.totalCents,message:t.closedServerSide?`Explicit approval window closed. Spent ${CE(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 LA(e){if(g.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 Ey(`${La()}/enroll-card?code=${encodeURIComponent(n)}`,e,"enrollment")}async function fy(){if(await G.clearAll(),de())try{await ji()}catch{}}async function UA(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};if(g.info("reset:attempt"),e.localOnly)return await fy(),g.info("reset:success",{localOnly:!0}),{success:!0,message:"Device reset locally. Local credentials and keys have been removed; server-side session and biometric state were not changed. Use the login tool or visa-cli setup to sign in with the GitHub account you want to use."};let n=!1;try{let r=await U.getStatus(t);if(r&&kt(r)){let s=await Ty(t);if(!s.success)return s;n=!0}}catch(r){let s=r?.message||"unknown error";if(!/not logged in|session.*expired|no local credentials/i.test(s))return{success:!1,message:`Could not check server biometric state: ${s}`};g.warn("reset:server_attestation_status_unavailable",{error:s})}try{await U.logout(void 0,t)}catch{}return await fy(),g.info("reset:success"),{success:!0,message:n?"Device reset. Server-side biometric state and local credentials have been cleared. Use the login tool or visa-cli setup to re-enroll.":"Device reset. Local credentials and keys have been removed. Use the login tool or visa-cli setup to re-enroll."}}async function DA(e){let t=e.query?.trim()||void 0,n=e.category?.trim()||void 0,r=!t&&!n;g.info("catalog:discover",{query:t,category:n,browseAll:r});try{let o=(await U.catalogSearch(t,n)).tools||[];if(o.length===0)return{content:[{type:"text",text:r?"The tool catalog is currently empty.":`No tools found for "${t||n}". Try a different search term.`}]};if(r){let a={};for(let l of o){let u=l.category||"other";(a[u]??=[]).push(l)}let c=Object.keys(a).sort().map(l=>{let u=a[l].map((f,m)=>`${m+1}. **${f.name}** (${f.id})
147
147
  ${f.description}
148
- Provider: ${f.provider} | Price: ${py(f)}${gy(f)}
148
+ Provider: ${f.provider} | Price: ${my(f)}${py(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)}
152
152
 
153
153
  ${u}`}).join(`
154
154
 
155
- `);return h.info("catalog:discovered",{count:o.length}),{content:[{type:"text",text:`Available ${o.length} tool(s) by category:
155
+ `);return g.info("catalog:discovered",{count:o.length}),{content:[{type:"text",text:`Available ${o.length} tool(s) by category:
156
156
 
157
157
  ${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: ${py(a)}${gy(a)}
161
+ Provider: ${a.provider} | Category: ${a.category} | Price: ${my(a)}${py(a)}
162
162
  Params: ${Object.keys(a.inputSchema?.properties||a.inputSchema||{}).join(", ")||"none"}`).join(`
163
163
 
164
- `);return h.info("catalog:discovered",{count:o.length}),{content:[{type:"text",text:`Found ${o.length} tool(s):
164
+ `);return g.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 py(e){return e.priceDisplay??`$${(e.priceCents/100).toFixed(2)}`}function gy(e){let t=e.protocol;return t==="mpp"||t==="x402"?" | Paid from your prepaid balance":""}function qE(e,t){return t==="image"||t==="video"||t==="audio"?t:e?.match(/\.(mp4|webm|mov)/)?"video":"image"}function KE(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=ol(a,c,l);if(u)return u}return null}async function Iy(e){let t=co(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 La(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 GE(e){let t=e;return t.platformRoute===!0||typeof t.platformMerchantSlug=="string"||t.executionKind==="platform_proxy"}function WE(e){let n=e.inputSchema?.properties;return!!n&&typeof n=="object"&&Object.keys(n).length>0}function YE(e){return La(e)&&GE(e)&&!WE(e)}function zE(e){return e.split(/[-_]/).filter(t=>t.length>0&&!/^[0-9a-f]{8,}$/i.test(t)).join(" ").trim()}async function JE(e){let t=zE(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 XE(e,t,n="execute_tool"){let{tool_id:r,params:s,...o}=e,i=s||o;if(!r)return ko("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 Iy(r);if(!a){let p=await JE(r),g=p.length?` Did you mean: ${p.map(b=>b.tool_id).join(", ")}?`:"";return ko(`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 ko(`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,b=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}),ko(b,"SURFACE_DISABLED",{tool_id:r,...p?{unavailable_reason:p}:{},...g?{flag:g}:{}})}let l=n&&n!=="execute_tool"?n:void 0,u=YE(a)?null:KE(a,i,l);if(u)return h.info("catalog:execute:validation_failed",{tool:r,metaTool:n,error:u}),ko(u);let d=await $o(r,i,t,n);if(d)return d;if(La(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 Ce(async()=>{let p;try{p=await Kn({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(b=>et(b));let g=qE(p.urls[0],p.mediaType);Po({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}),pt(p,f)):($y(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}),$A({toolId:r,surface:n,merchantName:f.merchantName,amount:f.amount,message:p?.message||"Tool execution failed."}))}}function $y(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};$y(e?.message)?h.warn("payment:ambiguous",n):h.error("payment:failure",n)}async function ZE(e){if(!e.name)return{success:!1,error:"name is required"};try{let{registerName:t,ensureMailbox:n}=await Promise.resolve().then(()=>(Ss(),Eo)),r=await t(e.name);return await n(e.name),{success:!0,...r}}catch(t){let{CardRequiredError:n}=await Promise.resolve().then(()=>(Ca(),Bh));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 QE(e){if(!e.name)return{success:!1,error:"name is required"};try{let{resolveMeshName:t}=await Promise.resolve().then(()=>(Ss(),Eo));return{success:!0,...await t(e.name)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async function e1(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(()=>(Ss(),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 t1(e){try{let{readInbox:t,resolveActingName:n,meshName:r}=await Promise.resolve().then(()=>(Ss(),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 Pt=class{static async subwayRegister(t){return ZE(t||{})}static async subwayFind(t){return QE(t||{})}static async subwaySend(t){return e1(t||{})}static async subwayInbox(t){return t1(t||{})}static async getStatus(t){return vE(t)}static async getVisaSmi(t,n){return tE(t,n)}static async getCards(t){return wE(t)}static async transactionHistory(t,n){return SE(t||{},n)}static async feedback(t,n){return xE(t,n)}static async updateSpendingControls(t,n){return AE(t,n)}static async configList(t){return EE(t||{})}static async configSet(t){return kE(t||{})}static async configUnset(t){return TE(t||{})}static async biometricStatus(t){return RE(t)}static async biometricOn(t){return IE(t)}static async biometricOff(t,n){return $E(t,n)}static async reset(t,n){return HE(t,n)}static async login(t){return ME(t)}static async enrollAgent(t){return LE()}static async closeSession(t){return BE()}static async startSession(t,n){return DE(t||{},n)}static async getSessionStatus(t){return jE()}static async addCard(t){return FE(t)}static async removeCard(t,n){return OE(t,n)}static async setDefaultCard(t,n){return NE(t,n)}static async buyCredits(t,n){return CE(t,n)}static async batch(t,n){return _E(t,n)}static async discoverTools(t){return VE(t)}static async executeTool(t,n,r="execute_tool"){return XE(t,n,r)}static async shortcut(t,n,r){switch(t){case"generate_image_card":return nE(n,r);case"generate_image_fast_card":return rE(n,r);case"generate_video_tempo_card":return sE(n,r);case"generate_music_tempo_card":return oE(n,r);case"check_music_status_tempo_card":return iE(n,r);case"query_onchain_prices_card":return aE(n,r);default:{let s=await $o(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 Kn({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=>et(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}),pt(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}}};Ht();function Py(e,t=process.stderr){if(vt()||!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 g.error("catalog:discover:error",{error:s.message}),new Error(`Failed to search tool catalog: ${s.message}`)}}function my(e){return e.priceDisplay??`$${(e.priceCents/100).toFixed(2)}`}function py(e){let t=e.protocol;return t==="mpp"||t==="x402"?" | Paid from your prepaid balance":""}function jA(e,t){return t==="image"||t==="video"||t==="audio"?t:e?.match(/\.(mp4|webm|mov)/)?"video":"image"}function BA(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=al(a,c,l);if(u)return u}return null}async function Ry(e){let t=lo(e);if(t)return t;try{return await U.catalogTool(e)}catch(n){return g.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 FA(e){let t=e;return t.platformRoute===!0||typeof t.platformMerchantSlug=="string"||t.executionKind==="platform_proxy"}function HA(e){let n=e.inputSchema?.properties;return!!n&&typeof n=="object"&&Object.keys(n).length>0}function VA(e){return Da(e)&&FA(e)&&!HA(e)}function qA(e){return e.split(/[-_]/).filter(t=>t.length>0&&!/^[0-9a-f]{8,}$/i.test(t)).join(" ").trim()}async function KA(e){let t=qA(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 g.warn("catalog:suggest:error",{tool:e,error:n?.message||String(n)}),[]}}async function GA(e,t,n="execute_tool"){let{tool_id:r,params:s,...o}=e,i=s||o;if(!r)return To("tool_id is required. Use discover_tools first to find available tools.","MISSING_TOOL_ID");g.info("catalog:execute",{tool:r,metaTool:n});let a=await Ry(r);if(!a){let p=await KA(r),h=p.length?` Did you mean: ${p.map(v=>v.tool_id).join(", ")}?`:"";return To(`Unknown tool: '${r}'.${h} 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 To(`Tool '${r}' is deprecated and is no longer available for new paid calls.${p}`,"DEPRECATED_TOOL")}if(a.status==="unavailable"){let p=a.unavailableReason,h=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 g.info("catalog:execute:surface_disabled",{tool:r,metaTool:n,unavailableReason:p??null,killSwitchFlag:h??null}),To(v,"SURFACE_DISABLED",{tool_id:r,...p?{unavailable_reason:p}:{},...h?{flag:h}:{}})}let l=n&&n!=="execute_tool"?n:void 0,u=VA(a)?null:BA(a,i,l);if(u)return g.info("catalog:execute:validation_failed",{tool:r,metaTool:n,error:u}),To(u);let d=await Po(r,i,t,n);if(d)return d;if(Da(a)){g.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=Ce.randomUUID();g.info("payment:attempt",{tool:r,amount:f.amount,merchant:f.merchantName});try{return await Ee(async()=>{let p;try{p=await Kn({toolId:r,toolParams:i,estimatedAmountCents:ln(f),userContext:t,metaTool:n,timeoutMs:12e4,idempotencyKey:m})}catch(h){if(h instanceof xe)return et(h);throw h}if(g.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=>tt(v));let h=jA(p.urls[0],p.mediaType);Oo({prompt:i.prompt||`${r} execution`,tool:r,mediaUrl:p.urls[0],mediaType:h,cost:p.amount??f.amount,transactionId:p.transactionId,userContext:t})}return p})}catch(p){return p instanceof he?(g.warn("payment:declined",{tool:r,amount:f.amount,merchant:f.merchantName,code:p.code,retryable:p.retryable}),gt(p,f)):(Iy(p?.message)?g.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`."}):g.error("payment:failure",{tool:r,amount:f.amount,merchant:f.merchantName,error:p.message}),AE({toolId:r,surface:n,merchantName:f.merchantName,amount:f.amount,message:p?.message||"Tool execution failed."}))}}function Iy(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};Iy(e?.message)?g.warn("payment:ambiguous",n):g.error("payment:failure",n)}async function WA(e){if(!e.name)return{success:!1,error:"name is required"};try{let{registerName:t,ensureMailbox:n}=await Promise.resolve().then(()=>(xs(),ko)),r=await t(e.name);return await n(e.name),{success:!0,...r}}catch(t){let{CardRequiredError:n}=await Promise.resolve().then(()=>(xo(),jh));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 YA(e){if(!e.name)return{success:!1,error:"name is required"};try{let{resolveMeshName:t}=await Promise.resolve().then(()=>(xs(),ko));return{success:!0,...await t(e.name)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async function zA(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(()=>(xs(),ko)),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 JA(e){try{let{readInbox:t,resolveActingName:n,meshName:r}=await Promise.resolve().then(()=>(xs(),ko)),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 Nt=class{static async subwayRegister(t){return WA(t||{})}static async subwayFind(t){return YA(t||{})}static async subwaySend(t){return zA(t||{})}static async subwayInbox(t){return JA(t||{})}static async getStatus(t){return gA(t)}static async getVisaSmi(t,n){return JE(t,n)}static async getCards(t){return hA(t)}static async transactionHistory(t,n){return yA(t||{},n)}static async feedback(t,n){return _A(t,n)}static async updateSpendingControls(t,n){return vA(t,n)}static async configList(t){return wA(t||{})}static async configSet(t){return SA(t||{})}static async configUnset(t){return xA(t||{})}static async biometricStatus(t){return CA(t)}static async biometricOn(t){return EA(t)}static async biometricOff(t,n){return AA(t,n)}static async reset(t,n){return UA(t,n)}static async login(t){return IA(t)}static async enrollAgent(t){return $A()}static async closeSession(t){return MA()}static async startSession(t,n){return OA(t||{},n)}static async getSessionStatus(t){return NA()}static async addCard(t){return LA(t)}static async removeCard(t,n){return TA(t,n)}static async setDefaultCard(t,n){return RA(t,n)}static async buyCredits(t,n){return bA(t,n)}static async batch(t,n){return mA(t,n)}static async discoverTools(t){return DA(t)}static async executeTool(t,n,r="execute_tool"){return GA(t,n,r)}static async shortcut(t,n,r){switch(t){case"generate_image_card":return XE(n,r);case"generate_image_fast_card":return ZE(n,r);case"generate_video_tempo_card":return QE(n,r);case"generate_music_tempo_card":return eA(n,r);case"check_music_status_tempo_card":return tA(n,r);case"query_onchain_prices_card":return nA(n,r);default:{let s=await Po(t,n,r);if(s)return s;let o=await cn(t,void 0,r,n);g.info("payment:attempt",{tool:t});try{let i=await Kn({toolId:t,toolParams:n,estimatedAmountCents:ln(o),userContext:r,timeoutMs:6e4});return g.info("payment:success",{tool:t,mode:"session"}),i.urls?.length&&i.urls.forEach(a=>tt(a)),i}catch(i){if(i instanceof xe)return et(i);if(i instanceof he)return g.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){g.info("feedback:submit",{length:t.length,transactionId:n,hasContext:!!r});try{let s=await U.submitFeedback(t,n,r);return g.info("feedback:submitted",{transactionId:n}),s}catch(s){let o=s instanceof Error?s.message:"Unknown error";throw g.error("feedback:error",{error:o,transactionId:n}),s}}static async getFeedback(t,n){g.info("feedback:list",{limit:t||20});try{let r=await U.getFeedback(t,n);return g.info("feedback:listed",{count:r?.feedback?.length||0}),r}catch(r){let s=r instanceof Error?r.message:"Unknown error";throw g.error("feedback:error",{error:s}),r}}};qt();function $y(e,t=process.stderr){if(wt()||!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 Ny(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]=Oy(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]=Oy(o,n[o]?.description);return s}function Oy(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 n1(e){let t=Ot(e.referralCode,"");if(!t)return[];let n=["Referrals",` Your code ${t}`],r=Ot(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 r1=20;function Ly(e,t,n,r){let s=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=u1(e.spendingControls).dailyLimit,a=Math.max(0,Oo(e.dailyCardFundedTopupSpent??e.dailySpent)),c=i>0?Math.min(i,Math.max(0,Oo(e.dailyCardFundedTopupRemaining??e.dailyRemaining??i-a))):0,l=i>0?Math.min(1,a/i):0,d=(Array.isArray(t)?t:[]).filter(i1),f=d.slice(0,3),m=a1(d,3),p=(e.cards??[]).slice(0,3),g=r.latestVersion?Lr(r.latestVersion):"",b=r.updateCheckDisabled?"update checks disabled":g?`update ready: v${g}`:"up to date",A=Math.round(l*100),_=Ot(e.status,e.enrolled?"approved":"not enrolled"),w=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${_} | touch id: ${n?"ready":"unavailable"}`,`Version: v${s} | ${b}`,`Top-up meter: ${My(l)} ${String(A).padStart(3," ")}% | remaining ${Es(c)}/day | daily top-up cap ${Es(i)}`,"","Card top-ups",` Remaining ${Es(c)} / ${Es(i)}`,` Usage ${My(l)} ${A}%`,` Top-ups today ${Es(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...p.length>0?p.map(E=>` ${l1(E)}`):[" No cards enrolled"],"","Last 3 services",...m.length>0?m.map((E,y)=>` ${y+1}. ${E}`):[" No paid services yet"],"","Recent receipts",...f.length>0?f.map(E=>` ${c1(E)}`):[" No receipts yet"]],T=n1(e);return T.length>0&&w.push("",...T),g&&!r.updateCheckDisabled?(w.push("",`Update: v${g} ready \u2014 run \`visa-cli update\``),r.updateMessage&&w.push(` ${Lr(r.updateMessage)}`)):r.updateMessage&&w.push("",`Update: ${Lr(r.updateMessage)}`),`${w.join(`
170
+ `),!0}function Oy(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]=Py(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]=Py(o,n[o]?.description);return s}function Py(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 XA(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 ZA=20;function My(e,t,n,r){let s=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=o1(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(t1),f=d.slice(0,3),m=n1(d,3),p=(e.cards??[]).slice(0,3),h=r.latestVersion?Ur(r.latestVersion):"",v=r.updateCheckDisabled?"update checks disabled":h?`update ready: v${h}`:"up to date",I=Math.round(l*100),_=Mt(e.status,e.enrolled?"approved":"not enrolled"),w=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${_} | touch id: ${n?"ready":"unavailable"}`,`Version: v${s} | ${v}`,`Top-up meter: ${Ny(l)} ${String(I).padStart(3," ")}% | remaining ${ks(c)}/day | daily top-up cap ${ks(i)}`,"","Card top-ups",` Remaining ${ks(c)} / ${ks(i)}`,` Usage ${Ny(l)} ${I}%`,` Top-ups today ${ks(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...p.length>0?p.map(A=>` ${s1(A)}`):[" No cards enrolled"],"","Last 3 services",...m.length>0?m.map((A,y)=>` ${y+1}. ${A}`):[" No paid services yet"],"","Recent receipts",...f.length>0?f.map(A=>` ${r1(A)}`):[" No receipts yet"]],T=XA(e);return T.length>0&&w.push("",...T),h&&!r.updateCheckDisabled?(w.push("",`Update: v${h} ready \u2014 run \`visa-cli update\``),r.updateMessage&&w.push(` ${Ur(r.updateMessage)}`)):r.updateMessage&&w.push("",`Update: ${Ur(r.updateMessage)}`),`${w.join(`
171
171
  `)}
172
- `}function s1(e){return e.tool_name!=null}function o1(e){return Oo(e.amount)===0&&e.status==="failed"}function i1(e){return s1(e)&&!o1(e)}function a1(e,t=1/0){let n=new Set,r=[];for(let s of e){if(r.length>=t)break;let o=Ot(s.merchant_name,"Unknown merchant"),i=Ot(s.tool_name,"unknown_tool"),a=`${o} :: ${i}`;n.has(a)||(n.add(a),r.push(`${o} [${i}]`))}return r}function c1(e){let t=Ot(e.merchant_name,"Unknown merchant"),n=Ot(e.tool_name,"unknown_tool"),r=Es(Oo(e.amount)),s=Ot(e.status,"unknown"),o=d1(e.created_at);return`${r} ${s.padEnd(9)} ${t} [${n}] ${o}`}function l1(e){let t=Ot(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function u1(e){return{dailyLimit:Oo(e?.daily_limit??e?.dailyLimit??0)}}function Oo(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function Es(e){return`$${e.toFixed(2)}`}function My(e,t=r1){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function Ot(e,t){let n=Lr(e??"").trim();return n.length>0?n:t}function d1(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?Ot(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function Lr(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 f1=/^[1-9]\d{0,9}$/;function qu(e){if(!f1.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 Uy(e){let t=Lr(e.brand||"Visa"),n=Lr(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=I(require("fs")),_e=I(require("path")),m1=["npm","pnpm","yarn","bun"],p1=/\s+/,g1=process.platform==="win32"?"visa-cli.cmd":"visa-cli",Ku=["node_modules","@visa","cli"];function h1(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(p1)[0]??"",r=n.indexOf("/"),s=r===-1?n:n.slice(0,r);return m1.includes(s)?s:void 0}function Gu(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 y1(e=process.argv[1]){return h1()??Gu(process.env.npm_execpath)??Gu(process.env.npm_node_execpath)??Gu(e)}function _1(e=process.env.PATH??""){let t=[];for(let n of e.split(_e.delimiter))n&&t.push(n);return t}function b1(e=process.env.PATH??""){let t=new Set,n=[];for(let r of _1(e))try{let s=_e.join(r,g1);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 Dy(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 v1(e){let t=_e.resolve(e).split(_e.sep);for(let n=t.length-Ku.length;n>=0;n--)if(Ku.every((r,s)=>t[n+s]===r)){let r=t.slice(0,n+Ku.length).join(_e.sep)||_e.sep;if(Dy(r))return r}}function w1(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 S1(e,t){let n=_e.resolve(e);try{n=Nt.realpathSync(e)}catch{}let r=v1(n);return{binPath:e,realPath:n,packageRoot:r,version:r?Dy(r):void 0,prefix:w1(r),isActive:n===t}}function x1(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,...b1(t)].filter(Boolean),o=new Map;for(let d of s){let f=S1(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 C1(e,t=process.platform){return/^[A-Za-z0-9_./:@+-]+$/.test(e)?e:t==="win32"?`"${e.replace(/"/g,'""')}"`:`'${e.replace(/'/g,"'\\''")}'`}function Wu(e,t,n,r={}){let s=t??y1(n)??"npm",o=r.withDiagnostics?x1(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 ${C1(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 A1(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 Yu(e,t){if(!e.hasConflictingInstalls)return null;let n=["Multiple Visa CLI installs detected.",...e.installs.map(A1)];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 Ka=I(os());function E1(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function jy(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=E1(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 By(){await G.deleteSessionToken()}var Vy=I(require("crypto"));wa();var Ge=I(require("fs")),Ua=I(require("os")),ks=I(require("path")),qy=I(require("node:readline")),zu="4.0.0-rc.15",k1=process.env.PORTER_API_URL??"https://porter-travel.up.railway.app",T1=process.env.TAP_REGISTRY_URL??"https://tap-production-eff9.up.railway.app",No=ks.join(Ua.homedir(),".visa-cli","agents");function R1(){return!!(process.env.VISA_DEV==="1"||zu==="0.0.0"||zu.startsWith("0.0.")||/-rc\.|-beta\./.test(zu))}function I1(){Ge.mkdirSync(No,{recursive:!0,mode:448})}function Zu(e){return ks.join(No,`${e}.json`)}function Ju(){return Ge.existsSync(No)?Ge.readdirSync(No).filter(e=>e.endsWith(".json")).map(e=>ks.join(No,e)):[]}function $1(e){let t=Zu(e);return Ge.existsSync(t)?JSON.parse(Ge.readFileSync(t,"utf8")):null}function P1(e){I1();let t=Zu(e.agent_id);Ge.writeFileSync(t,JSON.stringify(e,null,2),{mode:384})}async function Xu(e,t,n,r){let s=`${e.replace(/\/+$/,"")}${n}`,o=await fetch(s,{method:t,headers:{"Content-Type":"application/json"},body:r!==void 0?JSON.stringify(r):void 0}),i=await o.json().catch(()=>({}));if(!o.ok||i.errors?.length){let a=i.errors?.[0];throw new Error(`${t} ${s} failed (${o.status}): ${a?.code??"unknown"} \u2014 ${a?.message??"no message"}`)}if(i.data===void 0)throw new Error(`${t} ${s}: empty response data`);return i.data}var Fy=Xu;function O1(){let{secretKey:e}=$h(),t=Oh(e);return{publicKeyB64url:t.x,privateJwk:t}}function Ky(e,t){let n=So(t);return _s(wo(n,new TextEncoder().encode(e)))}async function N1(e){let{publicKeyB64url:t,privateJwk:n}=O1(),r=new Date().toISOString(),s=`tap:register:v1:${e.name}:${r}`,o=Ky(s,n),i=await Xu(e.registryUrl,"POST","/api/v1/agents",{name:e.name,public_key:t,signed_at:r,signature:o,visibility:"public",capabilities:["porter:book","visa:authorize_payment"]}),a=await Xu(e.porterUrl,"POST","/api/v1/tap/accounts",{public_key:t,name:e.name}),c={agent_id:i.agent_id,tap_registry_url:e.registryUrl,porter_url:e.porterUrl,tap_account_id:a.id,public_key_b64url:t,private_key_jwk:n,name:e.name,created_at:new Date().toISOString()};return P1(c),c}async function Gy(e){let t=await Fy(e.porter_url,"GET",`/api/v1/tap/challenge?public_key=${encodeURIComponent(e.public_key_b64url)}`),n=Ky(t.challenge,e.private_key_jwk),r=await Fy(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 M1(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=So(e),l=wo(c,new TextEncoder().encode(a));return`${a}.${_s(l)}`}var L1=["visa_authorize_payment"],U1={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 D1(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 j1(e,t){let n=Math.floor(Date.now()/1e3),r=n+300,s=`vpid_${Vy.randomBytes(16).toString("hex")}`,o=process.env.VISACLI_ISSUER??e.tap_registry_url??e.porter_url;return{jwt:M1(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 B1(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 Gy(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=D1(p);if(!g.ok){i(f,-32602,g.error);return}let b=g.value;try{let{jwt:A,jti:_,expiresAt:v}=j1(e,b);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: ${b.merchant}`,` amount: ${b.amount} ${b.currency.toUpperCase()}`,` jti: ${_}`,` expires: ${new Date(v*1e3).toISOString()}`].join(`
175
- `)},{type:"text",text:JSON.stringify({visa_payment_id:A,jti:_,agent_id:e.agent_id,amount:b.amount,currency:b.currency.toUpperCase(),merchant:b.merchant,expires_at:v})}]}})}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"&&L1.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 _=JSON.parse(A);l(f,_),o(_)}}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(U1)}async function u(f,m){let p=f.body?.getReader();if(!p)return;let g=new TextDecoder,b="";for(;;){let{done:A,value:_}=await p.read();if(A)break;b+=g.decode(_,{stream:!0});let v;for(;(v=b.indexOf(`
176
-
177
- `))>=0;){let w=b.slice(0,v);b=b.slice(v+2);for(let T of w.split(`
178
- `))if(T.startsWith("data: ")){let E=T.slice(6).trim();if(!E)continue;try{let y=JSON.parse(E);l(m,y),o(y)}catch{}}}}}await s().catch(()=>{});let d=qy.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 Hy(e){let t=Ju();if(t.length===0)throw new Error("No agents registered. Run `visa-cli agent register` first.");if(e){let n=$1(e);if(!n)throw new Error(`Agent not found: ${e}`);return n}if(t.length>1){let n=t.map(r=>ks.basename(r,".json")).map(r=>` - ${r}`).join(`
179
- `);throw new Error(`Multiple agents registered \u2014 pass --agent <id>:
180
- ${n}`)}return JSON.parse(Ge.readFileSync(t[0],"utf8"))}function Wy(e){if(!R1())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",k1).option("--registry <url>","TAP registry URL (publishes the JWKS)",T1).option("--name <name>","Human-readable name for this agent",`${process.env.USER??"user"}@${Ua.hostname()}`).action(async n=>{try{let r=await N1({registryUrl:n.registry,porterUrl:n.porter,name:n.name}),s=Ju().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: ${Zu(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
- `))}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=Hy(n.agent),{token:s,expiresInSeconds:o}=await Gy(r);n.export?process.stdout.write(`export X_TAP_TOKEN='${s}'
183
- `):process.stdout.write(`${s}
184
- `),process.stderr.write(`# expires in ${Math.round(o/3600)}h \xB7 agent ${r.agent_id}
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=Hy(n.agent);await B1(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=Ju();if(n.length===0){process.stdout.write("No agents registered. Run `visa-cli agent register` to add one.\n");return}for(let r of n){let s=JSON.parse(Ge.readFileSync(r,"utf8"));process.stdout.write(`${s.agent_id} ${s.porter_url} ${s.name}
188
- `)}})}zl();Ss();Ca();var F1="4.0.0-rc.15";async function Yy(e){let t=await ku(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 Mo=(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 zy(e){if(!xu(F1))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 Yy(n)}catch(r){Mo("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 Yy(n)}catch(r){Mo("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=ka(s.as),i=await Ru(o,n,r);console.log(`\u2713 sent to ${i.to} as ${i.as}`)}catch(o){Mo("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 Tu(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){Mo("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=ka(n.as),s=vs(r,{autoReconnect:!0});await ws(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){Mo("listen",r)}}),t.command("whoami").description("List names this CLI has registered on the relay.").action(()=>{let n=Iu();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}`)})}qt();Ht();qt();var H1=["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","enroll_agent","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"],V1=["generate_image","generate_video","generate_music","generate_audio","generate_3d","upscale_image","transcribe_audio","run_llm"];function q1(){let e=new Set;for(let t of H1)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of V1)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var K$=q1();var Qu=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 X$=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...Qu]);qt();var W=I(require("fs")),F=I(require("path")),Jy=I(require("os")),me=Jy.homedir(),K1=["Claude_","Anthropic.ClaudeDesktop_"],Ts=class extends Error{constructor(n,r,s){super(W1(n,r,s));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function Xy(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
189
- `)}function G1(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=Xy(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function W1(e,t,n){let r=t.replace(me,"~"),s=Xy(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 Lo(){return process.env.APPDATA||F.join(me,"AppData","Roaming")}function Y1(){return process.env.LOCALAPPDATA||F.join(me,"AppData","Local")}function ed(e){return process.platform==="win32"?e.win32:e.posix}function Zy(){if(process.platform!=="win32")return;let e=F.join(Y1(),"Packages");if(W.existsSync(e))try{let t=W.readdirSync(e,"utf-8");for(let n of K1){let r=t.filter(s=>s.startsWith(n)).sort()[0];if(r)return F.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function Qy(){if(process.platform==="win32"){let e=Zy();return e?F.join(e,"claude_desktop_config.json"):F.join(Lo(),"Claude","claude_desktop_config.json")}return F.join(me,"Library","Application Support","Claude","claude_desktop_config.json")}function e_(){if(process.platform!=="win32")return[F.join(me,"Library","Application Support","Claude")];let e=[F.join(Lo(),"Claude")],t=Zy();return t&&e.push(t),e}function Da(e){return e.id==="claude-desktop"?Qy():e.globalConfigPath}function z1(e){return e.id==="claude-desktop"?e_():e.detectPaths}var gt=[{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:Qy(),configKey:"mcpServers",detectPaths:e_(),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:ed({win32:F.join(Lo(),"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:ed({win32:F.join(Lo(),"Zed","settings.json"),posix:F.join(me,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:ed({win32:[F.join(Lo(),"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 td(e){return gt.find(t=>t.id===e)}function Uo(e){return z1(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 t_(){return{command:"node",args:[F.resolve(__dirname,"mcp-server/index.js")]}}function nd(e,t){return t==="project"?"json":e.configFormat??"json"}function J1(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 rd(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 sd(e,t){let n=e.split(`
191
- `),r=rd(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]]=J1(i[2]))}return Object.keys(s).length>0?s:void 0}function X1(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=rd(o,t);if(i){o.splice(i.start,i.end-i.start,...s);let c=o.join(`
172
+ `}function QA(e){return e.tool_name!=null}function e1(e){return No(e.amount)===0&&e.status==="failed"}function t1(e){return QA(e)&&!e1(e)}function n1(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 r1(e){let t=Mt(e.merchant_name,"Unknown merchant"),n=Mt(e.tool_name,"unknown_tool"),r=ks(No(e.amount)),s=Mt(e.status,"unknown"),o=i1(e.created_at);return`${r} ${s.padEnd(9)} ${t} [${n}] ${o}`}function s1(e){let t=Mt(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function o1(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 ks(e){return`$${e.toFixed(2)}`}function Ny(e,t=ZA){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 i1(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 a1=/^[1-9]\d{0,9}$/;function Gu(e){if(!a1.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 Ly(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 Lt=R(require("fs")),_e=R(require("path")),c1=["npm","pnpm","yarn","bun"],l1=/\s+/,u1=process.platform==="win32"?"visa-cli.cmd":"visa-cli",Wu=["node_modules","@visa","cli"];function d1(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(l1)[0]??"",r=n.indexOf("/"),s=r===-1?n:n.slice(0,r);return c1.includes(s)?s:void 0}function Yu(e){if(!e)return;let t=e;try{t=Lt.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 f1(e=process.argv[1]){return d1()??Yu(process.env.npm_execpath)??Yu(process.env.npm_node_execpath)??Yu(e)}function m1(e=process.env.PATH??""){let t=[];for(let n of e.split(_e.delimiter))n&&t.push(n);return t}function p1(e=process.env.PATH??""){let t=new Set,n=[];for(let r of m1(e))try{let s=_e.join(r,u1);Lt.accessSync(s,Lt.constants.X_OK);let o=_e.resolve(s);t.has(o)||(t.add(o),n.push(s))}catch{}return n}function Uy(e){try{let t=Lt.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 g1(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(Uy(r))return r}}function h1(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 y1(e,t){let n=_e.resolve(e);try{n=Lt.realpathSync(e)}catch{}let r=g1(n);return{binPath:e,realPath:n,packageRoot:r,version:r?Uy(r):void 0,prefix:h1(r),isActive:n===t}}function _1(e,t=process.env.PATH??""){let n=e??process.argv[1],r=n?_e.resolve(n):"";try{n&&(r=Lt.realpathSync(n))}catch{}let s=e?[e]:[n,...p1(t)].filter(Boolean),o=new Map;for(let d of s){let f=y1(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 b1(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??f1(n)??"npm",o=r.withDiagnostics?_1(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 ${b1(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 v1(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(v1)];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 w1(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function Dy(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=w1(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 jy(){await G.deleteSessionToken()}var Be=R(require("fs")),ja=R(require("os")),Dr=R(require("path"));xa();St();xo();var Xu="4.0.0-rc.16",Mo=Dr.join(ja.homedir(),".visa-cli","agents");function Fy(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.agent_jkt=="string"&&typeof t.name=="string"&&t.public_key_jwk?.kty==="OKP"&&t.public_key_jwk.crv==="Ed25519"&&typeof t.public_key_jwk.x=="string"&&t.private_key_jwk?.kty==="OKP"&&t.private_key_jwk.crv==="Ed25519"&&typeof t.private_key_jwk.x=="string"&&typeof t.private_key_jwk.d=="string"&&typeof t.binding_jwt=="string"&&typeof t.auth_url=="string"&&typeof t.created_at=="string"}function S1(){return!!(process.env.VISA_DEV==="1"||Xu==="0.0.0"||Xu.startsWith("0.0.")||/-rc\.|-beta\./.test(Xu))}function x1(e=Mo){Be.mkdirSync(e,{recursive:!0,mode:448})}function Ts(e,t=Mo){return Dr.join(t,`${e}.json`)}function C1(e=Mo){return Be.existsSync(e)?Be.readdirSync(e).filter(t=>t.endsWith(".json")).map(t=>Dr.join(e,t)):[]}function E1(e,t=Mo){let n=Ts(e,t);if(!Be.existsSync(n))return null;try{let r=JSON.parse(Be.readFileSync(n,"utf8"));return Fy(r)?r:null}catch{return null}}function By(e,t=Mo){x1(t);let n=Ts(e.agent_jkt,t);Be.writeFileSync(n,JSON.stringify(e,null,2),{mode:384})}function A1(e){let t=e.split(".");if(t.length!==3)return null;try{let n=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));return n===null||typeof n!="object"||Array.isArray(n)?null:n}catch{return null}}async function k1(e){let t=e.authUrl??Se(),n=e.apiKey??process.env.VISA_CLI_API_KEY?.trim();if(!n)throw new Error("No Visa Key configured \u2014 run `visa-cli setup` first, mint one with `visa-cli keys create`, and set VISA_CLI_API_KEY.");let{secretKey:r}=Ih(),s=Oh(r),o={kty:"OKP",crv:"Ed25519",x:s.x},i=Ca(o),a={agent_jkt:i,name:e.name,public_key_jwk:o,private_key_jwk:s,binding_jwt:"",auth_url:t,created_at:new Date().toISOString()};By(a,e.agentDir);let c;try{c=await So({authUrl:t,apiKey:n,seed:Sa(s),name:e.name,fetchImpl:e.fetchImpl,nowSec:e.nowSec})}catch(l){let u=l instanceof Nr||l instanceof Ze;if(u)try{Be.rmSync(Ts(i,e.agentDir),{force:!0})}catch{}let d=T1(l);throw u?d:new Error(`${d.message} The agent key was kept because issuance may have committed; inspect it with \`visa-cli agent show ${i}\` before creating another agent.`)}return a.binding_jwt=c.binding,By(a,e.agentDir),{record:a,expiresInSeconds:c.expires_in}}function T1(e){if(e instanceof Ze)return new Error(`No card on file \u2014 enroll a card first (visa-cli setup): ${e.enrollUrl}`);if(e instanceof Nr){if(e.status===404)return new Error("Agent binding issuance is not enabled on this server.");if(e.status===401)return new Error("Not authenticated \u2014 run `visa-cli setup` first (and set VISA_CLI_API_KEY to a valid Visa Key).")}return e instanceof Error?e:new Error(String(e))}function Hy(e){if(!S1())return;let t=e.command("agent").description("(dev/rc) Manage agent identities \u2014 Visa-signed bindings minted by the auth service.");t.command("create").description("Generate an Ed25519 keypair and mint a Visa-signed binding for it via POST /v2/harness/agents.").option("--name <name>","Human-readable name for this agent",`${process.env.USER??"user"}@${ja.hostname()}`).action(async n=>{try{let{record:r,expiresInSeconds:s}=await k1({name:n.name}),o=new Date(Date.now()+s*1e3).toISOString();process.stdout.write(["\u2713 Agent bound",` agent jkt: ${r.agent_jkt}`,` name: ${r.name}`,` expires: ${o} (${s}s)`,` key file: ${Ts(r.agent_jkt)}`,"","Inspect the binding claims with:","",` visa-cli agent show ${r.agent_jkt}`,""].join(`
174
+ `))}catch(r){process.stderr.write(`agent create failed: ${r instanceof Error?r.message:String(r)}
175
+ `),process.exit(1)}}),t.command("list").description("List locally stored agent identities.").action(()=>{let n=C1();if(n.length===0){process.stdout.write("No agents yet. Run `visa-cli agent create` to bind one.\n");return}for(let r of n){let s;try{s=JSON.parse(Be.readFileSync(r,"utf8"))}catch{process.stderr.write(`Skipped unreadable agent record: ${Dr.basename(r)}
176
+ `);continue}if(!Fy(s)){process.stderr.write(`Skipped legacy agent record: ${Dr.basename(r)}; run \`visa-cli agent create\` to migrate it.
177
+ `);continue}let o=s;process.stdout.write(`${o.agent_jkt} ${o.name} ${o.created_at}
178
+ `)}}),t.command("show <jkt>").description("Show an agent record and the decoded (unverified) binding claims.").action(n=>{let r=E1(n);if(!r){let o=Ts(n);process.stderr.write(Be.existsSync(o)?`Legacy or unreadable agent record: ${n}; run \`visa-cli agent create\` to migrate it.
179
+ `:`Agent not found: ${n}
180
+ `),process.exit(1)}let s=r.binding_jwt?A1(r.binding_jwt):null;process.stdout.write([`agent jkt: ${r.agent_jkt}`,`name: ${r.name}`,`created: ${r.created_at}`,`auth server: ${r.auth_url}`,`public key: ${r.public_key_jwk.x} (Ed25519, OKP)`,`key file: ${Ts(r.agent_jkt)}`,"binding claims (decoded locally, NOT verified):",s?JSON.stringify(s,null,2):" (no binding stored or malformed JWT)",""].join(`
181
+ `))})}Xl();xs();xo();var R1="4.0.0-rc.16";async function Vy(e){let t=await Ru(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 Ze){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 qy(e){if(!Eu(R1))return;e.command("register <name>").description(`Register a name on the "${Ie}" Subway mesh (reuses your CLI agent key \u2014 no TAP setup needed).`).action(async n=>{try{await Vy(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 Vy(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 $u(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 Iu(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=ws(r,{autoReconnect:!0});await Ss(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 ${Ar(r)} on "${Ie}" 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=Pu();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}`)})}St();qt();St();var I1=["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","enroll_agent","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"],$1=["generate_image","generate_video","generate_music","generate_audio","generate_3d","upscale_image","transcribe_audio","run_llm"];function P1(){let e=new Set;for(let t of I1)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of $1)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var M$=P1();var Zu=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 F$=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...Zu]);St();var W=R(require("fs")),F=R(require("path")),Ky=R(require("os")),me=Ky.homedir(),O1=["Claude_","Anthropic.ClaudeDesktop_"],Rs=class extends Error{constructor(n,r,s){super(M1(n,r,s));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function Gy(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
182
+ `)}function N1(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=Gy(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function M1(e,t,n){let r=t.replace(me,"~"),s=Gy(n).split(`
183
+ `).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 L1(){return process.env.LOCALAPPDATA||F.join(me,"AppData","Local")}function Qu(e){return process.platform==="win32"?e.win32:e.posix}function Wy(){if(process.platform!=="win32")return;let e=F.join(L1(),"Packages");if(W.existsSync(e))try{let t=W.readdirSync(e,"utf-8");for(let n of O1){let r=t.filter(s=>s.startsWith(n)).sort()[0];if(r)return F.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function Yy(){if(process.platform==="win32"){let e=Wy();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 zy(){if(process.platform!=="win32")return[F.join(me,"Library","Application Support","Claude")];let e=[F.join(Uo(),"Claude")],t=Wy();return t&&e.push(t),e}function Ba(e){return e.id==="claude-desktop"?Yy():e.globalConfigPath}function U1(e){return e.id==="claude-desktop"?zy():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:Yy(),configKey:"mcpServers",detectPaths:zy(),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:Qu({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:Qu({win32:F.join(Uo(),"Zed","settings.json"),posix:F.join(me,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:Qu({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 ed(e){return ht.find(t=>t.id===e)}function Do(e){return U1(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 Jy(){return{command:"node",args:[F.resolve(__dirname,"mcp-server/index.js")]}}function td(e,t){return t==="project"?"json":e.configFormat??"json"}function D1(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 nd(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 rd(e,t){let n=e.split(`
184
+ `),r=nd(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]]=D1(i[2]))}return Object.keys(s).length>0?s:void 0}function j1(e,t,n){let r=`[${n.args.map(c=>`"${c}"`).join(", ")}]`,s=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],o=e.split(`
185
+ `),i=nd(o,t);if(i){o.splice(i.start,i.end-i.start,...s);let c=o.join(`
193
186
  `);return c.endsWith(`
194
187
  `)?c:c+`
195
188
  `}let a=e.trimEnd();return a+(a.length>0?`
196
189
 
197
190
  `:"")+s.join(`
198
191
  `)+`
199
- `}function Z1(e,t){let n=e.split(`
200
- `),r=rd(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
192
+ `}function B1(e,t){let n=e.split(`
193
+ `),r=nd(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
201
194
  `).replace(/\n{3,}/g,`
202
195
 
203
- `)):e}function Do(e,t="global"){let n=t==="project"?F.join(process.cwd(),".mcp.json"):Da(e);try{let r=F.dirname(n);W.existsSync(r)||W.mkdirSync(r,{recursive:!0});let s=nd(e,t),o=t_();if(s==="toml"){let i=W.existsSync(n)?W.readFileSync(n,"utf-8"):"",a=X1(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 G1(r)?new Ts(e,n,r):r}return{installed:!0,configPath:n,message:e.postInstallHint}}function od(e,t="global"){let n=t==="project"?F.join(process.cwd(),".mcp.json"):Da(e);if(!W.existsSync(n))return{removed:!1,configPath:n};if(nd(e,t)==="toml"){let i=W.readFileSync(n,"utf-8");return sd(i,"visa-cli")?(W.writeFileSync(n,Z1(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 n_(e,t="global"){let n=t==="project"?F.join(process.cwd(),".mcp.json"):Da(e);if(!W.existsSync(n))return!1;if(nd(e,t)==="toml")try{let s=W.readFileSync(n,"utf-8");return!!sd(s,"visa-cli")}catch{return!1}try{return!!JSON.parse(W.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function Q1(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 ek(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 jo(){let e=t_(),t=e.args[e.args.length-1],n=[];for(let r of gt){let s=Da(r);if(!W.existsSync(s))continue;let o=r.configFormat??"json",i;if(o==="toml")try{let l=W.readFileSync(s,"utf-8");i=sd(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=Q1(i);if(!a||ek(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 id(e){return{configPath:Do(e.client,"global").configPath}}var ud=(0,f_.promisify)(d_.execFile);function ad(){let e=jt();setImmediate(()=>{Ac(e,{getCommand:()=>fi(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 ok(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 m_(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(ok(n))}function r_(e){console.log(` ! ${e.client.displayName} skipped: ${e.message}`)}function Mt(){this.help({error:!1})}var J=new u_.Command,ik=new Set(["pay",...Qu]),Fa=null,Bo=!1;function pe(){return Fa=new qe(()=>G.getSessionToken()),Fa}function s_(e){if(e instanceof Qn)return!0;let t=e instanceof Error?e.message:"";return/attestation required|invalid signature|rotate biometric key|biometric key/i.test(t)}var o_=0,i_="",ak="attestation-key-rotation",ck="api-keys-create",a_=0,c_="",lk=12e3;async function uk(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:o_,merchant:i_,context:ak})).toString("base64");return{signature:await Rn(n,"verify Visa CLI Touch ID setup"),nonce:t,amount:o_,merchant:i_}}async function dk(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:a_,merchant:c_,context:ck})).toString("base64");return{signature:await Rn(n,"create a Visa Key",{timeoutMs:lk}),nonce:t,amount:a_,merchant:c_}}async function fk(e){let t=await e.getStatus();return t.attestationRequired!==!1||At(t)}async function mk(e){let t=await vp(),n=await uk(e);await e.registerAttestationKey(t,n)}async function p_(e,t,n=!1){let r=await Li();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 cd(e){if(!await md(e))throw new Error("Could not clear stale server biometric state. Run `visa-cli config reset`, then `visa-cli setup`.");await p_(e,!0,!0)}function Ga(e){return async()=>{let t=await md(e);return{success:t,...t?{}:{message:"Biometric recovery was not completed."}}}}async function pk(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 md(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(!At(t))return!1;let n=qa.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 gc(r.recoveryUrl),await pk(n),console.log(" Server biometric state cleared."),!0}function Fo(e){return`$${(e/100).toFixed(2)}`}function gk(e){return typeof e=="number"?Fo(e):"no cap"}function Ha(e,t,n=!1){if(!e){let i=Fo(t);return n&&t>=0?`+${i}`:i}let r=(0,Ka.fromWire)(e),s=r%10000n===0n?2:6,o=(0,Ka.toDisplay)(r,{decimals:s});return n&&r>=0n?`+${o}`:o}function hk(e){return Ha(e,0)}function yk(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 _k(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=>ik.has(o));if(s)throw new Error(`Tool id "${s}" is retired for direct API-key access. Use discover/execute instead.`);return n}var dd=!1;async function g_(e){let t=(0,fd.createInterface)({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function bk(e,t=!1){let n=Qf(e,{json:t,isTTY:process.stdin.isTTY===!0});if(n!==void 0)return n;if(await Ic("Use recommended Visa Key caps ($5/day and $25 total)? Without caps, leaked keys can spend from prepaid balance until revoked.",!0))return dd=!0,500;let s=await g_("Daily cap USD (1-100): ");if(!s)throw new Error("--daily-cap is required when declining the recommended daily cap.");return Pc(s)}async function vk(e,t=!1){let n=em(e,{json:t,isTTY:process.stdin.isTTY===!0,recommendedCapsAccepted:dd});if(n!==void 0)return dd=!1,n;let r=await g_("Cumulative cap USD (1-10000, default 25): ");return Oc(r||"25")}function wk(e){return e&&e.length>0?e.join(", "):"all tools"}function h_(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 Wa(e,t={}){let n=t.format&&ei(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=Fr(c);if(d){let f=typeof e?.merchantName=="string"?e.merchantName:"media",m=typeof e?.transactionId=="string"?`${f}-${e.transactionId}`:f,p=Ls(d,{tag:m}),g=uc(i,e);g.success&&(g.filePath=p.filePath,g.mime=p.mime,g.bytes=p.bytes,u&&u.startsWith("data:")&&(g.urls=void 0)),Bs(g,a);return}}catch(d){Bs(Us(i,`Failed to save inline media: ${d instanceof Error?d.message:String(d)}`),a),process.exitCode=__;return}Bs(uc(i,e),a);return}if(e?.content?.[0]?.text&&typeof e.content[0].text=="string"){try{let i=Fr(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=Ls(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(Bd(e)){console.log("In Queue"),lc(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(`
196
+ `)):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=td(e,t),o=Jy();if(s==="toml"){let i=W.existsSync(n)?W.readFileSync(n,"utf-8"):"",a=j1(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)+`
197
+ `)}}catch(r){throw N1(r)?new Rs(e,n,r):r}return{installed:!0,configPath:n,message:e.postInstallHint}}function sd(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(td(e,t)==="toml"){let i=W.readFileSync(n,"utf-8");return rd(i,"visa-cli")?(W.writeFileSync(n,B1(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)+`
198
+ `),{removed:!0,configPath:n})}function Xy(e,t="global"){let n=t==="project"?F.join(process.cwd(),".mcp.json"):Ba(e);if(!W.existsSync(n))return!1;if(td(e,t)==="toml")try{let s=W.readFileSync(n,"utf-8");return!!rd(s,"visa-cli")}catch{return!1}try{return!!JSON.parse(W.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function F1(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 H1(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=Jy(),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=rd(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=F1(i);if(!a||H1(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 od(e){return{configPath:jo(e.client,"global").configPath}}var ld=(0,a_.promisify)(i_.execFile);function id(){let e=Ft();setImmediate(()=>{kc(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 W1(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)})
199
+ ${r}: ${n(e.currentPath)}`}function c_(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(W1(n))}function Zy(e){console.log(` ! ${e.client.displayName} skipped: ${e.message}`)}function Ut(){this.help({error:!1})}var J=new o_.Command,Y1=new Set(["pay",...Zu]),Va=null,Fo=!1;function pe(){return Va=new Ke(()=>G.getSessionToken()),Va}function Qy(e){if(e instanceof Qn)return!0;let t=e instanceof Error?e.message:"";return/attestation required|invalid signature|rotate biometric key|biometric key/i.test(t)}var e_=0,t_="",z1="attestation-key-rotation",J1="api-keys-create",n_=0,r_="",X1=12e3;async function Z1(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:e_,merchant:t_,context:z1})).toString("base64");return{signature:await Rn(n,"verify Visa CLI Touch ID setup"),nonce:t,amount:e_,merchant:t_}}async function Q1(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:n_,merchant:r_,context:J1})).toString("base64");return{signature:await Rn(n,"create a Visa Key",{timeoutMs:X1}),nonce:t,amount:n_,merchant:r_}}async function ek(e){let t=await e.getStatus();return t.attestationRequired!==!1||kt(t)}async function tk(e){let t=await bp(),n=await Z1(e);await e.registerAttestationKey(t,n)}async function l_(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&&g.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 ad(e){if(!await fd(e))throw new Error("Could not clear stale server biometric state. Run `visa-cli config reset`, then `visa-cli setup`.");await l_(e,!0,!0)}function Ya(e){return async()=>{let t=await fd(e);return{success:t,...t?{}:{message:"Biometric recovery was not completed."}}}}async function nk(e){let r=Date.now()+3e5;for(;Date.now()<r;)try{let s=await globalThis.fetch(`${Se()}/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=>{g.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=>{g.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 fd(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(!kt(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 nk(n),console.log(" Server biometric state cleared."),!0}function Ho(e){return`$${(e/100).toFixed(2)}`}function rk(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 sk(e){return qa(e,0)}function ok(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 ik(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=>Y1.has(o));if(s)throw new Error(`Tool id "${s}" is retired for direct API-key access. Use discover/execute instead.`);return n}var ud=!1;async function u_(e){let t=(0,dd.createInterface)({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function ak(e,t=!1){let n=Zf(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 ud=!0,500;let s=await u_("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 ck(e,t=!1){let n=Qf(e,{json:t,isTTY:process.stdin.isTTY===!0,recommendedCapsAccepted:ud});if(n!==void 0)return ud=!1,n;let r=await u_("Cumulative cap USD (1-10000, default 25): ");return Mc(r||"25")}function lk(e){return e&&e.length>0?e.join(", "):"all tools"}function d_(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=Vr(c);if(d){let f=typeof e?.merchantName=="string"?e.merchantName:"media",m=typeof e?.transactionId=="string"?`${f}-${e.transactionId}`:f,p=Us(d,{tag:m}),h=fc(i,e);h.success&&(h.filePath=p.filePath,h.mime=p.mime,h.bytes=p.bytes,u&&u.startsWith("data:")&&(h.urls=void 0)),Fs(h,a);return}}catch(d){Fs(Ds(i,`Failed to save inline media: ${d instanceof Error?d.message:String(d)}`),a),process.exitCode=m_;return}Fs(fc(i,e),a);return}if(e?.content?.[0]?.text&&typeof e.content[0].text=="string"){try{let i=Vr(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=Us(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(jd(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(`
207
200
  \u2139 Your request is processing. Poll for the result with:
208
201
  ${c}`);let l=JSON.stringify(e,null,2);l&&l!=="{}"&&(console.log(`
209
- Result:`),console.log(l));return}if(console.log("Done"),lc(e),s.length>0){console.log(`
202
+ Result:`),console.log(l));return}if(console.log("Done"),dc(e),s.length>0){console.log(`
210
203
  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 Sk=new Set(["INVALID_TOOL_PARAMS","MISSING_TOOL_ID","UNKNOWN_TOOL"]),y_=0,__=1,xk=2;function Ck(e){if(e?.success!==!1)return y_;let n=(typeof e?.error_code=="string"?e.error_code:typeof e?.code=="string"?e.code:"").toUpperCase();return Sk.has(n)?xk:__}function Ya(e){let t=Ck(e);t!==y_&&(process.exitCode=t)}function Rs(e,t,n={}){let r=typeof n=="boolean"?{json:n}:n,s=t instanceof Error?t.message:String(t),o=r.format&&ei(r.format)?r.format:void 0;if(r.json||o!==void 0){let i=o??"json";Bs(Us(e,s),i)}else console.error("Error:",s);process.exit(1)}async function Ak(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 pd=100,gd=200;function Va(e){let t=Number.parseInt(e,10);return Number.isNaN(t)?Number.NaN:t}function Ek(e){let t=typeof e.limit=="number"&&Number.isInteger(e.limit)?Math.max(1,Math.min(e.limit,gd)):pd,n=typeof e.offset=="number"&&Number.isInteger(e.offset)?Math.max(0,e.offset):0;return{limit:t,offset:n}}function kk(e){let t=`
204
+ Result:`),console.log(o))}var uk=new Set(["INVALID_TOOL_PARAMS","MISSING_TOOL_ID","UNKNOWN_TOOL"]),f_=0,m_=1,dk=2;function fk(e){if(e?.success!==!1)return f_;let n=(typeof e?.error_code=="string"?e.error_code:typeof e?.code=="string"?e.code:"").toUpperCase();return uk.has(n)?dk:m_}function Ja(e){let t=fk(e);t!==f_&&(process.exitCode=t)}function Is(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";Fs(Ds(e,s),i)}else console.error("Error:",s);process.exit(1)}async function mk(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 md=100,pd=200;function Ka(e){let t=Number.parseInt(e,10);return Number.isNaN(t)?Number.NaN:t}function pk(e){let t=typeof e.limit=="number"&&Number.isInteger(e.limit)?Math.max(1,Math.min(e.limit,pd)):md,n=typeof e.offset=="number"&&Number.isInteger(e.offset)?Math.max(0,e.offset):0;return{limit:t,offset:n}}function gk(e){let t=`
212
205
  Options:
213
206
  `,n=`
214
207
  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 Tk(e){if(!e.startsWith("Usage: "))return e;let t=e.indexOf(`
208
+ `,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 hk(e){if(!e.startsWith("Usage: "))return e;let t=e.indexOf(`
216
209
 
217
210
  `);if(t===-1)return e;let n=e.slice(0,t),r=e.slice(t+2),s=r.indexOf(`
218
211
 
@@ -220,18 +213,18 @@ Commands:
220
213
 
221
214
  ${n}
222
215
 
223
- ${i}`:e}function Rk(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(Ik).join(`
225
- `);return`${n}${r}${o}`})}function Ik(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 $k(e){return e.replace(/^(Usage: .+?) \[options\](?= |$)/gm,"$1")}function Pk(e){return e.replace(/^Options:$/gm,"Flags:")}function b_(e){let t=e.helpInformation.bind(e);e.helpInformation=()=>Pk($k(Rk(kk(Tk(t())))));for(let n of e.commands)b_(n)}function Ok(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(Ms().version).addHelpCommand(!1).action(Mt);J.hook("preAction",async()=>{await Dd()});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(`
216
+ ${i}`:e}function yk(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(`
217
+ `).map(_k).join(`
218
+ `);return`${n}${r}${o}`})}function _k(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 bk(e){return e.replace(/^(Usage: .+?) \[options\](?= |$)/gm,"$1")}function vk(e){return e.replace(/^Options:$/gm,"Flags:")}function p_(e){let t=e.helpInformation.bind(e);e.helpInformation=()=>vk(bk(yk(gk(hk(t())))));for(let n of e.commands)p_(n)}function wk(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(Ls().version).addHelpCommand(!1).action(Ut);J.hook("preAction",async()=>{await Ud()});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
219
 
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 v=jo();m_(v,"MCP config check:"),v.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=jo(),o=new Map(s.map(v=>[v.client.id,v])),i=new Set,a=new Set,c=new Set;for(let v of gt)if(Uo(v)){let w;try{w=Do(v)}catch(y){if(y instanceof Ts){r_(y),a.add(v.displayName),c.add(v.id);continue}throw y}let T=o.get(v.id),E=T?` \u2014 repaired stale ${T.staleReason} entry`:"";console.log(` \u2713 ${v.displayName} (${w.configPath.replace(re.homedir(),"~")})${E}`),T&&i.add(v.id)}let l=s.filter(v=>!i.has(v.client.id)&&!c.has(v.client.id)),u=0;for(let v of l){try{id(v)}catch(w){if(w instanceof Ts){r_(w),a.add(v.client.displayName),c.add(v.client.id);continue}throw w}console.log(` \u2713 ${v.client.displayName} (${v.configPath.replace(re.homedir(),"~")}) \u2014 repaired stale ${v.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(v){let w=v instanceof Error?v.message:"";w.includes("session has expired")||w.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await By(),f=null):console.log(` Couldn't verify session (${w||"unknown error"}) \u2014 continuing with existing token.`)}if(!f){let v=null;try{let{stdout:w}=await ud("gh",["auth","token"],{timeout:5e3});v=w.trim()}catch{}if(v||(v=process.env.GITHUB_TOKEN||null),v)try{console.log(" Found GitHub token \u2014 attempting headless login...");let w=await globalThis.fetch(`${$e()}/v1/auth/token-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({github_token:v}),signal:AbortSignal.timeout(1e4)});if(w.ok){let T=await w.json();if(T.success&&T.sessionToken){let E=T.sessionToken;f=E,await G.saveSessionToken(E),console.log(` Signed in as ${T.user} (headless).`)}}else(await w.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(v,w)=>{let T=qa.randomUUID(),E=`${$e()}/login?state=${T}`;await gc(E);let y=3e4,x=300*1e3,Y=Date.now()+x;for(;Date.now()<Y;)try{let X=await globalThis.fetch(`${$e()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:T,timeout:y}),signal:AbortSignal.timeout(y+5e3)});if(!X.ok){await hn(X,be=>{h.warn("auth_status:retry_after_http_error",{status:X.status,delayMs:be})});continue}let K=await X.json();if(K.status==="pending")continue;if(K.status==="expired"){w(new Error("Session expired. Please run setup again."));return}if(K.status==="complete"&&K.sessionToken){console.log(` Signed in as ${K.user}.`),v(K.sessionToken);return}}catch{await hn(void 0,X=>{h.warn("auth_status:retry_after_network_error",{delayMs:X})})}w(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 ud("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 v=pe();try{let w=await v.getStatus(),T=!0;if(At(w))if(await Ui())try{await mk(v),console.log(" Attestation key already registered with server."),console.log(" Existing local Touch ID key verified and preserved."),T=!1}catch(E){if(!s_(E))throw E;console.log(" Existing local Touch ID key does not match server biometric state."),await cd(v),T=!1}else console.log(" Server already has a biometric key, but this device has no local key."),await cd(v),T=!1;T&&await p_(v,w.attestationRequired===!1)}catch(w){let T=w?.message||"unknown error";if(s_(w)){console.log(" Server already has a biometric key for this account, but this device cannot prove access to it.");let E=!1;try{await cd(v),E=!0}catch(y){console.error(` Biometric recovery failed: ${y?.message||"unknown error"}`)}if(!E){let y=w instanceof Qn&&w.hint?w.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: ${T}`),process.exit(1)}}else{let v=pe(),w;try{w=await v.getStatus()}catch(E){console.error(" Biometric attestation (Touch ID or Windows Hello) is unavailable in this process."),console.error(` Could not verify server biometric policy: ${E?.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 T=jy(w);T.canContinue||(console.error(` ${T.message}`),T.hint&&console.error(` ${T.hint}`),process.exit(1)),console.log(` ${T.message}`)}let m=jt(),p=ce.existsSync(nt.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(Gf()),g=await Ic(" Install the Visa HUD now?",!1)),g)if(!p)console.log(`
220
+ 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 b=Bo();c_(b,"MCP config check:"),b.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(b=>[b.client.id,b])),i=new Set,a=new Set,c=new Set;for(let b of ht)if(Do(b)){let w;try{w=jo(b)}catch(y){if(y instanceof Rs){Zy(y),a.add(b.displayName),c.add(b.id);continue}throw y}let T=o.get(b.id),A=T?` \u2014 repaired stale ${T.staleReason} entry`:"";console.log(` \u2713 ${b.displayName} (${w.configPath.replace(re.homedir(),"~")})${A}`),T&&i.add(b.id)}let l=s.filter(b=>!i.has(b.client.id)&&!c.has(b.client.id)),u=0;for(let b of l){try{od(b)}catch(w){if(w instanceof Rs){Zy(w),a.add(b.client.displayName),c.add(b.client.id);continue}throw w}console.log(` \u2713 ${b.client.displayName} (${b.configPath.replace(re.homedir(),"~")}) \u2014 repaired stale ${b.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(`
221
+ Step 2: Checking authentication...`);let f=await G.getSessionToken();if(f)try{await new Ke(()=>Promise.resolve(f)).getStatus(),console.log(" Already authenticated.")}catch(b){let w=b instanceof Error?b.message:"";w.includes("session has expired")||w.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await jy(),f=null):console.log(` Couldn't verify session (${w||"unknown error"}) \u2014 continuing with existing token.`)}if(!f){let b=null;try{let{stdout:w}=await ld("gh",["auth","token"],{timeout:5e3});b=w.trim()}catch{}if(b||(b=process.env.GITHUB_TOKEN||null),b)try{console.log(" Found GitHub token \u2014 attempting headless login...");let w=await globalThis.fetch(`${Se()}/v1/auth/token-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({github_token:b}),signal:AbortSignal.timeout(1e4)});if(w.ok){let T=await w.json();if(T.success&&T.sessionToken){let A=T.sessionToken;f=A,await G.saveSessionToken(A),console.log(` Signed in as ${T.user} (headless).`)}}else(await w.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(b,w)=>{let T=Ga.randomUUID(),A=`${Se()}/login?state=${T}`;await yc(A);let y=3e4,x=300*1e3,Y=Date.now()+x;for(;Date.now()<Y;)try{let X=await globalThis.fetch(`${Se()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:T,timeout:y}),signal:AbortSignal.timeout(y+5e3)});if(!X.ok){await hn(X,be=>{g.warn("auth_status:retry_after_http_error",{status:X.status,delayMs:be})});continue}let K=await X.json();if(K.status==="pending")continue;if(K.status==="expired"){w(new Error("Session expired. Please run setup again."));return}if(K.status==="complete"&&K.sessionToken){console.log(` Signed in as ${K.user}.`),b(K.sessionToken);return}}catch{await hn(void 0,X=>{g.warn("auth_status:retry_after_network_error",{delayMs:X})})}w(new Error("Login timed out after 5 minutes. Please run setup again."))}),await G.saveSessionToken(f),console.log(" Session token saved.")),console.log(`
222
+ Step 3: Setting up authentication...`),de()){try{await ld("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 b=pe();try{let w=await b.getStatus(),T=!0;if(kt(w))if(await Di())try{await tk(b),console.log(" Attestation key already registered with server."),console.log(" Existing local Touch ID key verified and preserved."),T=!1}catch(A){if(!Qy(A))throw A;console.log(" Existing local Touch ID key does not match server biometric state."),await ad(b),T=!1}else console.log(" Server already has a biometric key, but this device has no local key."),await ad(b),T=!1;T&&await l_(b,w.attestationRequired===!1)}catch(w){let T=w?.message||"unknown error";if(Qy(w)){console.log(" Server already has a biometric key for this account, but this device cannot prove access to it.");let A=!1;try{await ad(b),A=!0}catch(y){console.error(` Biometric recovery failed: ${y?.message||"unknown error"}`)}if(!A){let y=w instanceof Qn&&w.hint?w.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: ${T}`),process.exit(1)}}else{let b=pe(),w;try{w=await b.getStatus()}catch(A){console.error(" Biometric attestation (Touch ID or Windows Hello) is unavailable in this process."),console.error(` Could not verify server biometric policy: ${A?.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 T=Dy(w);T.canContinue||(console.error(` ${T.message}`),T.hint&&console.error(` ${T.hint}`),process.exit(1)),console.log(` ${T.message}`)}let m=Ft(),p=ce.existsSync(rt.join(re.homedir(),".claude.json")),h=e.hud===!0;if(e.hud===void 0&&p&&!e.yes&&process.stdin.isTTY&&(console.log(`
223
+ Step 4: Visa HUD`),console.log(" Pin balance, card, spend, model, and session activity below the Claude Code input."),console.log(Kf()),h=await Pc(" Install the Visa HUD now?",!1)),h)if(!p)console.log(`
231
224
  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 v=Ws(m),w=v.installed==="new"||v.installed==="already-visa"||v.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${w}${v.message}`);try{let T=pe(),E=await T.getStatus(),y={currentVersion:T.getClientVersion(),latestVersion:T.lastSignals?.updateAvailable?.latestVersion,updateCheckDisabled:vt()},x=vc(E,y);wc(x,E),console.log(` Preview: ${x.split(`
225
+ Step 4: Enabling the Visa spend HUD...`);let b=Ys(m),w=b.installed==="new"||b.installed==="already-visa"||b.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${w}${b.message}`);try{let T=pe(),A=await T.getStatus(),y={currentVersion:T.getClientVersion(),latestVersion:T.lastSignals?.updateAvailable?.latestVersion,updateCheckDisabled:wt()},x=Sc(A,y);xc(x,A),console.log(` Preview: ${x.split(`
233
226
  `)[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 b="\x1B[1m",A="\x1B[2m",_="\x1B[0m";console.log(`
227
+ Step 4: Visa HUD not installed.`),console.log(" Enable later with: visa-cli config hud enable"));let v="\x1B[1m",I="\x1B[2m",_="\x1B[0m";console.log(`
235
228
  \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
236
229
  \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
230
  \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
@@ -239,90 +232,90 @@ Step 4: Visa HUD not installed.`),console.log(" Enable later with: visa-cli co
239
232
  \u255A\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551
240
233
  \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u2588 CLI
241
234
 
242
- ${b}Setup complete.${_} Restart Claude Code or run /mcp to connect.
235
+ ${v}Setup complete.${_} Restart Claude Code or run /mcp to connect.
243
236
 
244
- ${b}Try it out:${_}
237
+ ${v}Try it out:${_}
245
238
  \u2022 Ask Claude: "Generate an image of a neon cityscape"
246
239
  \u2022 Ask Claude: "What's the price of ETH on Base?"
247
240
  \u2022 Check balance: visa-cli balance show
248
241
 
249
242
  \u250C\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\u2510
250
- \u2502 ${b}Recommended: enable the spend HUD${_} \u2502
243
+ \u2502 ${v}Recommended: enable the spend HUD${_} \u2502
251
244
  \u2502 \u2502
252
245
  \u2502 Keep an eye on what your agents are spending. \u2502
253
246
  \u2502 Shows your balance, active card, and recent tool usage \u2502
254
247
  \u2502 on every prompt. \u2502
255
248
  \u2502 \u2502
256
- \u2502 ${A}$${_} visa-cli config hud enable \u2502
249
+ \u2502 ${I}$${_} visa-cli config hud enable \u2502
257
250
  \u2502 \u2502
258
251
  \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
252
 
260
- ${b}Verify:${_} visa-cli status
261
- ${b}Docs:${_} 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=jo();m_(o,"MCP config check:"),o.length>0&&process.exit(1);return}if(t.repair){let o=jo();if(o.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of o)id(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(re.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
253
+ ${v}Verify:${_} visa-cli status
254
+ ${v}Docs:${_} https://visacli.sh
255
+ `),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();c_(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)od(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(re.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
263
256
  Repaired ${o.length} stale MCP config ${o.length===1?"entry":"entries"}.`);return}if(t.list){console.log(`
264
257
  \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 gt){let c=Uo(a),l=n_(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 gt){if(!Uo(a)){i.push(a.displayName);continue}Do(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: ${gt.map(o=>o.id).join(", ")}`),process.exit(1));let r=td(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${gt.map(o=>o.id).join(", ")}`),process.exit(1)),n==="global"&&!Uo(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let s=Do(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()=>{Bo=!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:vt()};process.stdout.write(Ly(t,Array.isArray(n?.transactions)?n.transactions:[],de(),r)),Bo=!0}catch(e){Bo=!1,console.error("Error:",e.message),process.exit(1)}});function Nk(e){let t=e.map(Uy),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(`
258
+ `),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=Xy(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(`
259
+ Supported clients: ${ht.map(o=>o.id).join(", ")}`),process.exit(1));let r=ed(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}
260
+ `)}return{transactions:[]}})]),r={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:wt()};process.stdout.write(My(t,Array.isArray(n?.transactions)?n.transactions:[],de(),r)),Fo=!0}catch(e){Fo=!1,console.error("Error:",e.message),process.exit(1)}});function Sk(e){let t=e.map(Ly),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
261
  Cards
269
262
  `),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
263
  Use:`),console.log(" visa-cli cards default <id>"),console.log(` visa-cli cards remove <id>
271
- `)}async function v_(e,t){if(t.yes)return"confirmed";if(!process.stdin.isTTY)return"refused-non-tty";let n=(0,fd.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(Mt);za.command("list").alias("ls").description("List enrolled payment cards").action(async()=>{try{let e=await Pt.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}Nk(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 Pt.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=qu(e),r=await v_(`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 Pt.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=qu(e),n=await Pt.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 Mk(e){return/timed out waiting for touch id\/device approval|attestation[_\s-]?required/i.test(e)}function hd(e){let t=e instanceof Error?e.message:String(e);console.error("Error:",t),Mk(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 Lk(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 yd(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 _d=J.command("keys").description("Create and manage Visa Keys for apps and agents").addHelpCommand(!1).action(Mt);_d.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 bk(t.dailyCap,t.json),r=await vk(t.totalCap,t.json),s=await yd(async()=>{let o=pe(),i={label:yk(e),allowed_tools:_k(t.tools),daily_cap_cents:n,total_cap_cents:r};return await fk(o)?await br(o,async()=>{let a=await dk(o);return o.createAppApiKey({...i,attestation:a})},Ga(o)):await o.createAppApiKey(i)});if(t.json){console.log(JSON.stringify(s,null,2));return}process.stdout.write(Xf(s,{authUrl:$e()}))}catch(n){hd(n)}});_d.command("list").description("List Visa Keys for the authenticated user").option("--json","Output raw JSON").action(async e=>{try{let t=await yd(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: ${wk(r.allowed_tools)}`),console.log(` Daily cap: ${Fo(r.daily_cap_cents)}/day`),console.log(` Total cap: ${gk(r.total_cap_cents)}`),console.log(` Last used: ${r.last_used_at||"never"}`)}catch(t){hd(t)}});_d.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 yd(async()=>await pe().revokeAppApiKey(t));console.log(`Revoked Visa Key ${n.revoked}.`)}catch(t){hd(t)}});async function Uk(){if(await G.clearAll(),console.log(" Keychain credentials cleared."),de())try{await Di(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}}async function w_(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 md(t);try{await t.logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}}await Uk(),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(w_);var bd=J.command("balance").description("Manage prepaid balance").addHelpCommand(!1).action(Mt);bd.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: ${Ha(t.balanceMicros,t.balanceCents)}
264
+ `)}async function g_(e,t){if(t.yes)return"confirmed";if(!process.stdin.isTTY)return"refused-non-tty";let n=(0,dd.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(Ut);Xa.command("list").alias("ls").description("List enrolled payment cards").action(async()=>{try{let e=await Nt.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}Sk(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 Nt.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 g_(`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 Nt.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 Nt.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 xk(e){return/timed out waiting for touch id\/device approval|attestation[_\s-]?required/i.test(e)}function gd(e){let t=e instanceof Error?e.message:String(e);console.error("Error:",t),xk(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 Ck(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 hd(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 yd=J.command("keys").description("Create and manage Visa Keys for apps and agents").addHelpCommand(!1).action(Ut);yd.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 ak(t.dailyCap,t.json),r=await ck(t.totalCap,t.json),s=await hd(async()=>{let o=pe(),i={label:ok(e),allowed_tools:ik(t.tools),daily_cap_cents:n,total_cap_cents:r};return await ek(o)?await br(o,async()=>{let a=await Q1(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(Jf(s,{authUrl:Se()}))}catch(n){gd(n)}});yd.command("list").description("List Visa Keys for the authenticated user").option("--json","Output raw JSON").action(async e=>{try{let t=await hd(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: ${lk(r.allowed_tools)}`),console.log(` Daily cap: ${Ho(r.daily_cap_cents)}/day`),console.log(` Total cap: ${rk(r.total_cap_cents)}`),console.log(` Last used: ${r.last_used_at||"never"}`)}catch(t){gd(t)}});yd.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 hd(async()=>await pe().revokeAppApiKey(t));console.log(`Revoked Visa Key ${n.revoked}.`)}catch(t){gd(t)}});async function Ek(){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 h_(e={}){try{if(console.log(`Resetting Visa CLI...
265
+ `),e.localOnly)console.log(" Local-only reset: skipping server logout and biometric recovery.");else{let t=pe();await fd(t);try{await t.logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}}await Ek(),console.log(`
266
+ 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(h_);var _d=J.command("balance").description("Manage prepaid balance").addHelpCommand(!1).action(Ut);_d.command("show").description("Show prepaid balance + recent ledger entries").action(async()=>{try{let t=await new Ke(()=>G.getSessionToken()).getBalance();if(console.log(`
267
+ Balance: ${qa(t.balanceMicros,t.balanceCents)}
275
268
  `),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=Ha(u.deltaMicros,u.deltaCents,!0),p=hk(r[d]),g=(u.reason??"").slice(0,l),b=u.toolName??"";console.log(` ${f.padEnd(i)} ${m.padStart(a)} ${p.padStart(c)} ${g.padEnd(l)} ${b}`)}),console.log()}catch(e){e instanceof ot&&(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)}});bd.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=Gi(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(Wi);let o=qa.randomUUID(),i=await br(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})},Ga(s));if(i.success)console.log(`Top-up complete: +$${(n/100).toFixed(2)} \u2192 balance now ${Ha(i.balanceMicros,i.balanceCents??0)}`),i.transactionId&&console.log(`Transaction: ${i.transactionId}`),gf();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 ot&&(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 S_=bd.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(Mt);S_.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(`
269
+ `);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=sk(r[d]),h=(u.reason??"").slice(0,l),v=u.toolName??"";console.log(` ${f.padEnd(i)} ${m.padStart(a)} ${p.padStart(c)} ${h.padEnd(l)} ${v}`)}),console.log()}catch(e){e instanceof it&&(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)}});_d.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=Wi(e.amount);if(!t.ok)throw new Error(t.error);let n=t.cents,r=n/100,s=new Ke(()=>G.getSessionToken());if(!de())throw new Error(Yi);let o=Ga.randomUUID(),i=await br(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}`),pf();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 it&&(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 y_=_d.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(Ut);y_.command("show").description("Show current auto-topup configuration").action(async()=>{try{let t=await new Ke(()=>G.getSessionToken()).getAutoTopup();if(t.targetCents==null||t.targetCents===0){console.log(`
277
270
  Auto-topup: disabled
278
- `);return}let n=Fo(t.targetCents),r=Fo(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)}});S_.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 Dk=J.command("session",{hidden:!0}).description("Inspect session budgets");Dk.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(`
271
+ `);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)}});y_.command("disable").description("Disable auto-topup").action(async()=>{try{let t=await new Ke(()=>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 Ak=J.command("session",{hidden:!0}).description("Inspect session budgets");Ak.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 Ke(()=>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
272
  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
273
  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 x_(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(x_);J.command("update").description("Update Visa CLI to the latest stable version").action(async()=>{let e=Wu(void 0,void 0,void 0,{withDiagnostics:!0}),t=e.diagnostics?Yu(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 ud(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=Ac(jt(),{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 Lt=J.command("config").description("Manage CLI configuration and local integrations").addHelpCommand(!1).action(Mt);function C_(e){return[nt.join(e,".zshrc"),nt.join(e,".bashrc"),nt.join(e,".bash_profile"),nt.join(e,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),nt.join(e,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),nt.join(e,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),nt.join(e,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),nt.join(e,".config","powershell","Microsoft.PowerShell_profile.ps1")]}function jk(e){let t=new Map;for(let n of C_(e))try{ce.existsSync(n)&&t.set(n,ce.readFileSync(n,"utf-8"))}catch{}return t}function Bk(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 Fk(e){let t=[];for(let n of C_(e))try{if(!ce.existsSync(n))continue;let r=ce.readFileSync(n,"utf-8");Ks(r)!==r.trimEnd()&&t.push(n)}catch{}return t}Lt.command("feedback",{hidden:!0}).description("Deprecated alias for `feedback`").argument("[message]","Your feedback message").action(x_);Lt.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 uo({api:t,includeDev:!!e.dev});if(e.json){console.log(kp(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(Ep(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});Lt.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 uo({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 Hk(){return Object.entries(tr).map(([e,t])=>` ${e.padEnd(22)} (${t.type}) ${t.description}`).join(`
282
- `)}Lt.command("set <key> <value>").description("Persist a CLI setting to ~/.visa-mcp/settings.json").addHelpText("after",`
274
+ (no PSP references yet \u2014 no holds placed)`);console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});async function __(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(__);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 ld(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=kc(Ft(),{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 Dt=J.command("config").description("Manage CLI configuration and local integrations").addHelpCommand(!1).action(Ut);function b_(e){return[rt.join(e,".zshrc"),rt.join(e,".bashrc"),rt.join(e,".bash_profile"),rt.join(e,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),rt.join(e,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),rt.join(e,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),rt.join(e,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),rt.join(e,".config","powershell","Microsoft.PowerShell_profile.ps1")]}function kk(e){let t=new Map;for(let n of b_(e))try{ce.existsSync(n)&&t.set(n,ce.readFileSync(n,"utf-8"))}catch{}return t}function Tk(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 Rk(e){let t=[];for(let n of b_(e))try{if(!ce.existsSync(n))continue;let r=ce.readFileSync(n,"utf-8");Gs(r)!==r.trimEnd()&&t.push(n)}catch{}return t}Dt.command("feedback",{hidden:!0}).description("Deprecated alias for `feedback`").argument("[message]","Your feedback message").action(__);Dt.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(Ap(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(Ep(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});Dt.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 Ik(){return Object.entries(tr).map(([e,t])=>` ${e.padEnd(22)} (${t.type}) ${t.description}`).join(`
275
+ `)}Dt.command("set <key> <value>").description("Persist a CLI setting to ~/.visa-mcp/settings.json").addHelpText("after",`
283
276
  Settable keys:
284
- ${Hk()}`).action((e,t)=>{try{let n=Si(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 it||n instanceof Vt||n instanceof vn?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});Lt.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=xi(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)}});Lt.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(w_);var vd=Lt.command("biometric").description("Manage Touch ID / biometric attestation enforcement").addHelpCommand(!1).action(Mt);vd.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)}});vd.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 ji(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)}});vd.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 br(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})},Ga(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 br(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}})},Ga(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 Ur=Lt.command("shell-hud").description("Manage the shell prompt HUD (opt-in \u2014 prefer: visa-cli config hud enable)").addHelpCommand(!1).action(Mt);function A_(){let e=ai();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function E_(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 Vk(){E_(Rc(void 0,{homeDir:re.homedir(),installVisaStatusLine:Ws,installShellHud:ai}))}function k_(){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"),Vk()}function Ja(){let e=Dt();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}Ur.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(A_);Ur.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(k_);Ur.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Ja);Ur.command("disable").description("Disable the persistent shell HUD").action(Ja);Ur.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${ci()}
285
- `)});Ur.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
- `);let s=Gr();if(r("Shell detected",!!s,s??"none (zsh, bash, or PowerShell required)"),s){let d=qs(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=Vs(),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?`
277
+ ${Ik()}`).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 at||n instanceof Kt||n instanceof vn?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});Dt.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=Ci(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)}});Dt.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(h_);var bd=Dt.command("biometric").description("Manage Touch ID / biometric attestation enforcement").addHelpCommand(!1).action(Ut);bd.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)}});bd.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)}});bd.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 br(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 br(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 jr=Dt.command("shell-hud").description("Manage the shell prompt HUD (opt-in \u2014 prefer: visa-cli config hud enable)").addHelpCommand(!1).action(Ut);function v_(){let e=ci();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function w_(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 $k(){w_($c(void 0,{homeDir:re.homedir(),installVisaStatusLine:Ys,installShellHud:ci}))}function S_(){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"),$k()}function Za(){let e=Bt();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}jr.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(v_);jr.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(S_);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()}
278
+ `)});jr.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
279
+ `);let s=Yr();if(r("Shell detected",!!s,s??"none (zsh, bash, or PowerShell required)"),s){let d=Ks(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=qs(),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
280
  All checks passed.`:`
288
- Some checks failed \u2014 see above.`),n||process.exit(1)});async function T_(e){if(!(!e.force&&mf()))try{await hc();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"&&Lk(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:vt()},l=vc(i,c);wc(l,i)}catch(t){let n=t instanceof Error?t.message:"unknown refresh failure";pf(n)}finally{zn()}}Ur.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(T_);var Dr=J.command("shell-hud",{hidden:!0}).description("Deprecated alias for `config shell-hud`");Dr.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(A_);Dr.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(k_);Dr.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Ja);Dr.command("disable").description("Disable the persistent shell HUD").action(Ja);Dr.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${ci()}
289
- `)});Dr.command("doctor").description("Show the new shell HUD doctor command").action(()=>{console.log("Run: visa-cli config shell-hud doctor")});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(T_);async function R_(e){try{await hc();let t=await Rf(),n=ci(),r=n,s=n.split(`
290
- `)[0],o=hf();if(!t&&s.includes("loading")){process.stdout.write(`VISA | HUD not initialized \u2014 run: visa-cli config hud enable
291
- `),ad();return}if(e.json){let a=await Mf(r,t,o);process.stdout.write(`${JSON.stringify(a,null,2)}
292
- `),ad();return}let i=await Pf(r,t,o);process.stdout.write(`${i}
293
- `),ad()}catch(t){let n=t instanceof Error?t.message:"unknown error";console.error(`Failed to render Visa HUD: ${n}`),process.exit(1)}}Lt.command("statusline").description("Output the Visa HUD for agent statusline integrations").option("--json","Output structured JSON for clients that render their own HUD").action(R_);J.command("statusline",{hidden:!0}).description("Deprecated alias for `config statusline`").option("--json","Output structured JSON for clients that render their own HUD").action(R_);var Is=Lt.command("hud").description("Manage the Visa spend HUD \u2014 one command for all surfaces").addHelpCommand(!1);Is.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(`
281
+ Some checks failed \u2014 see above.`),n||process.exit(1)});async function x_(e){if(!(!e.force&&ff()))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"&&Ck(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:wt()},l=Sc(i,c);xc(l,i)}catch(t){let n=t instanceof Error?t.message:"unknown refresh failure";mf(n)}finally{zn()}}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(x_);var Br=J.command("shell-hud",{hidden:!0}).description("Deprecated alias for `config shell-hud`");Br.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(v_);Br.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(S_);Br.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Za);Br.command("disable").description("Disable the persistent shell HUD").action(Za);Br.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${li()}
282
+ `)});Br.command("doctor").description("Show the new shell HUD doctor command").action(()=>{console.log("Run: visa-cli config shell-hud doctor")});Br.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(x_);async function C_(e){try{await _c();let t=await Tf(),n=li(),r=n,s=n.split(`
283
+ `)[0],o=gf();if(!t&&s.includes("loading")){process.stdout.write(`VISA | HUD not initialized \u2014 run: visa-cli config hud enable
284
+ `),id();return}if(e.json){let a=await Nf(r,t,o);process.stdout.write(`${JSON.stringify(a,null,2)}
285
+ `),id();return}let i=await $f(r,t,o);process.stdout.write(`${i}
286
+ `),id()}catch(t){let n=t instanceof Error?t.message:"unknown error";console.error(`Failed to render Visa HUD: ${n}`),process.exit(1)}}Dt.command("statusline").description("Output the Visa HUD for agent statusline integrations").option("--json","Output structured JSON for clients that render their own HUD").action(C_);J.command("statusline",{hidden:!0}).description("Deprecated alias for `config statusline`").option("--json","Output structured JSON for clients that render their own HUD").action(C_);var $s=Dt.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
287
  ${e}Visa HUD Status${s}
295
- `);let o=jt(),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=Xn(re.homedir()),d=u.length>0||ii(),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()});Is.command("enable").description("Enable the Visa HUD \u2014 claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{E_(Rc(e,{homeDir:re.homedir(),installVisaStatusLine:Ws,installShellHud:ai}))});Is.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=Dt();o.removed||(console.error(o.message),process.exit(1)),console.log(o.message);return}let n=hi(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=jt(),i=Ec(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&&!pi()&&Xn(re.homedir()).length>0){let l=Dt();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=Dt();console.log(o.message),o.removed&&(s=!0),!o.removed&&n!=="all"&&(r=!0)}n==="all"&&!s&&(r=!0),r&&process.exit(1)});Is.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=Wu(void 0,void 0,void 0,{withDiagnostics:!0}),o=s.diagnostics?Yu(s.diagnostics,s.display):null;o&&(console.log(`\u26A0 ${o}`),console.log(""));let i=jt(),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=Fk(re.homedir()),l=Gr();if(n("Shell detected",!!l,l??"none (zsh, bash, or PowerShell required)"),l){let m=qs(l),p=ce.existsSync(m);if(n("RC file exists",p,m.replace(re.homedir(),"~")),p){let b=ce.readFileSync(m,"utf-8").includes("visa-cli shell hud v2");console.log(` ${b?"\u2713":"\u2013"} Shell HUD block: ${b?"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 v_(`Remove shell prompt HUD block from ${m}?`,{})==="confirmed"),p){let g=jk(re.homedir());Dt();let b=Bk(g);if(b.length>0){let A=b.map(_=>_.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),b=g<=30,A=typeof m.line=="string"?m.line:"",_=A.length>0&&li(A);if(console.log(` ${b?"\u2713":"\u26A0"} Cache freshness: ${g}s old${b?"":" (stale \u2014 will refresh on next prompt)"}`),_&&console.log(' \u26A0 Cache content: legacy placeholder (HUD will display "VISA | HUD not ready" until next successful refresh)'),e.fix&&(!b||_)){let v=!1;try{ce.rmSync(u,{force:!0}),v=!0}catch{}try{let w=Vs();ce.existsSync(w)&&(ce.rmSync(w,{force:!0}),v=!0)}catch{}if(v){let w=_?"cache held legacy placeholder":`cache was ${g}s stale`;console.log(` \u2713 --fix: cleared HUD cache (${w}); next prompt will trigger a fresh refresh`),r.push("cleared HUD cache");let T=nt.join(re.homedir(),".visa-cli","shell-hud.lock");ce.existsSync(T)&&(zn(),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=nt.join(re.homedir(),".visa-cli","shell-hud.lock");ce.existsSync(m)&&(zn(),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(`
288
+ `);let o=Ft(),i=!1,a=!1;try{if(ce.existsSync(o)){let p=JSON.parse(ce.readFileSync(o,"utf-8")),h=typeof p.statusLine=="object"?p.statusLine.command:"";i=bn(h),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=Xn(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(`
289
+ ${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=>{w_($c(e,{homeDir:re.homedir(),installVisaStatusLine:Ys,installShellHud:ci}))});$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=Bt();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=Ft(),i=Tc(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()&&Xn(re.homedir()).length>0){let l=Bt();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=Bt();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,h)=>{console.log(` ${p?"\u2713":"\u2717"} ${m}: ${h}`),p||(t=!1)};console.log(`Visa HUD Doctor
290
+ `);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=Ft(),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=Rk(re.homedir()),l=Yr();if(n("Shell detected",!!l,l??"none (zsh, bash, or PowerShell required)"),l){let m=Ks(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(h=>h.replace(re.homedir(),"~")).join(", "),p=e.yes===!0;if(!p&&process.stdin.isTTY&&(p=await g_(`Remove shell prompt HUD block from ${m}?`,{})==="confirmed"),p){let h=kk(re.homedir());Bt();let v=Tk(h);if(v.length>0){let I=v.map(_=>_.replace(re.homedir(),"~")).join(", ");console.log(` \u2713 --fix: cleaned legacy shell-prompt HUD block from ${I}`),r.push(`removed shell precmd block from ${I}`)}}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),h=Math.round(p/1e3),v=h<=30,I=typeof m.line=="string"?m.line:"",_=I.length>0&&ui(I);if(console.log(` ${v?"\u2713":"\u26A0"} Cache freshness: ${h}s old${v?"":" (stale \u2014 will refresh on next prompt)"}`),_&&console.log(' \u26A0 Cache content: legacy placeholder (HUD will display "VISA | HUD not ready" until next successful refresh)'),e.fix&&(!v||_)){let b=!1;try{ce.rmSync(u,{force:!0}),b=!0}catch{}try{let w=qs();ce.existsSync(w)&&(ce.rmSync(w,{force:!0}),b=!0)}catch{}if(b){let w=_?"cache held legacy placeholder":`cache was ${h}s stale`;console.log(` \u2713 --fix: cleared HUD cache (${w}); next prompt will trigger a fresh refresh`),r.push("cleared HUD cache");let T=rt.join(re.homedir(),".visa-cli","shell-hud.lock");ce.existsSync(T)&&(zn(),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=rt.join(re.homedir(),".visa-cli","shell-hud.lock");ce.existsSync(m)&&(zn(),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
291
  --fix: no locally fixable issues found.`):console.log(`
299
292
  --fix: applied ${r.length} change${r.length===1?"":"s"} \u2014 ${r.join("; ")}.`)),console.log(t?`
300
293
  All checks passed.`:`
301
- Some checks failed \u2014 see above.`),t||process.exit(1)});Is.command("enable-claude").description("Alias for: hud enable claude").action(()=>{let e=jt(),t=Ws(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});Is.command("disable-claude").description("Alias for: hud disable claude").action(()=>{let e=jt(),t=Ec(e);console.log(t.message),t.removed||process.exit(1)});var $s=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||qk.has(e)){$s.help({error:!1});return}await Gk(e,t,n)});$s.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(`
294
+ Some checks failed \u2014 see above.`),t||process.exit(1)});$s.command("enable-claude").description("Alias for: hud enable claude").action(()=>{let e=Ft(),t=Ys(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=Ft(),t=Tc(e);console.log(t.message),t.removed||process.exit(1)});var Ps=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||Pk.has(e)){Ps.help({error:!1});return}await Nk(e,t,n)});Ps.command("list").description("List live platform merchants").option("--json","Print machine-readable JSON").action(async e=>{try{let n=await new Ke(()=>G.getSessionToken()).listPublicMerchants();if(n.length===0){e.json?console.log(JSON.stringify({merchants:[]},null,2)):console.log(`
302
295
  No live platform merchants on this auth server.
303
296
  `);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
297
  ${s}Run 'visa-cli merchants tools' to browse tools by merchant.${o}
305
- `)}catch(t){console.error("Error:",t.message),process.exit(1)}});var qk=new Set(["list","tools","describe","run","refresh"]);async function wd(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(`
298
+ `)}catch(t){console.error("Error:",t.message),process.exit(1)}});var Pk=new Set(["list","tools","describe","run","refresh"]);async function vd(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
299
  ${n.id}
307
300
  `),console.log(n.description),console.log(`
308
- Price`),console.log(` ${so(n.priceCents,n.priceDisplay)}`),console.log(`
301
+ Price`),console.log(` ${oo(n.priceCents,n.priceDisplay)}`),console.log(`
309
302
  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=Vf(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=Ny(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 Sd(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?Kc(l):Sm(i,l);return}let{limit:n,offset:r}=Ek(e),{tools:s,hidden:o}=await Ak(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){Gc(o);return}console.log("No merchant tools found. Try: visa-cli tools --category image");return}e.verbose?Kc(s):wm(s),o&&o.count>0&&Gc(o)}catch(t){console.error("Error:",t.message),process.exit(1)}}$s.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 ${pd}, max ${gd})`,Va).option("--offset <n>","Pagination offset (default 0)",Va).action(Sd);$s.command("describe <tool>").description("Show tool schema, price, and examples").action(async e=>{await wd(e)});function Kk(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 Xa(e,t,n){return Kk(e)?Pt.shortcut(e,t,n):Pt.executeTool({tool_id:e,params:t},n,"execute_tool")}$s.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=h_(t.json,"--json");t.prompt&&(n.prompt=t.prompt),Ds({yes:t.yes}),console.log(`Running ${e}`);let r=await Xa(e,n,`visa-cli merchants run ${e}`);Wa(r),Ya(r)}catch(n){console.error("Error:",n.message),process.exit(1)}});$s.command("refresh").description("Hint: restart the MCP server (Claude/Cursor) to refresh discovered tools \u2014 discovery is in-process").action(()=>{console.log(`
303
+ 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=Hf(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(`
304
+ Examples`);let s=Oy(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 wd(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):wm(i,l);return}let{limit:n,offset:r}=pk(e),{tools:s,hidden:o}=await mk(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):vm(s),o&&o.count>0&&Yc(o)}catch(t){console.error("Error:",t.message),process.exit(1)}}Ps.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 ${md}, max ${pd})`,Ka).option("--offset <n>","Pagination offset (default 0)",Ka).action(wd);Ps.command("describe <tool>").description("Show tool schema, price, and examples").action(async e=>{await vd(e)});function Ok(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 Ok(e)?Nt.shortcut(e,t,n):Nt.executeTool({tool_id:e,params:t},n,"execute_tool")}Ps.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=d_(t.json,"--json");t.prompt&&(n.prompt=t.prompt),js({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)}});Ps.command("refresh").description("Hint: restart the MCP server (Claude/Cursor) to refresh discovered tools \u2014 discovery is in-process").action(()=>{console.log(`
312
305
  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 Gk(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 Sd({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(`
306
+ `)});async function Nk(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 wd({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
307
  ${r}
315
308
  `),a.description&&console.log(a.description),console.log(`
316
- Price`),console.log(` ${so(a.price_cents)}`),console.log(`
309
+ Price`),console.log(` ${oo(a.price_cents)}`),console.log(`
317
310
  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 wd(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=h_(i,"--json"),c=s("--prompt");c&&(a.prompt=c),Ds({yes:o}),console.log(`Running ${r}`);let l=await Xa(r,a,`visa-cli merchants ${e} run ${r}`);Wa(l),Ya(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 ${pd}, max ${gd})`,Va).option("--offset <n>","Pagination offset (default 0)",Va).action(Sd);J.command("describe <tool>").description("Show schema, price, and examples for a tool (alias for: merchants describe)").action(async e=>{await wd(e)});var Ho=J.command("generate").description("Generate media with merchant tools").addHelpCommand(!1).action(Mt);async function Vo(e){Ds({yes:e.yes}),e.json||e.format&&ei(e.format)||(console.log(`
311
+ `);return}await vd(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=d_(i,"--json"),c=s("--prompt");c&&(a.prompt=c),js({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 ${md}, max ${pd})`,Ka).option("--offset <n>","Pagination offset (default 0)",Ka).action(wd);J.command("describe <tool>").description("Show schema, price, and examples for a tool (alias for: merchants describe)").action(async e=>{await vd(e)});var Vo=J.command("generate").description("Generate media with merchant tools").addHelpCommand(!1).action(Ut);async function qo(e){js({yes:e.yes}),e.json||e.format&&ti(e.format)||(console.log(`
319
312
  ${e.kind}
320
313
  `),console.log(`Using: ${e.toolId}`),console.log(`Prompt: ${e.prompt}
321
- `));let n=await Xa(e.toolId,e.params,`visa-cli generate ${e.kind.toLowerCase()}: ${e.prompt}`);Wa(n,{json:e.json,format:e.format,command:e.command??`generate.${e.kind.toLowerCase().replace(/\s+/g,"_")}`}),Ya(n)}var Gn=(e,t)=>n=>(t.includes(n)||J.error(`error: option '${e}' accepts ${t.map(r=>`'${r}'`).join(", ")} (got '${n}')`,{exitCode:2}),n);Ho.command("image [prompt]").description("Generate an image from a prompt (accepts stdin via `-` or --stdin)").option("--quality <quality>","Image quality: standard or high",Gn("--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)",Gn("--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 Wn(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 Vo({kind:"Image generation",toolId:r,params:s,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.image"})}catch(n){Rs("generate.image",n,{json:t.json,format:t.format})}});Ho.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)",Gn("--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 Wn(e,t),r={prompt:n};t.aspectRatio&&(r.aspect_ratio=t.aspectRatio),t.duration&&(r.duration=Number(t.duration)),await Vo({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){Rs("generate.video",n,{json:t.json,format:t.format})}});Ho.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)",Gn("--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 Wn(e,t),r={prompt:n};t.instrumental&&(r.instrumental=!0),t.duration&&(r.duration=Number(t.duration)),await Vo({kind:"Music generation",toolId:t.tool??"fal-ace-step-music",params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.music"})}catch(n){Rs("generate.music",n,{json:t.json,format:t.format})}});Ho.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)",Gn("--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 Wn(e,t),s={text:r,audio_url:n};await Vo({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){Rs("generate.speech",n,{json:t.json,format:t.format})}});Ho.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)",Gn("--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 Wn(e,t),r={image_url:n};await Vo({kind:"3D generation",toolId:t.tool??"fal-trellis-3d",params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.3d"})}catch(n){Rs("generate.3d",n,{json:t.json,format:t.format})}});var ld="reasoning",I_={fast:"or-gpt-4o-mini",reasoning:"or-claude-sonnet",frontier_anthropic:"or-claude-opus",deep_reasoning:"or-deepseek-r1",search:"or-perplexity-sonar",open_source:"or-llama-70b",coding:"or-deepseek-chat"},l_=Object.keys(I_);J.command("run-llm [prompt]").description(`Run a chat-completion against an OpenRouter-backed LLM (default tier: ${ld})`).option("--tier <tier>",`LLM tier: ${l_.join(" | ")} (resolves to a catalog tool id)`,Gn("--tier",l_),ld).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)",Gn("--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 fc(),u=JSON.parse(l),d=Vd(u,t.fromStdin);n=n??d}let r=await Wn(e,{stdin:t.stdin&&!t.fromStdin});Ds({yes:t.yes});let s={prompt:r},o=await Kd(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??ld,a=t.model??I_[i],c=await Xa(a,s,"visa-cli run-llm");if(!t.json&&c?.success!==!1){console.log(`
314
+ `));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 Gn=(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",Gn("--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)",Gn("--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 Wn(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){Is("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)",Gn("--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 Wn(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){Is("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)",Gn("--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 Wn(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??"fal-ace-step-music",params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.music"})}catch(n){Is("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)",Gn("--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 Wn(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){Is("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)",Gn("--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 Wn(e,t),r={image_url:n};await qo({kind:"3D generation",toolId:t.tool??"fal-trellis-3d",params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.3d"})}catch(n){Is("generate.3d",n,{json:t.json,format:t.format})}});var cd="reasoning",E_={fast:"or-gpt-4o-mini",reasoning:"or-claude-sonnet",frontier_anthropic:"or-claude-opus",deep_reasoning:"or-deepseek-r1",search:"or-perplexity-sonar",open_source:"or-llama-70b",coding:"or-deepseek-chat"},s_=Object.keys(E_);J.command("run-llm [prompt]").description(`Run a chat-completion against an OpenRouter-backed LLM (default tier: ${cd})`).option("--tier <tier>",`LLM tier: ${s_.join(" | ")} (resolves to a catalog tool id)`,Gn("--tier",s_),cd).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)",Gn("--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=Hd(u,t.fromStdin);n=n??d}let r=await Wn(e,{stdin:t.stdin&&!t.fromStdin});js({yes:t.yes});let s={prompt:r},o=await qd(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??cd,a=t.model??E_[i],c=await Qa(a,s,"visa-cli run-llm");if(!t.json&&c?.success!==!1){console.log(`
322
315
  LLM completion
323
316
  `),console.log(`Using: ${a}`);let l=r.length>200?`${r.slice(0,200)}\u2026`:r;console.log(`Prompt: ${l}
324
- `)}Wa(c,{json:t.json,format:t.format,command:"run-llm"}),Ya(c)}catch(n){Rs("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 gt)od(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: ${gt.map(o=>o.id).join(", ")}`),process.exit(1));let r=td(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${gt.map(o=>o.id).join(", ")}`),process.exit(1));let s=od(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(Bo){Bo=!1;return}Fa&&Py(Fa.lastSignals)});Wy(J);zy(J);Ok(["setup","install","status","cards","keys","balance","tools","describe","merchants","generate","run-llm","config","feedback","update","uninstall"]);b_(J);J.parseAsync().catch(async e=>{console.error("Error:",e instanceof Error?e.message:String(e));let{reportFatal:t}=await Promise.resolve().then(()=>(Ba(),ja));await t(e)});process.on("uncaughtException",async e=>{console.error("Uncaught exception:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(Ba(),ja));await t(e)});process.on("unhandledRejection",async e=>{console.error("Unhandled rejection:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(Ba(),ja));await t(e)});0&&(module.exports={printGroupHelpAndExit});
317
+ `)}za(c,{json:t.json,format:t.format,command:"run-llm"}),Ja(c)}catch(n){Is("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)sd(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(`
318
+ Supported clients: ${ht.map(o=>o.id).join(", ")}`),process.exit(1));let r=ed(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${ht.map(o=>o.id).join(", ")}`),process.exit(1));let s=sd(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&&$y(Va.lastSignals)});Hy(J);qy(J);wk(["setup","install","status","cards","keys","balance","tools","describe","merchants","generate","run-llm","config","feedback","update","uninstall"]);p_(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});
326
319
  /*! Bundled license information:
327
320
 
328
321
  @noble/ed25519/index.js: