@visa/cli 4.0.0-rc.20 → 4.0.0-rc.21

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,18 +1,18 @@
1
- "use strict";var o_=Object.create;var zo=Object.defineProperty;var i_=Object.getOwnPropertyDescriptor;var a_=Object.getOwnPropertyNames;var c_=Object.getPrototypeOf,l_=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 lc=(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)zo(e,n,{get:t[n],enumerable:!0})},Vd=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of a_(t))!l_.call(e,s)&&s!==n&&zo(e,s,{get:()=>t[s],enumerable:!(r=i_(t,s))||r.enumerable});return e};var k=(e,t,n)=>(n=e!=null?o_(c_(e)):{},Vd(t||!e||!e.__esModule?zo(n,"default",{value:e,enumerable:!0}):n,e)),u_=e=>Vd(zo({},"__esModule",{value:!0}),e);var Ds=lc((AT,x_)=>{x_.exports={name:"@visa/cli",version:"4.0.0-rc.20",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 G0(){Be.existsSync(Kc)||Be.mkdirSync(Kc,{recursive:!0,mode:448})}function W0(){if(!qc){if(G0(),Be.existsSync(eo)&&Be.statSync(eo).size>K0){let t=eo+".1";Be.existsSync(t)&&Be.unlinkSync(t),Be.renameSync(eo,t)}qc=Be.createWriteStream(eo,{flags:"a"})}return qc}function Y0(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function Ci(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
- `;Y0(e)&&process.stderr.write(s),W0().write(s)}var Be,Gc,wm,Kc,eo,K0,qc,g,Kt=st(()=>{"use strict";Be=k(require("fs")),Gc=k(require("path")),wm=k(require("os")),Kc=Gc.join(wm.homedir(),".visa-mcp"),eo=Gc.join(Kc,"mcp-server.log"),K0=5*1024*1024,qc=null;g={debug:(...e)=>Ci("DEBUG",...e),info:(...e)=>Ci("INFO",...e),warn:(...e)=>Ci("WARN",...e),error:(...e)=>Ci("ERROR",...e)}});var Ai,Am,Em,Wc,to,km=st(()=>{"use strict";Ai=k(require("fs")),Am=k(require("path")),Em=k(require("os")),Wc=Am.join(Em.homedir(),".visa-mcp"),to=class{static ensureConfigDir(){Ai.existsSync(Wc)||Ai.mkdirSync(Wc,{recursive:!0,mode:448})}static getConfigDir(){return Wc}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 Tm(e){let t=Rm.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function no(){return Im.join(to.getConfigDir(),X0)}function Pm(e){if((0,zc.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function Q0(e){let t=e.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!t)return!1;let n=Number.parseInt(t[1],16),r=Number.parseInt(t[2],16);if(!Number.isFinite(n)||!Number.isFinite(r))return!1;let s=[n>>8&255,n&255,r>>8&255,r&255].join(".");return Pm(s)}function ev(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,zc.isIP)(t);return n===4?Pm(t):n===6?t==="::1"||Q0(t):!1}function Yc(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:"&&ev(n.hostname)))throw new Error(`${t} ${Z0}`)}function tr(){let e=no();if(!Sn.existsSync(e))return{};try{let t=Sn.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?(g.warn("settings:corrupt",{path:Tm(e),reason:"not_object"}),{}):n}catch(t){return g.warn("settings:corrupt",{path:Tm(e),error:t?.message||String(t)}),{}}}function Jc(e){to.ensureConfigDir();let t=no(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
3
- `;Sn.writeFileSync(n,r,{mode:384}),Sn.renameSync(n,t)}function Zc(e){let t=tr()[e];return typeof t=="string"?t:void 0}function ki(e){let t=tr()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function Qc(e){let t=tr()[e];if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim().length>0){let n=Number(t);if(Number.isFinite(n))return n}}function Ti(e,t){if($m.some(o=>e.startsWith(o)))throw new Gt(e);if(e in Ei)throw new wn(e);let n=nr[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=tr();return s[e]=r,Jc(s),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:no()}}function Ri(e){if($m.some(o=>e.startsWith(o)))throw new Gt(e);let t=nr[e];if(e in Ei){let o=tr(),i=e in o;return i&&(delete o[e],Jc(o)),{key:e,removed:i,requiresRestart:!1,path:no()}}if(!t)throw new at(e);let r=tr(),s=e in r;return s&&(delete r[e],Jc(r)),{key:e,removed:s,requiresRestart:s&&!!t.requiresRestart,path:no()}}function Nm(){let e=tr();return Object.entries(Ei).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}function rv(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function sv(){try{let e=Ds();return rv(e.version)}catch{return!1}}function ov(e){return e.envVar!==void 0&&e.envVar!==""?(Yc(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(Yc(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?nv:tv}function de(){return ov({envVar:process.env.VISA_AUTH_URL,settingValue:Zc("auth.serverUrl"),isPrerelease:sv()})}function Om(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":ki("ui.suppressBrowser")??!1}function Mm(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":ki("ui.suppressFeed")??!1}function Lm(){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=Qc("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):Xc}var Sn,zc,Rm,Im,X0,Z0,nr,Xc,Ei,at,Gt,wn,$m,tv,nv,ct=st(()=>{"use strict";Sn=k(require("fs")),zc=require("node:net"),Rm=k(require("os")),Im=k(require("path"));km();Kt();X0="settings.json",Z0="must use https unless it points at localhost/loopback for local development";nr={"auth.serverUrl":{type:"string",description:"Auth server base URL. Override for staging / self-hosted backends.",requiresRestart:!0,validate:e=>{if(typeof e!="string")throw new Error("auth.serverUrl must be a string");Yc(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)")}}},Xc=500,Ei={"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(nr).sort().join(", ");super(`Unknown setting "${t}". Settable keys: ${n}. For server-controlled values (biometric.*, spending.*) use the dedicated tools (biometric_on/off, update_spending_controls).`),this.name="UnknownSettingKeyError"}},Gt=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"}},wn=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+Ei[t]),this.name="RetiredSettingKeyError"}},$m=["biometric.","spending.","account.","cards.","biometric"];tv="https://auth.visacli.sh",nv="https://auth-visa-code-preview.up.railway.app"});var wp=lc(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.formatCents=vp;ut.formatUsd=Qw;ut.formatMicros=Ui;ut.formatMicrosWire=eS;ut.formatTxAmount=tS;ut.formatDate=nS;ut.formatRelativeTime=rS;ut.formatTime=sS;ut.formatAge=oS;var _p=1e6,Zw=100;function vp(e,t={}){let n=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return n;let s=(e/Zw).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${s}`:s}function Qw(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 Ui(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/_p).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??6});return t.showPlusSign&&r>0?`+${o}`:o}function eS(e,t,n={}){return e&&/^-?\d+$/.test(e)?Ui(e,n):t!=null&&Number.isFinite(t)?vp(t,n):n.fallback??"\u2014"}function tS(e,t={}){let n=Number(e.amount_micros);if(Number.isFinite(n)&&e.amount_micros!=null&&e.amount_micros!=="")return Ui(n,t);let r=Number(String(e.amount).replace(/^\$/,""));return Number.isFinite(r)?Ui(r*_p,t):t.fallback??"\u2014"}function nS(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 rS(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?cs(r,s,a,"minute"):c<24?cs(r,s,c,"hour"):l===1?s?"yesterday":"tomorrow":l<7?cs(r,s,l,"day"):u<4?cs(r,s,u,"week"):d<12?cs(r,s,d,"month"):cs(r,s,f,"year")}function cs(e,t,n,r){let s=n!==1?"s":"";return t?`${n} ${r}${s} ago`:`in ${n} ${r}${s}`}function sS(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 oS(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 ls=lc(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=iS;q.fromCents=aS;q.fromUsdc=cS;q.fromUsd=lS;q.toCents=uS;q.toCentsForAcquirer=dS;q.toUsdc=fS;q.toWire=mS;q.fromWire=pS;q.toDisplay=gS;q.toUsdRounded2dp=hS;q.add=yS;q.sub=bS;q.clampNonNegative=_S;q.isNonNegative=vS;q.max=wS;q.min=SS;var Xt=10000n,Sp=1000000n;function iS(e){return e}function aS(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*Xt}function cS(e){return e}function lS(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function uS(e){if(e>=0n)return Number(e/Xt);let t=e/Xt,n=e%Xt;return Number(n===0n?t:t-1n)}function dS(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/Xt)}function fS(e){return e}function mS(e){return e.toString()}function pS(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 gS(e,t={}){let n=t.decimals??2,r=t.symbol??"$",s=e<0n,o=s?-e:e,i=o/Sp,a=o%Sp,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 hS(e){let t=e<0n,n=t?-e:e,r=n/Xt,o=n%Xt*2n,i;o<Xt?i=r:o>Xt?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function yS(e,t){return e+t}function bS(e,t){return e-t}function _S(e){return e<0n?0n:e}function vS(e){return e>=0n}function wS(e,t){return e>t?e:t}function SS(e,t){return e<t?e:t}var Zt=wp();Object.defineProperty(q,"formatCents",{enumerable:!0,get:function(){return Zt.formatCents}});Object.defineProperty(q,"formatUsd",{enumerable:!0,get:function(){return Zt.formatUsd}});Object.defineProperty(q,"formatMicros",{enumerable:!0,get:function(){return Zt.formatMicros}});Object.defineProperty(q,"formatMicrosWire",{enumerable:!0,get:function(){return Zt.formatMicrosWire}});Object.defineProperty(q,"formatTxAmount",{enumerable:!0,get:function(){return Zt.formatTxAmount}});Object.defineProperty(q,"formatDate",{enumerable:!0,get:function(){return Zt.formatDate}});Object.defineProperty(q,"formatRelativeTime",{enumerable:!0,get:function(){return Zt.formatRelativeTime}});Object.defineProperty(q,"formatTime",{enumerable:!0,get:function(){return Zt.formatTime}});Object.defineProperty(q,"formatAge",{enumerable:!0,get:function(){return Zt.formatAge}})});function Ol(e,t){switch(e){case"name_not_found":return new dg(t);case"delivery_failed":return new fg(t);case"timeout":return new _o(t);case"not_registered":return new mg;case"register_failed":return new ea(t);case"invalid_message":return new pg(t);case"rate_limited":return new gg(t);default:return new Tt(e,t)}}var Tt,dg,fg,_o,mg,Oe,pg,ea,gg,Ml=st(()=>{"use strict";Tt=class extends Error{code;constructor(e,t){super(t),this.name="SubwayError",this.code=e}},dg=class extends Tt{constructor(e){super("name_not_found",`Agent not registered: ${e}`),this.name="NameNotFoundError"}},fg=class extends Tt{constructor(e){super("delivery_failed",e),this.name="DeliveryFailedError"}},_o=class extends Tt{constructor(e="RPC call timed out"){super("timeout",e),this.name="TimeoutError"}},mg=class extends Tt{constructor(){super("not_registered","Client has not registered with the bridge"),this.name="NotRegisteredError"}},Oe=class extends Tt{constructor(e){super("connection_failed",e),this.name="ConnectionError"}},pg=class extends Tt{constructor(e){super("invalid_message",e),this.name="InvalidMessageError"}},ea=class extends Tt{constructor(e){super("register_failed",e),this.name="RegisterFailedError"}},gg=class extends Tt{constructor(e="Rate limited"){super("rate_limited",e),this.name="RateLimitedError"}}});var hg,Ll=st(()=>{"use strict";hg=(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 kr(e){return e.includes(".")?e:`${e}.relay`}function Ul(){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 JS(){if(typeof WebSocket<"u")return WebSocket;try{let e=hg("ws");return e.default??e}catch{return}}function zS(e,t,n){return Math.min(Math.max(e,t),n)}function wx(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=wx(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 Cg(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 Sx(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 vo(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Hl(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function It(e,t){return e<<32-t|e>>>t}function nh(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 xx(e,t,n){return e&t^~e&n}function Cx(e,t,n){return e&t^e&n^t&n}function Ax(e,t=!1){return t?{h:Number(e&ta),l:Number(e>>Ag&ta)}:{h:Number(e>>Ag&ta)|0,l:Number(e&ta)|0}}function Ex(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}=Ax(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 Fx(e){return px(e)}function Vx(e,t){return yx(t,e)}function Kx(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Yx(e){let t=qx(Bx(e.payload)),n=`${e.messageId}
1
+ "use strict";var m_=Object.create;var Zo=Object.defineProperty;var p_=Object.getOwnPropertyDescriptor;var g_=Object.getOwnPropertyNames;var h_=Object.getPrototypeOf,y_=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 fc=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},qr=(e,t)=>{for(var n in t)Zo(e,n,{get:t[n],enumerable:!0})},Jd=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of g_(t))!y_.call(e,s)&&s!==n&&Zo(e,s,{get:()=>t[s],enumerable:!(r=p_(t,s))||r.enumerable});return e};var A=(e,t,n)=>(n=e!=null?m_(h_(e)):{},Jd(t||!e||!e.__esModule?Zo(n,"default",{value:e,enumerable:!0}):n,e)),b_=e=>Jd(Zo({},"__esModule",{value:!0}),e);var Hs=fc((jT,P_)=>{P_.exports={name:"@visa/cli",version:"4.0.0-rc.21",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 ev(){He.existsSync(Yc)||He.mkdirSync(Yc,{recursive:!0,mode:448})}function tv(){if(!Wc){if(ev(),He.existsSync(no)&&He.statSync(no).size>Q0){let t=no+".1";He.existsSync(t)&&He.unlinkSync(t),He.renameSync(no,t)}Wc=He.createWriteStream(no,{flags:"a"})}return Wc}function nv(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function Ai(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
+ `;nv(e)&&process.stderr.write(s),tv().write(s)}var He,Jc,km,Yc,no,Q0,Wc,g,Kt=st(()=>{"use strict";He=A(require("fs")),Jc=A(require("path")),km=A(require("os")),Yc=Jc.join(km.homedir(),".visa-mcp"),no=Jc.join(Yc,"mcp-server.log"),Q0=5*1024*1024,Wc=null;g={debug:(...e)=>Ai("DEBUG",...e),info:(...e)=>Ai("INFO",...e),warn:(...e)=>Ai("WARN",...e),error:(...e)=>Ai("ERROR",...e)}});var ki,Pm,$m,zc,Sn,Xc=st(()=>{"use strict";ki=A(require("fs")),Pm=A(require("path")),$m=A(require("os")),zc=Pm.join($m.homedir(),".visa-mcp"),Sn=class{static ensureConfigDir(){ki.existsSync(zc)||ki.mkdirSync(zc,{recursive:!0,mode:448})}static getConfigDir(){return zc}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 Nm(e){let t=Om.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function ro(){return Mm.join(Sn.getConfigDir(),ov)}function Lm(e){if((0,el.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function av(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 Lm(s)}function cv(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,el.isIP)(t);return n===4?Lm(t):n===6?t==="::1"||av(t):!1}function Zc(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:"&&cv(n.hostname)))throw new Error(`${t} ${iv}`)}function rr(){let e=ro();if(!Cn.existsSync(e))return{};try{let t=Cn.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?(g.warn("settings:corrupt",{path:Nm(e),reason:"not_object"}),{}):n}catch(t){return g.warn("settings:corrupt",{path:Nm(e),error:t?.message||String(t)}),{}}}function Qc(e){Sn.ensureConfigDir();let t=ro(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
3
+ `;Cn.writeFileSync(n,r,{mode:384}),Cn.renameSync(n,t)}function nl(e){let t=rr()[e];return typeof t=="string"?t:void 0}function Ri(e){let t=rr()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function rl(e){let t=rr()[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 Ii(e,t){if(Um.some(o=>e.startsWith(o)))throw new Gt(e);if(e in Ti)throw new xn(e);let n=sr[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=rr();return s[e]=r,Qc(s),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:ro()}}function Pi(e){if(Um.some(o=>e.startsWith(o)))throw new Gt(e);let t=sr[e];if(e in Ti){let o=rr(),i=e in o;return i&&(delete o[e],Qc(o)),{key:e,removed:i,requiresRestart:!1,path:ro()}}if(!t)throw new at(e);let r=rr(),s=e in r;return s&&(delete r[e],Qc(r)),{key:e,removed:s,requiresRestart:s&&!!t.requiresRestart,path:ro()}}function Dm(){let e=rr();return Object.entries(Ti).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}function dv(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function fv(){try{let e=Hs();return dv(e.version)}catch{return!1}}function mv(e){return e.envVar!==void 0&&e.envVar!==""?(Zc(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(Zc(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?uv:lv}function de(){return mv({envVar:process.env.VISA_AUTH_URL,settingValue:nl("auth.serverUrl"),isPrerelease:fv()})}function jm(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":Ri("ui.suppressBrowser")??!1}function Hm(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":Ri("ui.suppressFeed")??!1}function Bm(){let e=process.env.VISA_CREDIT_SESSION_CAP_CENTS;if(e!==void 0){let n=Number(e);if(Number.isFinite(n)&&n>=10&&n<=1e4)return Math.floor(n)}let t=rl("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):tl}var Cn,el,Om,Mm,ov,iv,sr,tl,Ti,at,Gt,xn,Um,lv,uv,ct=st(()=>{"use strict";Cn=A(require("fs")),el=require("node:net"),Om=A(require("os")),Mm=A(require("path"));Xc();Kt();ov="settings.json",iv="must use https unless it points at localhost/loopback for local development";sr={"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");Zc(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)")}}},tl=500,Ti={"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(sr).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"}},Gt=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"}},xn=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+Ti[t]),this.name="RetiredSettingKeyError"}},Um=["biometric.","spending.","account.","cards.","biometric"];lv="https://auth.visacli.sh",uv="https://auth-visa-code-preview.up.railway.app"});var Ap=fc(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.formatCents=Ep;ut.formatUsd=aS;ut.formatMicros=ji;ut.formatMicrosWire=cS;ut.formatTxAmount=lS;ut.formatDate=uS;ut.formatRelativeTime=dS;ut.formatTime=fS;ut.formatAge=mS;var Cp=1e6,iS=100;function Ep(e,t={}){let n=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return n;let s=(e/iS).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${s}`:s}function aS(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 ji(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/Cp).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??6});return t.showPlusSign&&r>0?`+${o}`:o}function cS(e,t,n={}){return e&&/^-?\d+$/.test(e)?ji(e,n):t!=null&&Number.isFinite(t)?Ep(t,n):n.fallback??"\u2014"}function lS(e,t={}){let n=Number(e.amount_micros);if(Number.isFinite(n)&&e.amount_micros!=null&&e.amount_micros!=="")return ji(n,t);let r=Number(String(e.amount).replace(/^\$/,""));return Number.isFinite(r)?ji(r*Cp,t):t.fallback??"\u2014"}function uS(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 dS(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?us(r,s,a,"minute"):c<24?us(r,s,c,"hour"):l===1?s?"yesterday":"tomorrow":l<7?us(r,s,l,"day"):u<4?us(r,s,u,"week"):d<12?us(r,s,d,"month"):us(r,s,f,"year")}function us(e,t,n,r){let s=n!==1?"s":"";return t?`${n} ${r}${s} ago`:`in ${n} ${r}${s}`}function fS(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 mS(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 ds=fc(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=pS;q.fromCents=gS;q.fromUsdc=hS;q.fromUsd=yS;q.toCents=bS;q.toCentsForAcquirer=_S;q.toUsdc=vS;q.toWire=wS;q.fromWire=SS;q.toDisplay=xS;q.toUsdRounded2dp=CS;q.add=ES;q.sub=AS;q.clampNonNegative=kS;q.isNonNegative=TS;q.max=RS;q.min=IS;var Xt=10000n,kp=1000000n;function pS(e){return e}function gS(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*Xt}function hS(e){return e}function yS(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function bS(e){if(e>=0n)return Number(e/Xt);let t=e/Xt,n=e%Xt;return Number(n===0n?t:t-1n)}function _S(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/Xt)}function vS(e){return e}function wS(e){return e.toString()}function SS(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 xS(e,t={}){let n=t.decimals??2,r=t.symbol??"$",s=e<0n,o=s?-e:e,i=o/kp,a=o%kp,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 CS(e){let t=e<0n,n=t?-e:e,r=n/Xt,o=n%Xt*2n,i;o<Xt?i=r:o>Xt?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function ES(e,t){return e+t}function AS(e,t){return e-t}function kS(e){return e<0n?0n:e}function TS(e){return e>=0n}function RS(e,t){return e>t?e:t}function IS(e,t){return e<t?e:t}var Zt=Ap();Object.defineProperty(q,"formatCents",{enumerable:!0,get:function(){return Zt.formatCents}});Object.defineProperty(q,"formatUsd",{enumerable:!0,get:function(){return Zt.formatUsd}});Object.defineProperty(q,"formatMicros",{enumerable:!0,get:function(){return Zt.formatMicros}});Object.defineProperty(q,"formatMicrosWire",{enumerable:!0,get:function(){return Zt.formatMicrosWire}});Object.defineProperty(q,"formatTxAmount",{enumerable:!0,get:function(){return Zt.formatTxAmount}});Object.defineProperty(q,"formatDate",{enumerable:!0,get:function(){return Zt.formatDate}});Object.defineProperty(q,"formatRelativeTime",{enumerable:!0,get:function(){return Zt.formatRelativeTime}});Object.defineProperty(q,"formatTime",{enumerable:!0,get:function(){return Zt.formatTime}});Object.defineProperty(q,"formatAge",{enumerable:!0,get:function(){return Zt.formatAge}})});function jl(e,t){switch(e){case"name_not_found":return new vg(t);case"delivery_failed":return new wg(t);case"timeout":return new wo(t);case"not_registered":return new Sg;case"register_failed":return new ra(t);case"invalid_message":return new xg(t);case"rate_limited":return new Cg(t);default:return new Tt(e,t)}}var Tt,vg,wg,wo,Sg,Oe,xg,ra,Cg,Hl=st(()=>{"use strict";Tt=class extends Error{code;constructor(e,t){super(t),this.name="SubwayError",this.code=e}},vg=class extends Tt{constructor(e){super("name_not_found",`Agent not registered: ${e}`),this.name="NameNotFoundError"}},wg=class extends Tt{constructor(e){super("delivery_failed",e),this.name="DeliveryFailedError"}},wo=class extends Tt{constructor(e="RPC call timed out"){super("timeout",e),this.name="TimeoutError"}},Sg=class extends Tt{constructor(){super("not_registered","Client has not registered with the bridge"),this.name="NotRegisteredError"}},Oe=class extends Tt{constructor(e){super("connection_failed",e),this.name="ConnectionError"}},xg=class extends Tt{constructor(e){super("invalid_message",e),this.name="InvalidMessageError"}},ra=class extends Tt{constructor(e){super("register_failed",e),this.name="RegisterFailedError"}},Cg=class extends Tt{constructor(e="Rate limited"){super("rate_limited",e),this.name="RateLimitedError"}}});var Eg,Bl=st(()=>{"use strict";Eg=(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 Rr(e){return e.includes(".")?e:`${e}.relay`}function Fl(){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 cx(){if(typeof WebSocket<"u")return WebSocket;try{let e=Eg("ws");return e.default??e}catch{return}}function lx(e,t,n){return Math.min(Math.max(e,t),n)}function Ox(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function uh(e,t,n=""){let r=Ox(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 Ng(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 Mx(e,t){uh(e,void 0,"digestInto() output");let n=t.outputLen;if(e.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function So(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Gl(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function It(e,t){return e<<32-t|e>>>t}function dh(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 Lx(e,t,n){return e&t^~e&n}function Ux(e,t,n){return e&t^e&n^t&n}function Dx(e,t=!1){return t?{h:Number(e&sa),l:Number(e>>Og&sa)}:{h:Number(e>>Og&sa)|0,l:Number(e&sa)|0}}function jx(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}=Dx(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 tC(e){return kx(e)}function nC(e,t){return Ix(t,e)}function sC(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function aC(e){let t=rC(Qx(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 Gx.encode(n)}function Jx(e,t,n,r,s,o,i){return Yx({messageId:e,senderPeerId:t,senderName:n,timestampMs:r,messageType:s,payload:o,nonce:i})}function zx(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 vC(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function vh(e,t,n=""){let r=vC(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 Lg(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 wC(e,t){vh(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 Xl(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Kl(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function SC(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 AC(e,t=!1){return t?{h:Number(e&sa),l:Number(e>>Ug&sa)}:{h:Number(e>>Ug&sa)|0,l:Number(e&sa)|0}}function EC(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}=AC(e[o],t);[r[o],s[o]]=[i,a]}return[r,s]}function sn(e,t,n,r){let s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}function DC(){return hC.randomSecretKey()}function Sh(e){return pC(e)}function jC(){let e=DC();return{secretKey:e,publicKey:Sh(e)}}function BC(e){if((0,Hn.existsSync)(e)){let n=(0,Hn.readFileSync)(e),r=new Uint8Array(n.buffer.slice(n.byteOffset,n.byteOffset+32));return{secretKey:r,publicKey:Sh(r)}}let t=jC();return(0,Hn.mkdirSync)((0,Fg.dirname)(e),{recursive:!0}),(0,Hn.writeFileSync)(e,new Uint8Array(t.secretKey)),t}function HC(e){let{secretKey:t,publicKey:n}=BC(e);return{privateKey:t,publicKey:n}}async function FC(e,t,n,r,s,o,i,a){let c=Jx(t,n,r,s,o,i,a);return{signature:await Vx(e,c),signatureInput:Wx.subwayAgentMsgV1}}function Hg(e){return Kx(e)}var Hn,Fg,XS,ZS,QS,ex,tx,Vg,la,aa,yg,bg,Dl,jl,nx,ga,rx,ke,sx,ox,ix,on,ha,Zl,qg,Ql,tn,_g,eu,Kg,ax,gs,cx,ua,xr,oe,vg,P,Gg,Wg,Yg,Jg,Bl,Gl,wo,Ir,Tr,zg,Xg,Rt,lx,wg,ux,Wl,tu,dx,Zg,fx,mx,px,gx,hx,yx,nu,Qg,da,bx,eh,Yl,_x,Sg,xg,vx,rh,sh,Mn,Me,ta,Ag,Eg,kg,ds,fs,na,ra,kx,Tx,Rx,Ix,Px,$x,Nx,Ln,Ox,Mx,oh,Lx,Ux,Un,Dn,Dx,jx,Bx,Hx,Tg,qx,ih,Gx,Wx,ah,Xx,ch,fa,ca,Rg,Ig,Fl,Vl,Zx,hs,Qx,Te,eC,tC,nC,Fn,ya,ru,lh,uh,rn,Pg,dh,fh,rC,su,sC,ma,Ar,ae,$g,$,oC,iC,mh,ph,ql,Jl,So,ys,Rr,aC,gh,Pt,cC,Ng,lC,uC,dC,fC,hh,mC,yh,pC,bh,gC,hC,pa,yC,_h,zl,bC,Og,Mg,_C,xC,CC,Le,sa,Ug,Dg,jg,ms,ps,oa,ia,kC,TC,RC,IC,PC,$C,wh,NC,OC,jn,Bn,MC,LC,UC,Bg,VC,qC,xh,ou=st(()=>{"use strict";Ml();Ml();Ll();Hn=require("fs"),Fg=require("path");XS=1e3,ZS=10,QS=3e4,ex=3e4,tx=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??ZS,this.pingInterval=e.pingInterval??QS}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=JS();if(!n){t(new Oe('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 Oe(`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 Oe("WebSocket closed before connection established")))},this.ws.onerror=()=>{r||(r=!0,t(new Oe(`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 Oe("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=zS(this.reconnectInterval*Math.pow(2,this.reconnectAttempt),this.reconnectInterval,ex);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)}}},Vg=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:la,n:aa,Gx:yg,Gy:bg,a:Dl,d:jl,h:nx}=Vg,ga=32,rx=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},ke=(e="")=>{let t=new Error(e);throw rx(t,ke),t},sx=e=>typeof e=="bigint",ox=e=>typeof e=="string",ix=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,on=(e,t,n="")=>{let r=ix(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},ha=e=>new Uint8Array(e),Zl=e=>Uint8Array.from(e),qg=(e,t)=>e.toString(16).padStart(t,"0"),Ql=e=>Array.from(on(e)).map(t=>qg(t,2)).join(""),tn={_0:48,_9:57,A:65,F:70,a:97,f:102},_g=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)},eu=e=>{let t="hex invalid";if(!ox(e))return ke(t);let n=e.length,r=n/2;if(n%2)return ke(t);let s=ha(r);for(let o=0,i=0;o<r;o++,i+=2){let a=_g(e.charCodeAt(i)),c=_g(e.charCodeAt(i+1));if(a===void 0||c===void 0)return ke(t);s[o]=a*16+c}return s},Kg=()=>globalThis?.crypto,ax=()=>Kg()?.subtle??ke("crypto.subtle must be defined, consider polyfill"),gs=(...e)=>{let t=0;for(let s of e)t+=on(s).length;let n=ha(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},cx=(e=ga)=>Kg().getRandomValues(ha(e)),ua=BigInt,xr=(e,t,n,r="bad number: out of range")=>{if(!sx(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},oe=(e,t=la)=>{let n=e%t;return n>=0n?n:t+n},vg=(1n<<255n)-1n,P=e=>{e<0n&&ke("negative coordinate");let t=(e>>255n)*19n+(e&vg);return t=(t>>255n)*19n+(t&vg),t%la},Gg=e=>oe(e,aa),Wg=(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")},Yg=e=>{let t=Qg[e];return typeof t!="function"&&ke("hashes."+e+" not set"),t},Jg=e=>on(e,64,"digest"),Bl=e=>e instanceof wo?e:ke("Point expected"),Gl=2n**256n,wo=class Cr{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=Gl;this.X=xr(t,0n,o),this.Y=xr(n,0n,o),this.Z=xr(r,1n,o),this.T=xr(s,0n,o),Object.freeze(this)}static CURVE(){return Vg}static fromAffine(t){return new Cr(t.x,t.y,1n,P(t.x*t.y))}static fromBytes(t,n=!1){let r=jl,s=Zl(on(t,ga)),o=t[31];s[31]=o&-129;let i=Xg(s);xr(i,0n,n?Gl:la);let c=P(i*i),l=oe(c-1n),u=P(r*c+1n),{isValid:d,value:f}=ux(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 Cr(f,i,1n,P(f*i))}static fromHex(t,n){return Cr.fromBytes(eu(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Dl,n=jl,r=this;if(r.is0())return ke("bad point: ZERO");let{X:s,Y:o,Z:i,T:a}=r,c=P(s*s),l=P(o*o),u=P(i*i),d=P(u*u),f=P(c*t),m=P(u*(f+l)),p=oe(d+P(n*P(c*l)));if(m!==p)return ke("bad point: equation left != right (1)");let h=P(s*o),v=P(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}=Bl(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 Cr(oe(-this.X),this.Y,this.Z,oe(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=Dl,o=P(t*t),i=P(n*n),a=P(2n*r*r),c=P(s*o),l=oe(t+n),u=oe(P(l*l)-o-i),d=oe(c+i),f=oe(d-a),m=oe(c-i),p=P(u*f),h=P(d*m),v=P(u*m),I=P(f*d);return new Cr(p,h,I,v)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=Bl(t),u=Dl,d=jl,f=P(n*i),m=P(r*a),p=P(P(o*d)*l),h=P(s*c),v=oe(P(oe(n+r)*oe(i+a))-f-m),I=oe(h-p),b=oe(h+p),_=oe(m-P(u*f)),w=P(v*I),R=P(b*_),E=P(v*_),y=P(I*b);return new Cr(w,R,y,E)}subtract(t){return this.add(Bl(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(xr(t,1n,aa),!n&&this.is0()))return Tr;if(t===1n)return this;if(this.equals(Ir))return vx(t).p;let r=Tr,s=Ir;for(let o=this;t>0n;o=o.double(),t>>=1n)t&1n?r=r.add(o):n&&(s=s.add(o));return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(this.equals(Tr))return{x:0n,y:1n};let s=Wg(r,la);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=zg(n);return r[31]|=t&1n?128:0,r}toHex(){return Ql(this.toBytes())}clearCofactor(){return this.multiply(ua(nx),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(aa/2n,!1).double();return aa%2n&&(t=t.add(this)),t.is0()}},Ir=new wo(yg,bg,1n,oe(yg*bg)),Tr=new wo(0n,1n,1n,0n);wo.BASE=Ir;wo.ZERO=Tr;zg=e=>eu(qg(xr(e,0n,Gl),64)).reverse(),Xg=e=>ua("0x"+Ql(Zl(on(e)).reverse())),Rt=(e,t)=>{let n=e;for(;t-- >0n;)n=P(n*n);return n},lx=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}},wg=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,ux=(e,t)=>{let n=P(t*P(t*t)),r=P(P(n*n)*t),s=lx(P(e*r)).pow_p_5_8,o=P(e*P(n*s)),i=P(t*P(o*o)),a=o,c=P(o*wg),l=i===e,u=i===oe(-e),d=i===oe(-e*wg);return l&&(o=a),(u||d)&&(o=c),(oe(o)&1n)===1n&&(o=oe(-o)),{isValid:l||u,value:o}},Wl=e=>Gg(Xg(e)),tu=(...e)=>Promise.resolve(Yg("sha512Async")(gs(...e))).then(Jg),dx=(...e)=>Jg(Yg("sha512")(gs(...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=Wl(n),o=Ir.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},fx=e=>tu(on(e,ga)).then(Zg),mx=e=>Zg(dx(on(e,ga))),px=e=>mx(e).pointBytes,gx=e=>tu(e.hashable).then(e.finish),hx=(e,t,n)=>{let{pointBytes:r,scalar:s}=e,o=Wl(t),i=Ir.multiply(o).toBytes();return{hashable:gs(i,r,n),finish:l=>{let u=Gg(o+Wl(l)*s);return on(gs(i,zg(u)),64)}}},yx=async(e,t)=>{let n=on(e),r=await fx(t),s=await tu(r.prefix,n);return gx(hx(r,s,n))},nu=Object.freeze({bytesToHex:Ql,hexToBytes:eu,concatBytes:gs,mod:oe,invert:Wg,randomBytes:cx}),Qg={sha512Async:async e=>{let t=ax(),n=gs(e);return ha(await t.digest("SHA-512",n.buffer))},sha512:void 0},da=8,bx=256,eh=Math.ceil(bx/da)+1,Yl=2**(da-1),_x=()=>{let e=[],t=Ir,n=t;for(let r=0;r<eh;r++){n=t,e.push(n);for(let s=1;s<Yl;s++)n=n.add(t),e.push(n);t=n.double()}return e},Sg=void 0,xg=(e,t)=>{let n=t.negate();return e?n:t},vx=e=>{let t=Sg||(Sg=_x()),n=Tr,r=Ir,s=2**da,o=s,i=ua(s-1),a=ua(da);for(let c=0;c<eh;c++){let l=Number(e&i);e>>=a,l>Yl&&(l-=o,e+=1n);let u=c*Yl,d=u,f=u+Math.abs(l)-1,m=c%2!==0,p=l<0;l===0?r=r.add(xg(m,t[d])):n=n.add(xg(p,t[f]))}return e!==0n&&ke("invalid wnaf"),{p:n,f:r}};rh=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});sh=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=Hl(this.buffer)}update(e){Cg(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=Hl(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){Cg(this),Sx(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,vo(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=Hl(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()}},Mn=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]),ta=BigInt(2**32-1),Ag=BigInt(32);Eg=(e,t,n)=>e>>>n,kg=(e,t,n)=>e<<32-n|t>>>n,ds=(e,t,n)=>e>>>n|t<<32-n,fs=(e,t,n)=>e<<32-n|t>>>n,na=(e,t,n)=>e<<64-n|t>>>n-32,ra=(e,t,n)=>e>>>n-32|t<<64-n;kx=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Tx=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Rx=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Ix=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,Px=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),$x=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,Nx=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ln=new Uint32Array(64),Ox=class extends sh{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:r,E:s,F:o,G:i,H:a}=this;return[e,t,n,r,s,o,i,a]}set(e,t,n,r,s,o,i,a){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=s|0,this.F=o|0,this.G=i|0,this.H=a|0}process(e,t){for(let u=0;u<16;u++,t+=4)Ln[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let d=Ln[u-15],f=Ln[u-2],m=It(d,7)^It(d,18)^d>>>3,p=It(f,17)^It(f,19)^f>>>10;Ln[u]=p+Ln[u-7]+m+Ln[u-16]|0}let{A:n,B:r,C:s,D:o,E:i,F:a,G:c,H:l}=this;for(let u=0;u<64;u++){let d=It(i,6)^It(i,11)^It(i,25),f=l+d+xx(i,a,c)+Nx[u]+Ln[u]|0,p=(It(n,2)^It(n,13)^It(n,22))+Cx(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(){vo(Ln)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),vo(this.buffer)}},Mx=class extends Ox{A=Mn[0]|0;B=Mn[1]|0;C=Mn[2]|0;D=Mn[3]|0;E=Mn[4]|0;F=Mn[5]|0;G=Mn[6]|0;H=Mn[7]|0;constructor(){super(32)}},oh=Ex(["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))),Lx=oh[0],Ux=oh[1],Un=new Uint32Array(80),Dn=new Uint32Array(80),Dx=class extends sh{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 b=0;b<16;b++,t+=4)Un[b]=e.getUint32(t),Dn[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let _=Un[b-15]|0,w=Dn[b-15]|0,R=ds(_,w,1)^ds(_,w,8)^Eg(_,w,7),E=fs(_,w,1)^fs(_,w,8)^kg(_,w,7),y=Un[b-2]|0,x=Dn[b-2]|0,Y=ds(y,x,19)^na(y,x,61)^Eg(y,x,6),X=fs(y,x,19)^ra(y,x,61)^kg(y,x,6),K=Rx(E,X,Dn[b-7],Dn[b-16]),ve=Ix(K,R,Y,Un[b-7],Un[b-16]);Un[b]=ve|0,Dn[b]=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 b=0;b<80;b++){let _=ds(u,d,14)^ds(u,d,18)^na(u,d,41),w=fs(u,d,14)^fs(u,d,18)^ra(u,d,41),R=u&f^~u&p,E=d&m^~d&h,y=Px(I,w,E,Ux[b],Dn[b]),x=$x(y,v,_,R,Lx[b],Un[b]),Y=y|0,X=ds(n,r,28)^na(n,r,34)^na(n,r,39),K=fs(n,r,28)^ra(n,r,34)^ra(n,r,39),ve=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}=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=kx(Y,K,se);n=Tx(Z,x,X,ve),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:h}=nn(this.Gh|0,this.Gl|0,p|0,h|0),{h:v,l:I}=nn(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(){vo(Un,Dn)}destroy(){this.destroyed=!0,vo(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},jx=class extends Dx{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)}},Bx=nh(()=>new Mx,rh(1)),Hx=nh(()=>new jx,rh(3)),Tg=Qg;Tg.sha512||(Tg.sha512=e=>Hx(e));qx=nu.bytesToHex,ih=nu.hexToBytes;nu.concatBytes;Gx=new TextEncoder,Wx={subwayAgentMsgV1:"message_id;sender_peer_id;sender_name;timestamp_ms;message_type;payload_hash;nonce"};ih("302e020100300506032b657004220420");ih("302a300506032b6570032100");ah="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",Xx=ah.length-1;if((ah.length&Xx)!==0)throw new Error("agent pairing code alphabet must contain a power-of-two number of symbols");ch=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:fa,n:ca,Gx:Rg,Gy:Ig,a:Fl,d:Vl,h:Zx}=ch,hs=32,Qx=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},Te=(e="")=>{let t=new Error(e);throw Qx(t,Te),t},eC=e=>typeof e=="bigint",tC=e=>typeof e=="string",nC=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=nC(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},ya=e=>new Uint8Array(e),ru=e=>Uint8Array.from(e),lh=(e,t)=>e.toString(16).padStart(t,"0"),uh=e=>Array.from(Fn(e)).map(t=>lh(t,2)).join(""),rn={_0:48,_9:57,A:65,F:70,a:97,f:102},Pg=e=>{if(e>=rn._0&&e<=rn._9)return e-rn._0;if(e>=rn.A&&e<=rn.F)return e-(rn.A-10);if(e>=rn.a&&e<=rn.f)return e-(rn.a-10)},dh=e=>{let t="hex invalid";if(!tC(e))return Te(t);let n=e.length,r=n/2;if(n%2)return Te(t);let s=ya(r);for(let o=0,i=0;o<r;o++,i+=2){let a=Pg(e.charCodeAt(i)),c=Pg(e.charCodeAt(i+1));if(a===void 0||c===void 0)return Te(t);s[o]=a*16+c}return s},fh=()=>globalThis?.crypto,rC=()=>fh()?.subtle??Te("crypto.subtle must be defined, consider polyfill"),su=(...e)=>{let t=0;for(let s of e)t+=Fn(s).length;let n=ya(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},sC=(e=hs)=>fh().getRandomValues(ya(e)),ma=BigInt,Ar=(e,t,n,r="bad number: out of range")=>{if(!eC(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},ae=(e,t=fa)=>{let n=e%t;return n>=0n?n:t+n},$g=(1n<<255n)-1n,$=e=>{e<0n&&Te("negative coordinate");let t=(e>>255n)*19n+(e&$g);return t=(t>>255n)*19n+(t&$g),t%fa},oC=e=>ae(e,ca),iC=(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")},mh=e=>{let t=bh[e];return typeof t!="function"&&Te("hashes."+e+" not set"),t},ph=e=>Fn(e,64,"digest"),ql=e=>e instanceof So?e:Te("Point expected"),Jl=2n**256n,So=class Er{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=Jl;this.X=Ar(t,0n,o),this.Y=Ar(n,0n,o),this.Z=Ar(r,1n,o),this.T=Ar(s,0n,o),Object.freeze(this)}static CURVE(){return ch}static fromAffine(t){return new Er(t.x,t.y,1n,$(t.x*t.y))}static fromBytes(t,n=!1){let r=Vl,s=ru(Fn(t,hs)),o=t[31];s[31]=o&-129;let i=gh(s);Ar(i,0n,n?Jl:fa);let c=$(i*i),l=ae(c-1n),u=$(r*c+1n),{isValid:d,value:f}=lC(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,$(f*i))}static fromHex(t,n){return Er.fromBytes(dh(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Fl,n=Vl,r=this;if(r.is0())return Te("bad point: ZERO");let{X:s,Y:o,Z:i,T:a}=r,c=$(s*s),l=$(o*o),u=$(i*i),d=$(u*u),f=$(c*t),m=$(u*(f+l)),p=ae(d+$(n*$(c*l)));if(m!==p)return Te("bad point: equation left != right (1)");let h=$(s*o),v=$(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}=ql(t),c=$(n*a),l=$(o*s),u=$(r*a),d=$(i*s);return c===l&&u===d}is0(){return this.equals(Rr)}negate(){return new Er(ae(-this.X),this.Y,this.Z,ae(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=Fl,o=$(t*t),i=$(n*n),a=$(2n*r*r),c=$(s*o),l=ae(t+n),u=ae($(l*l)-o-i),d=ae(c+i),f=ae(d-a),m=ae(c-i),p=$(u*f),h=$(d*m),v=$(u*m),I=$(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}=ql(t),u=Fl,d=Vl,f=$(n*i),m=$(r*a),p=$($(o*d)*l),h=$(s*c),v=ae($(ae(n+r)*ae(i+a))-f-m),I=ae(h-p),b=ae(h+p),_=ae(m-$(u*f)),w=$(v*I),R=$(b*_),E=$(v*_),y=$(I*b);return new Er(w,R,y,E)}subtract(t){return this.add(ql(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(Ar(t,1n,ca),!n&&this.is0()))return Rr;if(t===1n)return this;if(this.equals(ys))return _C(t).p;let r=Rr,s=ys;for(let o=this;t>0n;o=o.double(),t>>=1n)t&1n?r=r.add(o):n&&(s=s.add(o));return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(this.equals(Rr))return{x:0n,y:1n};let s=iC(r,fa);$(r*s)!==1n&&Te("invalid inverse");let o=$(t*s),i=$(n*s);return{x:o,y:i}}toBytes(){let{x:t,y:n}=this.toAffine(),r=aC(n);return r[31]|=t&1n?128:0,r}toHex(){return uh(this.toBytes())}clearCofactor(){return this.multiply(ma(Zx),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(ca/2n,!1).double();return ca%2n&&(t=t.add(this)),t.is0()}},ys=new So(Rg,Ig,1n,ae(Rg*Ig)),Rr=new So(0n,1n,1n,0n);So.BASE=ys;So.ZERO=Rr;aC=e=>dh(lh(Ar(e,0n,Jl),64)).reverse(),gh=e=>ma("0x"+uh(ru(Fn(e)).reverse())),Pt=(e,t)=>{let n=e;for(;t-- >0n;)n=$(n*n);return n},cC=e=>{let t=$(e*e),n=$(t*e),r=$(Pt(n,2n)*n),s=$(Pt(r,1n)*e),o=$(Pt(s,5n)*s),i=$(Pt(o,10n)*o),a=$(Pt(i,20n)*i),c=$(Pt(a,40n)*a),l=$(Pt(c,80n)*c),u=$(Pt(l,80n)*c),d=$(Pt(u,10n)*o);return{pow_p_5_8:$(Pt(d,2n)*e),b2:n}},Ng=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,lC=(e,t)=>{let n=$(t*$(t*t)),r=$($(n*n)*t),s=cC($(e*r)).pow_p_5_8,o=$(e*$(n*s)),i=$(t*$(o*o)),a=o,c=$(o*Ng),l=i===e,u=i===ae(-e),d=i===ae(-e*Ng);return l&&(o=a),(u||d)&&(o=c),(ae(o)&1n)===1n&&(o=ae(-o)),{isValid:l||u,value:o}},uC=e=>oC(gh(e)),dC=(...e)=>Promise.resolve(mh("sha512Async")(su(...e))).then(ph),fC=(...e)=>ph(mh("sha512")(su(...e))),hh=e=>{let t=ru(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=uC(n),o=ys.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},mC=e=>dC(Fn(e,hs)).then(hh),yh=e=>hh(fC(Fn(e,hs))),pC=e=>yh(e).pointBytes,bh={sha512Async:async e=>{let t=rC(),n=su(e);return ya(await t.digest("SHA-512",n.buffer))},sha512:void 0},gC=e=>(e=e===void 0?sC(hs):e,Fn(e,hs)),hC=Object.freeze({getExtendedPublicKeyAsync:mC,getExtendedPublicKey:yh,randomSecretKey:gC}),pa=8,yC=256,_h=Math.ceil(yC/pa)+1,zl=2**(pa-1),bC=()=>{let e=[],t=ys,n=t;for(let r=0;r<_h;r++){n=t,e.push(n);for(let s=1;s<zl;s++)n=n.add(t),e.push(n);t=n.double()}return e},Og=void 0,Mg=(e,t)=>{let n=t.negate();return e?n:t},_C=e=>{let t=Og||(Og=bC()),n=Rr,r=ys,s=2**pa,o=s,i=ma(s-1),a=ma(pa);for(let c=0;c<_h;c++){let l=Number(e&i);e>>=a,l>zl&&(l-=o,e+=1n);let u=c*zl,d=u,f=u+Math.abs(l)-1,m=c%2!==0,p=l<0;l===0?r=r.add(Mg(m,t[d])):n=n.add(Mg(p,t[f]))}return e!==0n&&Te("invalid wnaf"),{p:n,f:r}};xC=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),CC=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=Kl(this.buffer)}update(e){Lg(this),vh(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=Kl(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){Lg(this),wC(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,Xl(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=Kl(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]),sa=BigInt(2**32-1),Ug=BigInt(32);Dg=(e,t,n)=>e>>>n,jg=(e,t,n)=>e<<32-n|t>>>n,ms=(e,t,n)=>e>>>n|t<<32-n,ps=(e,t,n)=>e<<32-n|t>>>n,oa=(e,t,n)=>e<<64-n|t>>>n-32,ia=(e,t,n)=>e>>>n-32|t<<64-n;kC=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),TC=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,RC=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),IC=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,PC=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),$C=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,wh=EC(["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))),NC=wh[0],OC=wh[1],jn=new Uint32Array(80),Bn=new Uint32Array(80),MC=class extends CC{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 b=0;b<16;b++,t+=4)jn[b]=e.getUint32(t),Bn[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let _=jn[b-15]|0,w=Bn[b-15]|0,R=ms(_,w,1)^ms(_,w,8)^Dg(_,w,7),E=ps(_,w,1)^ps(_,w,8)^jg(_,w,7),y=jn[b-2]|0,x=Bn[b-2]|0,Y=ms(y,x,19)^oa(y,x,61)^Dg(y,x,6),X=ps(y,x,19)^ia(y,x,61)^jg(y,x,6),K=RC(E,X,Bn[b-7],Bn[b-16]),ve=IC(K,R,Y,jn[b-7],jn[b-16]);jn[b]=ve|0,Bn[b]=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 b=0;b<80;b++){let _=ms(u,d,14)^ms(u,d,18)^oa(u,d,41),w=ps(u,d,14)^ps(u,d,18)^ia(u,d,41),R=u&f^~u&p,E=d&m^~d&h,y=PC(I,w,E,OC[b],Bn[b]),x=$C(y,v,_,R,NC[b],jn[b]),Y=y|0,X=ms(n,r,28)^oa(n,r,34)^oa(n,r,39),K=ps(n,r,28)^ia(n,r,34)^ia(n,r,39),ve=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}=sn(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=kC(Y,K,se);n=TC(Z,x,X,ve),r=Z|0}({h:n,l:r}=sn(this.Ah|0,this.Al|0,n|0,r|0)),{h:s,l:o}=sn(this.Bh|0,this.Bl|0,s|0,o|0),{h:i,l:a}=sn(this.Ch|0,this.Cl|0,i|0,a|0),{h:c,l}=sn(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=sn(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:m}=sn(this.Fh|0,this.Fl|0,f|0,m|0),{h:p,l:h}=sn(this.Gh|0,this.Gl|0,p|0,h|0),{h:v,l:I}=sn(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(){Xl(jn,Bn)}destroy(){this.destroyed=!0,Xl(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},LC=class extends MC{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)}},UC=SC(()=>new LC,xC(3)),Bg=bh;Bg.sha512||(Bg.sha512=e=>UC(e));VC="ws://localhost:9001/ws",qC=3e4,xh=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=kr(e.name),e.keyPath)try{this._keypair=HC(e.keyPath)}catch{}this.options={name:this._name,url:e.url??VC,relay:e.relay??"",autoReconnect:e.autoReconnect??!0,reconnectInterval:e.reconnectInterval??1e3,maxReconnectAttempts:e.maxReconnectAttempts??10,rpcTimeout:e.rpcTimeout??qC,pingInterval:e.pingInterval??3e4,binding:e.binding??""},this.transport=new tx({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=zx(new Uint8Array(t));n&&(this._keypair={privateKey:n,publicKey:Fx(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=Hg(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 Oe(String(r)))}})}disconnect(){for(let[,e]of this.pendingCalls)clearTimeout(e.timer),e.reject(new Oe("Client disconnected"));this.pendingCalls.clear();for(let[,e]of this.pendingSend)e.reject(new Oe("Client disconnected"));this.pendingSend.clear();for(let[,e]of this.pendingResolve)e.reject(new Oe("Client disconnected"));this.pendingResolve.clear(),this.registerPromise&&(this.registerPromise.reject(new Oe("Client disconnected")),this.registerPromise=null),this.transport.disconnect(),this._peerId=null,this.hasConnectedOnce=!1}async send(e,t,n,r){let s=kr(e),o=Ul();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 Oe(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=kr(e),o=Ul(),i=Date.now(),a=Math.floor(Math.random()*2**32),c=new TextEncoder().encode(n),{signature:l,signatureInput:u}=await FC(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 Oe(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=kr(e),o=r?.correlationId??Ul(),i=r?.timeout??this.options.rpcTimeout;return new Promise((a,c)=>{let l=setTimeout(()=>{this.pendingCalls.delete(o),c(new _o(`RPC call to ${s}.${t} timed out after ${i}ms`))},i);this.pendingCalls.set(o,{resolve:a,reject:c,timer:l});try{this.transport.send({type:"call",to:s,method:t,payload:n??"",correlation_id:o})}catch(u){clearTimeout(l),this.pendingCalls.delete(o),c(u instanceof Error?u:new Oe(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=kr(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 Oe(String(s)))}setTimeout(()=>{this.pendingResolve.has(t)&&(this.pendingResolve.delete(t),r(new _o(`Resolve ${t} timed out`)))},1e4)})}on(e,t){let n=this.eventListeners.get(e);return n||(n=new Set,this.eventListeners.set(e,n)),n.add(t),()=>n.delete(t)}off(e,t){let n=this.eventListeners.get(e);n&&n.delete(t)}emit(e,...t){let n=this.eventListeners.get(e);if(n)for(let r of n)try{r(...t)}catch{}}handleBridgeMessage(e){switch(e.type){case"registered":this._peerId=e.peer_id,this._name=e.name,e.secret_key&&!this._keypair&&this.initKeypairFromSecret(e.secret_key),this.hasConnectedOnce=!0,this.registerPromise&&(this.registerPromise.resolve(),this.registerPromise=null),this.emit("connected",{name:e.name,peerId:e.peer_id}),this.resubscribeTopics();break;case"sent":{let t=this.pendingSend.get(e.to);t&&(this.pendingSend.delete(e.to),t.resolve({messageId:e.message_id,to:e.to}));break}case"call_result":{let t=this.pendingCalls.get(e.correlation_id);t&&(clearTimeout(t.timer),this.pendingCalls.delete(e.correlation_id),t.resolve({correlationId:e.correlation_id,success:e.success,payload:e.payload,error:e.error}));break}case"message":{let t={fromName:e.from_name,fromPeerId:e.from_peer_id,messageId:e.message_id,messageType:e.message_type,payload:e.payload,metadata:e.metadata??{},timestampMs:e.timestamp_ms,verified:e.verified,provenance:e.provenance?.map(n=>({signerName:n.signer_name,verified:n.verified})),attestation:e.attestation?{relayName:e.attestation.relay_name,verified:e.attestation.verified}:void 0,delegation:e.delegation?{parentName:e.delegation.parent_name,scope:e.delegation.scope,valid:e.delegation.valid,expired:e.delegation.expired}:void 0};for(let n of this.messageHandlers)try{n(t)}catch{}this.emit("message",t);break}case"inbound_call":this.handleInboundCall(e);break;case"broadcast_message":{let t={topic:e.topic,fromName:e.from_name,fromPeerId:e.from_peer_id,messageId:e.message_id,messageType:e.message_type,payload:e.payload,metadata:e.metadata??{},timestampMs:e.timestamp_ms,verified:e.verified,provenance:e.provenance?.map(r=>({signerName:r.signer_name,verified:r.verified})),attestation:e.attestation?{relayName:e.attestation.relay_name,verified:e.attestation.verified}:void 0,delegation:e.delegation?{parentName:e.delegation.parent_name,scope:e.delegation.scope,valid:e.delegation.valid,expired:e.delegation.expired}:void 0},n=this.topicHandlers.get(e.topic);if(n)for(let r of n)try{r(t)}catch{}this.emit("broadcast",t);break}case"resolved":{let t=this.pendingResolve.get(e.name);t&&(this.pendingResolve.delete(e.name),t.resolve({name:e.name,peerId:e.peer_id}));break}case"error":{let t=Ol(e.code,e.message);this.registerPromise&&e.code==="register_failed"&&(this.registerPromise.reject(new ea(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=Hg(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 uA(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Jh(e,t,n=""){let r=uA(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 Ph(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 dA(e,t){Jh(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 mu(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function lu(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function fA(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 gA(e,t=!1){return t?{h:Number(e&ba),l:Number(e>>$h&ba)}:{h:Number(e>>$h&ba)|0,l:Number(e&ba)|0}}function hA(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}=gA(e[o],t);[r[o],s[o]]=[i,a]}return[r,s]}function cn(e,t,n,r){let s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}function TA(){return iA.randomSecretKey()}function Ea(e){return tA(e)}function Su(){let e=TA();return{secretKey:e,publicKey:Ea(e)}}function ka(e,t){return sA(t,e)}function RA(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function IA(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 pu(e){return RA(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function PA(e){let t=e.length%4===0?0:4-e.length%4,n=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return IA(n)}function $A(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function xu(e){let t=Ea(e);return{kty:"OKP",crv:"Ed25519",x:pu(t),d:pu(e)}}function Ta(e){return{kty:"OKP",crv:"Ed25519",x:pu(e)}}function Cu(e){if($A(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return PA(e.d)}function Qh(){return Co.default.randomBytes(32).toString("base64url")}function ey(e){if(!/^[A-Za-z0-9_-]{43}$/.test(e))throw new Error("pairing verifier must be 32 unpadded base64url bytes");return ku(e)}function OA(e){return e.toUpperCase().replace(/[^A-Z0-9]/g,"")}function MA(e){let t=OA(e);return`${t.slice(0,4)}-${t.slice(4)}`}function ty(){return Co.default.randomBytes(32).toString("base64url")}function Eu(e){if(!/^[A-Za-z0-9_-]{43}$/.test(e))throw new Error("claim token must be 32 unpadded base64url bytes");return ku(`visa-agent-pairing-claim-token:v1:${e}`)}function Ra(e,t){Eu(t);let n=Co.default.createHash("sha256").update(`visa-agent-pairing-derived-code:v1:${e}:${t}`,"utf8").digest(),r="";for(let s=0;s<NA;s+=1)r+=Au[n[s]&Zh];return MA(r)}function ny(e){return oy("visa-agent-pairing-claim:v1",{agentJkt:e.agentJkt,claimTokenHash:e.claimTokenHash,contextLabel:e.runtime.contextLabel,pairingId:e.pairingId,platform:e.runtime.platform??"",runtime:e.runtime.runtime,serverNonce:e.serverNonce,walletPublicKey:e.walletPublicKey})}function ry(e){return oy("visa-agent-pairing-activation:v1",{agentJkt:e.agentJkt,artifactHash:e.artifactHash,pairingId:e.pairingId,termsHash:e.termsHash})}function sy(e){return ku(`visa-agent-pairing-artifacts:v1:${gu(e)}`)}function ku(e){return Co.default.createHash("sha256").update(e,"utf8").digest("base64url")}function oy(e,t){return`${e}
9
+ ${e.nonce}`;return oC.encode(n)}function cC(e,t,n,r,s,o,i){return aC({messageId:e,senderPeerId:t,senderName:n,timestampMs:r,messageType:s,payload:o,nonce:i})}function lC(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 NC(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=NC(e),s=e?.length;if(!r||t!==void 0){let i=n&&`"${n}" `,a="",c=r?`length=${s}`:`type=${typeof e}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):new TypeError(l)}return e}function Kg(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function OC(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 nu(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function zl(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function MC(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 DC(e,t=!1){return t?{h:Number(e&aa),l:Number(e>>Gg&aa)}:{h:Number(e>>Gg&aa)|0,l:Number(e&aa)|0}}function jC(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}=DC(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 XC(){return RC.randomSecretKey()}function Ph(e){return kC(e)}function ZC(){let e=XC();return{secretKey:e,publicKey:Ph(e)}}function QC(e){if((0,Vn.existsSync)(e)){let n=(0,Vn.readFileSync)(e),r=new Uint8Array(n.buffer.slice(n.byteOffset,n.byteOffset+32));return{secretKey:r,publicKey:Ph(r)}}let t=ZC();return(0,Vn.mkdirSync)((0,Xg.dirname)(e),{recursive:!0}),(0,Vn.writeFileSync)(e,new Uint8Array(t.secretKey)),t}function eE(e){let{secretKey:t,publicKey:n}=QC(e);return{privateKey:t,publicKey:n}}async function tE(e,t,n,r,s,o,i,a){let c=cC(t,n,r,s,o,i,a);return{signature:await nC(e,c),signatureInput:iC.subwayAgentMsgV1}}function zg(e){return sC(e)}var Vn,Xg,ux,dx,fx,mx,px,Zg,fa,ua,Ag,kg,Vl,ql,gx,ba,hx,ke,yx,bx,_x,an,_a,ru,Qg,su,nn,Tg,ou,eh,vx,ys,wx,ma,Er,oe,Rg,P,th,nh,rh,sh,Kl,Xl,xo,$r,Ir,oh,ih,Rt,Sx,Ig,xx,Zl,iu,Cx,ah,Ex,Ax,kx,Tx,Rx,Ix,au,ch,pa,Px,lh,Ql,$x,Pg,$g,Nx,fh,mh,Un,Me,sa,Og,Mg,Lg,ms,ps,oa,ia,Hx,Bx,Fx,Vx,qx,Kx,Gx,Dn,Wx,Yx,ph,Jx,zx,jn,Hn,Xx,Zx,Qx,eC,Ug,rC,gh,oC,iC,hh,uC,yh,ga,da,Dg,jg,Wl,Yl,dC,bs,fC,Te,mC,pC,gC,qn,va,cu,bh,_h,sn,Hg,vh,wh,hC,lu,yC,ha,kr,ae,Bg,$,bC,_C,Sh,xh,Jl,eu,Co,_s,Pr,vC,Ch,Pt,wC,Fg,SC,xC,CC,EC,Eh,AC,Ah,kC,kh,TC,RC,ya,IC,Th,tu,PC,Vg,qg,$C,LC,UC,Le,aa,Gg,Wg,Yg,gs,hs,ca,la,HC,BC,FC,VC,qC,KC,Ih,GC,WC,Bn,Fn,YC,JC,zC,Jg,nE,rE,$h,uu=st(()=>{"use strict";Hl();Hl();Bl();Vn=require("fs"),Xg=require("path");ux=1e3,dx=10,fx=3e4,mx=3e4,px=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??ux,this.maxReconnectAttempts=e.maxReconnectAttempts??dx,this.pingInterval=e.pingInterval??fx}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=cx();if(!n){t(new Oe('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 Oe(`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 Oe("WebSocket closed before connection established")))},this.ws.onerror=()=>{r||(r=!0,t(new Oe(`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 Oe("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=lx(this.reconnectInterval*Math.pow(2,this.reconnectAttempt),this.reconnectInterval,mx);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)}}},Zg=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:fa,n:ua,Gx:Ag,Gy:kg,a:Vl,d:ql,h:gx}=Zg,ba=32,hx=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},ke=(e="")=>{let t=new Error(e);throw hx(t,ke),t},yx=e=>typeof e=="bigint",bx=e=>typeof e=="string",_x=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,an=(e,t,n="")=>{let r=_x(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},_a=e=>new Uint8Array(e),ru=e=>Uint8Array.from(e),Qg=(e,t)=>e.toString(16).padStart(t,"0"),su=e=>Array.from(an(e)).map(t=>Qg(t,2)).join(""),nn={_0:48,_9:57,A:65,F:70,a:97,f:102},Tg=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)},ou=e=>{let t="hex invalid";if(!bx(e))return ke(t);let n=e.length,r=n/2;if(n%2)return ke(t);let s=_a(r);for(let o=0,i=0;o<r;o++,i+=2){let a=Tg(e.charCodeAt(i)),c=Tg(e.charCodeAt(i+1));if(a===void 0||c===void 0)return ke(t);s[o]=a*16+c}return s},eh=()=>globalThis?.crypto,vx=()=>eh()?.subtle??ke("crypto.subtle must be defined, consider polyfill"),ys=(...e)=>{let t=0;for(let s of e)t+=an(s).length;let n=_a(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},wx=(e=ba)=>eh().getRandomValues(_a(e)),ma=BigInt,Er=(e,t,n,r="bad number: out of range")=>{if(!yx(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},oe=(e,t=fa)=>{let n=e%t;return n>=0n?n:t+n},Rg=(1n<<255n)-1n,P=e=>{e<0n&&ke("negative coordinate");let t=(e>>255n)*19n+(e&Rg);return t=(t>>255n)*19n+(t&Rg),t%fa},th=e=>oe(e,ua),nh=(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")},rh=e=>{let t=ch[e];return typeof t!="function"&&ke("hashes."+e+" not set"),t},sh=e=>an(e,64,"digest"),Kl=e=>e instanceof xo?e:ke("Point expected"),Xl=2n**256n,xo=class Ar{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=Xl;this.X=Er(t,0n,o),this.Y=Er(n,0n,o),this.Z=Er(r,1n,o),this.T=Er(s,0n,o),Object.freeze(this)}static CURVE(){return Zg}static fromAffine(t){return new Ar(t.x,t.y,1n,P(t.x*t.y))}static fromBytes(t,n=!1){let r=ql,s=ru(an(t,ba)),o=t[31];s[31]=o&-129;let i=ih(s);Er(i,0n,n?Xl:fa);let c=P(i*i),l=oe(c-1n),u=P(r*c+1n),{isValid:d,value:f}=xx(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 Ar(f,i,1n,P(f*i))}static fromHex(t,n){return Ar.fromBytes(ou(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Vl,n=ql,r=this;if(r.is0())return ke("bad point: ZERO");let{X:s,Y:o,Z:i,T:a}=r,c=P(s*s),l=P(o*o),u=P(i*i),d=P(u*u),f=P(c*t),m=P(u*(f+l)),p=oe(d+P(n*P(c*l)));if(m!==p)return ke("bad point: equation left != right (1)");let h=P(s*o),_=P(i*a);return h!==_?ke("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=Kl(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(Ir)}negate(){return new Ar(oe(-this.X),this.Y,this.Z,oe(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=Vl,o=P(t*t),i=P(n*n),a=P(2n*r*r),c=P(s*o),l=oe(t+n),u=oe(P(l*l)-o-i),d=oe(c+i),f=oe(d-a),m=oe(c-i),p=P(u*f),h=P(d*m),_=P(u*m),I=P(f*d);return new Ar(p,h,I,_)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=Kl(t),u=Vl,d=ql,f=P(n*i),m=P(r*a),p=P(P(o*d)*l),h=P(s*c),_=oe(P(oe(n+r)*oe(i+a))-f-m),I=oe(h-p),b=oe(h+p),v=oe(m-P(u*f)),w=P(_*I),R=P(b*v),k=P(_*v),y=P(I*b);return new Ar(w,R,y,k)}subtract(t){return this.add(Kl(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(Er(t,1n,ua),!n&&this.is0()))return Ir;if(t===1n)return this;if(this.equals($r))return Nx(t).p;let r=Ir,s=$r;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(Ir))return{x:0n,y:1n};let s=nh(r,fa);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=oh(n);return r[31]|=t&1n?128:0,r}toHex(){return su(this.toBytes())}clearCofactor(){return this.multiply(ma(gx),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(ua/2n,!1).double();return ua%2n&&(t=t.add(this)),t.is0()}},$r=new xo(Ag,kg,1n,oe(Ag*kg)),Ir=new xo(0n,1n,1n,0n);xo.BASE=$r;xo.ZERO=Ir;oh=e=>ou(Qg(Er(e,0n,Xl),64)).reverse(),ih=e=>ma("0x"+su(ru(an(e)).reverse())),Rt=(e,t)=>{let n=e;for(;t-- >0n;)n=P(n*n);return n},Sx=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}},Ig=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,xx=(e,t)=>{let n=P(t*P(t*t)),r=P(P(n*n)*t),s=Sx(P(e*r)).pow_p_5_8,o=P(e*P(n*s)),i=P(t*P(o*o)),a=o,c=P(o*Ig),l=i===e,u=i===oe(-e),d=i===oe(-e*Ig);return l&&(o=a),(u||d)&&(o=c),(oe(o)&1n)===1n&&(o=oe(-o)),{isValid:l||u,value:o}},Zl=e=>th(ih(e)),iu=(...e)=>Promise.resolve(rh("sha512Async")(ys(...e))).then(sh),Cx=(...e)=>sh(rh("sha512")(ys(...e))),ah=e=>{let t=ru(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=Zl(n),o=$r.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},Ex=e=>iu(an(e,ba)).then(ah),Ax=e=>ah(Cx(an(e,ba))),kx=e=>Ax(e).pointBytes,Tx=e=>iu(e.hashable).then(e.finish),Rx=(e,t,n)=>{let{pointBytes:r,scalar:s}=e,o=Zl(t),i=$r.multiply(o).toBytes();return{hashable:ys(i,r,n),finish:l=>{let u=th(o+Zl(l)*s);return an(ys(i,oh(u)),64)}}},Ix=async(e,t)=>{let n=an(e),r=await Ex(t),s=await iu(r.prefix,n);return Tx(Rx(r,s,n))},au=Object.freeze({bytesToHex:su,hexToBytes:ou,concatBytes:ys,mod:oe,invert:nh,randomBytes:wx}),ch={sha512Async:async e=>{let t=vx(),n=ys(e);return _a(await t.digest("SHA-512",n.buffer))},sha512:void 0},pa=8,Px=256,lh=Math.ceil(Px/pa)+1,Ql=2**(pa-1),$x=()=>{let e=[],t=$r,n=t;for(let r=0;r<lh;r++){n=t,e.push(n);for(let s=1;s<Ql;s++)n=n.add(t),e.push(n);t=n.double()}return e},Pg=void 0,$g=(e,t)=>{let n=t.negate();return e?n:t},Nx=e=>{let t=Pg||(Pg=$x()),n=Ir,r=$r,s=2**pa,o=s,i=ma(s-1),a=ma(pa);for(let c=0;c<lh;c++){let l=Number(e&i);e>>=a,l>Ql&&(l-=o,e+=1n);let u=c*Ql,d=u,f=u+Math.abs(l)-1,m=c%2!==0,p=l<0;l===0?r=r.add($g(m,t[d])):n=n.add($g(p,t[f]))}return e!==0n&&ke("invalid wnaf"),{p:n,f:r}};fh=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});mh=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=Gl(this.buffer)}update(e){Ng(this),uh(e);let{view:t,buffer:n,blockLen:r}=this,s=e.length;for(let o=0;o<s;){let i=Math.min(r-this.pos,s-o);if(i===r){let a=Gl(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){Ng(this),Mx(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,So(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=Gl(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()}},Un=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]),sa=BigInt(2**32-1),Og=BigInt(32);Mg=(e,t,n)=>e>>>n,Lg=(e,t,n)=>e<<32-n|t>>>n,ms=(e,t,n)=>e>>>n|t<<32-n,ps=(e,t,n)=>e<<32-n|t>>>n,oa=(e,t,n)=>e<<64-n|t>>>n-32,ia=(e,t,n)=>e>>>n-32|t<<64-n;Hx=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Bx=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Fx=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Vx=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,qx=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),Kx=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,Gx=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]),Dn=new Uint32Array(64),Wx=class extends mh{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)Dn[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let d=Dn[u-15],f=Dn[u-2],m=It(d,7)^It(d,18)^d>>>3,p=It(f,17)^It(f,19)^f>>>10;Dn[u]=p+Dn[u-7]+m+Dn[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+Lx(i,a,c)+Gx[u]+Dn[u]|0,p=(It(n,2)^It(n,13)^It(n,22))+Ux(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(){So(Dn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),So(this.buffer)}},Yx=class extends Wx{A=Un[0]|0;B=Un[1]|0;C=Un[2]|0;D=Un[3]|0;E=Un[4]|0;F=Un[5]|0;G=Un[6]|0;H=Un[7]|0;constructor(){super(32)}},ph=jx(["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))),Jx=ph[0],zx=ph[1],jn=new Uint32Array(80),Hn=new Uint32Array(80),Xx=class extends mh{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 b=0;b<16;b++,t+=4)jn[b]=e.getUint32(t),Hn[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let v=jn[b-15]|0,w=Hn[b-15]|0,R=ms(v,w,1)^ms(v,w,8)^Mg(v,w,7),k=ps(v,w,1)^ps(v,w,8)^Lg(v,w,7),y=jn[b-2]|0,x=Hn[b-2]|0,Y=ms(y,x,19)^oa(y,x,61)^Mg(y,x,6),X=ps(y,x,19)^ia(y,x,61)^Lg(y,x,6),K=Fx(k,X,Hn[b-7],Hn[b-16]),ve=Vx(K,R,Y,jn[b-7],jn[b-16]);jn[b]=ve|0,Hn[b]=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:_,Hl:I}=this;for(let b=0;b<80;b++){let v=ms(u,d,14)^ms(u,d,18)^oa(u,d,41),w=ps(u,d,14)^ps(u,d,18)^ia(u,d,41),R=u&f^~u&p,k=d&m^~d&h,y=qx(I,w,k,zx[b],Hn[b]),x=Kx(y,_,v,R,Jx[b],jn[b]),Y=y|0,X=ms(n,r,28)^oa(n,r,34)^oa(n,r,39),K=ps(n,r,28)^ia(n,r,34)^ia(n,r,39),ve=n&s^n&i^s&i,se=r&o^r&a^o&a;_=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=Hx(Y,K,se);n=Bx(Z,x,X,ve),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:_,l:I}=rn(this.Hh|0,this.Hl|0,_|0,I|0),this.set(n,r,s,o,i,a,c,l,u,d,f,m,p,h,_,I)}roundClean(){So(jn,Hn)}destroy(){this.destroyed=!0,So(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Zx=class extends Xx{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)}},Qx=dh(()=>new Yx,fh(1)),eC=dh(()=>new Zx,fh(3)),Ug=ch;Ug.sha512||(Ug.sha512=e=>eC(e));rC=au.bytesToHex,gh=au.hexToBytes;au.concatBytes;oC=new TextEncoder,iC={subwayAgentMsgV1:"message_id;sender_peer_id;sender_name;timestamp_ms;message_type;payload_hash;nonce"};gh("302e020100300506032b657004220420");gh("302a300506032b6570032100");hh="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",uC=hh.length-1;if((hh.length&uC)!==0)throw new Error("agent pairing code alphabet must contain a power-of-two number of symbols");yh=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:ga,n:da,Gx:Dg,Gy:jg,a:Wl,d:Yl,h:dC}=yh,bs=32,fC=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},Te=(e="")=>{let t=new Error(e);throw fC(t,Te),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,qn=(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),cu=e=>Uint8Array.from(e),bh=(e,t)=>e.toString(16).padStart(t,"0"),_h=e=>Array.from(qn(e)).map(t=>bh(t,2)).join(""),sn={_0:48,_9:57,A:65,F:70,a:97,f:102},Hg=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)},vh=e=>{let t="hex invalid";if(!pC(e))return Te(t);let n=e.length,r=n/2;if(n%2)return Te(t);let s=va(r);for(let o=0,i=0;o<r;o++,i+=2){let a=Hg(e.charCodeAt(i)),c=Hg(e.charCodeAt(i+1));if(a===void 0||c===void 0)return Te(t);s[o]=a*16+c}return s},wh=()=>globalThis?.crypto,hC=()=>wh()?.subtle??Te("crypto.subtle must be defined, consider polyfill"),lu=(...e)=>{let t=0;for(let s of e)t+=qn(s).length;let n=va(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},yC=(e=bs)=>wh().getRandomValues(va(e)),ha=BigInt,kr=(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)},ae=(e,t=ga)=>{let n=e%t;return n>=0n?n:t+n},Bg=(1n<<255n)-1n,$=e=>{e<0n&&Te("negative coordinate");let t=(e>>255n)*19n+(e&Bg);return t=(t>>255n)*19n+(t&Bg),t%ga},bC=e=>ae(e,da),_C=(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")},Sh=e=>{let t=kh[e];return typeof t!="function"&&Te("hashes."+e+" not set"),t},xh=e=>qn(e,64,"digest"),Jl=e=>e instanceof Co?e:Te("Point expected"),eu=2n**256n,Co=class Tr{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=eu;this.X=kr(t,0n,o),this.Y=kr(n,0n,o),this.Z=kr(r,1n,o),this.T=kr(s,0n,o),Object.freeze(this)}static CURVE(){return yh}static fromAffine(t){return new Tr(t.x,t.y,1n,$(t.x*t.y))}static fromBytes(t,n=!1){let r=Yl,s=cu(qn(t,bs)),o=t[31];s[31]=o&-129;let i=Ch(s);kr(i,0n,n?eu:ga);let c=$(i*i),l=ae(c-1n),u=$(r*c+1n),{isValid:d,value:f}=SC(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 Tr(f,i,1n,$(f*i))}static fromHex(t,n){return Tr.fromBytes(vh(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Wl,n=Yl,r=this;if(r.is0())return Te("bad point: ZERO");let{X:s,Y:o,Z:i,T:a}=r,c=$(s*s),l=$(o*o),u=$(i*i),d=$(u*u),f=$(c*t),m=$(u*(f+l)),p=ae(d+$(n*$(c*l)));if(m!==p)return Te("bad point: equation left != right (1)");let h=$(s*o),_=$(i*a);return h!==_?Te("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=Jl(t),c=$(n*a),l=$(o*s),u=$(r*a),d=$(i*s);return c===l&&u===d}is0(){return this.equals(Pr)}negate(){return new Tr(ae(-this.X),this.Y,this.Z,ae(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=Wl,o=$(t*t),i=$(n*n),a=$(2n*r*r),c=$(s*o),l=ae(t+n),u=ae($(l*l)-o-i),d=ae(c+i),f=ae(d-a),m=ae(c-i),p=$(u*f),h=$(d*m),_=$(u*m),I=$(f*d);return new Tr(p,h,I,_)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=Jl(t),u=Wl,d=Yl,f=$(n*i),m=$(r*a),p=$($(o*d)*l),h=$(s*c),_=ae($(ae(n+r)*ae(i+a))-f-m),I=ae(h-p),b=ae(h+p),v=ae(m-$(u*f)),w=$(_*I),R=$(b*v),k=$(_*v),y=$(I*b);return new Tr(w,R,y,k)}subtract(t){return this.add(Jl(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(kr(t,1n,da),!n&&this.is0()))return Pr;if(t===1n)return this;if(this.equals(_s))return $C(t).p;let r=Pr,s=_s;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=_C(r,ga);$(r*s)!==1n&&Te("invalid inverse");let o=$(t*s),i=$(n*s);return{x:o,y:i}}toBytes(){let{x:t,y:n}=this.toAffine(),r=vC(n);return r[31]|=t&1n?128:0,r}toHex(){return _h(this.toBytes())}clearCofactor(){return this.multiply(ha(dC),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(da/2n,!1).double();return da%2n&&(t=t.add(this)),t.is0()}},_s=new Co(Dg,jg,1n,ae(Dg*jg)),Pr=new Co(0n,1n,1n,0n);Co.BASE=_s;Co.ZERO=Pr;vC=e=>vh(bh(kr(e,0n,eu),64)).reverse(),Ch=e=>ha("0x"+_h(cu(qn(e)).reverse())),Pt=(e,t)=>{let n=e;for(;t-- >0n;)n=$(n*n);return n},wC=e=>{let t=$(e*e),n=$(t*e),r=$(Pt(n,2n)*n),s=$(Pt(r,1n)*e),o=$(Pt(s,5n)*s),i=$(Pt(o,10n)*o),a=$(Pt(i,20n)*i),c=$(Pt(a,40n)*a),l=$(Pt(c,80n)*c),u=$(Pt(l,80n)*c),d=$(Pt(u,10n)*o);return{pow_p_5_8:$(Pt(d,2n)*e),b2:n}},Fg=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,SC=(e,t)=>{let n=$(t*$(t*t)),r=$($(n*n)*t),s=wC($(e*r)).pow_p_5_8,o=$(e*$(n*s)),i=$(t*$(o*o)),a=o,c=$(o*Fg),l=i===e,u=i===ae(-e),d=i===ae(-e*Fg);return l&&(o=a),(u||d)&&(o=c),(ae(o)&1n)===1n&&(o=ae(-o)),{isValid:l||u,value:o}},xC=e=>bC(Ch(e)),CC=(...e)=>Promise.resolve(Sh("sha512Async")(lu(...e))).then(xh),EC=(...e)=>xh(Sh("sha512")(lu(...e))),Eh=e=>{let t=cu(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=xC(n),o=_s.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},AC=e=>CC(qn(e,bs)).then(Eh),Ah=e=>Eh(EC(qn(e,bs))),kC=e=>Ah(e).pointBytes,kh={sha512Async:async e=>{let t=hC(),n=lu(e);return va(await t.digest("SHA-512",n.buffer))},sha512:void 0},TC=e=>(e=e===void 0?yC(bs):e,qn(e,bs)),RC=Object.freeze({getExtendedPublicKeyAsync:AC,getExtendedPublicKey:Ah,randomSecretKey:TC}),ya=8,IC=256,Th=Math.ceil(IC/ya)+1,tu=2**(ya-1),PC=()=>{let e=[],t=_s,n=t;for(let r=0;r<Th;r++){n=t,e.push(n);for(let s=1;s<tu;s++)n=n.add(t),e.push(n);t=n.double()}return e},Vg=void 0,qg=(e,t)=>{let n=t.negate();return e?n:t},$C=e=>{let t=Vg||(Vg=PC()),n=Pr,r=_s,s=2**ya,o=s,i=ha(s-1),a=ha(ya);for(let c=0;c<Th;c++){let l=Number(e&i);e>>=a,l>tu&&(l-=o,e+=1n);let u=c*tu,d=u,f=u+Math.abs(l)-1,m=c%2!==0,p=l<0;l===0?r=r.add(qg(m,t[d])):n=n.add(qg(p,t[f]))}return e!==0n&&Te("invalid wnaf"),{p:n,f:r}};LC=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),UC=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=zl(this.buffer)}update(e){Kg(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=zl(e);for(;r<=s-o;o+=r)this.process(a,o);continue}n.set(e.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Kg(this),OC(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,nu(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=zl(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]),aa=BigInt(2**32-1),Gg=BigInt(32);Wg=(e,t,n)=>e>>>n,Yg=(e,t,n)=>e<<32-n|t>>>n,gs=(e,t,n)=>e>>>n|t<<32-n,hs=(e,t,n)=>e<<32-n|t>>>n,ca=(e,t,n)=>e<<64-n|t>>>n-32,la=(e,t,n)=>e>>>n-32|t<<64-n;HC=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),BC=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,FC=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),VC=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,qC=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),KC=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,Ih=jC(["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))),GC=Ih[0],WC=Ih[1],Bn=new Uint32Array(80),Fn=new Uint32Array(80),YC=class extends UC{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 b=0;b<16;b++,t+=4)Bn[b]=e.getUint32(t),Fn[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let v=Bn[b-15]|0,w=Fn[b-15]|0,R=gs(v,w,1)^gs(v,w,8)^Wg(v,w,7),k=hs(v,w,1)^hs(v,w,8)^Yg(v,w,7),y=Bn[b-2]|0,x=Fn[b-2]|0,Y=gs(y,x,19)^ca(y,x,61)^Wg(y,x,6),X=hs(y,x,19)^la(y,x,61)^Yg(y,x,6),K=FC(k,X,Fn[b-7],Fn[b-16]),ve=VC(K,R,Y,Bn[b-7],Bn[b-16]);Bn[b]=ve|0,Fn[b]=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:_,Hl:I}=this;for(let b=0;b<80;b++){let v=gs(u,d,14)^gs(u,d,18)^ca(u,d,41),w=hs(u,d,14)^hs(u,d,18)^la(u,d,41),R=u&f^~u&p,k=d&m^~d&h,y=qC(I,w,k,WC[b],Fn[b]),x=KC(y,_,v,R,GC[b],Bn[b]),Y=y|0,X=gs(n,r,28)^ca(n,r,34)^ca(n,r,39),K=hs(n,r,28)^la(n,r,34)^la(n,r,39),ve=n&s^n&i^s&i,se=r&o^r&a^o&a;_=p|0,I=h|0,p=f|0,h=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=BC(Z,x,X,ve),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:h}=on(this.Gh|0,this.Gl|0,p|0,h|0),{h:_,l:I}=on(this.Hh|0,this.Hl|0,_|0,I|0),this.set(n,r,s,o,i,a,c,l,u,d,f,m,p,h,_,I)}roundClean(){nu(Bn,Fn)}destroy(){this.destroyed=!0,nu(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},JC=class extends YC{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)}},zC=MC(()=>new JC,LC(3)),Jg=kh;Jg.sha512||(Jg.sha512=e=>zC(e));nE="ws://localhost:9001/ws",rE=3e4,$h=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=Rr(e.name),e.keyPath)try{this._keypair=eE(e.keyPath)}catch{}this.options={name:this._name,url:e.url??nE,relay:e.relay??"",autoReconnect:e.autoReconnect??!0,reconnectInterval:e.reconnectInterval??1e3,maxReconnectAttempts:e.maxReconnectAttempts??10,rpcTimeout:e.rpcTimeout??rE,pingInterval:e.pingInterval??3e4,binding:e.binding??""},this.transport=new px({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=lC(new Uint8Array(t));n&&(this._keypair={privateKey:n,publicKey:tC(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=zg(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 Oe(String(r)))}})}disconnect(){for(let[,e]of this.pendingCalls)clearTimeout(e.timer),e.reject(new Oe("Client disconnected"));this.pendingCalls.clear();for(let[,e]of this.pendingSend)e.reject(new Oe("Client disconnected"));this.pendingSend.clear();for(let[,e]of this.pendingResolve)e.reject(new Oe("Client disconnected"));this.pendingResolve.clear(),this.registerPromise&&(this.registerPromise.reject(new Oe("Client disconnected")),this.registerPromise=null),this.transport.disconnect(),this._peerId=null,this.hasConnectedOnce=!1}async send(e,t,n,r){let s=Rr(e),o=Fl();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 Oe(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=Rr(e),o=Fl(),i=Date.now(),a=Math.floor(Math.random()*2**32),c=new TextEncoder().encode(n),{signature:l,signatureInput:u}=await tE(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 Oe(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=Rr(e),o=r?.correlationId??Fl(),i=r?.timeout??this.options.rpcTimeout;return new Promise((a,c)=>{let l=setTimeout(()=>{this.pendingCalls.delete(o),c(new wo(`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 Oe(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=Rr(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 Oe(String(s)))}setTimeout(()=>{this.pendingResolve.has(t)&&(this.pendingResolve.delete(t),r(new wo(`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=jl(e.code,e.message);this.registerPromise&&e.code==="register_failed"&&(this.registerPromise.reject(new ra(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=zg(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 xE(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function sy(e,t,n=""){let r=xE(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 Hh(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 CE(e,t){sy(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 bu(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function pu(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function EE(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 TE(e,t=!1){return t?{h:Number(e&wa),l:Number(e>>Bh&wa)}:{h:Number(e>>Bh&wa)|0,l:Number(e&wa)|0}}function RE(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}=TE(e[o],t);[r[o],s[o]]=[i,a]}return[r,s]}function ln(e,t,n,r){let s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}function BE(){return _E.randomSecretKey()}function Ra(e){return pE(e)}function ku(){let e=BE();return{secretKey:e,publicKey:Ra(e)}}function Ia(e,t){return yE(t,e)}function FE(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function VE(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 _u(e){return FE(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function qE(e){let t=e.length%4===0?0:4-e.length%4,n=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return VE(n)}function KE(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function Tu(e){let t=Ra(e);return{kty:"OKP",crv:"Ed25519",x:_u(t),d:_u(e)}}function Pa(e){return{kty:"OKP",crv:"Ed25519",x:_u(e)}}function Ru(e){if(KE(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return qE(e.d)}function cy(){return Ao.default.randomBytes(32).toString("base64url")}function ly(e){if(!/^[A-Za-z0-9_-]{43}$/.test(e))throw new Error("pairing verifier must be 32 unpadded base64url bytes");return $u(e)}function WE(e){return e.toUpperCase().replace(/[^A-Z0-9]/g,"")}function YE(e){let t=WE(e);return`${t.slice(0,4)}-${t.slice(4)}`}function uy(){return Ao.default.randomBytes(32).toString("base64url")}function Pu(e){if(!/^[A-Za-z0-9_-]{43}$/.test(e))throw new Error("claim token must be 32 unpadded base64url bytes");return $u(`visa-agent-pairing-claim-token:v1:${e}`)}function $a(e,t){Pu(t);let n=Ao.default.createHash("sha256").update(`visa-agent-pairing-derived-code:v1:${e}:${t}`,"utf8").digest(),r="";for(let s=0;s<GE;s+=1)r+=Iu[n[s]&ay];return YE(r)}function dy(e){return py("visa-agent-pairing-claim:v1",{agentJkt:e.agentJkt,claimTokenHash:e.claimTokenHash,contextLabel:e.runtime.contextLabel,pairingId:e.pairingId,platform:e.runtime.platform??"",runtime:e.runtime.runtime,serverNonce:e.serverNonce,walletPublicKey:e.walletPublicKey})}function fy(e){return py("visa-agent-pairing-activation:v1",{agentJkt:e.agentJkt,artifactHash:e.artifactHash,pairingId:e.pairingId,termsHash:e.termsHash})}function my(e){return $u(`visa-agent-pairing-artifacts:v1:${vu(e)}`)}function $u(e){return Ao.default.createHash("sha256").update(e,"utf8").digest("base64url")}function py(e,t){return`${e}
10
10
  ${Object.entries(t).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${n}=${r}`).join(`
11
- `)}`}function gu(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(gu).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${gu(t[n])}`).join(",")}}`}var Co,Lh,Sa,wa,Ch,Ah,iu,au,KC,vs,GC,Re,WC,YC,JC,Nt,Aa,hu,Uh,yu,an,Eh,bu,Dh,zC,ws,jh,xa,Pr,ie,kh,N,Bh,Hh,Fh,Vh,cu,uu,xo,Or,Nr,qh,Kh,$t,XC,Th,ZC,du,QC,_u,Gh,eA,vu,tA,nA,rA,sA,wu,Wh,oA,iA,Ca,aA,Yh,fu,cA,Rh,Ih,lA,mA,pA,Ue,ba,$h,Nh,Oh,bs,_s,_a,va,yA,bA,_A,vA,wA,SA,zh,xA,CA,Vn,qn,AA,EA,kA,Mh,Z2,Xh,Q2,eP,tP,nP,Au,NA,Zh,Ao=st(()=>{"use strict";Co=k(require("node:crypto"),1),Lh=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:Sa,n:wa,Gx:Ch,Gy:Ah,a:iu,d:au,h:KC}=Lh,vs=32,GC=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},Re=(e="")=>{let t=new Error(e);throw GC(t,Re),t},WC=e=>typeof e=="bigint",YC=e=>typeof e=="string",JC=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,Nt=(e,t,n="")=>{let r=JC(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},Aa=e=>new Uint8Array(e),hu=e=>Uint8Array.from(e),Uh=(e,t)=>e.toString(16).padStart(t,"0"),yu=e=>Array.from(Nt(e)).map(t=>Uh(t,2)).join(""),an={_0:48,_9:57,A:65,F:70,a:97,f:102},Eh=e=>{if(e>=an._0&&e<=an._9)return e-an._0;if(e>=an.A&&e<=an.F)return e-(an.A-10);if(e>=an.a&&e<=an.f)return e-(an.a-10)},bu=e=>{let t="hex invalid";if(!YC(e))return Re(t);let n=e.length,r=n/2;if(n%2)return Re(t);let s=Aa(r);for(let o=0,i=0;o<r;o++,i+=2){let a=Eh(e.charCodeAt(i)),c=Eh(e.charCodeAt(i+1));if(a===void 0||c===void 0)return Re(t);s[o]=a*16+c}return s},Dh=()=>globalThis?.crypto,zC=()=>Dh()?.subtle??Re("crypto.subtle must be defined, consider polyfill"),ws=(...e)=>{let t=0;for(let s of e)t+=Nt(s).length;let n=Aa(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},jh=(e=vs)=>Dh().getRandomValues(Aa(e)),xa=BigInt,Pr=(e,t,n,r="bad number: out of range")=>{if(!WC(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},ie=(e,t=Sa)=>{let n=e%t;return n>=0n?n:t+n},kh=(1n<<255n)-1n,N=e=>{e<0n&&Re("negative coordinate");let t=(e>>255n)*19n+(e&kh);return t=(t>>255n)*19n+(t&kh),t%Sa},Bh=e=>ie(e,wa),Hh=(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")},Fh=e=>{let t=Wh[e];return typeof t!="function"&&Re("hashes."+e+" not set"),t},Vh=e=>Nt(e,64,"digest"),cu=e=>e instanceof xo?e:Re("Point expected"),uu=2n**256n,xo=class $r{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=uu;this.X=Pr(t,0n,o),this.Y=Pr(n,0n,o),this.Z=Pr(r,1n,o),this.T=Pr(s,0n,o),Object.freeze(this)}static CURVE(){return Lh}static fromAffine(t){return new $r(t.x,t.y,1n,N(t.x*t.y))}static fromBytes(t,n=!1){let r=au,s=hu(Nt(t,vs)),o=t[31];s[31]=o&-129;let i=Kh(s);Pr(i,0n,n?uu:Sa);let c=N(i*i),l=ie(c-1n),u=N(r*c+1n),{isValid:d,value:f}=ZC(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,N(f*i))}static fromHex(t,n){return $r.fromBytes(bu(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=iu,n=au,r=this;if(r.is0())return Re("bad point: ZERO");let{X:s,Y:o,Z:i,T:a}=r,c=N(s*s),l=N(o*o),u=N(i*i),d=N(u*u),f=N(c*t),m=N(u*(f+l)),p=ie(d+N(n*N(c*l)));if(m!==p)return Re("bad point: equation left != right (1)");let h=N(s*o),v=N(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}=cu(t),c=N(n*a),l=N(o*s),u=N(r*a),d=N(i*s);return c===l&&u===d}is0(){return this.equals(Nr)}negate(){return new $r(ie(-this.X),this.Y,this.Z,ie(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=iu,o=N(t*t),i=N(n*n),a=N(2n*r*r),c=N(s*o),l=ie(t+n),u=ie(N(l*l)-o-i),d=ie(c+i),f=ie(d-a),m=ie(c-i),p=N(u*f),h=N(d*m),v=N(u*m),I=N(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}=cu(t),u=iu,d=au,f=N(n*i),m=N(r*a),p=N(N(o*d)*l),h=N(s*c),v=ie(N(ie(n+r)*ie(i+a))-f-m),I=ie(h-p),b=ie(h+p),_=ie(m-N(u*f)),w=N(v*I),R=N(b*_),E=N(v*_),y=N(I*b);return new $r(w,R,y,E)}subtract(t){return this.add(cu(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(Pr(t,1n,wa),!n&&this.is0()))return Nr;if(t===1n)return this;if(this.equals(Or))return lA(t).p;let r=Nr,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(Nr))return{x:0n,y:1n};let s=Hh(r,Sa);N(r*s)!==1n&&Re("invalid inverse");let o=N(t*s),i=N(n*s);return{x:o,y:i}}toBytes(){let{x:t,y:n}=this.toAffine(),r=qh(n);return r[31]|=t&1n?128:0,r}toHex(){return yu(this.toBytes())}clearCofactor(){return this.multiply(xa(KC),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(wa/2n,!1).double();return wa%2n&&(t=t.add(this)),t.is0()}},Or=new xo(Ch,Ah,1n,ie(Ch*Ah)),Nr=new xo(0n,1n,1n,0n);xo.BASE=Or;xo.ZERO=Nr;qh=e=>bu(Uh(Pr(e,0n,uu),64)).reverse(),Kh=e=>xa("0x"+yu(hu(Nt(e)).reverse())),$t=(e,t)=>{let n=e;for(;t-- >0n;)n=N(n*n);return n},XC=e=>{let t=N(e*e),n=N(t*e),r=N($t(n,2n)*n),s=N($t(r,1n)*e),o=N($t(s,5n)*s),i=N($t(o,10n)*o),a=N($t(i,20n)*i),c=N($t(a,40n)*a),l=N($t(c,80n)*c),u=N($t(l,80n)*c),d=N($t(u,10n)*o);return{pow_p_5_8:N($t(d,2n)*e),b2:n}},Th=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,ZC=(e,t)=>{let n=N(t*N(t*t)),r=N(N(n*n)*t),s=XC(N(e*r)).pow_p_5_8,o=N(e*N(n*s)),i=N(t*N(o*o)),a=o,c=N(o*Th),l=i===e,u=i===ie(-e),d=i===ie(-e*Th);return l&&(o=a),(u||d)&&(o=c),(ie(o)&1n)===1n&&(o=ie(-o)),{isValid:l||u,value:o}},du=e=>Bh(Kh(e)),QC=(...e)=>Promise.resolve(Fh("sha512Async")(ws(...e))).then(Vh),_u=(...e)=>Vh(Fh("sha512")(ws(...e))),Gh=e=>{let t=hu(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=du(n),o=Or.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},eA=e=>QC(Nt(e,vs)).then(Gh),vu=e=>Gh(_u(Nt(e,vs))),tA=e=>vu(e).pointBytes,nA=e=>e.finish(_u(e.hashable)),rA=(e,t,n)=>{let{pointBytes:r,scalar:s}=e,o=du(t),i=Or.multiply(o).toBytes();return{hashable:ws(i,r,n),finish:l=>{let u=Bh(o+du(l)*s);return Nt(ws(i,qh(u)),64)}}},sA=(e,t)=>{let n=Nt(e),r=vu(t),s=_u(r.prefix,n);return nA(rA(r,s,n))},wu=Object.freeze({bytesToHex:yu,hexToBytes:bu,concatBytes:ws,mod:ie,invert:Hh,randomBytes:jh}),Wh={sha512Async:async e=>{let t=zC(),n=ws(e);return Aa(await t.digest("SHA-512",n.buffer))},sha512:void 0},oA=e=>(e=e===void 0?jh(vs):e,Nt(e,vs)),iA=Object.freeze({getExtendedPublicKeyAsync:eA,getExtendedPublicKey:vu,randomSecretKey:oA}),Ca=8,aA=256,Yh=Math.ceil(aA/Ca)+1,fu=2**(Ca-1),cA=()=>{let e=[],t=Or,n=t;for(let r=0;r<Yh;r++){n=t,e.push(n);for(let s=1;s<fu;s++)n=n.add(t),e.push(n);t=n.double()}return e},Rh=void 0,Ih=(e,t)=>{let n=t.negate();return e?n:t},lA=e=>{let t=Rh||(Rh=cA()),n=Nr,r=Or,s=2**Ca,o=s,i=xa(s-1),a=xa(Ca);for(let c=0;c<Yh;c++){let l=Number(e&i);e>>=a,l>fu&&(l-=o,e+=1n);let u=c*fu,d=u,f=u+Math.abs(l)-1,m=c%2!==0,p=l<0;l===0?r=r.add(Ih(m,t[d])):n=n.add(Ih(p,t[f]))}return e!==0n&&Re("invalid wnaf"),{p:n,f:r}};mA=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),pA=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=lu(this.buffer)}update(e){Ph(this),Jh(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=lu(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){Ph(this),dA(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,mu(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=lu(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]),ba=BigInt(2**32-1),$h=BigInt(32);Nh=(e,t,n)=>e>>>n,Oh=(e,t,n)=>e<<32-n|t>>>n,bs=(e,t,n)=>e>>>n|t<<32-n,_s=(e,t,n)=>e<<32-n|t>>>n,_a=(e,t,n)=>e<<64-n|t>>>n-32,va=(e,t,n)=>e>>>n-32|t<<64-n;yA=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),bA=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,_A=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),vA=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,wA=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),SA=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,zh=hA(["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))),xA=zh[0],CA=zh[1],Vn=new Uint32Array(80),qn=new Uint32Array(80),AA=class extends pA{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 b=0;b<16;b++,t+=4)Vn[b]=e.getUint32(t),qn[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let _=Vn[b-15]|0,w=qn[b-15]|0,R=bs(_,w,1)^bs(_,w,8)^Nh(_,w,7),E=_s(_,w,1)^_s(_,w,8)^Oh(_,w,7),y=Vn[b-2]|0,x=qn[b-2]|0,Y=bs(y,x,19)^_a(y,x,61)^Nh(y,x,6),X=_s(y,x,19)^va(y,x,61)^Oh(y,x,6),K=_A(E,X,qn[b-7],qn[b-16]),ve=vA(K,R,Y,Vn[b-7],Vn[b-16]);Vn[b]=ve|0,qn[b]=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 b=0;b<80;b++){let _=bs(u,d,14)^bs(u,d,18)^_a(u,d,41),w=_s(u,d,14)^_s(u,d,18)^va(u,d,41),R=u&f^~u&p,E=d&m^~d&h,y=wA(I,w,E,CA[b],qn[b]),x=SA(y,v,_,R,xA[b],Vn[b]),Y=y|0,X=bs(n,r,28)^_a(n,r,34)^_a(n,r,39),K=_s(n,r,28)^va(n,r,34)^va(n,r,39),ve=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}=cn(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=yA(Y,K,se);n=bA(Z,x,X,ve),r=Z|0}({h:n,l:r}=cn(this.Ah|0,this.Al|0,n|0,r|0)),{h:s,l:o}=cn(this.Bh|0,this.Bl|0,s|0,o|0),{h:i,l:a}=cn(this.Ch|0,this.Cl|0,i|0,a|0),{h:c,l}=cn(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=cn(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:m}=cn(this.Fh|0,this.Fl|0,f|0,m|0),{h:p,l:h}=cn(this.Gh|0,this.Gl|0,p|0,h|0),{h:v,l:I}=cn(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(){mu(Vn,qn)}destroy(){this.destroyed=!0,mu(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},EA=class extends AA{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)}},kA=fA(()=>new EA,mA(3)),Mh=Wh;Mh.sha512||(Mh.sha512=e=>kA(e));Z2=wu.bytesToHex,Xh=wu.hexToBytes,Q2=wu.concatBytes;eP=new TextEncoder;tP=Xh("302e020100300506032b657004220420"),nP=Xh("302a300506032b6570032100"),Au="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",NA=8,Zh=Au.length-1;if((Au.length&Zh)!==0)throw new Error("agent pairing code alphabet must contain a power-of-two number of symbols");});var uy={};Fr(uy,{BindingIssuanceError:()=>Eo,CardRequiredError:()=>Ot,buildIssuanceRequest:()=>ly,enrollCardUrl:()=>Ia,jkt:()=>ko,proofPayload:()=>cy,readSeed:()=>$a,requestVisaBinding:()=>Pa});function ko(e){let t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return iy.createHash("sha256").update(t,"utf8").digest("base64url")}function cy(e,t,n){return`visa-agent-binding:v1:${e}:${t}:${n}`}function ly(e,t,n="visa",r=Math.floor(Date.now()/1e3)){let s=Ta(Ea(e)),o=Buffer.from(cy(t,ko(s),r),"utf8"),i=Buffer.from(ka(e,o)).toString("base64url");return{name:t,mesh:n,mode:"card",agent_pubkey:s,proof:{ts:r,sig:i}}}function Ia(e){try{return new URL("/enroll-card",e).toString()}catch{return"https://auth.visacli.sh/enroll-card"}}async function Pa(e){let t=ly(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 Ot("No card on file \u2014 enroll a card to register on the trusted .visa mesh.",Ia(e.authUrl),"no_card"):new Eo(`Visa binding issuance failed (${s.status})${o?`: ${o}`:""}`,s.status,i||void 0)}return await s.json()}function $a(e){return new Uint8Array(ay.readFileSync(e))}var iy,ay,Ot,Eo,Ss=st(()=>{"use strict";iy=k(require("crypto")),ay=k(require("fs"));Ao();Ot=class extends Error{enrollUrl;reason;constructor(t,n,r){super(t),this.name="CardRequiredError",this.enrollUrl=n,this.reason=r}},Eo=class extends Error{status;code;constructor(t,n,r){super(t),this.name="BindingIssuanceError",this.status=n,this.code=r}}});var Ou={};Fr(Ou,{SUBWAY_PROTOCOL:()=>wy,registerDirect:()=>YA,resolveDirect:()=>JA});function Iu(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 Pu(e,t){return e<<3|t}function To(e,t,n){e.push(Pu(t,2)),Iu(e,n.length);for(let r of n)e.push(r)}function LA(e,t){let n=[];return To(n,1,Ru.encode(e)),t&&t.length>0&&To(n,2,Ru.encode(t)),Uint8Array.from(n)}function UA(e,t,n){let r=[];return n!==0n&&(r.push(Pu(1,0)),Iu(r,n)),To(r,2,LA(e,t)),Uint8Array.from(r)}function DA(e){let t=[];return To(t,1,Ru.encode(e)),Uint8Array.from(t)}function jA(e,t){let n=[];return t!==0n&&(n.push(Pu(1,0)),Iu(n,t)),To(n,3,DA(e)),Uint8Array.from(n)}function BA(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=_y.decode(e.subarray(l,u)),t=u}else t=$u(e,t,i)}return n}function HA(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=_y.decode(e.subarray(l,u)),t=u}else t=$u(e,t,i)}return n}function $u(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 vy(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=BA(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=HA(e.subarray(l,u)),t=u}else t=$u(e,t,i)}return n}function FA(e){let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t}function Nu(e){return new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1)}function VA(e){if(e.length<4)return{success:!1,error:"short reply (no length prefix)"};let t=Nu(e.subarray(0,4));return e.length<4+t?{success:!1,error:`truncated frame (have ${e.length-4}, need ${t})`}:vy(e.subarray(4,4+t)).registerNameResponse??{success:!1,error:"reply carried no register_name_response"}}function qA(e){if(e.length<4)return{peerId:new Uint8Array(0),error:"short reply (no length prefix)"};let t=Nu(e.subarray(0,4));return e.length<4+t?{peerId:new Uint8Array(0),error:`truncated frame (have ${e.length-4}, need ${t})`}:vy(e.subarray(4,4+t)).resolveNameResponse??{peerId:new Uint8Array(0),error:"reply carried no resolve_name_response"}}function Tu(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 WA(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>dy)throw new Error("subway: reply exceeded max size");if(r<0&&n>=4&&(r=4+Nu(Tu(t).subarray(0,4)),r>dy))throw new Error("subway: declared frame exceeds max size");if(r>=0&&n>=r)return Tu(t).subarray(0,r)}return Tu(t)}async function Sy(e){return(0,fy.createLibp2p)({...e?{privateKey:await(0,hy.generateKeyPairFromSeed)("Ed25519",e)}:{},transports:[(0,my.tcp)()],connectionEncrypters:[(0,py.noise)()],streamMuxers:[(0,gy.yamux)()],connectionGater:{denyDialMultiaddr:async()=>!1}})}async function xy(e,t,n){let r=await e.dialProtocol((0,yy.multiaddr)(t),wy,{signal:AbortSignal.timeout(KA)});r.send(FA(n));let s;return Promise.race([WA(r),new Promise((o,i)=>{s=setTimeout(()=>i(new Error("subway: request timed out")),GA)})]).finally(()=>clearTimeout(s))}async function YA(e){let t=await Sy(e.seed);try{let n=await xy(t,e.relayMultiaddr,UA(e.name,e.binding,e.requestId??1n)),r=VA(n);return{success:r.success,error:r.error,peerId:t.peerId.toString()}}finally{await t.stop()}}async function JA(e){let t=await Sy(e.seed);try{let n=await xy(t,e.relayMultiaddr,jA(e.name,e.requestId??1n)),r=qA(n);return r.peerId.length===0?{found:!1,peerId:"",error:r.error||"name not found"}:{found:!0,peerId:(0,by.toString)(r.peerId,"base58btc"),error:""}}finally{await t.stop()}}var fy,my,py,gy,hy,yy,by,Ru,_y,wy,KA,GA,dy,Mu=st(()=>{"use strict";Ll();fy=require("libp2p"),my=require("@libp2p/tcp"),py=require("@chainsafe/libp2p-noise"),gy=require("@chainsafe/libp2p-yamux"),hy=require("@libp2p/crypto/keys"),yy=require("@multiformats/multiaddr"),by=require("uint8arrays/to-string"),Ru=new TextEncoder,_y=new TextDecoder;wy="/subway/p2p/1.0.0",KA=15e3,GA=15e3,dy=1<<20});var Po={};Fr(Po,{MESH:()=>Ie,RELAY_URL:()=>Io,connectOrThrow:()=>As,ensureMailbox:()=>Yu,isSubwayEnabled:()=>Bu,listRegistered:()=>Wu,loadBindingFor:()=>Vu,loadRegistry:()=>Mr,makeClient:()=>Cs,maybeMintVisaBinding:()=>Ey,meshName:()=>mt,readInbox:()=>ZA,registerName:()=>qu,resolveActingName:()=>Ma,resolveMeshName:()=>Ku,seedSubwayKeyFromTapAgent:()=>Ay,sendMessage:()=>Gu,sendVia:()=>QA,subwayKeyPath:()=>Oa});function mt(e){return e.includes(".")?e:`${e}.${Ie}`}function Bu(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 Fu(){we.mkdirSync(Hu,{recursive:!0,mode:448})}function zA(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function Oa(e){return xs.join(Hu,`${zA(e)}.key`)}function Mr(){if(!we.existsSync(ju))return{};try{return JSON.parse(we.readFileSync(ju,"utf8"))}catch{return{}}}function Uu(e){Fu(),we.writeFileSync(ju,JSON.stringify(e,null,2),{mode:384})}function Du(){try{return Ro.userInfo().username}catch{return"local"}}function Ay(e){if(we.existsSync(e)||!we.existsSync(Lu))return null;let t=we.readdirSync(Lu).filter(r=>r.endsWith(".json"));if(t.length===0)return null;let n=t.map(r=>xs.join(Lu,r)).sort((r,s)=>we.statSync(s).mtimeMs-we.statSync(r).mtimeMs)[0];try{let r=JSON.parse(we.readFileSync(n,"utf8"));if(!r.private_key_jwk)return null;let s=Cu(r.private_key_jwk);return Fu(),we.writeFileSync(e,Buffer.from(s),{mode:384}),r.agent_id??null}catch{return null}}function Cs(e,t={}){return new xh({name:mt(e),url:Io,keyPath:Oa(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function Vu(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 As(e,t=15e3){await Promise.race([e.connect(),new Promise((n,r)=>setTimeout(()=>r(new Error(`Subway relay connect timed out after ${t}ms (${Io})`)),t))])}function Ma(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 Ey(e){if(Ie!=="visa")return null;let t=process.env.VISA_CLI_API_KEY?.trim();if(!t)throw new Ot("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.",Ia(de()),"no_key");try{return await Pa({authUrl:de(),apiKey:t,seed:$a(Oa(e)),name:mt(e)})}catch(n){if(n instanceof Ot)throw n;return console.warn(`[subway] Visa binding not minted: ${n instanceof Error?n.message:String(n)}`),null}}async function qu(e){let t=Oa(e),n=Ay(t),r=mt(e);Ie==="visa"&&!we.existsSync(t)&&(Fu(),we.writeFileSync(t,(0,Cy.randomBytes)(32),{mode:384}));let s=await Ey(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(()=>(Mu(),Ou)),l=await c({relayMultiaddr:i,seed:$a(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:Du(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},Uu(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:Du(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},Uu(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=Cs(e,{autoReconnect:!1,binding:s?.binding});try{await As(a);let c=Mr();return c[e]={relayName:r,mesh:Ie,peerId:a.peerId,owner:Du(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},Uu(c),{relayName:r,mesh:Ie,peerId:a.peerId,tapAgentId:n,...s?{binding:s.binding}:{}}}finally{a.disconnect()}}async function Ku(e){let t=mt(e),n=process.env.SUBWAY_RELAY_MULTIADDR;if(Ie==="visa"&&n){let{resolveDirect:r}=await Promise.resolve().then(()=>(Mu(),Ou)),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 Gu(e,t,n){let r=Cs(e,{autoReconnect:!1,binding:Vu(e)});try{await As(r);let s=mt(t);return await r.sendSigned(s,"chat",n),{to:s,as:mt(e)}}finally{r.disconnect()}}function Wu(){let e=Mr();return Object.entries(e).map(([t,n])=>({name:t,...n}))}async function Yu(e){let t=Na.get(e);if(t)return{relayName:mt(e),peerId:t.client.peerId};let n=Cs(e,{autoReconnect:!0,binding:Vu(e)}),r=[];return n.onMessage(s=>{r.push({from:s.fromName,text:s.payload,ts:s.timestampMs,verified:!!s.verified}),r.length>XA&&r.shift()}),Na.set(e,{client:n,buffer:r}),await As(n),{relayName:mt(e),peerId:n.peerId}}async function ZA(e,t=20,n=!1){await Yu(e);let r=Na.get(e);if(!r)return[];let s=r.buffer.slice(-t);return n&&(r.buffer.length=0),s}async function QA(e,t,n){await Yu(e);let r=Na.get(e);if(!r)throw new Error(`mailbox for ${e} unavailable`);let s=mt(t);return await r.client.sendSigned(s,"chat",n),{to:s,as:mt(e)}}var we,Ro,xs,Cy,Ie,Io,Hu,ju,Lu,Na,XA,Es=st(()=>{"use strict";ou();Ao();we=k(require("fs")),Ro=k(require("os")),xs=k(require("path")),Cy=require("crypto");ct();Ss();Ie=process.env.SUBWAY_MESH??"relay",Io=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";Hu=xs.join(Ro.homedir(),".visa-cli","subway"),ju=xs.join(Hu,"registry.json"),Lu=xs.join(Ro.homedir(),".visa-cli","agents");Na=new Map,XA=200});var za={};Fr(za,{initSentry:()=>k1,isSentryConfigured:()=>E1,reportFatal:()=>T1});function E1(){return!1}async function k1(){return null}async function T1(e,t){process.exit(t?.exitCode??1)}var Xa=st(()=>{});var bT={};Fr(bT,{printGroupHelpAndExit:()=>Dt});module.exports=u_(bT);var Db=require("commander"),tc=k(require("crypto")),ce=k(require("fs")),re=k(require("os")),rt=k(require("path")),jb=require("child_process"),Pd=require("node:readline/promises"),Bb=require("util");var Qo=require("child_process"),Qd=require("util"),pn=k(require("fs")),ei=k(require("os")),gc=k(require("path"));var Wd=k(require("crypto"));var Bt="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";var Yd="VISA_ALLOW_INSECURE_MOCKS",qd,Kd,Gd;function uc(e){return`${e}-${Wd.randomBytes(24).toString("base64url")}`}function Jd(e=process.env){return e.NODE_ENV==="test"||e[Yd]==="true"}function fn(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&Jd(e)}function Vr(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&Jd(e)}function dc(){return`Set ${Yd}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function zd(){return qd??=uc("mock-session"),qd}function Xd(e=process.env){return e.NODE_ENV==="test"?Bt:(Kd??=uc("mock-rc"),Kd)}function Zd(){return Gd??=uc("mock-signature"),Gd}var bt=(0,Qd.promisify)(Qo.execFile),hc=gc.join(ei.homedir(),".visa-mcp"),Us=gc.join(hc,"session-token"),Ye="visa-cli",mn="session-token",Xo="rc-access",d_=5e3,Zo=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function f_(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
12
- `)}function ef(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=f_(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function m_(){try{let{stdout:e}=await bt("security",["find-generic-password","-s",Ye,"-a",mn,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(ef(e))throw new Zo("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 p_(e){try{try{await bt("security",["delete-generic-password","-s",Ye,"-a",mn],{timeout:5e3})}catch{}return await bt("security",["add-generic-password","-s",Ye,"-a",mn,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function g_(){try{await bt("security",["delete-generic-password","-s",Ye,"-a",mn],{timeout:5e3})}catch{}}async function h_(){if(!yc())return null;try{let{stdout:e}=await bt("secret-tool",["lookup","service",Ye,"account",mn],{timeout:5e3});return e.trim()||null}catch{return null}}async function y_(e){if(!yc())return!1;try{let t=(0,Qo.execFile)("secret-tool",["store","--label",`${Ye} ${mn}`,"service",Ye,"account",mn]);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"))},d_))]),!0):!1}catch{return!1}}async function b_(){if(yc())try{await bt("secret-tool",["clear","service",Ye,"account",mn],{timeout:5e3})}catch{}}function yc(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function __(){try{let{stdout:e}=await bt("security",["find-generic-password","-s",Ye,"-a",Xo,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function v_(e){try{try{await bt("security",["delete-generic-password","-s",Ye,"-a",Xo],{timeout:5e3})}catch{}await bt("security",["add-generic-password","-s",Ye,"-a",Xo,"-w",e],{timeout:5e3})}catch{}}async function w_(){try{await bt("security",["delete-generic-password","-s",Ye,"-a",Xo],{timeout:5e3})}catch{}}function mc(){try{return pn.readFileSync(Us,"utf-8").trim()||null}catch(e){if(ef(e))throw new Zo(`Unable to read Visa CLI credentials from ${Us}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function tf(e){pn.mkdirSync(hc,{recursive:!0,mode:448}),pn.writeFileSync(Us,e,{mode:384}),process.platform==="win32"&&S_(Us)}function pc(){try{pn.unlinkSync(Us)}catch{}}function S_(e){try{let t=ei.userInfo().username;(0,Qo.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 fc(){switch(process.platform){case"darwin":return{get:m_,store:p_,delete:g_};case"linux":return{get:h_,store:y_,delete:b_};default:return{get:async()=>mc(),store:async e=>{try{return tf(e),!0}catch{return!1}},delete:async()=>pc(),storesInSessionFile:!0}}}var G=class{static async getSessionToken(){if(fn())return Promise.resolve(zd());let t=fc(),n=await t.get();if(n)return n;let r=mc();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(fn())return;let n=fc();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||pc();return}await n.delete()}if(tf(t),mc()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${hc} is writable.`))}static async getRcAccessToken(){return fn()?Xd():__()}static async saveRcAccessToken(t){fn()||await v_(t)}static async deleteSessionToken(){if(fn())return;await fc().delete(),pc()}static async clearAll(){await this.deleteSessionToken(),await w_()}};var ti=k(require("crypto")),ni=k(require("tty")),ri=k(require("fs"));function C_(e){return/-rc\.|-beta\./.test(e)}function bc(e){return ti.createHash("sha256").update(e.trim()).digest("hex")}function nf(e){return Bt==="SKIP"?!0:ti.timingSafeEqual(Buffer.from(bc(e)),Buffer.from(Bt))}function A_(){try{let e=ri.openSync("/dev/tty","r+"),t=new ni.ReadStream(e),n=new ni.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{ri.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 E_(e){return new Promise((t,n)=>{let r;try{r=A_()}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
+ `)}`}function vu(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(vu).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${vu(t[n])}`).join(",")}}`}var Ao,Kh,Ea,Ca,Nh,Oh,du,fu,sE,Ss,oE,Re,iE,aE,cE,Nt,Ta,wu,Gh,Su,cn,Mh,xu,Wh,lE,xs,Yh,Aa,Nr,ie,Lh,N,Jh,zh,Xh,Zh,mu,gu,Eo,Lr,Mr,Qh,ey,$t,uE,Uh,dE,hu,fE,Cu,ty,mE,Eu,pE,gE,hE,yE,Au,ny,bE,_E,ka,vE,ry,yu,wE,Dh,jh,SE,AE,kE,Ue,wa,Bh,Fh,Vh,vs,ws,Sa,xa,IE,PE,$E,NE,OE,ME,oy,LE,UE,Kn,Gn,DE,jE,HE,qh,pP,iy,gP,hP,yP,bP,Iu,GE,ay,ko=st(()=>{"use strict";Ao=A(require("node:crypto"),1),Kh=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:Ea,n:Ca,Gx:Nh,Gy:Oh,a:du,d:fu,h:sE}=Kh,Ss=32,oE=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},Re=(e="")=>{let t=new Error(e);throw oE(t,Re),t},iE=e=>typeof e=="bigint",aE=e=>typeof e=="string",cE=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,Nt=(e,t,n="")=>{let r=cE(e),s=e?.length,o=t!==void 0;if(!r||o&&s!==t){let i=n&&`"${n}" `,a=o?` of length ${t}`:"",c=r?`length=${s}`:`type=${typeof e}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):new TypeError(l)}return e},Ta=e=>new Uint8Array(e),wu=e=>Uint8Array.from(e),Gh=(e,t)=>e.toString(16).padStart(t,"0"),Su=e=>Array.from(Nt(e)).map(t=>Gh(t,2)).join(""),cn={_0:48,_9:57,A:65,F:70,a:97,f:102},Mh=e=>{if(e>=cn._0&&e<=cn._9)return e-cn._0;if(e>=cn.A&&e<=cn.F)return e-(cn.A-10);if(e>=cn.a&&e<=cn.f)return e-(cn.a-10)},xu=e=>{let t="hex invalid";if(!aE(e))return Re(t);let n=e.length,r=n/2;if(n%2)return Re(t);let s=Ta(r);for(let o=0,i=0;o<r;o++,i+=2){let a=Mh(e.charCodeAt(i)),c=Mh(e.charCodeAt(i+1));if(a===void 0||c===void 0)return Re(t);s[o]=a*16+c}return s},Wh=()=>globalThis?.crypto,lE=()=>Wh()?.subtle??Re("crypto.subtle must be defined, consider polyfill"),xs=(...e)=>{let t=0;for(let s of e)t+=Nt(s).length;let n=Ta(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},Yh=(e=Ss)=>Wh().getRandomValues(Ta(e)),Aa=BigInt,Nr=(e,t,n,r="bad number: out of range")=>{if(!iE(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},ie=(e,t=Ea)=>{let n=e%t;return n>=0n?n:t+n},Lh=(1n<<255n)-1n,N=e=>{e<0n&&Re("negative coordinate");let t=(e>>255n)*19n+(e&Lh);return t=(t>>255n)*19n+(t&Lh),t%Ea},Jh=e=>ie(e,Ca),zh=(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")},Xh=e=>{let t=ny[e];return typeof t!="function"&&Re("hashes."+e+" not set"),t},Zh=e=>Nt(e,64,"digest"),mu=e=>e instanceof Eo?e:Re("Point expected"),gu=2n**256n,Eo=class Or{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=gu;this.X=Nr(t,0n,o),this.Y=Nr(n,0n,o),this.Z=Nr(r,1n,o),this.T=Nr(s,0n,o),Object.freeze(this)}static CURVE(){return Kh}static fromAffine(t){return new Or(t.x,t.y,1n,N(t.x*t.y))}static fromBytes(t,n=!1){let r=fu,s=wu(Nt(t,Ss)),o=t[31];s[31]=o&-129;let i=ey(s);Nr(i,0n,n?gu:Ea);let c=N(i*i),l=ie(c-1n),u=N(r*c+1n),{isValid:d,value:f}=dE(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 Or(f,i,1n,N(f*i))}static fromHex(t,n){return Or.fromBytes(xu(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=du,n=fu,r=this;if(r.is0())return Re("bad point: ZERO");let{X:s,Y:o,Z:i,T:a}=r,c=N(s*s),l=N(o*o),u=N(i*i),d=N(u*u),f=N(c*t),m=N(u*(f+l)),p=ie(d+N(n*N(c*l)));if(m!==p)return Re("bad point: equation left != right (1)");let h=N(s*o),_=N(i*a);return h!==_?Re("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=mu(t),c=N(n*a),l=N(o*s),u=N(r*a),d=N(i*s);return c===l&&u===d}is0(){return this.equals(Mr)}negate(){return new Or(ie(-this.X),this.Y,this.Z,ie(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=du,o=N(t*t),i=N(n*n),a=N(2n*r*r),c=N(s*o),l=ie(t+n),u=ie(N(l*l)-o-i),d=ie(c+i),f=ie(d-a),m=ie(c-i),p=N(u*f),h=N(d*m),_=N(u*m),I=N(f*d);return new Or(p,h,I,_)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=mu(t),u=du,d=fu,f=N(n*i),m=N(r*a),p=N(N(o*d)*l),h=N(s*c),_=ie(N(ie(n+r)*ie(i+a))-f-m),I=ie(h-p),b=ie(h+p),v=ie(m-N(u*f)),w=N(_*I),R=N(b*v),k=N(_*v),y=N(I*b);return new Or(w,R,y,k)}subtract(t){return this.add(mu(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(Nr(t,1n,Ca),!n&&this.is0()))return Mr;if(t===1n)return this;if(this.equals(Lr))return SE(t).p;let r=Mr,s=Lr;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(Mr))return{x:0n,y:1n};let s=zh(r,Ea);N(r*s)!==1n&&Re("invalid inverse");let o=N(t*s),i=N(n*s);return{x:o,y:i}}toBytes(){let{x:t,y:n}=this.toAffine(),r=Qh(n);return r[31]|=t&1n?128:0,r}toHex(){return Su(this.toBytes())}clearCofactor(){return this.multiply(Aa(sE),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Ca/2n,!1).double();return Ca%2n&&(t=t.add(this)),t.is0()}},Lr=new Eo(Nh,Oh,1n,ie(Nh*Oh)),Mr=new Eo(0n,1n,1n,0n);Eo.BASE=Lr;Eo.ZERO=Mr;Qh=e=>xu(Gh(Nr(e,0n,gu),64)).reverse(),ey=e=>Aa("0x"+Su(wu(Nt(e)).reverse())),$t=(e,t)=>{let n=e;for(;t-- >0n;)n=N(n*n);return n},uE=e=>{let t=N(e*e),n=N(t*e),r=N($t(n,2n)*n),s=N($t(r,1n)*e),o=N($t(s,5n)*s),i=N($t(o,10n)*o),a=N($t(i,20n)*i),c=N($t(a,40n)*a),l=N($t(c,80n)*c),u=N($t(l,80n)*c),d=N($t(u,10n)*o);return{pow_p_5_8:N($t(d,2n)*e),b2:n}},Uh=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,dE=(e,t)=>{let n=N(t*N(t*t)),r=N(N(n*n)*t),s=uE(N(e*r)).pow_p_5_8,o=N(e*N(n*s)),i=N(t*N(o*o)),a=o,c=N(o*Uh),l=i===e,u=i===ie(-e),d=i===ie(-e*Uh);return l&&(o=a),(u||d)&&(o=c),(ie(o)&1n)===1n&&(o=ie(-o)),{isValid:l||u,value:o}},hu=e=>Jh(ey(e)),fE=(...e)=>Promise.resolve(Xh("sha512Async")(xs(...e))).then(Zh),Cu=(...e)=>Zh(Xh("sha512")(xs(...e))),ty=e=>{let t=wu(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=hu(n),o=Lr.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},mE=e=>fE(Nt(e,Ss)).then(ty),Eu=e=>ty(Cu(Nt(e,Ss))),pE=e=>Eu(e).pointBytes,gE=e=>e.finish(Cu(e.hashable)),hE=(e,t,n)=>{let{pointBytes:r,scalar:s}=e,o=hu(t),i=Lr.multiply(o).toBytes();return{hashable:xs(i,r,n),finish:l=>{let u=Jh(o+hu(l)*s);return Nt(xs(i,Qh(u)),64)}}},yE=(e,t)=>{let n=Nt(e),r=Eu(t),s=Cu(r.prefix,n);return gE(hE(r,s,n))},Au=Object.freeze({bytesToHex:Su,hexToBytes:xu,concatBytes:xs,mod:ie,invert:zh,randomBytes:Yh}),ny={sha512Async:async e=>{let t=lE(),n=xs(e);return Ta(await t.digest("SHA-512",n.buffer))},sha512:void 0},bE=e=>(e=e===void 0?Yh(Ss):e,Nt(e,Ss)),_E=Object.freeze({getExtendedPublicKeyAsync:mE,getExtendedPublicKey:Eu,randomSecretKey:bE}),ka=8,vE=256,ry=Math.ceil(vE/ka)+1,yu=2**(ka-1),wE=()=>{let e=[],t=Lr,n=t;for(let r=0;r<ry;r++){n=t,e.push(n);for(let s=1;s<yu;s++)n=n.add(t),e.push(n);t=n.double()}return e},Dh=void 0,jh=(e,t)=>{let n=t.negate();return e?n:t},SE=e=>{let t=Dh||(Dh=wE()),n=Mr,r=Lr,s=2**ka,o=s,i=Aa(s-1),a=Aa(ka);for(let c=0;c<ry;c++){let l=Number(e&i);e>>=a,l>yu&&(l-=o,e+=1n);let u=c*yu,d=u,f=u+Math.abs(l)-1,m=c%2!==0,p=l<0;l===0?r=r.add(jh(m,t[d])):n=n.add(jh(p,t[f]))}return e!==0n&&Re("invalid wnaf"),{p:n,f:r}};AE=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),kE=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=pu(this.buffer)}update(e){Hh(this),sy(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=pu(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){Hh(this),CE(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,bu(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=pu(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]),wa=BigInt(2**32-1),Bh=BigInt(32);Fh=(e,t,n)=>e>>>n,Vh=(e,t,n)=>e<<32-n|t>>>n,vs=(e,t,n)=>e>>>n|t<<32-n,ws=(e,t,n)=>e<<32-n|t>>>n,Sa=(e,t,n)=>e<<64-n|t>>>n-32,xa=(e,t,n)=>e>>>n-32|t<<64-n;IE=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),PE=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,$E=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),NE=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,OE=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),ME=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,oy=RE(["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))),LE=oy[0],UE=oy[1],Kn=new Uint32Array(80),Gn=new Uint32Array(80),DE=class extends kE{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 b=0;b<16;b++,t+=4)Kn[b]=e.getUint32(t),Gn[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let v=Kn[b-15]|0,w=Gn[b-15]|0,R=vs(v,w,1)^vs(v,w,8)^Fh(v,w,7),k=ws(v,w,1)^ws(v,w,8)^Vh(v,w,7),y=Kn[b-2]|0,x=Gn[b-2]|0,Y=vs(y,x,19)^Sa(y,x,61)^Fh(y,x,6),X=ws(y,x,19)^xa(y,x,61)^Vh(y,x,6),K=$E(k,X,Gn[b-7],Gn[b-16]),ve=NE(K,R,Y,Kn[b-7],Kn[b-16]);Kn[b]=ve|0,Gn[b]=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:_,Hl:I}=this;for(let b=0;b<80;b++){let v=vs(u,d,14)^vs(u,d,18)^Sa(u,d,41),w=ws(u,d,14)^ws(u,d,18)^xa(u,d,41),R=u&f^~u&p,k=d&m^~d&h,y=OE(I,w,k,UE[b],Gn[b]),x=ME(y,_,v,R,LE[b],Kn[b]),Y=y|0,X=vs(n,r,28)^Sa(n,r,34)^Sa(n,r,39),K=ws(n,r,28)^xa(n,r,34)^xa(n,r,39),ve=n&s^n&i^s&i,se=r&o^r&a^o&a;_=p|0,I=h|0,p=f|0,h=m|0,f=u|0,m=d|0,{h:u,l:d}=ln(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=IE(Y,K,se);n=PE(Z,x,X,ve),r=Z|0}({h:n,l:r}=ln(this.Ah|0,this.Al|0,n|0,r|0)),{h:s,l:o}=ln(this.Bh|0,this.Bl|0,s|0,o|0),{h:i,l:a}=ln(this.Ch|0,this.Cl|0,i|0,a|0),{h:c,l}=ln(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=ln(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:m}=ln(this.Fh|0,this.Fl|0,f|0,m|0),{h:p,l:h}=ln(this.Gh|0,this.Gl|0,p|0,h|0),{h:_,l:I}=ln(this.Hh|0,this.Hl|0,_|0,I|0),this.set(n,r,s,o,i,a,c,l,u,d,f,m,p,h,_,I)}roundClean(){bu(Kn,Gn)}destroy(){this.destroyed=!0,bu(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},jE=class extends DE{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)}},HE=EE(()=>new jE,AE(3)),qh=ny;qh.sha512||(qh.sha512=e=>HE(e));pP=Au.bytesToHex,iy=Au.hexToBytes,gP=Au.concatBytes;hP=new TextEncoder;yP=iy("302e020100300506032b657004220420"),bP=iy("302a300506032b6570032100"),Iu="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",GE=8,ay=Iu.length-1;if((Iu.length&ay)!==0)throw new Error("agent pairing code alphabet must contain a power-of-two number of symbols");});var _y={};qr(_y,{BindingIssuanceError:()=>To,CardRequiredError:()=>Ot,buildIssuanceRequest:()=>by,enrollCardUrl:()=>Na,jkt:()=>Ro,proofPayload:()=>yy,readSeed:()=>Ma,requestVisaBinding:()=>Oa});function Ro(e){let t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return gy.createHash("sha256").update(t,"utf8").digest("base64url")}function yy(e,t,n){return`visa-agent-binding:v1:${e}:${t}:${n}`}function by(e,t,n="visa",r=Math.floor(Date.now()/1e3)){let s=Pa(Ra(e)),o=Buffer.from(yy(t,Ro(s),r),"utf8"),i=Buffer.from(Ia(e,o)).toString("base64url");return{name:t,mesh:n,mode:"card",agent_pubkey:s,proof:{ts:r,sig:i}}}function Na(e){try{return new URL("/enroll-card",e).toString()}catch{return"https://auth.visacli.sh/enroll-card"}}async function Oa(e){let t=by(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 Ot("No card on file \u2014 enroll a card to register on the trusted .visa mesh.",Na(e.authUrl),"no_card"):new To(`Visa binding issuance failed (${s.status})${o?`: ${o}`:""}`,s.status,i||void 0)}return await s.json()}function Ma(e){return new Uint8Array(hy.readFileSync(e))}var gy,hy,Ot,To,Cs=st(()=>{"use strict";gy=A(require("crypto")),hy=A(require("fs"));ko();Ot=class extends Error{enrollUrl;reason;constructor(t,n,r){super(t),this.name="CardRequiredError",this.enrollUrl=n,this.reason=r}},To=class extends Error{status;code;constructor(t,n,r){super(t),this.name="BindingIssuanceError",this.status=n,this.code=r}}});var ju={};qr(ju,{SUBWAY_PROTOCOL:()=>Iy,registerDirect:()=>aA,resolveDirect:()=>cA});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 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 Lu(e,t){return e<<3|t}function Io(e,t,n){e.push(Lu(t,2)),Mu(e,n.length);for(let r of n)e.push(r)}function JE(e,t){let n=[];return Io(n,1,Ou.encode(e)),t&&t.length>0&&Io(n,2,Ou.encode(t)),Uint8Array.from(n)}function zE(e,t,n){let r=[];return n!==0n&&(r.push(Lu(1,0)),Mu(r,n)),Io(r,2,JE(e,t)),Uint8Array.from(r)}function XE(e){let t=[];return Io(t,1,Ou.encode(e)),Uint8Array.from(t)}function ZE(e,t){let n=[];return t!==0n&&(n.push(Lu(1,0)),Mu(n,t)),Io(n,3,XE(e)),Uint8Array.from(n)}function QE(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=Ty.decode(e.subarray(l,u)),t=u}else t=Uu(e,t,i)}return n}function eA(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=Ty.decode(e.subarray(l,u)),t=u}else t=Uu(e,t,i)}return n}function Uu(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 Ry(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=QE(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=eA(e.subarray(l,u)),t=u}else t=Uu(e,t,i)}return n}function tA(e){let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t}function Du(e){return new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1)}function nA(e){if(e.length<4)return{success:!1,error:"short reply (no length prefix)"};let t=Du(e.subarray(0,4));return e.length<4+t?{success:!1,error:`truncated frame (have ${e.length-4}, need ${t})`}:Ry(e.subarray(4,4+t)).registerNameResponse??{success:!1,error:"reply carried no register_name_response"}}function rA(e){if(e.length<4)return{peerId:new Uint8Array(0),error:"short reply (no length prefix)"};let t=Du(e.subarray(0,4));return e.length<4+t?{peerId:new Uint8Array(0),error:`truncated frame (have ${e.length-4}, need ${t})`}:Ry(e.subarray(4,4+t)).resolveNameResponse??{peerId:new Uint8Array(0),error:"reply carried no resolve_name_response"}}function Nu(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 iA(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>vy)throw new Error("subway: reply exceeded max size");if(r<0&&n>=4&&(r=4+Du(Nu(t).subarray(0,4)),r>vy))throw new Error("subway: declared frame exceeds max size");if(r>=0&&n>=r)return Nu(t).subarray(0,r)}return Nu(t)}async function Py(e){return(0,wy.createLibp2p)({...e?{privateKey:await(0,Ey.generateKeyPairFromSeed)("Ed25519",e)}:{},transports:[(0,Sy.tcp)()],connectionEncrypters:[(0,xy.noise)()],streamMuxers:[(0,Cy.yamux)()],connectionGater:{denyDialMultiaddr:async()=>!1}})}async function $y(e,t,n){let r=await e.dialProtocol((0,Ay.multiaddr)(t),Iy,{signal:AbortSignal.timeout(sA)});r.send(tA(n));let s;return Promise.race([iA(r),new Promise((o,i)=>{s=setTimeout(()=>i(new Error("subway: request timed out")),oA)})]).finally(()=>clearTimeout(s))}async function aA(e){let t=await Py(e.seed);try{let n=await $y(t,e.relayMultiaddr,zE(e.name,e.binding,e.requestId??1n)),r=nA(n);return{success:r.success,error:r.error,peerId:t.peerId.toString()}}finally{await t.stop()}}async function cA(e){let t=await Py(e.seed);try{let n=await $y(t,e.relayMultiaddr,ZE(e.name,e.requestId??1n)),r=rA(n);return r.peerId.length===0?{found:!1,peerId:"",error:r.error||"name not found"}:{found:!0,peerId:(0,ky.toString)(r.peerId,"base58btc"),error:""}}finally{await t.stop()}}var wy,Sy,xy,Cy,Ey,Ay,ky,Ou,Ty,Iy,sA,oA,vy,Hu=st(()=>{"use strict";Bl();wy=require("libp2p"),Sy=require("@libp2p/tcp"),xy=require("@chainsafe/libp2p-noise"),Cy=require("@chainsafe/libp2p-yamux"),Ey=require("@libp2p/crypto/keys"),Ay=require("@multiformats/multiaddr"),ky=require("uint8arrays/to-string"),Ou=new TextEncoder,Ty=new TextDecoder;Iy="/subway/p2p/1.0.0",sA=15e3,oA=15e3,vy=1<<20});var No={};qr(No,{MESH:()=>Ie,RELAY_URL:()=>$o,connectOrThrow:()=>ks,ensureMailbox:()=>Qu,isSubwayEnabled:()=>Ku,listRegistered:()=>Zu,loadBindingFor:()=>Yu,loadRegistry:()=>Ur,makeClient:()=>As,maybeMintVisaBinding:()=>My,meshName:()=>mt,readInbox:()=>dA,registerName:()=>Ju,resolveActingName:()=>Da,resolveMeshName:()=>zu,seedSubwayKeyFromTapAgent:()=>Oy,sendMessage:()=>Xu,sendVia:()=>fA,subwayKeyPath:()=>Ua});function mt(e){return e.includes(".")?e:`${e}.${Ie}`}function Ku(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 Wu(){we.mkdirSync(Gu,{recursive:!0,mode:448})}function lA(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function Ua(e){return Es.join(Gu,`${lA(e)}.key`)}function Ur(){if(!we.existsSync(qu))return{};try{return JSON.parse(we.readFileSync(qu,"utf8"))}catch{return{}}}function Fu(e){Wu(),we.writeFileSync(qu,JSON.stringify(e,null,2),{mode:384})}function Vu(){try{return Po.userInfo().username}catch{return"local"}}function Oy(e){if(we.existsSync(e)||!we.existsSync(Bu))return null;let t=we.readdirSync(Bu).filter(r=>r.endsWith(".json"));if(t.length===0)return null;let n=t.map(r=>Es.join(Bu,r)).sort((r,s)=>we.statSync(s).mtimeMs-we.statSync(r).mtimeMs)[0];try{let r=JSON.parse(we.readFileSync(n,"utf8"));if(!r.private_key_jwk)return null;let s=Ru(r.private_key_jwk);return Wu(),we.writeFileSync(e,Buffer.from(s),{mode:384}),r.agent_id??null}catch{return null}}function As(e,t={}){return new $h({name:mt(e),url:$o,keyPath:Ua(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function Yu(e){if(Ie!=="visa")return;let t=Ur()[e];if(t?.binding&&!(t.bindingExpiresAt&&Date.parse(t.bindingExpiresAt)<=Date.now()))return t.binding}async function ks(e,t=15e3){await Promise.race([e.connect(),new Promise((n,r)=>setTimeout(()=>r(new Error(`Subway relay connect timed out after ${t}ms (${$o})`)),t))])}function Da(e){if(e)return e;let t=Object.keys(Ur());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 My(e){if(Ie!=="visa")return null;let t=process.env.VISA_CLI_API_KEY?.trim();if(!t)throw new Ot("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.",Na(de()),"no_key");try{return await Oa({authUrl:de(),apiKey:t,seed:Ma(Ua(e)),name:mt(e)})}catch(n){if(n instanceof Ot)throw n;return console.warn(`[subway] Visa binding not minted: ${n instanceof Error?n.message:String(n)}`),null}}async function Ju(e){let t=Ua(e),n=Oy(t),r=mt(e);Ie==="visa"&&!we.existsSync(t)&&(Wu(),we.writeFileSync(t,(0,Ny.randomBytes)(32),{mode:384}));let s=await My(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(()=>(Hu(),ju)),l=await c({relayMultiaddr:i,seed:Ma(t),name:r,binding:s?.binding});if(!l.success)throw new Error(`.visa relay admission failed: ${l.error||"unknown"}`);let u=Ur();return u[e]={relayName:r,mesh:Ie,peerId:l.peerId,owner:Vu(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},Fu(u),{relayName:r,mesh:Ie,peerId:l.peerId,tapAgentId:n,...s?{binding:s.binding}:{}}}if(Ie==="visa"&&!process.env.SUBWAY_RELAY){let c=Ur();return c[e]={relayName:r,mesh:Ie,peerId:null,owner:Vu(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},Fu(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=As(e,{autoReconnect:!1,binding:s?.binding});try{await ks(a);let c=Ur();return c[e]={relayName:r,mesh:Ie,peerId:a.peerId,owner:Vu(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},Fu(c),{relayName:r,mesh:Ie,peerId:a.peerId,tapAgentId:n,...s?{binding:s.binding}:{}}}finally{a.disconnect()}}async function zu(e){let t=mt(e),n=process.env.SUBWAY_RELAY_MULTIADDR;if(Ie==="visa"&&n){let{resolveDirect:r}=await Promise.resolve().then(()=>(Hu(),ju)),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 Xu(e,t,n){let r=As(e,{autoReconnect:!1,binding:Yu(e)});try{await ks(r);let s=mt(t);return await r.sendSigned(s,"chat",n),{to:s,as:mt(e)}}finally{r.disconnect()}}function Zu(){let e=Ur();return Object.entries(e).map(([t,n])=>({name:t,...n}))}async function Qu(e){let t=La.get(e);if(t)return{relayName:mt(e),peerId:t.client.peerId};let n=As(e,{autoReconnect:!0,binding:Yu(e)}),r=[];return n.onMessage(s=>{r.push({from:s.fromName,text:s.payload,ts:s.timestampMs,verified:!!s.verified}),r.length>uA&&r.shift()}),La.set(e,{client:n,buffer:r}),await ks(n),{relayName:mt(e),peerId:n.peerId}}async function dA(e,t=20,n=!1){await Qu(e);let r=La.get(e);if(!r)return[];let s=r.buffer.slice(-t);return n&&(r.buffer.length=0),s}async function fA(e,t,n){await Qu(e);let r=La.get(e);if(!r)throw new Error(`mailbox for ${e} unavailable`);let s=mt(t);return await r.client.sendSigned(s,"chat",n),{to:s,as:mt(e)}}var we,Po,Es,Ny,Ie,$o,Gu,qu,Bu,La,uA,Ts=st(()=>{"use strict";uu();ko();we=A(require("fs")),Po=A(require("os")),Es=A(require("path")),Ny=require("crypto");ct();Cs();Ie=process.env.SUBWAY_MESH??"relay",$o=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";Gu=Es.join(Po.homedir(),".visa-cli","subway"),qu=Es.join(Gu,"registry.json"),Bu=Es.join(Po.homedir(),".visa-cli","agents");La=new Map,uA=200});var Qa={};qr(Qa,{initSentry:()=>B1,isSentryConfigured:()=>H1,reportFatal:()=>F1});function H1(){return!1}async function B1(){return null}async function F1(e,t){process.exit(t?.exitCode??1)}var ec=st(()=>{});var $T={};qr($T,{printGroupHelpAndExit:()=>Dt});module.exports=b_($T);var Gb=require("commander"),sc=A(require("crypto")),ce=A(require("fs")),re=A(require("os")),rt=A(require("path")),Wb=require("child_process"),Ud=require("node:readline/promises"),Yb=require("util");var ti=require("child_process"),of=require("util"),gn=A(require("fs")),ni=A(require("os")),bc=A(require("path"));var Qd=A(require("crypto"));var Ht="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";var ef="VISA_ALLOW_INSECURE_MOCKS",zd,Xd,Zd;function mc(e){return`${e}-${Qd.randomBytes(24).toString("base64url")}`}function tf(e=process.env){return e.NODE_ENV==="test"||e[ef]==="true"}function mn(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&tf(e)}function Kr(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&tf(e)}function pc(){return`Set ${ef}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function nf(){return zd??=mc("mock-session"),zd}function rf(e=process.env){return e.NODE_ENV==="test"?Ht:(Xd??=mc("mock-rc"),Xd)}function sf(){return Zd??=mc("mock-signature"),Zd}var bt=(0,of.promisify)(ti.execFile),_c=bc.join(ni.homedir(),".visa-mcp"),js=bc.join(_c,"session-token"),Ye="visa-cli",pn="session-token",Qo="rc-access",__=5e3,ei=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function v_(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
12
+ `)}function af(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=v_(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function w_(){try{let{stdout:e}=await bt("security",["find-generic-password","-s",Ye,"-a",pn,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(af(e))throw new ei("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 S_(e){try{try{await bt("security",["delete-generic-password","-s",Ye,"-a",pn],{timeout:5e3})}catch{}return await bt("security",["add-generic-password","-s",Ye,"-a",pn,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function x_(){try{await bt("security",["delete-generic-password","-s",Ye,"-a",pn],{timeout:5e3})}catch{}}async function C_(){if(!vc())return null;try{let{stdout:e}=await bt("secret-tool",["lookup","service",Ye,"account",pn],{timeout:5e3});return e.trim()||null}catch{return null}}async function E_(e){if(!vc())return!1;try{let t=(0,ti.execFile)("secret-tool",["store","--label",`${Ye} ${pn}`,"service",Ye,"account",pn]);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"))},__))]),!0):!1}catch{return!1}}async function A_(){if(vc())try{await bt("secret-tool",["clear","service",Ye,"account",pn],{timeout:5e3})}catch{}}function vc(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function k_(){try{let{stdout:e}=await bt("security",["find-generic-password","-s",Ye,"-a",Qo,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function T_(e){try{try{await bt("security",["delete-generic-password","-s",Ye,"-a",Qo],{timeout:5e3})}catch{}await bt("security",["add-generic-password","-s",Ye,"-a",Qo,"-w",e],{timeout:5e3})}catch{}}async function R_(){try{await bt("security",["delete-generic-password","-s",Ye,"-a",Qo],{timeout:5e3})}catch{}}function hc(){try{return gn.readFileSync(js,"utf-8").trim()||null}catch(e){if(af(e))throw new ei(`Unable to read Visa CLI credentials from ${js}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function cf(e){gn.mkdirSync(_c,{recursive:!0,mode:448}),gn.writeFileSync(js,e,{mode:384}),process.platform==="win32"&&I_(js)}function yc(){try{gn.unlinkSync(js)}catch{}}function I_(e){try{let t=ni.userInfo().username;(0,ti.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 gc(){switch(process.platform){case"darwin":return{get:w_,store:S_,delete:x_};case"linux":return{get:C_,store:E_,delete:A_};default:return{get:async()=>hc(),store:async e=>{try{return cf(e),!0}catch{return!1}},delete:async()=>yc(),storesInSessionFile:!0}}}var G=class{static async getSessionToken(){if(mn())return Promise.resolve(nf());let t=gc(),n=await t.get();if(n)return n;let r=hc();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(mn())return;let n=gc();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||yc();return}await n.delete()}if(cf(t),hc()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${_c} is writable.`))}static async getRcAccessToken(){return mn()?rf():k_()}static async saveRcAccessToken(t){mn()||await T_(t)}static async deleteSessionToken(){if(mn())return;await gc().delete(),yc()}static async clearAll(){await this.deleteSessionToken(),await R_()}};var ri=A(require("crypto")),si=A(require("tty")),oi=A(require("fs"));function $_(e){return/-rc\.|-beta\./.test(e)}function wc(e){return ri.createHash("sha256").update(e.trim()).digest("hex")}function lf(e){return Ht==="SKIP"?!0:ri.timingSafeEqual(Buffer.from(wc(e)),Buffer.from(Ht))}function N_(){try{let e=oi.openSync("/dev/tty","r+"),t=new si.ReadStream(e),n=new si.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{oi.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 O_(e){return new Promise((t,n)=>{let r;try{r=N_()}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===`
13
13
  `?(o.write(`
14
14
  `),a(),t(c)):u===""?(o.write(`
15
- `),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 k_=`
15
+ `),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 M_=`
16
16
  \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
17
17
  \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
18
18
  \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
@@ -21,25 +21,25 @@ ${Object.entries(t).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${n}=${r}`
21
21
  \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D
22
22
 
23
23
  This is a Release Candidate build. Access is restricted to Visa employees.
24
- `;async function rf(e={}){let t=e.version??Ds().version;if(!C_(t))return;let n=process.env.VISA_RC_CODE;if(n&&nf(n)){await G.saveRcAccessToken(bc(n));return}if(e.isMcp??!1){let i=await G.getRcAccessToken();if(i&&(Bt==="SKIP"||i===Bt))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
25
- `),process.exit(1)}let s=await G.getRcAccessToken();if(s&&(Bt==="SKIP"||s===Bt))return;console.log(k_);let o=3;for(let i=1;i<=o;i++){let a;try{a=await E_(" Enter RC access code: ")}catch{process.exit(1)}if(nf(a)){await G.saveRcAccessToken(bc(a)),console.log(`
24
+ `;async function uf(e={}){let t=e.version??Hs().version;if(!$_(t))return;let n=process.env.VISA_RC_CODE;if(n&&lf(n)){await G.saveRcAccessToken(wc(n));return}if(e.isMcp??!1){let i=await G.getRcAccessToken();if(i&&(Ht==="SKIP"||i===Ht))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
25
+ `),process.exit(1)}let s=await G.getRcAccessToken();if(s&&(Ht==="SKIP"||s===Ht))return;console.log(M_);let o=3;for(let i=1;i<=o;i++){let a;try{a=await O_(" Enter RC access code: ")}catch{process.exit(1)}if(lf(a)){await G.saveRcAccessToken(wc(a)),console.log(`
26
26
  Access granted. Welcome.
27
27
  `);return}i<o&&console.log(`
28
28
  Invalid code. ${o-i} attempt(s) remaining.
29
29
  `)}console.log(`
30
30
  Invalid code. Contact your team lead.
31
- `),process.exit(1)}var si=k(require("fs")),sf=k(require("os")),_c=k(require("path")),T_=[{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"}}],R_=/^data:(image\/(png|jpeg|jpg|gif|webp));base64,([A-Za-z0-9+/=]+)$/;function qr(e){if(typeof e!="string"||e.length===0)return null;let t=e.trim(),n=R_.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 T_)if(r.startsWith(s))return{base64:r,sig:o};return null}function js(e,t={}){let n=t.outputDir??_c.join(sf.tmpdir(),"visa-cli");si.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=_c.join(n,`${r}-${s}.${e.sig.ext}`),i=Buffer.from(e.base64,"base64");return si.writeFileSync(o,i,{mode:384}),{filePath:o,bytes:i.length,mime:e.sig.mime}}function of(e){return typeof e?.status=="string"&&(e.status==="IN_QUEUE"||e.status==="PENDING")}function vc(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 I_(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 Bs(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 wc(e,t){if(!t||typeof t!="object")return Bs(e,"No result payload from tool");let n=t;if(n.success===!1)return Bs(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 I_(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 Sc=require("process");async function xc(){let e="";Sc.stdin.setEncoding("utf8");for await(let t of Sc.stdin)e+=t;return e.endsWith(`
32
- `)?e.slice(0,-1):e}async function Yn(e,t){if(e==="-"||t.stdin===!0&&!e){let s=(await xc()).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 Hs(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 uf=k(require("fs")),oi=k(require("path"));var gn=class extends Error{constructor(t){super(t),this.name="FromStdinFieldError"}},af=new Set;function P_(e){af.add(e)}function cf(e){return af.has(e)}function lf(e,t){if(!t.startsWith("."))throw new gn(`--from-stdin path must start with "." (got: "${t}")`);let n=$_(t),r=e;for(let o of n){if(r==null)throw new gn(`--from-stdin path "${t}" failed: hit ${r===null?"null":"undefined"} at segment "${o}"`);if(typeof r!="object")throw new gn(`--from-stdin path "${t}" failed: cannot descend into primitive at segment "${o}"`);if(typeof o=="number"){if(!Array.isArray(r))throw new gn(`--from-stdin path "${t}" failed: expected array at segment [${o}], got object`);r=r[o]}else r=r[o]}if(r==null)throw new gn(`--from-stdin path "${t}" resolved to ${r===null?"null":"undefined"}`);if(typeof r=="object")throw new gn(`--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 P_(s),s}function $_(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 Cc=class extends Error{constructor(t){super(t),this.name="FileShorthandStdinSourceError"}};async function df(e){if(e===void 0)return;if(!e.startsWith("@"))return e;if(cf(e))throw new Cc("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("~")?oi.join(process.env.HOME??"",t.slice(1)):oi.resolve(process.cwd(),t),r=await uf.promises.readFile(n,"utf8");return r.endsWith(`
33
- `)?r.slice(0,-1):r}var Fs=require("process"),hn=["json","yaml","tsv","table"];function ii(e){return hn.includes(e)}function Vs(e,t){switch(t){case"json":Fs.stdout.write(JSON.stringify(e)+`
34
- `);return;case"yaml":Fs.stdout.write(N_(e)+`
35
- `);return;case"tsv":Fs.stdout.write(O_(e)+`
36
- `);return;case"table":Fs.stdout.write(M_(e)+`
37
- `);return}}function N_(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(` - ${ff(s)}`)}else r!==null&&typeof r=="object"?t.push(`${n}: ${JSON.stringify(r)}`):t.push(`${n}: ${ff(r)}`);return t.join(`
38
- `)}function ff(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 O_(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(`
39
- `)}function M_(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(`
40
- `)}var pf=require("child_process");function Ac(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 L_(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(`
41
- `)}function qs(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 gf(e,t){let n=qs(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 hf(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 yf(e,t=process.platform){let n=qs(e);return n?hf(n,t):null}function mf(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function Kr(e,t={}){let n=t.log??(l=>console.log(l)),r=t.env??process.env,s=t.platform??process.platform,o=qs(e),i=t.spawn??((l,u,d)=>{(0,pf.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 L_(o??e).split(`
42
- `))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=Ac(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=hf(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?mf(n,d):(n(" Opened browser. Waiting for you to sign in..."),n("")),l()};try{i(c.cmd,c.args,u)}catch(d){mf(n,d instanceof Error?d:new Error(String(d))),l()}})}function U_(e){return new Promise(t=>setTimeout(t,e))}function bf(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 _f(e){return!Number.isFinite(e)||e===null||e<=0?1e3:Math.min(Math.max(Math.ceil(e),1e3),3e4)}async function D_(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=bf(e.headers?.get("Retry-After"));if(r!==null)return n(_f(r));if(typeof e.json=="function")try{let s=await e.json();return n(_f(bf(s?.retryAfter)))}catch{return n(1e3)}return n(1e3)}async function yn(e,t){let n=await D_(e);return t?.(n),await U_(n),n}var Df=k(require("crypto")),jf=require("child_process"),Se=k(require("fs")),Bf=k(require("os")),De=k(require("path"));var J=k(require("fs")),Xn=k(require("os")),Q=k(require("path")),Ef=require("child_process"),Tc=require("crypto");var Wr=k(require("fs")),ai=k(require("tty"));function wf(e=process.env){let t=(e.COLORTERM??"").toLowerCase();if(t==="truecolor"||t==="24bit")return!0;let n=(e.TERM??"").toLowerCase();return n.includes("truecolor")||n.includes("24bit")}function Sf(e,t){let n=(s,o,i)=>`\x1B[38;2;${s};${o};${i}m`,r=s=>`\x1B[38;5;${s}m`;return e==="light"?{reset:"\x1B[0m",visaBlue:t?n(20,52,203):r(26),visaBlueSoft:t?n(11,78,162):r(25),visaGold:t?n(122,82,0):r(94),green:t?n(15,107,47):r(22),muted:t?n(92,100,112):r(241),chrome:t?n(138,138,138):r(245)}:{reset:"\x1B[0m",visaBlue:t?n(168,184,255):r(153),visaBlueSoft:t?n(127,149,242):r(111),visaGold:t?n(255,210,74):r(221),green:t?n(86,211,100):r(77),muted:t?n(199,205,215):r(251),chrome:t?n(110,118,129):r(243)}}function xf(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 vf(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 j_=80,B_="/dev/tty";function H_(e=B_){if(process.platform==="win32")return null;let t,n;try{t=Wr.openSync(e,"r"),n=Wr.openSync(e,"w");let r=new ai.ReadStream(t),s=new ai.WriteStream(n);return{stdin:r,stdout:s,close:()=>{try{r.destroy?.()}catch{}try{s.destroy?.()}catch{}}}}catch{try{t!==void 0&&Wr.closeSync(t)}catch{}try{n!==void 0&&Wr.closeSync(n)}catch{}return null}}function F_(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??H_)(e.ttyPath);return o?.stdout.isTTY&&o.stdin.isTTY&&typeof o.stdin.setRawMode=="function"?o:(o?.close?.(),null)}async function V_(e={}){let t=F_(e);if(!t)return null;let{stdin:n,stdout:r}=t,s=e.timeoutMs??j_,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=vf(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=vf(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 Jn,Ks;function q_(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=xf(e.COLORFGBG);return n||"dark"}function ci(e=process.env){return Jn!==void 0||(Jn=q_(e)),Jn}function Pe(e=process.env){if(Ks!==void 0)return Ks;let t=ci(e),n=wf(e);return Ks=Sf(t==="light"?"light":"dark",n),Ks}function li(e=process.env){return ci(e)==="no-color"}async function Ec(e={}){if(Jn!==void 0)return Jn;let t=e.env??process.env;if((t.NO_COLOR??"")!=="")return Gr("no-color",t);let n=(t.VISA_CLI_HUD_THEME??"").toLowerCase().trim();if(n==="light")return Gr("light",t);if(n==="dark")return Gr("dark",t);let r=xf(t.COLORFGBG);if(r)return Gr(r,t);let s=await V_(e);return Gr(s||"dark",t)}function Gr(e,t){Jn=e;let n=wf(t);return Ks=Sf(e==="light"?"light":"dark",n),e}var K_=2,ui="# >>> visa-cli shell hud v2 >>>",di="# <<< visa-cli shell hud v2 <<<",G_="# >>> visa-cli shell hud >>>",W_="# <<< visa-cli shell hud <<<",kf=3e4,Y_=6e4,J_="VISA | HUD not ready \u2014 run: visa-cli config hud doctor",z_={currentVersion:"0.0.0"},X_=15e3;function Rc(){try{return Q.join($c(),".visa-cli")}catch{return Q.join(Xn.tmpdir(),".visa-cli")}}function bn(){return Q.join(Rc(),"shell-hud.json")}function Gs(){return Q.join(Rc(),"shell-hud.line")}function Tf(){return Q.join(Rc(),"shell-hud.lock")}function zr(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 Ws(e){let t=$c();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 Rf(e,t){let n=t??$c(),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 Z_(e){let t="$HOME/.visa-cli/shell-hud.line",n=h0(e),r=y0(e);if(e==="zsh")return`${ui}
31
+ `),process.exit(1)}var ii=A(require("fs")),df=A(require("os")),Sc=A(require("path")),L_=[{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"}}],U_=/^data:(image\/(png|jpeg|jpg|gif|webp));base64,([A-Za-z0-9+/=]+)$/;function Gr(e){if(typeof e!="string"||e.length===0)return null;let t=e.trim(),n=U_.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 L_)if(r.startsWith(s))return{base64:r,sig:o};return null}function Bs(e,t={}){let n=t.outputDir??Sc.join(df.tmpdir(),"visa-cli");ii.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=Sc.join(n,`${r}-${s}.${e.sig.ext}`),i=Buffer.from(e.base64,"base64");return ii.writeFileSync(o,i,{mode:384}),{filePath:o,bytes:i.length,mime:e.sig.mime}}function ff(e){return typeof e?.status=="string"&&(e.status==="IN_QUEUE"||e.status==="PENDING")}function xc(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 D_(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 Fs(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 Cc(e,t){if(!t||typeof t!="object")return Fs(e,"No result payload from tool");let n=t;if(n.success===!1)return Fs(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 D_(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 Ec=require("process");async function Ac(){let e="";Ec.stdin.setEncoding("utf8");for await(let t of Ec.stdin)e+=t;return e.endsWith(`
32
+ `)?e.slice(0,-1):e}async function zn(e,t){if(e==="-"||t.stdin===!0&&!e){let s=(await Ac()).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 Vs(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 hf=A(require("fs")),ai=A(require("path"));var hn=class extends Error{constructor(t){super(t),this.name="FromStdinFieldError"}},mf=new Set;function j_(e){mf.add(e)}function pf(e){return mf.has(e)}function gf(e,t){if(!t.startsWith("."))throw new hn(`--from-stdin path must start with "." (got: "${t}")`);let n=H_(t),r=e;for(let o of n){if(r==null)throw new hn(`--from-stdin path "${t}" failed: hit ${r===null?"null":"undefined"} at segment "${o}"`);if(typeof r!="object")throw new hn(`--from-stdin path "${t}" failed: cannot descend into primitive at segment "${o}"`);if(typeof o=="number"){if(!Array.isArray(r))throw new hn(`--from-stdin path "${t}" failed: expected array at segment [${o}], got object`);r=r[o]}else r=r[o]}if(r==null)throw new hn(`--from-stdin path "${t}" resolved to ${r===null?"null":"undefined"}`);if(typeof r=="object")throw new hn(`--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 j_(s),s}function H_(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 kc=class extends Error{constructor(t){super(t),this.name="FileShorthandStdinSourceError"}};async function yf(e){if(e===void 0)return;if(!e.startsWith("@"))return e;if(pf(e))throw new kc("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("~")?ai.join(process.env.HOME??"",t.slice(1)):ai.resolve(process.cwd(),t),r=await hf.promises.readFile(n,"utf8");return r.endsWith(`
33
+ `)?r.slice(0,-1):r}var qs=require("process"),yn=["json","yaml","tsv","table"];function ci(e){return yn.includes(e)}function Ks(e,t){switch(t){case"json":qs.stdout.write(JSON.stringify(e)+`
34
+ `);return;case"yaml":qs.stdout.write(B_(e)+`
35
+ `);return;case"tsv":qs.stdout.write(F_(e)+`
36
+ `);return;case"table":qs.stdout.write(V_(e)+`
37
+ `);return}}function B_(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(` - ${bf(s)}`)}else r!==null&&typeof r=="object"?t.push(`${n}: ${JSON.stringify(r)}`):t.push(`${n}: ${bf(r)}`);return t.join(`
38
+ `)}function bf(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 F_(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(`
39
+ `)}function V_(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(`
40
+ `)}var vf=require("child_process");function Tc(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 q_(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(`
41
+ `)}function Gs(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 wf(e,t){let n=Gs(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 Sf(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 xf(e,t=process.platform){let n=Gs(e);return n?Sf(n,t):null}function _f(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function Wr(e,t={}){let n=t.log??(l=>console.log(l)),r=t.env??process.env,s=t.platform??process.platform,o=Gs(e),i=t.spawn??((l,u,d)=>{(0,vf.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 q_(o??e).split(`
42
+ `))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=Tc(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=Sf(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?_f(n,d):(n(" Opened browser. Waiting for you to sign in..."),n("")),l()};try{i(c.cmd,c.args,u)}catch(d){_f(n,d instanceof Error?d:new Error(String(d))),l()}})}function K_(e){return new Promise(t=>setTimeout(t,e))}function Cf(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 Ef(e){return!Number.isFinite(e)||e===null||e<=0?1e3:Math.min(Math.max(Math.ceil(e),1e3),3e4)}async function G_(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=Cf(e.headers?.get("Retry-After"));if(r!==null)return n(Ef(r));if(typeof e.json=="function")try{let s=await e.json();return n(Ef(Cf(s?.retryAfter)))}catch{return n(1e3)}return n(1e3)}async function bn(e,t){let n=await G_(e);return t?.(n),await K_(n),n}var qf=A(require("crypto")),Kf=require("child_process"),Se=A(require("fs")),Gf=A(require("os")),De=A(require("path"));var J=A(require("fs")),Qn=A(require("os")),Q=A(require("path")),$f=require("child_process"),Pc=require("crypto");var Jr=A(require("fs")),li=A(require("tty"));function kf(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 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 Af(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 W_=80,Y_="/dev/tty";function J_(e=Y_){if(process.platform==="win32")return null;let t,n;try{t=Jr.openSync(e,"r"),n=Jr.openSync(e,"w");let r=new li.ReadStream(t),s=new li.WriteStream(n);return{stdin:r,stdout:s,close:()=>{try{r.destroy?.()}catch{}try{s.destroy?.()}catch{}}}}catch{try{t!==void 0&&Jr.closeSync(t)}catch{}try{n!==void 0&&Jr.closeSync(n)}catch{}return null}}function z_(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??J_)(e.ttyPath);return o?.stdout.isTTY&&o.stdin.isTTY&&typeof o.stdin.setRawMode=="function"?o:(o?.close?.(),null)}async function X_(e={}){let t=z_(e);if(!t)return null;let{stdin:n,stdout:r}=t,s=e.timeoutMs??W_,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 _=Af(l),I=l.includes("\x07")||l.includes("\x1B\\");_!==null&&I&&m(_>.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=Af(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 Xn,Ws;function Z_(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 ui(e=process.env){return Xn!==void 0||(Xn=Z_(e)),Xn}function Pe(e=process.env){if(Ws!==void 0)return Ws;let t=ui(e),n=kf(e);return Ws=Tf(t==="light"?"light":"dark",n),Ws}function di(e=process.env){return ui(e)==="no-color"}async function Rc(e={}){if(Xn!==void 0)return Xn;let t=e.env??process.env;if((t.NO_COLOR??"")!=="")return Yr("no-color",t);let n=(t.VISA_CLI_HUD_THEME??"").toLowerCase().trim();if(n==="light")return Yr("light",t);if(n==="dark")return Yr("dark",t);let r=Rf(t.COLORFGBG);if(r)return Yr(r,t);let s=await X_(e);return Yr(s||"dark",t)}function Yr(e,t){Xn=e;let n=kf(t);return Ws=Tf(e==="light"?"light":"dark",n),e}var Q_=2,fi="# >>> visa-cli shell hud v2 >>>",mi="# <<< visa-cli shell hud v2 <<<",e0="# >>> visa-cli shell hud >>>",t0="# <<< visa-cli shell hud <<<",Nf=3e4,n0=6e4,r0="VISA | HUD not ready \u2014 run: visa-cli config hud doctor",s0={currentVersion:"0.0.0"},o0=15e3;function $c(){try{return Q.join(Mc(),".visa-cli")}catch{return Q.join(Qn.tmpdir(),".visa-cli")}}function _n(){return Q.join($c(),"shell-hud.json")}function Ys(){return Q.join($c(),"shell-hud.line")}function Of(){return Q.join($c(),"shell-hud.lock")}function Zr(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 Js(e){let t=Mc();if(e==="zsh")return Q.join(t,".zshrc");if(e==="bash")return Q.join(t,".bashrc");let n=(process.platform==="win32","PowerShell");return Q.join(t,"Documents",n,"Microsoft.PowerShell_profile.ps1")}function Mf(e,t){let n=t??Mc(),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 i0(e){let t="$HOME/.visa-cli/shell-hud.line",n=C0(e),r=E0(e);if(e==="zsh")return`${fi}
43
43
  _visa_cli_shell_hud_precmd() {
44
44
  setopt localoptions no_bg_nice
45
45
  if [[ -f "${t}" ]]; then
@@ -56,7 +56,7 @@ autoload -Uz add-zsh-hook
56
56
  if [[ -z "\${precmd_functions[(r)_visa_cli_shell_hud_precmd]}" ]]; then
57
57
  add-zsh-hook precmd _visa_cli_shell_hud_precmd
58
58
  fi
59
- ${di}`;if(e==="powershell"){let s="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${ui}
59
+ ${mi}`;if(e==="powershell"){let s="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${fi}
60
60
  if (-not (Test-Path Function:\\global:__visa_cli_original_prompt)) {
61
61
  $function:global:__visa_cli_original_prompt = if (Test-Path Function:\\prompt) { $function:prompt } else { { '' } }
62
62
  }
@@ -75,7 +75,7 @@ function global:prompt {
75
75
  }
76
76
  & $function:global:__visa_cli_original_prompt
77
77
  }
78
- ${di}`}return`${ui}
78
+ ${mi}`}return`${fi}
79
79
  __visa_cli_shell_hud_precmd() {
80
80
  if [ -f "${t}" ]; then
81
81
  cat "${t}"
@@ -92,62 +92,62 @@ case ";$PROMPT_COMMAND;" in
92
92
  *";__visa_cli_shell_hud_precmd;"*) ;;
93
93
  *) PROMPT_COMMAND="__visa_cli_shell_hud_precmd\${PROMPT_COMMAND:+;$PROMPT_COMMAND}" ;;
94
94
  esac
95
- ${di}`}function Q_(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 e0(e,t,n){let r=new RegExp(`(^|\\n)([ \\t]*${Af(t)}[ \\t]*\\r?\\n)([\\s\\S]*?)(\\r?\\n[ \\t]*${Af(n)}[ \\t]*)(?=\\r?\\n|$)(\\r?\\n)?`,"g");return e.replace(r,(s,o,i,a,c,l,u)=>{if(!Q_(a))return s;let d=u>0?e[u-1]:"";return o===`
95
+ ${mi}`}function a0(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 c0(e,t,n){let r=new RegExp(`(^|\\n)([ \\t]*${Pf(t)}[ \\t]*\\r?\\n)([\\s\\S]*?)(\\r?\\n[ \\t]*${Pf(n)}[ \\t]*)(?=\\r?\\n|$)(\\r?\\n)?`,"g");return e.replace(r,(s,o,i,a,c,l,u)=>{if(!a0(a))return s;let d=u>0?e[u-1]:"";return o===`
96
96
  `&&d!==`
97
97
  `?`
98
- `:""})}function Ys(e){let t=e;for(let[n,r]of[[ui,di],[G_,W_]])t=e0(t,n,r);return t.trimEnd()}function If(e){return Ys(e)!==e.trimEnd()}function t0(e,t){let n=Ys(e).trimEnd(),r=Z_(t);return n.length>0?`${n}
98
+ `:""})}function zs(e){let t=e;for(let[n,r]of[[fi,mi],[e0,t0]])t=c0(t,n,r);return t.trimEnd()}function Lf(e){return zs(e)!==e.trimEnd()}function l0(e,t){let n=zs(e).trimEnd(),r=i0(t);return n.length>0?`${n}
99
99
 
100
100
  ${r}
101
101
  `:`${r}
102
- `}function fi(e=zr()){if(!e)return!1;try{let t=Ws(e),n=J.readFileSync(t,"utf-8");return If(n)}catch{return!1}}function Zn(e=Xn.homedir()){let t=[],n=n0(e);for(let r of n)try{if(!J.existsSync(r))continue;let s=J.readFileSync(r,"utf-8");If(s)&&t.push(r)}catch{}return t}function n0(e){return Rf(null,e).map(t=>t.rcPath)}function mi(e=zr()){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=Ws(e);let n=J.existsSync(t)?J.readFileSync(t,"utf-8"):"",r=t0(n,e),s=r!==n;return s&&Jr(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}: ${kc(n)}`}}}function Ht(e=zr(),t){let n=[],r=[],s=[];try{for(let o of Rf(e,t))if(r.push(o.rcPath),!!J.existsSync(o.rcPath))try{let i=J.readFileSync(o.rcPath,"utf-8"),a=Ys(i);if(a===i.trimEnd())continue;Jr(o.rcPath,a.length>0?`${a}
103
- `:""),n.push(o.rcPath)}catch(i){s.push(`${o.rcPath}: ${kc(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: ${kc(o)}`}}}function Ic(e,t){let n=t??z_,r=n.currentVersion==="0.0.0"&&e.version?e.version:n.currentVersion,s=_n(r),o=` ${te("\u2502",ee.chrome)} `,i=Pf(n),a=a0(n,i),c=n.updateCheckDisabled?"":i,l=i0(s,c);if(!e.enrolled)return[l,te("setup needed",ee.visaGold),a].filter(Boolean).join(o);let u=g0(e),d=o0(e),f=_n(Xn.hostname().split(".")[0]),m=[l,f?te(f,ee.muted):"",te(u,ee.visaGold),a].filter(Boolean).join(o),p=[d,r0(e)].filter(Boolean),h=p.length>0?p.join(o):"";return h?`${m}
104
- ${h}`:m}function r0(e){let t=` ${te("\u2502",ee.chrome)} `,n=[];if(typeof e.spentToday=="number"&&Number.isFinite(e.spentToday)&&n.push(te(`spent today ${Yr(Math.max(0,e.spentToday))}`,ee.muted)),e.lastService&&typeof e.lastService.toolName=="string"&&e.lastService.toolName.length>0){let r=p0(_n(e.lastService.toolName)),s=s0(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 s0(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 o0(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`${m0(l)} ${te(`${Yr(a/100)} in session`,ee.green)} ${te(`(${Yr(c/100)}/${Yr(i/100)} cap)`,ee.muted)} ${te("\xB7",ee.chrome)} ${te(`${Yr(r)} balance`,ee.muted)}`}let s=10,o=`balance ${Yr(r)}`;return t>=s?te(o,ee.green):te(`${o} \u2014 top up via buy_credits`,ee.visaGold)}function i0(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 a0(e,t){return t&&!e.updateCheckDisabled?te("run: visa-cli update",ee.visaGold):t?null:c0(e)}function Pf(e){return e.latestVersion?_n(e.latestVersion):""}function c0(e){let t=Pf(e);return t?te(`update ready v${t}`,ee.visaGold):null}function $f(){let e=Js();return!(!e||Date.now()-e.renderedAt>kf||e.cwd&&e.cwd!==process.cwd())}function pi(){let e=Js(),t=Date.now();if(e&&t-e.renderedAt<=kf||(u0(),e?.line))return Cf(e.line,e,t);try{let n=Gs();if(J.existsSync(n)){let r=J.readFileSync(n,"utf-8").trimEnd();if(r&&!gi(r))return r}}catch{}return J_}function Cf(e,t,n){let r=n-t.renderedAt,s=typeof t.refreshFailedAt=="number"&&t.refreshFailedAt>t.renderedAt,o=[];if(r>=Y_&&o.push(`stale ${l0(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(`
102
+ `}function pi(e=Zr()){if(!e)return!1;try{let t=Js(e),n=J.readFileSync(t,"utf-8");return Lf(n)}catch{return!1}}function er(e=Qn.homedir()){let t=[],n=u0(e);for(let r of n)try{if(!J.existsSync(r))continue;let s=J.readFileSync(r,"utf-8");Lf(s)&&t.push(r)}catch{}return t}function u0(e){return Mf(null,e).map(t=>t.rcPath)}function gi(e=Zr()){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=Js(e);let n=J.existsSync(t)?J.readFileSync(t,"utf-8"):"",r=l0(n,e),s=r!==n;return s&&Xr(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}: ${Ic(n)}`}}}function Bt(e=Zr(),t){let n=[],r=[],s=[];try{for(let o of Mf(e,t))if(r.push(o.rcPath),!!J.existsSync(o.rcPath))try{let i=J.readFileSync(o.rcPath,"utf-8"),a=zs(i);if(a===i.trimEnd())continue;Xr(o.rcPath,a.length>0?`${a}
103
+ `:""),n.push(o.rcPath)}catch(i){s.push(`${o.rcPath}: ${Ic(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: ${Ic(o)}`}}}function Nc(e,t){let n=t??s0,r=n.currentVersion==="0.0.0"&&e.version?e.version:n.currentVersion,s=vn(r),o=` ${te("\u2502",ee.chrome)} `,i=Uf(n),a=g0(n,i),c=n.updateCheckDisabled?"":i,l=p0(s,c);if(!e.enrolled)return[l,te("setup needed",ee.visaGold),a].filter(Boolean).join(o);let u=x0(e),d=m0(e),f=vn(Qn.hostname().split(".")[0]),m=[l,f?te(f,ee.muted):"",te(u,ee.visaGold),a].filter(Boolean).join(o),p=[d,d0(e)].filter(Boolean),h=p.length>0?p.join(o):"";return h?`${m}
104
+ ${h}`:m}function d0(e){let t=` ${te("\u2502",ee.chrome)} `,n=[];if(typeof e.spentToday=="number"&&Number.isFinite(e.spentToday)&&n.push(te(`spent today ${zr(Math.max(0,e.spentToday))}`,ee.muted)),e.lastService&&typeof e.lastService.toolName=="string"&&e.lastService.toolName.length>0){let r=S0(vn(e.lastService.toolName)),s=f0(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 f0(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 m0(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`${w0(l)} ${te(`${zr(a/100)} in session`,ee.green)} ${te(`(${zr(c/100)}/${zr(i/100)} cap)`,ee.muted)} ${te("\xB7",ee.chrome)} ${te(`${zr(r)} balance`,ee.muted)}`}let s=10,o=`balance ${zr(r)}`;return t>=s?te(o,ee.green):te(`${o} \u2014 top up via buy_credits`,ee.visaGold)}function p0(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 g0(e,t){return t&&!e.updateCheckDisabled?te("run: visa-cli update",ee.visaGold):t?null:h0(e)}function Uf(e){return e.latestVersion?vn(e.latestVersion):""}function h0(e){let t=Uf(e);return t?te(`update ready v${t}`,ee.visaGold):null}function Df(){let e=Xs();return!(!e||Date.now()-e.renderedAt>Nf||e.cwd&&e.cwd!==process.cwd())}function hi(){let e=Xs(),t=Date.now();if(e&&t-e.renderedAt<=Nf||(b0(),e?.line))return If(e.line,e,t);try{let n=Ys();if(J.existsSync(n)){let r=J.readFileSync(n,"utf-8").trimEnd();if(r&&!yi(r))return r}}catch{}return r0}function If(e,t,n){let r=n-t.renderedAt,s=typeof t.refreshFailedAt=="number"&&t.refreshFailedAt>t.renderedAt,o=[];if(r>=n0&&o.push(`stale ${y0(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(`
105
105
  `);for(let c=a.length-1;c>=0;c--)if(a[c].length>0)return a[c]=`${a[c]}${i}`,a.join(`
106
- `);return`${e}${i}`}function l0(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 Pc(e,t){try{let n=Q.dirname(bn());J.mkdirSync(n,{recursive:!0});let r=e.split(`
107
- `).map(o=>f0(o)).filter(o=>o.length>0).join(`
108
- `),s={hudVersion:K_,renderedAt:Date.now(),line:r,cwd:process.cwd(),status:t};Jr(bn(),JSON.stringify(s)+`
109
- `),Jr(Gs(),r+`
110
- `)}catch{}}function Nf(e){try{let t=Js();if(!t)return;let n=Math.max(Date.now(),t.renderedAt+1),r={...t,refreshFailedAt:n,refreshErrorReason:_n(e).slice(0,200)};Jr(bn(),JSON.stringify(r)+`
111
- `)}catch{}}function Of(){try{let e=Js();if(!e)return;let t={...e,renderedAt:0};Jr(bn(),JSON.stringify(t)+`
112
- `)}catch{}}function zn(){try{J.unlinkSync(Tf())}catch{}}function Js(){let e=bn();if(!J.existsSync(e))return null;try{let t=JSON.parse(J.readFileSync(e,"utf-8"));return typeof t?.line=="string"&&gi(t.line)?null:t}catch{return null}}function gi(e){for(let t of e.split(`
113
- `)){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 Mf(){return Js()?.status??null}function u0(){if(process.env.JEST_WORKER_ID)return;let e=Tf();try{if(J.mkdirSync(Q.dirname(e),{recursive:!0}),!b0(e))return;let t=process.argv[1]?Q.resolve(process.argv[1]):"";if(!t){zn();return}let n=ci(),r=(process.env.VISA_CLI_HUD_THEME??"").toLowerCase().trim(),s=n==="no-color"||r==="light"||r==="dark"?{}:{VISA_CLI_HUD_THEME:n},o=(0,Ef.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 d0=/^\u001B\[(?:0|38;2;\d{1,3};\d{1,3};\d{1,3}|38;5;\d{1,3})m$/;function f0(e){let t=[],n=`__VISA_CLI_HUD_SGR_${(0,Tc.randomBytes)(8).toString("hex")}_`,r=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,o=>{if(!d0.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 m0(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 Yr(e){return`$${e.toFixed(2)}`}function p0(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 g0(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 Pe().reset},get visaBlue(){return Pe().visaBlue},get visaBlueSoft(){return Pe().visaBlueSoft},get visaGold(){return Pe().visaGold},get green(){return Pe().green},get muted(){return Pe().muted},get chrome(){return Pe().chrome}};function te(e,t){return e.length===0||process.env.NO_COLOR||li()?e:`${t}${e}${ee.reset}`}function Af(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $c(){let e=Xn.homedir();if(!e||!Q.isAbsolute(e))throw new Error("unable to determine a valid home directory");return Q.resolve(e)}function h0(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function y0(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function b0(e){for(let t=0;t<2;t+=1){let n;try{return n=J.openSync(e,"wx"),J.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=J.statSync(e);if(Date.now()-s.mtimeMs<=X_)return!1;J.unlinkSync(e)}catch{}}finally{n!==void 0&&J.closeSync(n)}}return!1}function kc(e){return e instanceof Error?e.message:"unknown file system error"}function Jr(e,t){J.mkdirSync(Q.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${(0,Tc.randomBytes)(8).toString("hex")}.tmp`;try{J.writeFileSync(n,t),J.renameSync(n,e)}catch(r){try{J.unlinkSync(n)}catch{}throw r}}var _0=1440*60*1e3;function yi(e,t){Se.mkdirSync(De.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Df.randomBytes(8).toString("hex")}.tmp`;try{Se.writeFileSync(n,JSON.stringify(t,null,2)+`
114
- `),Se.renameSync(n,e)}catch(r){try{Se.unlinkSync(n)}catch{}throw r}}function Lf(e){return`'${e.replace(/'/g,"'\\''")}'`}var Oc="# visa-cli-hud-v1";function bi(e,t){if(!e&&!t&&v0())return`visa-cli config statusline ${Oc}`;let n=e??process.execPath,r=t??process.argv[1]??"",s=r?De.resolve(r):"";return`${s?`${Lf(n)} ${Lf(s)} config statusline`:"visa-cli config statusline"} ${Oc}`}function v0(){try{return(0,jf.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function vn(e){return typeof e!="string"?!1:e.includes(Oc)?!0:e.includes("visa-cli")&&e.includes("statusline")}function w0(){return"4.0.0-rc.20"}function _i(e){let t=De.dirname(De.resolve(e));return De.basename(t)===".claude"?De.dirname(t):Bf.homedir()}function hi(e,t){let n=De.relative(t,e);return!n.startsWith("..")&&!De.isAbsolute(n)?`~/${n}`:e}function S0(e){return De.join(_i(e),".visa-cli","hud-self-heal.json")}function x0(e,t,n,r){try{if(!Se.existsSync(e))return!1;let s=JSON.parse(Se.readFileSync(e,"utf-8"));return s.version===t&&typeof s.checkedAt=="number"&&n-s.checkedAt<r}catch{return!1}}function Nc(e,t,n){try{yi(e,{version:t,checkedAt:n})}catch{}}function C0(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function Mc(e,t={}){let n=t.now??Date.now(),r=t.version??w0(),s=t.stampPath??S0(e),o=t.minIntervalMs??_0,i=[],a=!1,c=!1;if(!t.force&&x0(s,r,n,o))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:i,skippedReason:"recently checked"};try{if(!Se.existsSync(e))return Nc(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let l=JSON.parse(Se.readFileSync(e,"utf-8")),u=l.statusLine,d=u&&typeof u=="object"&&!Array.isArray(u)?u.command:"";if(!vn(d))return Nc(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let f=(t.getCommand??bi)();if(d!==f&&(l.statusLine=C0(u,f),yi(e,l),a=!0,i.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!vi()){let m=_i(e);if(Zn(m).length>0){let h=Ht(null,m);if(h.removed&&h.rcPaths&&h.rcPaths.length>0){let v=h.rcPaths.map(I=>hi(I,m)).join(", ");c=!0,i.push(`Cleaned legacy shell-prompt HUD block from ${v}.`)}}}return Nc(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
115
- `)}catch{}}return{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i}}}function A0(e,t){let n=_i(t),r=Zn(n);if(r.length===0)return e;let s=r.map(o=>hi(o,n)).join(", ");return`${e}
116
- Note: a shell-prompt HUD block was detected in ${s}. If it is unintended, remove it with: visa-cli config hud disable shell`}function vi(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 Uf(e,t){let n=_i(t),r=Zn(n);if(r.length===0)return e;let s=r.map(i=>hi(i,n)).join(", ");if(vi())return`${e}
117
- 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=Ht(null,n);if(o.removed&&o.rcPaths&&o.rcPaths.length>0){let i=o.rcPaths.map(a=>hi(a,n)).join(", ");return`${e}
106
+ `);return`${e}${i}`}function y0(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 Oc(e,t){try{let n=Q.dirname(_n());J.mkdirSync(n,{recursive:!0});let r=e.split(`
107
+ `).map(o=>v0(o)).filter(o=>o.length>0).join(`
108
+ `),s={hudVersion:Q_,renderedAt:Date.now(),line:r,cwd:process.cwd(),status:t};Xr(_n(),JSON.stringify(s)+`
109
+ `),Xr(Ys(),r+`
110
+ `)}catch{}}function jf(e){try{let t=Xs();if(!t)return;let n=Math.max(Date.now(),t.renderedAt+1),r={...t,refreshFailedAt:n,refreshErrorReason:vn(e).slice(0,200)};Xr(_n(),JSON.stringify(r)+`
111
+ `)}catch{}}function Hf(){try{let e=Xs();if(!e)return;let t={...e,renderedAt:0};Xr(_n(),JSON.stringify(t)+`
112
+ `)}catch{}}function Zn(){try{J.unlinkSync(Of())}catch{}}function Xs(){let e=_n();if(!J.existsSync(e))return null;try{let t=JSON.parse(J.readFileSync(e,"utf-8"));return typeof t?.line=="string"&&yi(t.line)?null:t}catch{return null}}function yi(e){for(let t of e.split(`
113
+ `)){let n=t.trim();if(n.length===0)continue;let r=n.replace(/\[[0-?]*[ -/]*[@-~]/g,"").trim();if(/^VISA\s*\|\s*loading\b/i.test(r)||/^VISA\s*\|\s*HUD\s+not\s+(ready|initialized)\b/i.test(r))return!0}return!1}function Bf(){return Xs()?.status??null}function b0(){if(process.env.JEST_WORKER_ID)return;let e=Of();try{if(J.mkdirSync(Q.dirname(e),{recursive:!0}),!A0(e))return;let t=process.argv[1]?Q.resolve(process.argv[1]):"";if(!t){Zn();return}let n=ui(),r=(process.env.VISA_CLI_HUD_THEME??"").toLowerCase().trim(),s=n==="no-color"||r==="light"||r==="dark"?{}:{VISA_CLI_HUD_THEME:n},o=(0,$f.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 vn(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 _0=/^\u001B\[(?:0|38;2;\d{1,3};\d{1,3};\d{1,3}|38;5;\d{1,3})m$/;function v0(e){let t=[],n=`__VISA_CLI_HUD_SGR_${(0,Pc.randomBytes)(8).toString("hex")}_`,r=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,o=>{if(!_0.test(o))return"";let i=`${n}${t.length}__`;return t.push(o),i}),s=new RegExp(`${n}(\\d+)__`,"g");return vn(r).replace(s,(o,i)=>t[Number(i)]??"")}function w0(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 zr(e){return`$${e.toFixed(2)}`}function S0(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 x0(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=vn(n.toUpperCase()),o=vn(r);return`${t.isDefault?"default":"active"} ${s} ****${o}`}var ee={get reset(){return Pe().reset},get visaBlue(){return Pe().visaBlue},get visaBlueSoft(){return Pe().visaBlueSoft},get visaGold(){return Pe().visaGold},get green(){return Pe().green},get muted(){return Pe().muted},get chrome(){return Pe().chrome}};function te(e,t){return e.length===0||process.env.NO_COLOR||di()?e:`${t}${e}${ee.reset}`}function Pf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Mc(){let e=Qn.homedir();if(!e||!Q.isAbsolute(e))throw new Error("unable to determine a valid home directory");return Q.resolve(e)}function C0(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function E0(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function A0(e){for(let t=0;t<2;t+=1){let n;try{return n=J.openSync(e,"wx"),J.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=J.statSync(e);if(Date.now()-s.mtimeMs<=o0)return!1;J.unlinkSync(e)}catch{}}finally{n!==void 0&&J.closeSync(n)}}return!1}function Ic(e){return e instanceof Error?e.message:"unknown file system error"}function Xr(e,t){J.mkdirSync(Q.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${(0,Pc.randomBytes)(8).toString("hex")}.tmp`;try{J.writeFileSync(n,t),J.renameSync(n,e)}catch(r){try{J.unlinkSync(n)}catch{}throw r}}var k0=1440*60*1e3;function _i(e,t){Se.mkdirSync(De.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${qf.randomBytes(8).toString("hex")}.tmp`;try{Se.writeFileSync(n,JSON.stringify(t,null,2)+`
114
+ `),Se.renameSync(n,e)}catch(r){try{Se.unlinkSync(n)}catch{}throw r}}function Ff(e){return`'${e.replace(/'/g,"'\\''")}'`}var Uc="# visa-cli-hud-v1";function vi(e,t){if(!e&&!t&&T0())return`visa-cli config statusline ${Uc}`;let n=e??process.execPath,r=t??process.argv[1]??"",s=r?De.resolve(r):"";return`${s?`${Ff(n)} ${Ff(s)} config statusline`:"visa-cli config statusline"} ${Uc}`}function T0(){try{return(0,Kf.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function wn(e){return typeof e!="string"?!1:e.includes(Uc)?!0:e.includes("visa-cli")&&e.includes("statusline")}function R0(){return"4.0.0-rc.21"}function wi(e){let t=De.dirname(De.resolve(e));return De.basename(t)===".claude"?De.dirname(t):Gf.homedir()}function bi(e,t){let n=De.relative(t,e);return!n.startsWith("..")&&!De.isAbsolute(n)?`~/${n}`:e}function I0(e){return De.join(wi(e),".visa-cli","hud-self-heal.json")}function P0(e,t,n,r){try{if(!Se.existsSync(e))return!1;let s=JSON.parse(Se.readFileSync(e,"utf-8"));return s.version===t&&typeof s.checkedAt=="number"&&n-s.checkedAt<r}catch{return!1}}function Lc(e,t,n){try{_i(e,{version:t,checkedAt:n})}catch{}}function $0(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function Dc(e,t={}){let n=t.now??Date.now(),r=t.version??R0(),s=t.stampPath??I0(e),o=t.minIntervalMs??k0,i=[],a=!1,c=!1;if(!t.force&&P0(s,r,n,o))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:i,skippedReason:"recently checked"};try{if(!Se.existsSync(e))return Lc(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let l=JSON.parse(Se.readFileSync(e,"utf-8")),u=l.statusLine,d=u&&typeof u=="object"&&!Array.isArray(u)?u.command:"";if(!wn(d))return Lc(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let f=(t.getCommand??vi)();if(d!==f&&(l.statusLine=$0(u,f),_i(e,l),a=!0,i.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!Si()){let m=wi(e);if(er(m).length>0){let h=Bt(null,m);if(h.removed&&h.rcPaths&&h.rcPaths.length>0){let _=h.rcPaths.map(I=>bi(I,m)).join(", ");c=!0,i.push(`Cleaned legacy shell-prompt HUD block from ${_}.`)}}}return Lc(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
115
+ `)}catch{}}return{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i}}}function N0(e,t){let n=wi(t),r=er(n);if(r.length===0)return e;let s=r.map(o=>bi(o,n)).join(", ");return`${e}
116
+ Note: a shell-prompt HUD block was detected in ${s}. If it is unintended, remove it with: visa-cli config hud disable shell`}function Si(e=process.env.VISA_HUD_KEEP_SHELL){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function Vf(e,t){let n=wi(t),r=er(n);if(r.length===0)return e;let s=r.map(i=>bi(i,n)).join(", ");if(Si())return`${e}
117
+ 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=>bi(a,n)).join(", ");return`${e}
118
118
  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}
119
- Note: a legacy shell-prompt HUD block was detected in ${s} but could not be auto-removed (${o.message}). Remove it manually with: visa-cli config hud disable shell`}function zs(e,t=bi){let n={},r=!1;if(Se.existsSync(e)){r=!0;try{n=JSON.parse(Se.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 vn(s)?{installed:"already-visa",message:Uf("Visa HUD already registered in ~/.claude/settings.json.",e)}:{installed:"other-hud-present",message:A0("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()},yi(e,n),{installed:"new",message:Uf(`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 Lc(e){if(!Se.existsSync(e))return{removed:!1,status:"missing-settings",message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(Se.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(!vn(n))return{removed:!1,status:"foreign-statusline",message:"statusLine is owned by another tool \u2014 leaving it alone."};delete t.statusLine;try{yi(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 Hf=k(require("os")),Ff=k(require("path"));function Ft(e=Hf.homedir()){return Ff.join(e,".claude","settings.json")}var Vt=k(require("fs")),_t=k(require("path"));var E0=1,Qn={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},k0=["terminal","claude","claude-code","all"];function Si(e){let t=e.toLowerCase();return k0.includes(t)?t:null}var T0=50,R0=64*1024,Vf=10,Uc=80,M={get reset(){return Pe().reset},get visaBlue(){return Pe().visaBlue},get visaBlueSoft(){return Pe().visaBlueSoft},get visaGold(){return Pe().visaGold},get green(){return Pe().green},get muted(){return Pe().muted},get chrome(){return Pe().chrome}};function L(e,t){return e.length===0||process.env.NO_COLOR||li()?e:`${t}${e}${M.reset}`}function qf(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function Yf(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)},T0);e.on("data",i),e.on("end",a),e.on("error",c)})}function Xs(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 I0(e){if(sm(e))return $0(e);let t=` ${L("\u2502",M.chrome)} `,n=wi(e)||"claude",r=e.cwd?he(_t.basename(e.cwd)):"",s=xi(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=he(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,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,b;if(u>0||d!==null){let E=`${String(Math.round(v*100)).padStart(2," ")}%`,y=u>0?` ${L(`(${Zs(I)}/${Zs(u)})`,M.muted)}`:"";b=`${L("Context",M.muted)} ${Xs(v)} ${L(E,M.green)}${y}`}else b=`${L("Context",M.muted)} ${L("-",M.muted)}`;let _=Jf(e.rate_limits),w=[b];_&&w.push(_);let R=w.join(t);return`${l}
120
- ${R}`}function P0(e){if(sm(e))return null;let t=` ${L("\u2502",M.chrome)} `,n=wi(e)||"claude",r=e.cwd?he(_t.basename(e.cwd)):"",s=xi(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=he(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,R)=>w+R,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," ")}%`,R=l>0?` ${L(`(${Zs(v)}/${Zs(l)})`,M.muted)}`:"";I=`${L("Context",M.muted)} ${Xs(h)} ${L(w,M.green)}${R}`}else I=`${L("Context",M.muted)} ${L("-",M.muted)}`;let b=Jf(e.rate_limits),_=[I];return b&&_.push(b),{identity:a.join(t),metrics:_.join(t)}}function $0(e){let t=` ${L("\u2502",M.chrome)} `,n=om(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)} ${Xs(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)} ${Xs(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}
121
- ${a}`}function N0(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 Kf(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=Xs(r),o=n>=90?"\x1B[38;5;196m":n>=70?M.visaGold:M.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=N0(e.resets_at),c=a?` ${L(`(${a} / ${t})`,M.muted)}`:` ${L(`(${t})`,M.muted)}`;return`${s} ${L(i,o)}${c}`}function Jf(e){if(!e)return null;let t=Kf(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?Kf(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 zf(e){let t;try{let n=Vt.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let s=Math.min(r,R0),o=r-s;t=Vt.openSync(e,"r");let i=Buffer.alloc(s);Vt.readSync(t,i,0,s,o);let a=i.toString("utf-8");if(o>0){let c=Buffer.alloc(1);if(Vt.readSync(t,c,0,1,o-1),c[0]!==10){let l=a.indexOf(`
122
- `);l>=0&&(a=a.slice(l+1))}}return a}catch{return null}finally{if(t!==void 0)try{Vt.closeSync(t)}catch{}}}function O0(e){if(!e||typeof e!="object")return;let t=e,n=["file_path","path","notebook_path","pattern","command","url"];for(let r of n){let s=t[r];if(typeof s=="string"&&s.length>0){if(r.endsWith("_path")||r==="path"){let o=_t.basename(_t.dirname(s)),i=_t.basename(s);return o&&o!=="."&&o!=="/"?`${o}/${i}`:i}return s}}}function M0(e){let t=e.split(`
123
- `),n=[],r=new Set;for(let s=t.length-1;s>=0&&n.length<Vf*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:O0(d.input),running:m})}}}return n.reverse(),n.slice(Math.max(0,n.length-Vf))}function L0(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 U0(e){let t=e.running?L("\u25D0",M.visaGold):L("\u2713",M.green),n=e.running?M.visaGold:M.visaBlueSoft,r=L(he(e.name),n),s=e.target?he(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 D0(e){let t=` ${L("\u2502",M.chrome)} `,n=qf(t),r=e.slice();for(;r.length>0;){let c=r.join(t);if(qf(c)<=Uc)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>Uc-n-1?i.slice(0,Uc-n-1)+s:i;return`${L(s,M.muted)}${t}${a}`}async function Gf(e){if(!e||typeof e!="string")return null;let t=zf(e);if(!t)return null;let n;try{n=M0(t)}catch{return null}if(n.length===0)return null;let s=L0(n).map(U0);return D0(s)||null}async function Xf(e,t,n){return(await Qf(e,t,n)).join(`
124
- `)}function Zf(e,t,n){let r=!!t?.activeSession||e.includes("in session"),s=n?B0(n):!1;return{isActive:r||s,hasSession:r,hasToolActivity:s}}async function Qf(e,t,n){let{isActive:r}=Zf(e,n,t?.transcript_path),s=e.split(`
125
- `).filter(a=>a.length>0),i=t&&!r?s.map(a=>L(Dc(a),M.muted)):[...s];if(t){let a=P0(t);if(a){if(i.push(a.identity),t.transcript_path){let c=await Gf(t.transcript_path);c&&i.push(...c.split(`
126
- `))}i.push(a.metrics)}else{let c=I0(t);if(c&&i.push(...c.split(`
127
- `)),t.transcript_path){let l=await Gf(t.transcript_path);l&&i.push(...l.split(`
128
- `))}}}return i}var j0=["generate_image","generate_video","generate_music","generate_audio","generate_3d","upscale_image","run_llm","transcribe_audio","pay","get_status","buy_credits","get_cards","add_card","set_session_mode","query_onchain_prices","allium_explorer"];function B0(e){let t=zf(e);if(!t)return!1;let n=t.slice(-16384).toLowerCase();return j0.some(r=>n.includes(`"${r}"`))}async function em(e,t,n){let r=await Qf(e,t,n),s=r.join(`
129
- `),{isActive:o}=Zf(e,n,t?.transcript_path);return{schemaVersion:E0,client:t?rm(t):Qn.UNKNOWN,rendered:s,lines:r.map(Dc),visa:{spendLine:Dc(e),balanceCents:n?.balanceCents,balanceMicros:n?.balanceMicros,balanceUsd:n?.amountUsd,sessionMode:n?.sessionMode,activeSession:n?.activeSession,isVisaActive:o},context:t?om(t):{}}}function he(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 xi(e){if(typeof e=="string")return he(_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 he(t?_t.basename(t):e.name)}function tm(e){return he(e.app_name??e.appName??e.app??e.client)}function wi(e){return he(e.model?.display_name??e.model?.id??e.model_name??e.modelName)}function nm(e){return he(e.cwd??e.current_dir??e.project_root)}function Wf(e){let t=he(e.project);if(t)return t;let n=nm(e);if(n)return he(_t.basename(n));let r=xi(e.workspace);return r||""}function ot(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function rm(e){let t=tm(e).toLowerCase();return t.includes("codex")?Qn.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?Qn.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||ot(e.context_used)!==void 0?Qn.CODEX:Qn.UNKNOWN}function sm(e){return rm(e)===Qn.CODEX}function om(e){let t=tm(e),n=nm(e),r=xi(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}:{},...wi(e)?{model:wi(e)}:{},...Wf(e)?{project:Wf(e)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...he(e.git_branch??e.branch)?{gitBranch:he(e.git_branch??e.branch)}:{},...he(e.status??e.run_state??e.runState)?{status:he(e.status??e.run_state??e.runState)}:{},...he(e.thread_title??e.threadTitle)?{threadTitle:he(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 Dc(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}var am=k(require("path"));function im(e){return e instanceof Error?e.message:String(e)}function jc(e,t){let n=[],r=[],s=e??"claude",o=Si(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: ${im(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=am.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: ${im(c)}`)}}return{ok:i,messages:n,errors:r}}function cm(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 lm=k(require("os")),um=require("node:readline/promises"),Qs={card:"default VISA ****7242",balance:"balance $6.38",spentToday:"spent today $0.62",lastActivity:"last Visa tool 38m",model:"Opus 4.6"};async function Bc(e,t=!1){if(!process.stdin.isTTY)return t;let n=t?"[Y/n]":"[y/N]",r,s;try{r=(0,um.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 H0(e,t){return e.replace(/[\x00-\x1F\x7F\u202A-\u202E\u2066-\u2069]/g,"").trim()||t}function dm(e=lm.hostname()){let t=Ds().version,n=H0(e,"this-machine");return[" Preview if installed (sample):",` VISA CLI v${t} | ${n} | ${Qs.card}`,` ${Qs.balance} | ${Qs.spentToday} | ${Qs.lastActivity}`,` [${Qs.model}] | you`," Activity live"].join(`
130
- `)}function fm(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 Hc(e){return`$${(e/100).toFixed(2)}`}function mm(e){return typeof e=="number"?Hc(e):"no cap"}function pm(e){return e.length>0?e.join(", "):"all tools"}var F0=[" \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 V0(){return[...fm(null),...F0].join(`
131
- `)}var gm="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 q0(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 hm(e,t={}){let n=t.authUrl??"https://auth.visacli.sh",r=[...V0().split(`
132
- `),"","Visa Key active","Scoped agent spend credential ready for apps and agents","",...q0([["Key",e.key],["Label",e.label],["Owner",e.owner],["Daily cap",`${Hc(e.daily_cap_cents)}/day`],["Total cap",mm(e.total_cap_cents)],["Allowed tools",pm(e.allowed_tools)]]),"","Guardrails",`- Spend: ${Hc(e.daily_cap_cents)}/day, ${mm(e.total_cap_cents)} total`,`- Tools: ${pm(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("",gm,`Server warning: ${e.biometric_warning}`):e.biometric_enabled&&r.push("",gm),`${r.join(`
119
+ Note: a legacy shell-prompt HUD block was detected in ${s} but could not be auto-removed (${o.message}). Remove it manually with: visa-cli config hud disable shell`}function Zs(e,t=vi){let n={},r=!1;if(Se.existsSync(e)){r=!0;try{n=JSON.parse(Se.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 wn(s)?{installed:"already-visa",message:Vf("Visa HUD already registered in ~/.claude/settings.json.",e)}:{installed:"other-hud-present",message:N0("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()},_i(e,n),{installed:"new",message:Vf(`Visa HUD registered in ~/.claude/settings.json${r?"":" (new file)"}. Restart Claude Code to see it pinned below the input.`,e)}}catch(s){return{installed:"error",message:`Failed to write settings: ${s.message}. Enable manually later with: visa-cli config hud enable claude`}}}function jc(e){if(!Se.existsSync(e))return{removed:!1,status:"missing-settings",message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(Se.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(!wn(n))return{removed:!1,status:"foreign-statusline",message:"statusLine is owned by another tool \u2014 leaving it alone."};delete t.statusLine;try{_i(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=A(require("os")),Yf=A(require("path"));function Ft(e=Wf.homedir()){return Yf.join(e,".claude","settings.json")}var Vt=A(require("fs")),_t=A(require("path"));var O0=1,tr={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},M0=["terminal","claude","claude-code","all"];function Ci(e){let t=e.toLowerCase();return M0.includes(t)?t:null}var L0=50,U0=64*1024,Jf=10,Hc=80,M={get reset(){return Pe().reset},get visaBlue(){return Pe().visaBlue},get visaBlueSoft(){return Pe().visaBlueSoft},get visaGold(){return Pe().visaGold},get green(){return Pe().green},get muted(){return Pe().muted},get chrome(){return Pe().chrome}};function L(e,t){return e.length===0||process.env.NO_COLOR||di()?e:`${t}${e}${M.reset}`}function zf(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function em(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)},L0);e.on("data",i),e.on("end",a),e.on("error",c)})}function Qs(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 eo(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 D0(e){if(um(e))return H0(e);let t=` ${L("\u2502",M.chrome)} `,n=xi(e)||"claude",r=e.cwd?he(_t.basename(e.cwd)):"",s=Ei(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=he(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(k=>typeof k=="number"&&Number.isFinite(k)),p=m.length>0?m.reduce((k,y)=>k+y,0):null,h=Number(e.context_window?.total_input_tokens??p??f?.input_tokens??0),_=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(_*u):h,b;if(u>0||d!==null){let k=`${String(Math.round(_*100)).padStart(2," ")}%`,y=u>0?` ${L(`(${eo(I)}/${eo(u)})`,M.muted)}`:"";b=`${L("Context",M.muted)} ${Qs(_)} ${L(k,M.green)}${y}`}else b=`${L("Context",M.muted)} ${L("-",M.muted)}`;let v=tm(e.rate_limits),w=[b];v&&w.push(v);let R=w.join(t);return`${l}
120
+ ${R}`}function j0(e){if(um(e))return null;let t=` ${L("\u2502",M.chrome)} `,n=xi(e)||"claude",r=e.cwd?he(_t.basename(e.cwd)):"",s=Ei(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=he(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,R)=>w+R,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,_=u!==null&&l>0?Math.round(h*l):p,I;if(l>0||u!==null){let w=`${String(Math.round(h*100)).padStart(2," ")}%`,R=l>0?` ${L(`(${eo(_)}/${eo(l)})`,M.muted)}`:"";I=`${L("Context",M.muted)} ${Qs(h)} ${L(w,M.green)}${R}`}else I=`${L("Context",M.muted)} ${L("-",M.muted)}`;let b=tm(e.rate_limits),v=[I];return b&&v.push(b),{identity:a.join(t),metrics:v.join(t)}}function H0(e){let t=` ${L("\u2502",M.chrome)} `,n=dm(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)} ${Qs(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)} ${Qs(l)} ${L(`${Math.round(c)}%`,M.green)}`)}typeof n.usedTokens=="number"&&i.push(`${L("Tokens",M.muted)} ${eo(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}
121
+ ${a}`}function B0(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 Xf(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=Qs(r),o=n>=90?"\x1B[38;5;196m":n>=70?M.visaGold:M.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=B0(e.resets_at),c=a?` ${L(`(${a} / ${t})`,M.muted)}`:` ${L(`(${t})`,M.muted)}`;return`${s} ${L(i,o)}${c}`}function tm(e){if(!e)return null;let t=Xf(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?Xf(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 nm(e){let t;try{let n=Vt.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let s=Math.min(r,U0),o=r-s;t=Vt.openSync(e,"r");let i=Buffer.alloc(s);Vt.readSync(t,i,0,s,o);let a=i.toString("utf-8");if(o>0){let c=Buffer.alloc(1);if(Vt.readSync(t,c,0,1,o-1),c[0]!==10){let l=a.indexOf(`
122
+ `);l>=0&&(a=a.slice(l+1))}}return a}catch{return null}finally{if(t!==void 0)try{Vt.closeSync(t)}catch{}}}function F0(e){if(!e||typeof e!="object")return;let t=e,n=["file_path","path","notebook_path","pattern","command","url"];for(let r of n){let s=t[r];if(typeof s=="string"&&s.length>0){if(r.endsWith("_path")||r==="path"){let o=_t.basename(_t.dirname(s)),i=_t.basename(s);return o&&o!=="."&&o!=="/"?`${o}/${i}`:i}return s}}}function V0(e){let t=e.split(`
123
+ `),n=[],r=new Set;for(let s=t.length-1;s>=0&&n.length<Jf*3;s-=1){let o=t[s].trim();if(!o)continue;let i;try{i=JSON.parse(o)}catch{continue}if(!i||typeof i!="object")continue;let c=i.message;if(!c||typeof c!="object")continue;let l=c.content;if(Array.isArray(l))for(let u of l){if(!u||typeof u!="object")continue;let d=u;if(d.type==="tool_result"&&typeof d.tool_use_id=="string")r.add(d.tool_use_id);else if(d.type==="tool_use"&&typeof d.name=="string"){let f=typeof d.id=="string"?d.id:"",m=f.length>0?!r.has(f):!1;n.push({name:d.name,target:F0(d.input),running:m})}}}return n.reverse(),n.slice(Math.max(0,n.length-Jf))}function q0(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 K0(e){let t=e.running?L("\u25D0",M.visaGold):L("\u2713",M.green),n=e.running?M.visaGold:M.visaBlueSoft,r=L(he(e.name),n),s=e.target?he(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 G0(e){let t=` ${L("\u2502",M.chrome)} `,n=zf(t),r=e.slice();for(;r.length>0;){let c=r.join(t);if(zf(c)<=Hc)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>Hc-n-1?i.slice(0,Hc-n-1)+s:i;return`${L(s,M.muted)}${t}${a}`}async function Zf(e){if(!e||typeof e!="string")return null;let t=nm(e);if(!t)return null;let n;try{n=V0(t)}catch{return null}if(n.length===0)return null;let s=q0(n).map(K0);return G0(s)||null}async function rm(e,t,n){return(await om(e,t,n)).join(`
124
+ `)}function sm(e,t,n){let r=!!t?.activeSession||e.includes("in session"),s=n?Y0(n):!1;return{isActive:r||s,hasSession:r,hasToolActivity:s}}async function om(e,t,n){let{isActive:r}=sm(e,n,t?.transcript_path),s=e.split(`
125
+ `).filter(a=>a.length>0),i=t&&!r?s.map(a=>L(Bc(a),M.muted)):[...s];if(t){let a=j0(t);if(a){if(i.push(a.identity),t.transcript_path){let c=await Zf(t.transcript_path);c&&i.push(...c.split(`
126
+ `))}i.push(a.metrics)}else{let c=D0(t);if(c&&i.push(...c.split(`
127
+ `)),t.transcript_path){let l=await Zf(t.transcript_path);l&&i.push(...l.split(`
128
+ `))}}}return i}var W0=["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 Y0(e){let t=nm(e);if(!t)return!1;let n=t.slice(-16384).toLowerCase();return W0.some(r=>n.includes(`"${r}"`))}async function im(e,t,n){let r=await om(e,t,n),s=r.join(`
129
+ `),{isActive:o}=sm(e,n,t?.transcript_path);return{schemaVersion:O0,client:t?lm(t):tr.UNKNOWN,rendered:s,lines:r.map(Bc),visa:{spendLine:Bc(e),balanceCents:n?.balanceCents,balanceMicros:n?.balanceMicros,balanceUsd:n?.amountUsd,sessionMode:n?.sessionMode,activeSession:n?.activeSession,isVisaActive:o},context:t?dm(t):{}}}function he(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 Ei(e){if(typeof e=="string")return he(_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 he(t?_t.basename(t):e.name)}function am(e){return he(e.app_name??e.appName??e.app??e.client)}function xi(e){return he(e.model?.display_name??e.model?.id??e.model_name??e.modelName)}function cm(e){return he(e.cwd??e.current_dir??e.project_root)}function Qf(e){let t=he(e.project);if(t)return t;let n=cm(e);if(n)return he(_t.basename(n));let r=Ei(e.workspace);return r||""}function ot(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function lm(e){let t=am(e).toLowerCase();return t.includes("codex")?tr.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?tr.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||ot(e.context_used)!==void 0?tr.CODEX:tr.UNKNOWN}function um(e){return lm(e)===tr.CODEX}function dm(e){let t=am(e),n=cm(e),r=Ei(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}:{},...xi(e)?{model:xi(e)}:{},...Qf(e)?{project:Qf(e)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...he(e.git_branch??e.branch)?{gitBranch:he(e.git_branch??e.branch)}:{},...he(e.status??e.run_state??e.runState)?{status:he(e.status??e.run_state??e.runState)}:{},...he(e.thread_title??e.threadTitle)?{threadTitle:he(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 Bc(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}var mm=A(require("path"));function fm(e){return e instanceof Error?e.message:String(e)}function Fc(e,t){let n=[],r=[],s=e??"claude",o=Ci(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: ${fm(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=mm.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: ${fm(c)}`)}}return{ok:i,messages:n,errors:r}}function pm(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 gm=A(require("os")),hm=require("node:readline/promises"),to={card:"default VISA ****7242",balance:"balance $6.38",spentToday:"spent today $0.62",lastActivity:"last Visa tool 38m",model:"Opus 4.6"};async function Vc(e,t=!1){if(!process.stdin.isTTY)return t;let n=t?"[Y/n]":"[y/N]",r,s;try{r=(0,hm.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 J0(e,t){return e.replace(/[\x00-\x1F\x7F\u202A-\u202E\u2066-\u2069]/g,"").trim()||t}function ym(e=gm.hostname()){let t=Hs().version,n=J0(e,"this-machine");return[" Preview if installed (sample):",` VISA CLI v${t} | ${n} | ${to.card}`,` ${to.balance} | ${to.spentToday} | ${to.lastActivity}`,` [${to.model}] | you`," Activity live"].join(`
130
+ `)}function bm(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 qc(e){return`$${(e/100).toFixed(2)}`}function _m(e){return typeof e=="number"?qc(e):"no cap"}function vm(e){return e.length>0?e.join(", "):"all tools"}var z0=[" \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 X0(){return[...bm(null),...z0].join(`
131
+ `)}var wm="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 Z0(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 Sm(e,t={}){let n=t.authUrl??"https://auth.visacli.sh",r=[...X0().split(`
132
+ `),"","Visa Key active","Scoped agent spend credential ready for apps and agents","",...Z0([["Key",e.key],["Label",e.label],["Owner",e.owner],["Daily cap",`${qc(e.daily_cap_cents)}/day`],["Total cap",_m(e.total_cap_cents)],["Allowed tools",vm(e.allowed_tools)]]),"","Guardrails",`- Spend: ${qc(e.daily_cap_cents)}/day, ${_m(e.total_cap_cents)} total`,`- Tools: ${vm(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("",wm,`Server warning: ${e.biometric_warning}`):e.biometric_enabled&&r.push("",wm),`${r.join(`
133
133
  `)}
134
- `}function ym(e){return e.json===!0||e.isTTY!==!0}function Fc(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 Vc(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 bm(e,t){let n=Fc(e);if(n!==void 0)return n;if(ym(t))return 500}function _m(e,t){let n=Vc(e);if(n!==void 0)return n;if(ym(t)||t.recommendedCapsAccepted===!0)return 2500}async function vt(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,s=setTimeout(()=>r.abort(),n);try{let{timeoutMs:o,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(s)}}var er=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},Xr=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}},qt=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}},wt=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}},ye=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 vm={ENOTFOUND:"Cannot resolve the Visa CLI server hostname (DNS error). Check your internet connection or the auth.serverUrl setting.",EAI_AGAIN:"DNS lookup for the Visa CLI server failed temporarily. Check your internet connection and try again.",ECONNREFUSED:"The Visa CLI server refused the connection. The service may be down \u2014 check https://visacli.sh for status.",ECONNRESET:"The connection to the Visa CLI server was reset mid-request. Try again in a moment.",EHOSTUNREACH:"The Visa CLI server is unreachable from this network. Check your internet connection.",ETIMEDOUT:"The connection to the Visa CLI server timed out. Try again or check https://visacli.sh for status.",CERT_HAS_EXPIRED:"The Visa CLI server's TLS certificate is expired. Check https://visacli.sh for status; do not bypass the cert.",UND_ERR_CONNECT_TIMEOUT:"The connection to the Visa CLI server timed out before it could be established. Try again in a moment.",UND_ERR_SOCKET:"The connection to the Visa CLI server was interrupted. Try again in a moment."};function Zr(e){let t=e&&typeof e=="object"?e:{};if(t.name==="AbortError"||typeof t.message=="string"&&t.message.includes("aborted"))return"The request timed out. The server may be under heavy load. Please try again.";let n=(t.cause&&typeof t.cause=="object"?t.cause.code:void 0)??(typeof t.code=="string"?t.code:void 0);return n&&vm[n]?vm[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.`}Kt();var J0=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function xm(e,t){let n=Sm(e),r=Sm(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:z0(n.pre,r.pre)>0}function Sm(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(J0);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function z0(e,t){let n=e.split("."),r=t.split("."),s=Math.max(n.length,r.length);for(let o=0;o<s;o++){if(o>=n.length)return-1;if(o>=r.length)return 1;let i=n[o],a=r[o],c=/^\d+$/.test(i),l=/^\d+$/.test(a);if(c&&l){let u=Number(i)-Number(a);if(u!==0)return u}else{if(c)return-1;if(l)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function St(){return!!(Cm(process.env.VISA_CLI_NO_UPDATE_CHECK)||Cm(process.env.CI)||process.env.NODE_ENV==="test")}function Cm(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}ct();var iv="CARD_REENROLLMENT_REQUIRED",av="https://auth.visacli.sh/enroll-card";function cv(){try{return new URL("/enroll-card",de()).toString()}catch{return av}}function lv(e){let t=cv();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 xn="4.0.0-rc.20",uv=/^(?:VisaKey_[A-Za-z0-9_-]{16,128}|visakey_[A-Za-z0-9_-]{16,128}|vk_[A-Za-z0-9_-]{32,128})$/;async function ro(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 so(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 dv(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 el(e){return e==="TOPUP_CHARGE_AMBIGUOUS"||e==="TOPUP_RECONCILIATION_REQUIRED"?e:null}var fv="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function Qr(e){return typeof e=="string"?e.trim():""}function oo(e){let t=e&&typeof e=="object"?e:{},n=Qr(t.error)||Qr(t.message);if(!n)return fv;let r=Qr(t.error_code),s=[["surface",Qr(t.disabled_surface)],["flag",Qr(t.flag)],["correlation_id",Qr(t.correlation_id)]].filter(([,i])=>i).map(([i,a])=>`${i}=${a}`),o=s.length?` (${s.join(" ")})`:"";return r?`503 [${r}] ${n}${o}`:`503 ${n}${o}`}function io(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?uv.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(`
135
- `)}var Ke=class{constructor(t){this.getSessionToken=t;this.baseUrl=de()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!St()){let r=t.headers.get("X-Latest-Version");r&&xm(r,xn)&&(this.lastSignals.updateAvailable={currentVersion:xn,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return xn}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new er(t.error||"Your biometric key is out of sync with the server.",typeof t.hint=="string"?t.hint:void 0)}async throwServerUnavailable(t){let n=null;try{n=await t.json()}catch{}throw new Error(oo(n))}async request(t,n,r,s,o,i){let a=await this.getSessionToken();if(!a)throw new Error(io());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 vt(`${this.baseUrl}${n}`,{method:t,headers:{...c,"X-Visa-CLI-Version":xn,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:s})}catch(d){throw new Error(Zr(d))}if(this.parseServerSignals(l),l.status===401)throw await ro(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===iv){let f=typeof u?.last4=="string"?u.last4:"",m=typeof u?.brand=="string"?u.brand:"card",p=lv(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=el(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 ye(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 so(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(io());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":xn,"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 vt(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(p){throw new Error(Zr(p))}if(this.parseServerSignals(d),d.status===401)throw await ro(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 qt(m?.message||m?.error||"Session budget is being modified by another request. Retry shortly.",v,d.status)}throw new Error(oo(m))}let p=dv(m?.error_code);if(p||d.status===410){let v=p??"BUDGET_CLOSED";throw new Xr(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 ye(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=el(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}):so(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(io());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":xn,"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 vt(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(p){throw new Error(Zr(p))}if(this.parseServerSignals(d),d.status===401)throw await ro(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 wt("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 wt(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 qt(m?.message||m?.error||"Session budget is being modified by another request. Retry shortly.",v,d.status)}throw new Error(oo(m))}if(m?.declined){let v=Number(m.retryAfter??d.headers.get("Retry-After"));throw new ye(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=el(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}):so(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(io());let s={Authorization:`Bearer ${r}`,"X-Visa-CLI-Version":xn,"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 vt(`${this.baseUrl}${n}`,{method:"POST",headers:s,body:JSON.stringify(o),timeoutMs:void 0})}catch(u){throw new Error(Zr(u))}if(this.parseServerSignals(i),i.status===401)throw await ro(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 wt("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 wt(a?.error||"Parentless batch is not enabled on this server.",{status:i.status,serverErrorCode:u});if(i.status===503)throw new Error(oo(a));if(a?.declined){let d=Number(a.retryAfter??i.headers.get("Retry-After"));throw new ye(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 so(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(io());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":xn,"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 vt(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(p){throw new Error(Zr(p))}if(this.parseServerSignals(d),d.status===401)throw await ro(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 qt(m?.message||m?.error||"Batch parent is being modified by another request. Retry shortly.",p,d.status)}throw new Error(oo(m))}if(m?.declined){let p=Number(m.retryAfter??d.headers.get("Retry-After"));throw new ye(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 so(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 vt(`${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 vt(`${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 ao(e,t){return t||(typeof e!="number"||!Number.isFinite(e)?"price unknown":`$${(e/100).toFixed(2)}`)}function Dm(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 Um(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function mv(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 pv(e){return Math.max(4,e.reduce((t,n)=>Math.max(t,n.id.length),0))}function gv(e){return Math.max(8,Math.min(14,e.reduce((t,n)=>Math.max(t,(n.category||"").length),0)))}function hv(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 jm(e){let t=pv(e),n=7,r=gv(e),s=hv(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)} ${ao(o.priceCents,o.priceDisplay).padEnd(n)} ${Um(o.category||"other",r).padEnd(r)} ${Um(Dm(o),s)}`)}function Bm(e){console.log(`
134
+ `}function xm(e){return e.json===!0||e.isTTY!==!0}function Kc(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 Gc(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 Cm(e,t){let n=Kc(e);if(n!==void 0)return n;if(xm(t))return 500}function Em(e,t){let n=Gc(e);if(n!==void 0)return n;if(xm(t)||t.recommendedCapsAccepted===!0)return 2500}async function vt(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 nr=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},Qr=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}},qt=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}},wt=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}},ye=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 Am={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 es(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&&Am[n]?Am[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.`}Kt();var rv=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Rm(e,t){let n=Tm(e),r=Tm(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:sv(n.pre,r.pre)>0}function Tm(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(rv);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function sv(e,t){let n=e.split("."),r=t.split("."),s=Math.max(n.length,r.length);for(let o=0;o<s;o++){if(o>=n.length)return-1;if(o>=r.length)return 1;let i=n[o],a=r[o],c=/^\d+$/.test(i),l=/^\d+$/.test(a);if(c&&l){let u=Number(i)-Number(a);if(u!==0)return u}else{if(c)return-1;if(l)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function St(){return!!(Im(process.env.VISA_CLI_NO_UPDATE_CHECK)||Im(process.env.CI)||process.env.NODE_ENV==="test")}function Im(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}ct();var pv="CARD_REENROLLMENT_REQUIRED",gv="https://auth.visacli.sh/enroll-card";function hv(){try{return new URL("/enroll-card",de()).toString()}catch{return gv}}function yv(e){let t=hv();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 En="4.0.0-rc.21",bv=/^(?:VisaKey_[A-Za-z0-9_-]{16,128}|visakey_[A-Za-z0-9_-]{16,128}|vk_[A-Za-z0-9_-]{32,128})$/;async function so(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 oo(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 _v(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 sl(e){return e==="TOPUP_CHARGE_AMBIGUOUS"||e==="TOPUP_RECONCILIATION_REQUIRED"?e:null}var vv="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function ts(e){return typeof e=="string"?e.trim():""}function io(e){let t=e&&typeof e=="object"?e:{},n=ts(t.error)||ts(t.message);if(!n)return vv;let r=ts(t.error_code),s=[["surface",ts(t.disabled_surface)],["flag",ts(t.flag)],["correlation_id",ts(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 ao(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?bv.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(`
135
+ `)}var Ke=class{constructor(t){this.getSessionToken=t;this.baseUrl=de()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!St()){let r=t.headers.get("X-Latest-Version");r&&Rm(r,En)&&(this.lastSignals.updateAvailable={currentVersion:En,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return En}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new nr(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(io(n))}async request(t,n,r,s,o,i){let a=await this.getSessionToken();if(!a)throw new Error(ao());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 vt(`${this.baseUrl}${n}`,{method:t,headers:{...c,"X-Visa-CLI-Version":En,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:s})}catch(d){throw new Error(es(d))}if(this.parseServerSignals(l),l.status===401)throw await so(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===pv){let f=typeof u?.last4=="string"?u.last4:"",m=typeof u?.brand=="string"?u.brand:"card",p=yv(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=sl(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 ye(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 oo(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(ao());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":En,"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 vt(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(p){throw new Error(es(p))}if(this.parseServerSignals(d),d.status===401)throw await so(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 _=Number(d.headers.get("Retry-After"))||1;throw new qt(m?.message||m?.error||"Session budget is being modified by another request. Retry shortly.",_,d.status)}throw new Error(io(m))}let p=_v(m?.error_code);if(p||d.status===410){let _=p??"BUDGET_CLOSED";throw new Qr(m?.message||m?.error||"Your session was invalidated by the server.",_,{budgetId:n.session_budget_id,status:d.status})}if(m?.declined){let _=Number(m.retryAfter??d.headers.get("Retry-After"));throw new ye(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite(_)&&_>0?_:void 0)}let h=sl(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}):oo(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(ao());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":En,"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 vt(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(p){throw new Error(es(p))}if(this.parseServerSignals(d),d.status===401)throw await so(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 wt("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 wt(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 _=Number(d.headers.get("Retry-After"))||1;throw new qt(m?.message||m?.error||"Session budget is being modified by another request. Retry shortly.",_,d.status)}throw new Error(io(m))}if(m?.declined){let _=Number(m.retryAfter??d.headers.get("Retry-After"));throw new ye(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite(_)&&_>0?_:void 0)}let h=sl(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}):oo(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(ao());let s={Authorization:`Bearer ${r}`,"X-Visa-CLI-Version":En,"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 vt(`${this.baseUrl}${n}`,{method:"POST",headers:s,body:JSON.stringify(o),timeoutMs:void 0})}catch(u){throw new Error(es(u))}if(this.parseServerSignals(i),i.status===401)throw await so(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 wt("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 wt(a?.error||"Parentless batch is not enabled on this server.",{status:i.status,serverErrorCode:u});if(i.status===503)throw new Error(io(a));if(a?.declined){let d=Number(a.retryAfter??i.headers.get("Retry-After"));throw new ye(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 oo(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(ao());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":En,"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 vt(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(p){throw new Error(es(p))}if(this.parseServerSignals(d),d.status===401)throw await so(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 qt(m?.message||m?.error||"Batch parent is being modified by another request. Retry shortly.",p,d.status)}throw new Error(io(m))}if(m?.declined){let p=Number(m.retryAfter??d.headers.get("Retry-After"));throw new ye(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 oo(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 vt(`${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 vt(`${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 co(e,t){return t||(typeof e!="number"||!Number.isFinite(e)?"price unknown":`$${(e/100).toFixed(2)}`)}function Vm(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 Fm(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function wv(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 Sv(e){return Math.max(4,e.reduce((t,n)=>Math.max(t,n.id.length),0))}function xv(e){return Math.max(8,Math.min(14,e.reduce((t,n)=>Math.max(t,(n.category||"").length),0)))}function Cv(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 qm(e){let t=Sv(e),n=7,r=xv(e),s=Cv(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)} ${co(o.priceCents,o.priceDisplay).padEnd(n)} ${Fm(o.category||"other",r).padEnd(r)} ${Fm(Vm(o),s)}`)}function Km(e){console.log(`
136
136
  Merchant tools
137
- `),jm(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 tl(e){console.log(`
137
+ `),qm(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 ol(e){console.log(`
138
138
  Merchant tools
139
- `);for(let[t,n]of mv(e)){console.log(t[0]?.toUpperCase()+t.slice(1));for(let r of n)console.log(` ${r.id.padEnd(28)} ${ao(r.priceCents,r.priceDisplay).padEnd(8)} ${r.description}`),console.log(` Params: ${Dm(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"
140
- `)}function Hm(e,t){console.log(`
139
+ `);for(let[t,n]of wv(e)){console.log(t[0]?.toUpperCase()+t.slice(1));for(let r of n)console.log(` ${r.id.padEnd(28)} ${co(r.priceCents,r.priceDisplay).padEnd(8)} ${r.description}`),console.log(` Params: ${Vm(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"
140
+ `)}function Gm(e,t){console.log(`
141
141
  ${e} tools
142
- `),jm(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>\`
143
- `)}function nl(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(`
144
- 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:()=>Fv,DIRTY:()=>rr,EMPTY_PATH:()=>vv,INVALID:()=>D,NEVER:()=>Ew,OK:()=>$e,ParseStatus:()=>Ee,Schema:()=>F,ZodAny:()=>En,ZodArray:()=>zt,ZodBigInt:()=>or,ZodBoolean:()=>ir,ZodBranded:()=>lo,ZodCatch:()=>yr,ZodDate:()=>ar,ZodDefault:()=>hr,ZodDiscriminatedUnion:()=>$i,ZodEffects:()=>Xe,ZodEnum:()=>pr,ZodError:()=>He,ZodFirstPartyTypeKind:()=>j,ZodFunction:()=>Oi,ZodIntersection:()=>dr,ZodIssueCode:()=>S,ZodLazy:()=>fr,ZodLiteral:()=>mr,ZodMap:()=>os,ZodNaN:()=>as,ZodNativeEnum:()=>gr,ZodNever:()=>lt,ZodNull:()=>lr,ZodNullable:()=>At,ZodNumber:()=>sr,ZodObject:()=>Fe,ZodOptional:()=>Je,ZodParsedType:()=>T,ZodPipeline:()=>uo,ZodPromise:()=>kn,ZodReadonly:()=>br,ZodRecord:()=>Ni,ZodSchema:()=>F,ZodSet:()=>is,ZodString:()=>An,ZodSymbol:()=>rs,ZodTransformer:()=>Xe,ZodTuple:()=>Ct,ZodType:()=>F,ZodUndefined:()=>cr,ZodUnion:()=>ur,ZodUnknown:()=>Jt,ZodVoid:()=>ss,addIssueToContext:()=>A,any:()=>Xv,array:()=>tw,bigint:()=>Gv,boolean:()=>Zm,coerce:()=>Aw,custom:()=>Jm,date:()=>Wv,datetimeRegex:()=>Wm,defaultErrorMap:()=>Wt,discriminatedUnion:()=>ow,effect:()=>yw,enum:()=>pw,function:()=>dw,getErrorMap:()=>es,getParsedType:()=>xt,instanceof:()=>qv,intersection:()=>iw,isAborted:()=>Ii,isAsync:()=>ts,isDirty:()=>Pi,isValid:()=>Cn,late:()=>Vv,lazy:()=>fw,literal:()=>mw,makeIssue:()=>co,map:()=>lw,nan:()=>Kv,nativeEnum:()=>gw,never:()=>Qv,null:()=>zv,nullable:()=>_w,number:()=>Xm,object:()=>nw,objectUtil:()=>rl,oboolean:()=>Cw,onumber:()=>xw,optional:()=>bw,ostring:()=>Sw,pipeline:()=>ww,preprocess:()=>vw,promise:()=>hw,quotelessJson:()=>yv,record:()=>cw,set:()=>uw,setErrorMap:()=>_v,strictObject:()=>rw,string:()=>zm,symbol:()=>Yv,transformer:()=>yw,tuple:()=>aw,undefined:()=>Jv,union:()=>sw,unknown:()=>Zv,util:()=>V,void:()=>ew});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 rl;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(rl||(rl={}));var T=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 T.undefined;case"string":return T.string;case"number":return Number.isNaN(e)?T.nan:T.number;case"boolean":return T.boolean;case"function":return T.function;case"bigint":return T.bigint;case"symbol":return T.symbol;case"object":return Array.isArray(e)?T.array:e===null?T.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?T.promise:typeof Map<"u"&&e instanceof Map?T.map:typeof Set<"u"&&e instanceof Set?T.set:typeof Date<"u"&&e instanceof Date?T.date:T.object;default:return T.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"]),yv=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 bv=(e,t)=>{let n;switch(e.code){case S.invalid_type:e.received===T.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}},Wt=bv;var Fm=Wt;function _v(e){Fm=e}function es(){return Fm}var co=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}},vv=[];function A(e,t){let n=es(),r=co({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Wt?void 0:Wt].filter(s=>!!s)});e.common.issues.push(r)}var Ee=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let s of n){if(s.status==="aborted")return D;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let s of n){let o=await s.key,i=await s.value;r.push({key:o,value:i})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let s of n){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return D;o.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(r[o.value]=i.value)}return{status:t.value,value:r}}},D=Object.freeze({status:"aborted"}),rr=e=>({status:"dirty",value:e}),$e=e=>({status:"valid",value:e}),Ii=e=>e.status==="aborted",Pi=e=>e.status==="dirty",Cn=e=>e.status==="valid",ts=e=>typeof Promise<"u"&&e instanceof Promise;var O;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(O||(O={}));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}},Vm=(e,t)=>{if(Cn(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 F=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 Ee,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(ts(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 Vm(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 Cn(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=>Cn(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(ts(s)?s:Promise.resolve(s));return Vm(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 Xe({schema:this,typeName:j.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Je.create(this,this._def)}nullable(){return At.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return zt.create(this)}promise(){return kn.create(this,this._def)}or(t){return ur.create([this,t],this._def)}and(t){return dr.create(this,t,this._def)}transform(t){return new Xe({...B(this._def),schema:this,typeName:j.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new hr({...B(this._def),innerType:this,defaultValue:n,typeName:j.ZodDefault})}brand(){return new lo({typeName:j.ZodBranded,type:this,...B(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new yr({...B(this._def),innerType:this,catchValue:n,typeName:j.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return uo.create(this,t)}readonly(){return br.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},wv=/^c[^\s-]{8,}$/i,Sv=/^[0-9a-z]+$/,xv=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Cv=/^[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,Av=/^[a-z0-9_-]{21}$/i,Ev=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,kv=/^[-+]?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)?)??$/,Tv=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Rv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",sl,Iv=/^(?:(?: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])$/,Pv=/^(?:(?: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])$/,$v=/^(([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]))$/,Nv=/^(([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])$/,Ov=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Mv=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Km="((\\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])))",Lv=new RegExp(`^${Km}$`);function Gm(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 Uv(e){return new RegExp(`^${Gm(e)}$`)}function Wm(e){let t=`${Km}T${Gm(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 Dv(e,t){return!!((t==="v4"||!t)&&Iv.test(e)||(t==="v6"||!t)&&$v.test(e))}function jv(e,t){if(!Ev.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||t&&s.alg!==t)}catch{return!1}}function Bv(e,t){return!!((t==="v4"||!t)&&Pv.test(e)||(t==="v6"||!t)&&Nv.test(e))}var An=class e extends F{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==T.string){let o=this._getOrReturnCtx(t);return A(o,{code:S.invalid_type,expected:T.string,received:o.parsedType}),D}let r=new Ee,s;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(s=this._getOrReturnCtx(t,s),A(s,{code: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),A(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?A(s,{code:S.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&A(s,{code:S.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")Tv.test(t.data)||(s=this._getOrReturnCtx(t,s),A(s,{validation:"email",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")sl||(sl=new RegExp(Rv,"u")),sl.test(t.data)||(s=this._getOrReturnCtx(t,s),A(s,{validation:"emoji",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")Cv.test(t.data)||(s=this._getOrReturnCtx(t,s),A(s,{validation:"uuid",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")Av.test(t.data)||(s=this._getOrReturnCtx(t,s),A(s,{validation:"nanoid",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")wv.test(t.data)||(s=this._getOrReturnCtx(t,s),A(s,{validation:"cuid",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")Sv.test(t.data)||(s=this._getOrReturnCtx(t,s),A(s,{validation:"cuid2",code:S.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")xv.test(t.data)||(s=this._getOrReturnCtx(t,s),A(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),A(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),A(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),A(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),A(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),A(s,{code:S.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?Wm(o).test(t.data)||(s=this._getOrReturnCtx(t,s),A(s,{code:S.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?Lv.test(t.data)||(s=this._getOrReturnCtx(t,s),A(s,{code:S.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?Uv(o).test(t.data)||(s=this._getOrReturnCtx(t,s),A(s,{code:S.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?kv.test(t.data)||(s=this._getOrReturnCtx(t,s),A(s,{validation:"duration",code:S.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?Dv(t.data,o.version)||(s=this._getOrReturnCtx(t,s),A(s,{validation:"ip",code:S.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?jv(t.data,o.alg)||(s=this._getOrReturnCtx(t,s),A(s,{validation:"jwt",code:S.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?Bv(t.data,o.version)||(s=this._getOrReturnCtx(t,s),A(s,{validation:"cidr",code:S.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?Ov.test(t.data)||(s=this._getOrReturnCtx(t,s),A(s,{validation:"base64",code:S.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?Mv.test(t.data)||(s=this._getOrReturnCtx(t,s),A(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,...O.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...O.errToObj(t)})}url(t){return this._addCheck({kind:"url",...O.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...O.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...O.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...O.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...O.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...O.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...O.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...O.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...O.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...O.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...O.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...O.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,...O.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,...O.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...O.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...O.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...O.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...O.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...O.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...O.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...O.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...O.errToObj(n)})}nonempty(t){return this.min(1,O.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}};An.create=e=>new An({checks:[],typeName:j.ZodString,coerce:e?.coerce??!1,...B(e)});function Hv(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,o=Number.parseInt(e.toFixed(s).replace(".","")),i=Number.parseInt(t.toFixed(s).replace(".",""));return o%i/10**s}var sr=class e extends F{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)!==T.number){let o=this._getOrReturnCtx(t);return A(o,{code:S.invalid_type,expected:T.number,received:o.parsedType}),D}let r,s=new Ee;for(let o of this._def.checks)o.kind==="int"?V.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),A(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),A(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),A(r,{code:S.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?Hv(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),A(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),A(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,O.toString(n))}gt(t,n){return this.setLimit("min",t,!1,O.toString(n))}lte(t,n){return this.setLimit("max",t,!0,O.toString(n))}lt(t,n){return this.setLimit("max",t,!1,O.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:O.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:O.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:O.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:O.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:O.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:O.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:O.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:O.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:O.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:O.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)}};sr.create=e=>new sr({checks:[],typeName:j.ZodNumber,coerce:e?.coerce||!1,...B(e)});var or=class e extends F{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)!==T.bigint)return this._getInvalidInput(t);let r,s=new Ee;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code: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),A(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),A(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 A(n,{code:S.invalid_type,expected:T.bigint,received:n.parsedType}),D}gte(t,n){return this.setLimit("min",t,!0,O.toString(n))}gt(t,n){return this.setLimit("min",t,!1,O.toString(n))}lte(t,n){return this.setLimit("max",t,!0,O.toString(n))}lt(t,n){return this.setLimit("max",t,!1,O.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:O.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:O.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:O.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:O.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:O.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:O.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};or.create=e=>new or({checks:[],typeName:j.ZodBigInt,coerce:e?.coerce??!1,...B(e)});var ir=class extends F{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==T.boolean){let r=this._getOrReturnCtx(t);return A(r,{code:S.invalid_type,expected:T.boolean,received:r.parsedType}),D}return $e(t.data)}};ir.create=e=>new ir({typeName:j.ZodBoolean,coerce:e?.coerce||!1,...B(e)});var ar=class e extends F{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==T.date){let o=this._getOrReturnCtx(t);return A(o,{code:S.invalid_type,expected:T.date,received:o.parsedType}),D}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return A(o,{code:S.invalid_date}),D}let r=new Ee,s;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(s=this._getOrReturnCtx(t,s),A(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),A(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:O.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:O.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};ar.create=e=>new ar({checks:[],coerce:e?.coerce||!1,typeName:j.ZodDate,...B(e)});var rs=class extends F{_parse(t){if(this._getType(t)!==T.symbol){let r=this._getOrReturnCtx(t);return A(r,{code:S.invalid_type,expected:T.symbol,received:r.parsedType}),D}return $e(t.data)}};rs.create=e=>new rs({typeName:j.ZodSymbol,...B(e)});var cr=class extends F{_parse(t){if(this._getType(t)!==T.undefined){let r=this._getOrReturnCtx(t);return A(r,{code:S.invalid_type,expected:T.undefined,received:r.parsedType}),D}return $e(t.data)}};cr.create=e=>new cr({typeName:j.ZodUndefined,...B(e)});var lr=class extends F{_parse(t){if(this._getType(t)!==T.null){let r=this._getOrReturnCtx(t);return A(r,{code:S.invalid_type,expected:T.null,received:r.parsedType}),D}return $e(t.data)}};lr.create=e=>new lr({typeName:j.ZodNull,...B(e)});var En=class extends F{constructor(){super(...arguments),this._any=!0}_parse(t){return $e(t.data)}};En.create=e=>new En({typeName:j.ZodAny,...B(e)});var Jt=class extends F{constructor(){super(...arguments),this._unknown=!0}_parse(t){return $e(t.data)}};Jt.create=e=>new Jt({typeName:j.ZodUnknown,...B(e)});var lt=class extends F{_parse(t){let n=this._getOrReturnCtx(t);return A(n,{code:S.invalid_type,expected:T.never,received:n.parsedType}),D}};lt.create=e=>new lt({typeName:j.ZodNever,...B(e)});var ss=class extends F{_parse(t){if(this._getType(t)!==T.undefined){let r=this._getOrReturnCtx(t);return A(r,{code:S.invalid_type,expected:T.void,received:r.parsedType}),D}return $e(t.data)}};ss.create=e=>new ss({typeName:j.ZodVoid,...B(e)});var zt=class e extends F{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==T.array)return A(n,{code:S.invalid_type,expected:T.array,received:n.parsedType}),D;if(s.exactLength!==null){let i=n.data.length>s.exactLength.value,a=n.data.length<s.exactLength.value;(i||a)&&(A(n,{code:i?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&&(A(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&&(A(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=>Ee.mergeArray(r,i));let o=[...n.data].map((i,a)=>s.type._parseSync(new ze(n,i,n.path,a)));return Ee.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:O.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:O.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:O.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 ns(e){if(e instanceof Fe){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Je.create(ns(r))}return new Fe({...e._def,shape:()=>t})}else return e instanceof zt?new zt({...e._def,type:ns(e.element)}):e instanceof Je?Je.create(ns(e.unwrap())):e instanceof At?At.create(ns(e.unwrap())):e instanceof Ct?Ct.create(e.items.map(t=>ns(t))):e}var Fe=class e extends F{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)!==T.object){let l=this._getOrReturnCtx(t);return A(l,{code:S.invalid_type,expected:T.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 lt&&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 lt){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(l==="strict")a.length>0&&(A(s,{code: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=>Ee.mergeObjectSync(r,l)):Ee.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(t){return O.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:O.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 ns(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 Je;)o=o._def.innerType;n[r]=o}return new e({...this._def,shape:()=>n})}keyof(){return Ym(V.objectKeys(this.shape))}};Fe.create=(e,t)=>new Fe({shape:()=>e,unknownKeys:"strip",catchall:lt.create(),typeName:j.ZodObject,...B(t)});Fe.strictCreate=(e,t)=>new Fe({shape:()=>e,unknownKeys:"strict",catchall:lt.create(),typeName:j.ZodObject,...B(t)});Fe.lazycreate=(e,t)=>new Fe({shape:e,unknownKeys:"strip",catchall:lt.create(),typeName:j.ZodObject,...B(t)});var ur=class extends F{_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 A(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 A(n,{code:S.invalid_union,unionErrors:a}),D}}get options(){return this._def.options}};ur.create=(e,t)=>new ur({options:e,typeName:j.ZodUnion,...B(t)});var Yt=e=>e instanceof fr?Yt(e.schema):e instanceof Xe?Yt(e.innerType()):e instanceof mr?[e.value]:e instanceof pr?e.options:e instanceof gr?V.objectValues(e.enum):e instanceof hr?Yt(e._def.innerType):e instanceof cr?[void 0]:e instanceof lr?[null]:e instanceof Je?[void 0,...Yt(e.unwrap())]:e instanceof At?[null,...Yt(e.unwrap())]:e instanceof lo||e instanceof br?Yt(e.unwrap()):e instanceof yr?Yt(e._def.innerType):[],$i=class e extends F{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==T.object)return A(n,{code:S.invalid_type,expected:T.object,received:n.parsedType}),D;let r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(A(n,{code: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=Yt(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 ol(e,t){let n=xt(e),r=xt(t);if(e===t)return{valid:!0,data:e};if(n===T.object&&r===T.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=ol(e[a],t[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===T.array&&r===T.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=ol(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===T.date&&r===T.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var dr=class extends F{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=(o,i)=>{if(Ii(o)||Ii(i))return D;let a=ol(o.value,i.value);return a.valid?((Pi(o)||Pi(i))&&n.dirty(),{status:n.value,value:a.data}):(A(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}))}};dr.create=(e,t,n)=>new dr({left:e,right:t,typeName:j.ZodIntersection,...B(n)});var Ct=class e extends F{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==T.array)return A(r,{code:S.invalid_type,expected:T.array,received:r.parsedType}),D;if(r.data.length<this._def.items.length)return A(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&&(A(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=>Ee.mergeArray(n,i)):Ee.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 Ni=class e extends F{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!==T.object)return A(r,{code:S.invalid_type,expected:T.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?Ee.mergeObjectAsync(n,s):Ee.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof F?new e({keyType:t,valueType:n,typeName:j.ZodRecord,...B(r)}):new e({keyType:An.create(),valueType:t,typeName:j.ZodRecord,...B(n)})}},os=class extends F{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!==T.map)return A(r,{code:S.invalid_type,expected:T.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}}}};os.create=(e,t,n)=>new os({valueType:t,keyType:e,typeName:j.ZodMap,...B(n)});var is=class e extends F{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==T.set)return A(r,{code:S.invalid_type,expected:T.set,received:r.parsedType}),D;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(A(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&&(A(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:O.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:O.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};is.create=(e,t)=>new is({valueType:e,minSize:null,maxSize:null,typeName:j.ZodSet,...B(t)});var Oi=class e extends F{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==T.function)return A(n,{code:S.invalid_type,expected:T.function,received:n.parsedType}),D;function r(a,c){return co({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,es(),Wt].filter(l=>!!l),issueData:{code:S.invalid_arguments,argumentsError:c}})}function s(a,c){return co({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,es(),Wt].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 kn){let a=this;return $e(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 $e(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(Jt.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(Jt.create()),returns:n||Jt.create(),typeName:j.ZodFunction,...B(r)})}},fr=class extends F{get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};fr.create=(e,t)=>new fr({getter:e,typeName:j.ZodLazy,...B(t)});var mr=class extends F{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return A(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}};mr.create=(e,t)=>new mr({value:e,typeName:j.ZodLiteral,...B(t)});function Ym(e,t){return new pr({values:e,typeName:j.ZodEnum,...B(t)})}var pr=class e extends F{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return A(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 A(n,{received:n.data,code:S.invalid_enum_value,options:r}),D}return $e(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};pr.create=Ym;var gr=class extends F{_parse(t){let n=V.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==T.string&&r.parsedType!==T.number){let s=V.objectValues(n);return A(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 A(r,{received:r.data,code:S.invalid_enum_value,options:s}),D}return $e(t.data)}get enum(){return this._def.values}};gr.create=(e,t)=>new gr({values:e,typeName:j.ZodNativeEnum,...B(t)});var kn=class extends F{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==T.promise&&n.common.async===!1)return A(n,{code:S.invalid_type,expected:T.promise,received:n.parsedType}),D;let r=n.parsedType===T.promise?n.data:Promise.resolve(n.data);return $e(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};kn.create=(e,t)=>new kn({type:e,typeName:j.ZodPromise,...B(t)});var Xe=class extends F{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===j.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,o={addIssue:i=>{A(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(r.data,o);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return D;let c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?D:c.status==="dirty"?rr(c.value):n.value==="dirty"?rr(c.value):c});{if(n.value==="aborted")return D;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?D:a.status==="dirty"?rr(a.value):n.value==="dirty"?rr(a.value):a}}if(s.type==="refinement"){let i=a=>{let c=s.refinement(a,o);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?D:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?D:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(s.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Cn(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=>Cn(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:n.value,value:a})):D);V.assertNever(s)}};Xe.create=(e,t,n)=>new Xe({schema:e,typeName:j.ZodEffects,effect:t,...B(n)});Xe.createWithPreprocess=(e,t,n)=>new Xe({schema:t,effect:{type:"preprocess",transform:e},typeName:j.ZodEffects,...B(n)});var Je=class extends F{_parse(t){return this._getType(t)===T.undefined?$e(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Je.create=(e,t)=>new Je({innerType:e,typeName:j.ZodOptional,...B(t)});var At=class extends F{_parse(t){return this._getType(t)===T.null?$e(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};At.create=(e,t)=>new At({innerType:e,typeName:j.ZodNullable,...B(t)});var hr=class extends F{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===T.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};hr.create=(e,t)=>new hr({innerType:e,typeName:j.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...B(t)});var yr=class extends F{_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 ts(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}};yr.create=(e,t)=>new yr({innerType:e,typeName:j.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...B(t)});var as=class extends F{_parse(t){if(this._getType(t)!==T.nan){let r=this._getOrReturnCtx(t);return A(r,{code:S.invalid_type,expected:T.nan,received:r.parsedType}),D}return{status:"valid",value:t.data}}};as.create=e=>new as({typeName:j.ZodNaN,...B(e)});var Fv=Symbol("zod_brand"),lo=class extends F{_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}},uo=class e extends F{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?D:o.status==="dirty"?(n.dirty(),rr(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?D:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:j.ZodPipeline})}},br=class extends F{_parse(t){let n=this._def.innerType._parse(t),r=s=>(Cn(s)&&(s.value=Object.freeze(s.value)),s);return ts(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};br.create=(e,t)=>new br({innerType:e,typeName:j.ZodReadonly,...B(t)});function qm(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Jm(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=qm(t,r),c=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=qm(t,r),a=i.fatal??n??!0;s.addIssue({code:"custom",...i,fatal:a})}}):En.create()}var Vv={object:Fe.lazycreate},j;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(j||(j={}));var qv=(e,t={message:`Input not instance of ${e.name}`})=>Jm(n=>n instanceof e,t),zm=An.create,Xm=sr.create,Kv=as.create,Gv=or.create,Zm=ir.create,Wv=ar.create,Yv=rs.create,Jv=cr.create,zv=lr.create,Xv=En.create,Zv=Jt.create,Qv=lt.create,ew=ss.create,tw=zt.create,nw=Fe.create,rw=Fe.strictCreate,sw=ur.create,ow=$i.create,iw=dr.create,aw=Ct.create,cw=Ni.create,lw=os.create,uw=is.create,dw=Oi.create,fw=fr.create,mw=mr.create,pw=pr.create,gw=gr.create,hw=kn.create,yw=Xe.create,bw=Je.create,_w=At.create,vw=Xe.createWithPreprocess,ww=uo.create,Sw=()=>zm().optional(),xw=()=>Xm().optional(),Cw=()=>Zm().optional(),Aw={string:(e=>An.create({...e,coerce:!0})),number:(e=>sr.create({...e,coerce:!0})),boolean:(e=>ir.create({...e,coerce:!0})),bigint:(e=>or.create({...e,coerce:!0})),date:(e=>ar.create({...e,coerce:!0}))};var Ew=D;var kw=/^[A-Za-z0-9._-]+$/,Tw=/^[A-Za-z0-9._-]+(\|[A-Za-z0-9._-]+)*$/,Qm=new Set([".",".."]),je=class extends Error{pattern;constructor(t,n){super(`Invalid freeReadPathPattern ${JSON.stringify(n)}: ${t}`),this.pattern=n,this.name="FreePathPatternError"}};function Rw(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(!Tw.test(s))throw new je(`malformed alternation segment ${JSON.stringify(e)}`,t);let o=s.split("|");if(o.some(i=>Qm.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(kw.test(e)){if(Qm.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 Iw(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=>Rw(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 il(e){Iw(e)}var ep=["tempo","mpp_self","merchant_self"],tp=["catalog_static","fal_direct","fal_queue","openrouter_chat","openrouter_image","platform_proxy","tempo_gateway","x402_gateway"],np=["image","audio","queued_audio","video","queued_video","model_3d","llm","transcription","utility"],rp=["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 cl=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()}),Pw=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:cl.optional()}).passthrough(),ll=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")})]),ul=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()}),sp=C.object({attestation:C.boolean().optional(),rateLimitMs:C.number().positive().optional()}),op=C.object({displayName:C.string().optional(),feedbackEligible:C.boolean().optional(),suggestionEligible:C.boolean().optional(),batchable:C.boolean().optional()}),ip=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(),$w=C.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),Nw=120,Ow=120,Mw=1200,Lw=/^[^\u0000-\u001F\u007F]+$/;function al(e,t){return C.string().min(1).max(e).regex(Lw,`${t} must not contain control characters`)}var dl={id:C.string().min(1),name:al(Nw,"name"),description:al(Mw,"description"),provider:C.string().min(1),model:C.string().min(1),category:$w,priceCents:C.number().nonnegative(),inputSchema:C.record(C.unknown()),gatewayUrl:C.string().min(1),merchantName:al(Ow,"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:cl.optional(),priceDisplay:C.string().optional(),pricingModel:C.enum(["per-call","per-token","band"]).optional(),pricingInfo:Pw.optional(),status:C.enum(["available","unavailable"]).optional(),handler:ll.optional(),pricing:ul.optional(),security:sp.optional(),engagement:op.optional(),gatewayConfig:ip.optional(),freeReadPathPattern:C.string().optional().superRefine((e,t)=>{if(e!==void 0)try{il(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(ep).optional(),executionKind:C.enum(tp).optional(),resultKind:C.enum(np).optional(),extractionMode:C.enum(rp).optional(),pricingStrategy:C.enum(["flat","token","band"]).optional()},ap=C.object({...dl,dispatch:C.literal("routed"),routedPath:C.string().min(1).startsWith("/")}).strict(),cp=C.object({...dl,dispatch:C.literal("enveloped")}).strict(),lp=C.object({...dl,handler:ll,pricing:ul}).strict(),up=C.union([C.discriminatedUnion("dispatch",[ap,cp]),lp]);var jw="https://fal.run",pp="https://openrouter.mpp.tempo.xyz",ml=1024,Li=8192,Bw=4096,Hw=10;function Fw(e){return e>=Hw?Bw:Li}function gp(e,t){let n=typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):ml;return Math.min(n,t)}var Vw=["num_images","num_outputs","num_samples","num_videos","batch_size","n"];function hp(e){for(let t of Vw)delete e[t];return e}function qw(e){let{attestation:t,tool_id:n,...r}=e;return hp(r)}var dp={"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 Mi(e){let{attestation:t,tool_id:n,aspect_ratio:r,image_size:s,...o}=e,i=hp({...o});return typeof s=="string"&&s.length>0?(i.image_size=s,i):(typeof r=="string"&&dp[r]&&(i.image_size=dp[r]),i)}function Kw(e){let{attestation:t,tool_id:n,...r}=e;return r}function fp(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 Gw(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 Ww(e,t,n,r,s,o,i,a){return Gw(e,t,n,"suno-ai",r,s,o,i,{merchantName:"Suno AI",...a})}function be(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:`${jw}/${r}`,merchantName:"fal.ai",buildBody:qw,tags:[],...a}}function yp(e,t=Li){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:gp(c??l,t),usage:{include:!0}}}}function bp(e,t=Li){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:gp(c??l,t),usage:{include:!0}}}}function le(e,t,n,r,s,o,i){let a=i?.maxOutputTokens??Fw(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: ${ml}); 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:`${pp}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:yp(r,a),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:s,outputPerMillion:o,...c>0?{perRequestFeeCents:c}:{}},...p}}function fl(e,t,n,r,s,o){let i=o?.maxOutputTokens??Li,{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: ${ml}); 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:`${pp}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:bp(r,i),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...c}}var pl=[be("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"]}),be("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:Mi}),be("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:Mi}),be("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:Mi}),be("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"]}),fl("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),fl("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}}),fl("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}}),be("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"]}),be("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"]}),be("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"]}),be("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"]}),be("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"]}),be("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"]}),be("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"]}),be("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"]}),be("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"]}),Ww("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}}}),be("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"]}),be("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"]}),be("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"]}),be("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:fp,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:Kw,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=>Mi({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"]},be("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"}),be("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:fp,tags:["onchain","prices","allium","crypto","legacy"]}];function fo(e){return pl.find(t=>t.id===e)}var zw=[{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=>zw.filter(i=>i.type===o)),s=new Set(r.filter(o=>o.matches(e)).map(o=>o.type));return{declared:r,matched:s}}function gl(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 ja=k(ls());var Hi=require("child_process"),$p=require("util"),Np=k(require("crypto")),ne=k(require("fs")),Op=k(require("os")),Ne=k(require("path"));Kt();var dt=(0,$p.promisify)(Hi.execFile),xS=6e4,CS=()=>process.platform==="darwin",Tn=()=>process.platform==="win32",Rn=Ne.join(Op.homedir(),".visa-mcp","bin"),_r=Ne.join(Rn,"Visa CLI"),Qt=Ne.join(Rn,"visa-keychain-win.exe"),Mp=Ne.join(__dirname,"..","native"),xp="6",Cp=Ne.join(Rn,"visa-keychain.version"),Ap=Ne.join(Rn,"visa-keychain.sha256"),Ep="1",kp=Ne.join(Rn,"visa-keychain-win.version"),Tp=Ne.join(Rn,"visa-keychain-win.sha256"),Lp=[Ne.join(Mp,"bin","win32-x64","visa-keychain-win.exe"),Ne.resolve(__dirname,"..","..","native","bin","win32-x64","visa-keychain-win.exe"),Ne.resolve(__dirname,"..","native","bin","win32-x64","visa-keychain-win.exe")];function Di(e){let t=ne.readFileSync(e);return Np.createHash("sha256").update(t).digest("hex")}function AS(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 Rp(e){let t=typeof e?.message=="string"?e.message:"";return e?.code==="ETIMEDOUT"||e?.killed===!0||/timed out|timeout/i.test(t)}function Ip(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 hl(){try{if(ne.readFileSync(Cp,"utf-8").trim()===xp&&ne.existsSync(_r)){let r=ne.readFileSync(Ap,"utf-8").trim();if(Di(_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=Ne.join(Mp,"visa-keychain.m");if(ne.existsSync(e)||(e=Ne.resolve(__dirname,"..","..","native","visa-keychain.m")),ne.existsSync(e)||(e=Ne.resolve(__dirname,"..","native","visa-keychain.m")),!ne.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");ne.mkdirSync(Rn,{recursive:!0,mode:448});try{await dt("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=Di(_r);return ne.writeFileSync(Ap,t,{mode:384}),ne.writeFileSync(Cp,xp,{mode:384}),_r}function Up(){for(let e of Lp)if(ne.existsSync(e))return e;return null}async function us(){try{if(ne.readFileSync(kp,"utf-8").trim()===Ep&&ne.existsSync(Qt)){let r=ne.readFileSync(Tp,"utf-8").trim();if(Di(Qt)!==r)g.warn("binary:hash-mismatch:win32",{message:"Windows binary hash mismatch. Redeploying."}),ne.unlinkSync(Qt);else return Qt}}catch{}let e=Up();if(!e)throw new Error(`visa-keychain-win.exe not found in package. Reinstall @visa/cli.
145
- If building from source, run native/build-win.bat first.`);ne.mkdirSync(Rn,{recursive:!0}),ne.copyFileSync(e,Qt);let t=Di(Qt);return ne.writeFileSync(Tp,t,{mode:384}),ne.writeFileSync(kp,Ep,{mode:384}),Qt}async function ES(){return Tn()?us():hl()}var ji="visa-cli",Bi="attestation-key";async function kS(e){try{await dt("security",["delete-generic-password","-s",ji,"-a",Bi],{timeout:5e3})}catch{}await dt("security",["add-generic-password","-s",ji,"-a",Bi,"-w",e],{timeout:5e3})}function TS(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 RS(){try{let{stdout:e}=await dt("security",["find-generic-password","-s",ji,"-a",Bi,"-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:TS(e)}}}async function yl(){let e=await RS();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 Dp(e){let t=await ES(),n;try{n=(await dt(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 AS(n)}var Pp=!1;function IS(){if(!Tn())return!1;try{return ne.existsSync(Qt)||Up()!==null?!0:(Pp||(Pp=!0,g.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:Qt,searchedPrebuiltPaths:Lp})),!1)}catch{return!1}}function fe(){return Vr()||CS()?!0:Tn()?IS():!1}async function Fi(){if(Tn()){let s=await us(),{stdout:o}=await dt(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 Dp(["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 kS(n),r}async function Vi(){if(Tn())try{let e=await us(),{stdout:t}=await dt(e,["public-key"],{timeout:1e4});return t.trim().startsWith("OK:")}catch{return!1}return await yl()!==null}async function jp(){if(Vr())return"mock-public-key-spki";if(Tn()){let n=await us(),{stdout:r}=await dt(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 yl();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await hl();return new Promise((n,r)=>{let s=(0,Hi.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 In(e,t,n={}){if(Vr())return Promise.resolve(Zd());let r=n.timeoutMs??xS;if(Tn()){let a=await us(),c=["sign",e];t&&c.push(t);let l;try{l=(await dt(a,c,{timeout:r})).stdout}catch(d){throw Rp(d)?Ip(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 yl();if(!s)throw new Error("Attestation key not found. Run setup to generate a new key.");let o=await hl(),i=["sign",e];return t&&i.push(t),new Promise((a,c)=>{let l=(0,Hi.execFile)(o,i,{timeout:r},(u,d)=>{let f=(d||"").trim();if(u){f.startsWith("ERROR:")?c(new Error(f.slice(6))):Rp(u)?c(Ip(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 qi(){if(Tn()){try{let e=await us();await dt(e,["delete-key"],{timeout:1e4})}catch{}return}try{await dt("security",["delete-generic-password","-s",ji,"-a",Bi],{timeout:5e3})}catch{}try{await Dp(["delete-key"])}catch{}}Kt();var PS=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],$S=[...PS.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 bl(e,t=$S){for(let n of t)if(n.toolId===e.requestedTool)return n.targetToolId;return null}function _l(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function Bp(e=process.env){return _l(e)!==null}var NS=new Set(["false","0","no","off","disable","disabled"]),OS=new Set(["true","1","yes","on","enable","enabled"]);function Hp(e){let t=(e??"").trim().toLowerCase();return t?NS.has(t)?!1:!!OS.has(t):!0}function Fp(e=process.env){return Hp(e.VISA_CLI_PARENTLESS_SINGLE_CALL)}function Vp(e=process.env){return Hp(e.VISA_CLI_PARENTLESS_BATCH)}var By=require("child_process"),Ce=k(require("crypto")),gt=k(require("fs")),Mo=k(require("os")),Ba=k(require("path"));function Et(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"?qr(s):null,i=Array.isArray(n.urls)?n.urls[0]:void 0,c=typeof i=="string"&&i.startsWith("data:")?qr(i):null;if(!o&&!c)return e;let l=o??c,u=o?"content":"urls",d;try{d=js(l,{tag:MS(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 MS(e,t){let n=typeof t.transactionId=="string"?t.transactionId:typeof t.transaction_id=="string"?t.transaction_id:null;return n?`${e}-${n}`:e}Kt();var vl=!1;async function vr(e,t,n){try{return await t()}catch(r){if(!(r.message==="Invalid signature"||r.code==="ATTESTATION_KEY_DRIFT"||r.error_code==="ATTESTATION_KEY_DRIFT"||r.name==="AttestationDriftError")||!fe())throw r;if(g.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(vl)throw g.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;vl=!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 Fi();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 vl=!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 Ki(e,t){if(!fe())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 Vi())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."}}ct();var qp="4.0.0-rc.20";function wl(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function Sl(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=ki(t);return s!==void 0?{value:s,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function Ze(e){return e==null?"\u2014":e?"yes":"no"}function Gi(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function LS(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function US(){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=Qc("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:Xc,source:{kind:"default"}}}async function po(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=Zc("auth.serverUrl"),i=de(),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:Ze(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:Ze(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:Ze(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:fe(),formatted:Ze(fe()),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:Gi(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:Gi(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:Gi(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:Gi(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=US();r.push({key:"credit.sessionCapCents",value:m.value,formatted:LS(m.value),source:m.source});let p=Nm();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 h=Sl("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:h.value,formatted:Ze(h.value),source:h.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let v=Sl("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:v.value,formatted:Ze(v.value),source:v.source});let I=St(),b;process.env.VISA_CLI_NO_UPDATE_CHECK?b={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?b={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?b={kind:"env",var:"NODE_ENV"}:b={kind:"default"},r.push({key:"ui.updateCheck",value:!I,formatted:Ze(!I),source:b});let _=Sl("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:_.value,formatted:Ze(_.value),source:_.source});let w=process.env.VISA_DRY_RUN,R=Bp();if(r.push({key:"tools.dryRun",value:R,formatted:Ze(R),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:qp,formatted:qp,source:{kind:"default"}}),e.includeDev){let E=process.env.VISA_MOCK_KEYCHAIN,y=fn();r.push({key:"dev.mockKeychain",value:y,formatted:Ze(y),source:wl("VISA_MOCK_KEYCHAIN",!!E),hint:dc()});let x=process.env.VISA_MOCK_TOUCHID,Y=Vr();r.push({key:"dev.mockTouchid",value:Y,formatted:Ze(Y),source:wl("VISA_MOCK_TOUCHID",!!x),hint:dc()});let X=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!X,formatted:Ze(!!X),source:wl("VISA_CLI_DEBUG",!!X)})}return{entries:r,statusError:n}}function DS(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 Kp(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}(${DS(o.source)})`),t.verbose&&o.hint&&s.push(` ${"\u21B3".padStart(n)} ${o.hint}`)}return s.join(`
146
- `)}function Gp(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 Wp(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"}]}}}ct();Kt();var Pn=require("fs"),Jp=require("os"),xl=require("path"),jS=(0,xl.join)((0,Jp.homedir)(),".visa-mcp"),Yp=(0,xl.join)(jS,"mcp-session-budget.json");function Wi(){try{(0,Pn.existsSync)(Yp)&&(0,Pn.unlinkSync)(Yp)}catch{}}var Al=require("crypto"),ft=k(ls()),Sr=null,Ge=0,Nn=0,Ve=0,$n=null,El=null,kl=null,wr=Promise.resolve();function BS(e){return Number((0,ft.fromCents)(e))}function Xp(e){return(0,ft.toCents)((0,ft.micros)(BigInt(e)))}function zp(e){return(0,ft.toWire)((0,ft.fromCents)(e))}function Cl(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Yi(e){return typeof e=="string"&&/^\d+$/.test(e)}var HS=43,FS=new RegExp(`^[A-Za-z0-9_-]{${HS}}$`);function VS(e){return typeof e=="string"&&FS.test(e)}function qS(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||Sr&&e.session_id!==Sr||typeof e.nonce!="string"||e.nonce.length===0||!VS(e.server_signature)||!Cl(e.cumulative)||!Cl(e.remaining)||!Cl(e.delta)||e.cumulative<Ge||Ve>0&&e.cumulative>Ve||Ve>0&&e.remaining>Ve||e.cumulative_micros!==void 0&&!Yi(e.cumulative_micros)||e.remaining_micros!==void 0&&!Yi(e.remaining_micros)||e.delta_micros!==void 0&&!Yi(e.delta_micros)||e.reserved_micros!==void 0&&!Yi(e.reserved_micros))}function en(e){Sr=e,Ge=0,Nn=0,Ve=0,$n=null,El=null,kl=null,wr=Promise.resolve()}function go(e){Ve=Math.max(0,Math.floor(e))}function Tl(){return Sr}function Rl(e){if(!Sr)return null;let t=Ge+Nn;return Ve>0&&t>Ve&&(t=Ve),{session_budget_id:Sr,cumulative_micros:BS(t),nonce:(0,Al.randomUUID)(),idempotency_key:e||(0,Al.randomUUID)()}}function ho(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 qS(r)?(Ge=Math.max(Ge,r.cumulative),Nn=0,$n=r,r):null}function Zp(){return $n}function Il(e){let t=Xp(e.cumulative_micros);Ge=Math.max(Ge,t),Nn=0;let n={status:"accepted",session_id:e.session_budget_id,cumulative:Ge,remaining:Math.max(0,Ve-Ge),delta:0,cumulative_micros:zp(Ge),remaining_micros:zp(Math.max(0,Ve-Ge)),delta_micros:"0",nonce:e.nonce};return $n=n,n}function yo(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,ft.toCents)((0,ft.micros)(n));if(!Number.isFinite(r)||r<0)return;El=t;let s=e,o=typeof s.session_id=="string"?s.session_id:Sr??"";$n?(typeof s.remaining_micros=="string"&&/^\d+$/.test(s.remaining_micros)&&($n.remaining_micros=s.remaining_micros),typeof s.charged_micros=="string"&&/^\d+$/.test(s.charged_micros)&&($n.delta_micros=s.charged_micros)):$n={session_id:o,cumulative:r,remaining:0,delta:0,nonce:typeof s.transaction_id=="string"?s.transaction_id:"",remaining_micros:typeof s.remaining_micros=="string"&&/^\d+$/.test(s.remaining_micros)?s.remaining_micros:void 0,delta_micros:typeof s.charged_micros=="string"&&/^\d+$/.test(s.charged_micros)?s.charged_micros:void 0}}function Qp(e){let t=e.receipt??null;kl={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:Xp(e.voucher.cumulative_micros),estimatedCumulativeCents:Ji(),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 eg(){return kl}function tg(){return Ge}function ng(){return El}function Ji(){let e=Ge+Nn;return Ve>0&&e>Ve&&(e=Ve),e}function Pl(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return wr=wr.then(()=>{Nn+=t}),wr}function bo(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return wr=wr.then(()=>{Nn=Math.max(0,Nn-t)}),wr}var KS=10,GS=1,me=null,rg=Promise.resolve();function $l(e){let t=rg.catch(()=>{}).then(e);return rg=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 Nl(e,t,n){return $l(()=>sg(e,t,n))}async function sg(e,t,n){if(Wi(),me&&new Date(me.expiresAt).getTime()>Date.now())return Tl()!==me.budgetId&&(en(me.budgetId),go(me.totalCents)),g.info("mcp-session:active-hit",{budgetId:me.budgetId,tool:n.toolName,remainingEstimatedCents:me.totalCents-Ji()}),{budgetId:me.budgetId,isFresh:!1,totalCents:me.totalCents,requestedCapCents:me.totalCents,appliedCapCents:me.totalCents,clampedReason:null};me&&(me=null,en(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"?GS:KS,i=Math.max(o,Math.ceil(n.minRequiredCents??o));if(r.balanceCents<i)throw new xe(r.balanceCents,i);let a=n.capCentsOverride??Lm(),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 me=f,en(f.budgetId),go(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 og(e,t,n){return $l(async()=>{let s=On()?await ig(e):null,o=await sg(e,t,n);return{budgetId:o.budgetId,totalCents:o.totalCents,closedPrevious:s,requestedCapCents:o.requestedCapCents,appliedCapCents:o.appliedCapCents,clampedReason:o.clampedReason}})}async function ig(e){let n=On()?.budgetId??Tl(),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 Wi(),me=null,en(null),{closedServerSide:r,budgetId:n,finalCumulativeCents:s,finalCumulativeMicros:o}}async function zi(e){return $l(()=>ig(e))}function On(){return Wi(),me?new Date(me.expiresAt).getTime()<=Date.now()?(me=null,en(null),null):{budgetId:me.budgetId,totalCents:me.totalCents,lastReceiptCumulative:tg(),lastReceiptCumulativeMicros:Zp()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:ng(),estimatedCumulative:Ji(),lastToolSpend:eg(),expiresAt:me.expiresAt}:null}var cg=k(ls()),ag=10000n;function WS(e){return e<=0n?0:Number((e+ag-1n)/ag)}function lg(e){return WS((0,cg.fromUsd)(e))}var Xi=k(ls()),YS=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;function Zi(e){if(typeof e!="string"||!YS.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,Xi.toDisplay)((0,Xi.fromCents)(s),{symbol:""})}}var Qi="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.",ug="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.";ct();var ky=Promise.resolve();function eE(e,t){if(e)try{let n=(0,ja.fromWire)(e),r=n%10000n===0n?2:6;return(0,ja.toDisplay)(n,{decimals:r})}catch{}return`$${(t/100).toFixed(2)}`}var Ty=!1,Ry=!1,Iy=!1;function Ha(e){let t=ky.catch(()=>{}).then(e);return ky=t.then(()=>{},()=>{}),t}async function Hy(e){let t=await Ae(()=>Nl(U,nt,{toolName:e.toolId,userContext:e.userContext}));await Pl(e.estimatedAmountCents);let n=Rl(e.idempotencyKey);if(!n)throw await bo(e.estimatedAmountCents),new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await uE(),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 qt){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 bo(e.estimatedAmountCents),u instanceof Xr){if(g.warn("mcp-session:server-invalidated-budget",{code:u.code,budgetId:u.budgetId??t.budgetId,tool:e.toolId}),await zi(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.
147
- 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}),Fy(e)}throw u instanceof qt?(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=ho(o)??(n?Il(n):null);if(yo(s?.receipt_v2),Qp({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),ed(s))return Et(s);let c=await Qu();if(e.idempotencyKey&&td(s,c,e.idempotencyKey))return Et(s);let l=c?No(c):null;return Et(nd(s,r,l))}function et(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function La(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(La).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${La(r)}`).join(",")}}`}function Zu(e,t,n,r){let s=Ce.createHash("sha256").update(`${n}:${La(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${s}`}function tE(e,t){return`${e}:${t}`}function nE(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 Ua(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,s=pt(r),o=s!==null?s.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=nE(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),c=i!=null?String(i):a;return{batch_id:e,item_id:tE(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 Fy(e){return Ae(()=>sE(e))}async function Vy(e,t,n){if(ed(e))return Et(e);let r=await Qu();if(n&&td(e,r,n))return Et(e);let s=r?No(r):null;return Et(nd(e,t,s))}async function rE(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 ho(i),yo(o?.receipt_v2),g.info("parentless-single-call:completed",{tool:e.toolId}),Vy(o,e.beforeBalanceMicros,e.idempotencyKey)}async function sE(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=No(n);if(Fp()&&!Ty){let u=e.idempotencyKey??Ce.randomUUID();try{return await rE({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 wt)Ty=!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;en(c),go(a.budget.totalCents),g.info("on-demand-session:opened",{budgetId:c,capCents:a.budget.totalCents,tool:e.toolId});let l=!1;try{await Pl(e.estimatedAmountCents);let u=Rl(e.idempotencyKey);if(!u)throw await bo(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(ho(f)||Il(u),l=!0,yo(d?.receipt_v2),ed(d))return Et(d);let m=await Qu();if(e.idempotencyKey&&td(d,m,e.idempotencyKey))return Et(d);let p=m?No(m):null;return Et(nd(d,s,p))}catch(u){throw l||await bo(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)})}en(null),g.info("on-demand-session:closed",{budgetId:c,tool:e.toolId})}}async function Gn(e){return Ha(async()=>On()?Hy(e):Fy(e))}function Fa(){return de()}var oE="https://v4-verify-web-visa-code-preview.up.railway.app";function iE(e=rd){return/^\d+\.\d+\.\d+$/.test(e)&&e!=="0.0.0"}function qy(e=process.env,t=rd){return e.VISA_VERIFY_WEB_URL?e.VISA_VERIFY_WEB_URL:iE(t)?null:oE}var U=new Ke(()=>G.getSessionToken());function pt(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function No(e){return pt(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function aE(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 cE(e){let t=pt(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=pt(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=pt(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function $o(e,t="INVALID_TOOL_PARAMS",n){return{success:!1,error_code:t,code:t,error:e,message:e,...n??{}}}function lE(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 uE(){try{let e=await U.getBalance();return e.success?No(e):null}catch{return null}}async function Qu(){try{let e=await U.getBalance();return e.success?e:null}catch{return null}}function ed(e){if(!e||e.success===!1)return!1;let t=pt(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=pt(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 td(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=pt(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 nd(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 rd="4.0.0-rc.20",DP=["","","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(`
148
- `);function tt(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=qs(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(Om())return{opened:!1,url:t,blockedReason:"suppressed"};let n=Ac();if(n.headless)return g.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let s=[Fa(),qy()].filter(i=>!!i).map(i=>gf(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=yf(s);return o?((0,By.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 "${Mo.platform()}". URL: ${s}`),{opened:!1,url:s,blockedReason:"unsupported_platform"})}async function Ae(e){return vr(U,e,Qy)}var Ky="get_cards",Gy="set_default_card";function dE(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 '${Ky}' to see enrolled cards and '${Gy}' to switch, then retry the original request.`}function fE(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 '${Ky}' to see enrolled cards and '${Gy}' to switch. Do not retry automatically.`}function ht(e,t){let n=e.retryable?dE(e.code,e.retryAfter):fE(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 mE(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 Ts=null,pE=3e4;function Wy(){Ts=null}var Kn=class extends Error{constructor(n){super(`${Da()} attestation is required for this action, but it is not available in this MCP process. `+sd());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function Va(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. `+sd()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function gE(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:Qi,agent_guidance:ug}}function Da(){return process.platform==="darwin"?"Touch ID":"local biometric"}function sd(){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 hE(e){let t=Date.now();if(Ts&&Ts.expiresAt>t)return{required:Ts.required,hasRegisteredKey:Ts.hasRegisteredKey};try{let n=await U.getStatus(e),r=kt(n),s=n.attestationRequired!==!1;return Ts={required:s,hasRegisteredKey:r,expiresAt:t+pE},{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 hE(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(!fe())throw g.warn("attestation:unavailable",{context:e}),new Kn(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 In(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 Py="[dry-run] https://placeholder.visa-cli.dev/image.png",yE=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"]),bE=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 _E(e){return e.startsWith("or-")?"llm":yE.has(e)?"image":bE.has(e)?"video":vE(e)?"media":null}function vE(e){let t=fo(e);return t?!qa(t):!1}function wE(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function SE(e){return e==="llm"?"OpenRouter":"fal.ai"}function Rs(e,t,n,r){let s={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:SE(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${wE(n)}`;return{...s,content:i,data:{content:i,model:t,dry_run:!0}}}return{...s,urls:[Py],data:{[e==="video"?"videoUrl":e==="image"?"imageUrl":"url"]:Py,metadata:{dry_run:!0}}}}async function Ju(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 xE="https://openrouter.ai/api/v1/chat/completions",CE="openrouter/free",AE=50,EE=15e3;function kE(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 TE(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:Rs("llm",e,t,n),degraded:!0,resolvedModel:null};let s=kE(t),o;try{o=await vt(xE,{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:CE,messages:[{role:"user",content:s}],max_tokens:AE}),timeoutMs:EE})}catch(u){return g.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:Rs("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:Rs("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:Rs("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 Lo(e,t,n,r){let s=_l();if(!s)return null;let o=_E(e);if(!o)return null;let i=Date.now();if(s==="mock"){let l=Rs(o,e,t,r);return await Ju({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=Rs(o,e,t,r);return await Ju({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 TE(e,t,r);return await Ju({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 ln(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 un(e){return lg(e.amount)}function RE(e,t,n){return n.has(e.resolvedTool)?0:Math.max(1,un(t[e.resolvedTool]))}function IE(){return Ba.join(Mo.homedir(),".visa-mcp","allium-results")}var jP=16*1024,BP=50*1024*1024;function PE(){let e=IE();try{if(!gt.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=gt.readdirSync(e),n=0,r=0;for(let s of t)try{let o=gt.statSync(Ba.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 $y=3600*1e3,zu=0;function $E(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function Uo(e){if(!Mm()&&!(Date.now()<zu))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($E(t)){let n=zu===0;zu=Date.now()+$y,n&&g.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:$y});return}g.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function NE(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 Ae(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 ye)return g.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:l.code,retryable:l.retryable}),ht(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 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 Lo("generate_image_card",e,t);if(n)return n;let r=await ln("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 Ae(async()=>{let o;try{o=await Gn({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:un(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)),Uo({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 ye)return g.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),ht(o,r);throw dn(o,{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName}),o}}async function ME(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 Lo("generate_image_fast_card",e,t);if(n)return n;let r=await ln("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 Ae(async()=>{let o;try{o=await Gn({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:un(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)),Uo({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 ye)return g.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),ht(o,r);throw dn(o,{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName}),o}}async function LE(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 Lo("generate_video_tempo_card",e,t);if(n)return n;let r=await ln("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 Ae(async()=>{let o;try{o=await Gn({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:un(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)),Uo({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 ye)return g.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),ht(o,r);throw dn(o,{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName}),o}}async function UE(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 ln("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 Ae(async()=>{let s;try{s=await Gn({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:un(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)),Uo({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 ye)return g.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),ht(s,n);throw dn(s,{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName}),s}}async function DE(e,t){let n=await ln("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 Ae(async()=>{let s;try{s=await Gn({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:un(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 ye)return g.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),ht(s,n);throw dn(s,{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName}),s}}async function jE(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 ln("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 Ae(async()=>{let s;try{s=await Gn({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:un(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 ye)return g.warn("payment:declined",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),ht(s,n);throw dn(s,{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName}),s}}var BE=["generate_music_tempo_card"],ks=10,Ny=5,Oy=new Map;function My(e){let t=Oy.get(e);if(t!==void 0)return t;let r=fo(e)?.isAsync===!0||BE.includes(e);return Oy.set(e,r),r}var HE=36e4,FE=18e4,VE=15e3,qE=12e4,KE=2e3;function Xu(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}function GE(e,t){return Ce.createHash("sha256").update(`${e}:${La(t)}`).digest("hex")}function WE(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,...Ua(n,r,o)});let l=0,u=0n;if(o?.success!==!1){let d=pt(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 YE(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 JE(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}`,b=`spend up to $${(h/100).toFixed(2)} across a batch of ${t.length}`,{batchParentId:_}=await Ae(async()=>{let y=await nt("batch_open",h,I,b,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:_});let w=[],R=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:Ms}=await U.shortcutParentlessBatchItem(x.resolvedTool,{batch_parent_id:_,batch_id:m,batch_index:y,batch_request_hash:GE(x.resolvedTool,x.params),item_ceiling_cents:o[y],idempotency_key:Zu(m,y,x.resolvedTool,x.params)},x.params,f,p,"batch");ho(Ms),yo(Z?.receipt_v2),K=await Vy(Z,null,Zu(m,y,x.resolvedTool,x.params))}let{deltaCharged:ve,deltaMicros:se}=WE({results:w,batchId:m,index:y,item:x,itemResult:K,preview:Y,isFree:X,catalogName:s[x.resolvedTool]?.name});R+=ve,E+=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,...Ua(m,y),error:K?.message||String(K)})}}return YE({results:w,resolvedItems:t,uniqueTools:a,isHomogeneous:c,primaryTool:l,merchantNames:u,totalAmount:d,totalCharged:R,totalChargedMicros:E,batchId:m,mode:"parentless"})}catch(y){if(y instanceof ye)return g.warn("payment:declined",{tool:"batch",batchTool:l,count:t.length,totalAmount:d,merchant:u,code:y.code,retryable:y.retryable}),ht(y,{amount:d,merchantName:u});throw dn(y,{tool:"batch",batchTool:l,count:t.length,totalAmount:d,merchant:u}),y}}async function zE(e,t){let n;if(Array.isArray(e.requests)&&e.requests.length>ks)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${ks} items. Please split into smaller batches.`};if(e.requests?.some(y=>y.tool||y.tool_id)&&e.requests)n=e.requests.map(y=>{let 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=bl({requestedTool:x})??x,{tool:X,tool_id:K,tier:ve,params:se,...Z}=y,Ms=se&&typeof se=="object"?{...se,...Z}:Z;return{resolvedTool:Y,params:Ms}});else if(e.tool){let y=bl({requestedTool:e.tool})??e.tool;if(e.count!==void 0){if(!Number.isSafeInteger(e.count)||e.count<1)return Xu("BATCH_INVALID_COUNT","Batch count must be a positive integer.");if(e.count>ks)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${ks} items. Please split into smaller batches.`}}n=(e.requests||(e.count!==void 0&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(Y=>({resolvedTool:y,params:Y}))}else return Xu("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return Xu("BATCH_EMPTY","Batch requires at least one item.");if(n.length>ks)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${ks} items. Please split into smaller batches.`};if([...new Set(n.map(y=>y.resolvedTool))].some(My)&&n.length>Ny)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${Ny} 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 eb(y);let l=new Set(i.filter(y=>c[y]&&qa(c[y]))),u={};for(let y of i)l.has(y)||(u[y]=await ln(y,void 0,t));let d=0;for(let y of n)d+=u[y.resolvedTool]?.amount??0;let f=n.map(y=>RE(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=>My(y.resolvedTool)),I=n.some(y=>y.resolvedTool.startsWith("or-")||y.resolvedTool==="run_llm"||y.resolvedTool==="execute_tool"),b=v?HE:I?FE+n.length*VE:qE+n.length*KE,_=Ce.randomUUID(),w=[],R=0,E=0n;return Ha(async()=>{let y=!On();if(Vp()&&!Ry&&y&&m>0)try{return await JE({resolvedItems:n,previews:u,freeTools:l,catalogEntries:c,itemCeilingCents:f,batchCeilingCents:m,uniqueTools:i,isHomogeneous:a,primaryTool:h,merchantNames:p,totalAmount:d,timeoutMs:b,batchId:_,userContext:t})}catch(x){if(x instanceof wt)Ry=!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 Ae(()=>Nl(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],Ms=u[Z.resolvedTool];try{let ue=l.has(Z.resolvedTool)?await U.shortcut(Z.resolvedTool,Z.params,b,t,"batch"):await Hy({toolId:Z.resolvedTool,toolParams:Z.params,estimatedAmountCents:f[se],userContext:t,metaTool:"batch",timeoutMs:b,idempotencyKey:Zu(_,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,...Ua(_,se,ue)}),ue?.success!==!1){let Ls=pt(ue?.amountMicros??ue?.amount_micros),Fd=typeof ue?.amount=="number"?ue.amount:Ms?.amount??0;Ls!==null&&Ls>0n?E+=Ls:E+=BigInt(Math.round(Fd*1e6)),R+=Fd}ue?.urls&&ue.urls.forEach(Ls=>tt(Ls))}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,...Ua(_,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((R+Number.EPSILON)*100)/100,ve=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:ve,mode:"session",batchId:_}),{success:Y>0,outcome:ve,batch_id:_,tool:a?i[0]:h,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 ye)return g.warn("payment:declined",{tool:"batch",batchTool:h,count:n.length,totalAmount:d,merchant:p,code:x.code,retryable:x.retryable}),ht(x,{amount:d,merchantName:p});throw dn(x,{tool:"batch",batchTool:h,count:n.length,totalAmount:d,merchant:p}),x}finally{if(y){let x=await zi(U);g.info("batch-session:closed",{budgetId:x.budgetId,closedServerSide:x.closedServerSide})}}})}function XE(){let e=!1,t;try{let r=Ba.join(Mo.homedir(),".claude","settings.json");if(gt.existsSync(r)){let s=JSON.parse(gt.readFileSync(r,"utf-8")),o=typeof s.statusLine=="object"?s.statusLine.command:"";e=vn(o)}}catch{}let n=fi();return n||(t="visa-cli config hud enable"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function ZE(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=PE();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=XE(),!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=rd,Array.isArray(t.cards)&&(t.cards=t.cards.map(o=>({...o,displayName:od(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 od(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 Yy(e,t){try{let r=((await U.getStatus(t)).cards||[]).find(s=>s?.id===e);if(r)return od(r)}catch(n){g.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function QE(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:od(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 ek(e,t){return await U.getTransactions({limit:e.limit,offset:e.offset},t)}async function tk(e,t){return await U.feedback(e.message,e.transaction_id,t)}async function nk(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Lr("MISSING_CONFIRMATION","Please confirm by setting confirm: true to charge your enrolled card for credits.");if(!e.amount||!Number.isFinite(e.amount)||e.amount<=0)return{success:!1,error:"amount must be a positive number in USD (e.g. 5.00)"};let n=Zi(String(e.amount));if(n.ok===!1)return{success:!1,error:n.error};let r=n.cents,s=r/100,o=Ce.randomUUID();g.info("buy_credits:attempt",{amountCents:r});try{return await Ae(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=eE(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 Kn)return gE();if(i instanceof it)return g.warn("buy_credits:ambiguous",{amountCents:r,code:i.code,transactionId:i.transactionId}),mE(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 rk(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 Ae(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 Kn)return Va(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 sk(e){let t=await po({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 id=new Set(["auth.serverUrl"]);function Oo(){return Object.keys(nr).filter(e=>!id.has(e)).sort()}function Jy(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:Oo()}}async function ok(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(id.has(e.key))return g.warn("config:set:rejected:mcp-forbidden",{key:e.key}),Jy(e.key,"set");g.info("config:set",{key:e.key});try{let t=Ti(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 Gt?"SERVER_CONTROLLED":t instanceof wn?"RETIRED_KEY":"INVALID_VALUE",r=t instanceof at?`Unknown setting "${e.key}". MCP-settable keys: ${Oo().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:Oo()}}}async function ik(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(id.has(e.key))return g.warn("config:unset:rejected:mcp-forbidden",{key:e.key}),Jy(e.key,"unset");g.info("config:unset",{key:e.key});try{let t=Ri(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 Gt?"SERVER_CONTROLLED":t instanceof wn?"RETIRED_KEY":"INVALID_VALUE",r=t instanceof at?`Unknown setting "${e.key}". MCP-settable keys: ${Oo().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:Oo()}}}async function ak(e){let t=await U.getStatus(e),n=t.attestationRequired!==!1,r=kt(t),s=fe(),o=n?r?s?`${Da()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${Da()} is not available in this process. ${sd()}`:"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 ck(e){g.info("biometric:on");let t=await Ki(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?(Wy(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:n.error||"unknown error"}}async function lk(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 Ae(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(`${Da()} 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 Wy(),{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 Kn)return Va(n,"biometric_off");throw n}}var Ly=3e4,uk=3e5;async function zy(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"?Xy(s,o,n):o.opened?{...await Zy(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 Xy(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 Zy(e,t,n="login"){let r=Date.now()+uk;for(;Date.now()<r;)try{let o=await fetch(`${Fa()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:Ly,...t&&{user_context:t}}),signal:AbortSignal.timeout(Ly+5e3)});if(!o.ok){await yn(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=Wp(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 yn(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 Qy(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"?Xy(n.recoveryUrl,r,"attestation-recovery"):r.opened?{...await Zy(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 dk(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 Yy(n,t)}`;try{return await Ae(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 Kn)return Va(o,"remove_card");throw o}}async function fk(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 Yy(n,t)} as default`;try{return await Ae(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 Kn)return Va(o,"set_default_card");throw o}}async function mk(e){return g.info("auth:login_attempt"),zy(`${Fa()}/login`,e)}async function pk(e=qy()){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 gk(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 hk(e={},t){let n;try{n=gk(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return Ha(async()=>{let r=await Ae(()=>og(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 yk(){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 bk(){return Ha(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 zi(U);g.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=cE(e),r=pt(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 ${aE(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 _k(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 zy(`${Fa()}/enroll-card?code=${encodeURIComponent(n)}`,e,"enrollment")}async function Uy(){if(await G.clearAll(),fe())try{await qi()}catch{}}async function vk(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 Uy(),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 Qy(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 Uy(),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 wk(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})
142
+ `),qm(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>\`
143
+ `)}function il(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(`
144
+ 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={};qr(C,{BRAND:()=>zv,DIRTY:()=>or,EMPTY_PATH:()=>Tv,INVALID:()=>D,NEVER:()=>Ow,OK:()=>$e,ParseStatus:()=>Ae,Schema:()=>F,ZodAny:()=>Tn,ZodArray:()=>zt,ZodBigInt:()=>ar,ZodBoolean:()=>cr,ZodBranded:()=>uo,ZodCatch:()=>_r,ZodDate:()=>lr,ZodDefault:()=>br,ZodDiscriminatedUnion:()=>Oi,ZodEffects:()=>Xe,ZodEnum:()=>hr,ZodError:()=>Be,ZodFirstPartyTypeKind:()=>j,ZodFunction:()=>Li,ZodIntersection:()=>mr,ZodIssueCode:()=>S,ZodLazy:()=>pr,ZodLiteral:()=>gr,ZodMap:()=>as,ZodNaN:()=>ls,ZodNativeEnum:()=>yr,ZodNever:()=>lt,ZodNull:()=>dr,ZodNullable:()=>Et,ZodNumber:()=>ir,ZodObject:()=>Fe,ZodOptional:()=>Je,ZodParsedType:()=>T,ZodPipeline:()=>fo,ZodPromise:()=>Rn,ZodReadonly:()=>vr,ZodRecord:()=>Mi,ZodSchema:()=>F,ZodSet:()=>cs,ZodString:()=>kn,ZodSymbol:()=>os,ZodTransformer:()=>Xe,ZodTuple:()=>Ct,ZodType:()=>F,ZodUndefined:()=>ur,ZodUnion:()=>fr,ZodUnknown:()=>Jt,ZodVoid:()=>is,addIssueToContext:()=>E,any:()=>ow,array:()=>lw,bigint:()=>ew,boolean:()=>rp,coerce:()=>Nw,custom:()=>ep,date:()=>tw,datetimeRegex:()=>Zm,defaultErrorMap:()=>Wt,discriminatedUnion:()=>mw,effect:()=>Ew,enum:()=>Sw,function:()=>_w,getErrorMap:()=>ns,getParsedType:()=>xt,instanceof:()=>Zv,intersection:()=>pw,isAborted:()=>$i,isAsync:()=>rs,isDirty:()=>Ni,isValid:()=>An,late:()=>Xv,lazy:()=>vw,literal:()=>ww,makeIssue:()=>lo,map:()=>yw,nan:()=>Qv,nativeEnum:()=>xw,never:()=>aw,null:()=>sw,nullable:()=>kw,number:()=>np,object:()=>uw,objectUtil:()=>al,oboolean:()=>$w,onumber:()=>Pw,optional:()=>Aw,ostring:()=>Iw,pipeline:()=>Rw,preprocess:()=>Tw,promise:()=>Cw,quotelessJson:()=>Ev,record:()=>hw,set:()=>bw,setErrorMap:()=>kv,strictObject:()=>dw,string:()=>tp,symbol:()=>nw,transformer:()=>Ew,tuple:()=>gw,undefined:()=>rw,union:()=>fw,unknown:()=>iw,util:()=>V,void:()=>cw});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 al;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(al||(al={}));var T=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 T.undefined;case"string":return T.string;case"number":return Number.isNaN(e)?T.nan:T.number;case"boolean":return T.boolean;case"function":return T.function;case"bigint":return T.bigint;case"symbol":return T.symbol;case"object":return Array.isArray(e)?T.array:e===null?T.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?T.promise:typeof Map<"u"&&e instanceof Map?T.map:typeof Set<"u"&&e instanceof Set?T.set:typeof Date<"u"&&e instanceof Date?T.date:T.object;default:return T.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"]),Ev=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),Be=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(o){return o.message},r={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(n(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return s(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,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()}};Be.create=e=>new Be(e);var Av=(e,t)=>{let n;switch(e.code){case S.invalid_type:e.received===T.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}},Wt=Av;var Wm=Wt;function kv(e){Wm=e}function ns(){return Wm}var lo=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}},Tv=[];function E(e,t){let n=ns(),r=lo({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Wt?void 0:Wt].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"}),or=e=>({status:"dirty",value:e}),$e=e=>({status:"valid",value:e}),$i=e=>e.status==="aborted",Ni=e=>e.status==="dirty",An=e=>e.status==="valid",rs=e=>typeof Promise<"u"&&e instanceof Promise;var O;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(O||(O={}));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}},Ym=(e,t)=>{if(An(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new Be(e.common.issues);return this._error=n,this._error}}};function H(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 F=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(rs(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 Ym(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 An(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=>An(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(rs(s)?s:Promise.resolve(s));return Ym(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 Xe({schema:this,typeName:j.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Je.create(this,this._def)}nullable(){return Et.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return zt.create(this)}promise(){return Rn.create(this,this._def)}or(t){return fr.create([this,t],this._def)}and(t){return mr.create(this,t,this._def)}transform(t){return new Xe({...H(this._def),schema:this,typeName:j.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new br({...H(this._def),innerType:this,defaultValue:n,typeName:j.ZodDefault})}brand(){return new uo({typeName:j.ZodBranded,type:this,...H(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new _r({...H(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 fo.create(this,t)}readonly(){return vr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Rv=/^c[^\s-]{8,}$/i,Iv=/^[0-9a-z]+$/,Pv=/^[0-9A-HJKMNP-TV-Z]{26}$/i,$v=/^[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,Nv=/^[a-z0-9_-]{21}$/i,Ov=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Mv=/^[-+]?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)?)??$/,Lv=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Uv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",cl,Dv=/^(?:(?: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])$/,jv=/^(?:(?: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])$/,Hv=/^(([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]))$/,Bv=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Fv=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Vv=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,zm="((\\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])))",qv=new RegExp(`^${zm}$`);function Xm(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 Kv(e){return new RegExp(`^${Xm(e)}$`)}function Zm(e){let t=`${zm}T${Xm(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 Gv(e,t){return!!((t==="v4"||!t)&&Dv.test(e)||(t==="v6"||!t)&&Hv.test(e))}function Wv(e,t){if(!Ov.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||t&&s.alg!==t)}catch{return!1}}function Yv(e,t){return!!((t==="v4"||!t)&&jv.test(e)||(t==="v6"||!t)&&Bv.test(e))}var kn=class e extends F{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==T.string){let o=this._getOrReturnCtx(t);return E(o,{code:S.invalid_type,expected:T.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")Lv.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")cl||(cl=new RegExp(Uv,"u")),cl.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")$v.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")Nv.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")Rv.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")Iv.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")Pv.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"?Zm(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"?qv.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{code:S.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?Kv(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"?Mv.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"duration",code:S.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?Gv(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"?Wv(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"?Yv(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"?Fv.test(t.data)||(s=this._getOrReturnCtx(t,s),E(s,{validation:"base64",code:S.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?Vv.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,...O.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...O.errToObj(t)})}url(t){return this._addCheck({kind:"url",...O.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...O.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...O.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...O.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...O.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...O.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...O.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...O.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...O.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...O.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...O.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...O.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,...O.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,...O.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...O.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...O.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...O.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...O.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...O.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...O.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...O.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...O.errToObj(n)})}nonempty(t){return this.min(1,O.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}};kn.create=e=>new kn({checks:[],typeName:j.ZodString,coerce:e?.coerce??!1,...H(e)});function Jv(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 ir=class e extends F{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)!==T.number){let o=this._getOrReturnCtx(t);return E(o,{code:S.invalid_type,expected:T.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"?Jv(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,O.toString(n))}gt(t,n){return this.setLimit("min",t,!1,O.toString(n))}lte(t,n){return this.setLimit("max",t,!0,O.toString(n))}lt(t,n){return this.setLimit("max",t,!1,O.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:O.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:O.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:O.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:O.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:O.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:O.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:O.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:O.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:O.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:O.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)}};ir.create=e=>new ir({checks:[],typeName:j.ZodNumber,coerce:e?.coerce||!1,...H(e)});var ar=class e extends F{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)!==T.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:T.bigint,received:n.parsedType}),D}gte(t,n){return this.setLimit("min",t,!0,O.toString(n))}gt(t,n){return this.setLimit("min",t,!1,O.toString(n))}lte(t,n){return this.setLimit("max",t,!0,O.toString(n))}lt(t,n){return this.setLimit("max",t,!1,O.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:O.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:O.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:O.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:O.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:O.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:O.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}};ar.create=e=>new ar({checks:[],typeName:j.ZodBigInt,coerce:e?.coerce??!1,...H(e)});var cr=class extends F{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==T.boolean){let r=this._getOrReturnCtx(t);return E(r,{code:S.invalid_type,expected:T.boolean,received:r.parsedType}),D}return $e(t.data)}};cr.create=e=>new cr({typeName:j.ZodBoolean,coerce:e?.coerce||!1,...H(e)});var lr=class e extends F{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==T.date){let o=this._getOrReturnCtx(t);return E(o,{code:S.invalid_type,expected:T.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:O.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:O.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}};lr.create=e=>new lr({checks:[],coerce:e?.coerce||!1,typeName:j.ZodDate,...H(e)});var os=class extends F{_parse(t){if(this._getType(t)!==T.symbol){let r=this._getOrReturnCtx(t);return E(r,{code:S.invalid_type,expected:T.symbol,received:r.parsedType}),D}return $e(t.data)}};os.create=e=>new os({typeName:j.ZodSymbol,...H(e)});var ur=class extends F{_parse(t){if(this._getType(t)!==T.undefined){let r=this._getOrReturnCtx(t);return E(r,{code:S.invalid_type,expected:T.undefined,received:r.parsedType}),D}return $e(t.data)}};ur.create=e=>new ur({typeName:j.ZodUndefined,...H(e)});var dr=class extends F{_parse(t){if(this._getType(t)!==T.null){let r=this._getOrReturnCtx(t);return E(r,{code:S.invalid_type,expected:T.null,received:r.parsedType}),D}return $e(t.data)}};dr.create=e=>new dr({typeName:j.ZodNull,...H(e)});var Tn=class extends F{constructor(){super(...arguments),this._any=!0}_parse(t){return $e(t.data)}};Tn.create=e=>new Tn({typeName:j.ZodAny,...H(e)});var Jt=class extends F{constructor(){super(...arguments),this._unknown=!0}_parse(t){return $e(t.data)}};Jt.create=e=>new Jt({typeName:j.ZodUnknown,...H(e)});var lt=class extends F{_parse(t){let n=this._getOrReturnCtx(t);return E(n,{code:S.invalid_type,expected:T.never,received:n.parsedType}),D}};lt.create=e=>new lt({typeName:j.ZodNever,...H(e)});var is=class extends F{_parse(t){if(this._getType(t)!==T.undefined){let r=this._getOrReturnCtx(t);return E(r,{code:S.invalid_type,expected:T.void,received:r.parsedType}),D}return $e(t.data)}};is.create=e=>new is({typeName:j.ZodVoid,...H(e)});var zt=class e extends F{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==T.array)return E(n,{code:S.invalid_type,expected:T.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:O.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:O.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:O.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,...H(t)});function ss(e){if(e instanceof Fe){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Je.create(ss(r))}return new Fe({...e._def,shape:()=>t})}else return e instanceof zt?new zt({...e._def,type:ss(e.element)}):e instanceof Je?Je.create(ss(e.unwrap())):e instanceof Et?Et.create(ss(e.unwrap())):e instanceof Ct?Ct.create(e.items.map(t=>ss(t))):e}var Fe=class e extends F{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)!==T.object){let l=this._getOrReturnCtx(t);return E(l,{code:S.invalid_type,expected:T.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 lt&&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 lt){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 O.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:O.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 ss(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 Je;)o=o._def.innerType;n[r]=o}return new e({...this._def,shape:()=>n})}keyof(){return Qm(V.objectKeys(this.shape))}};Fe.create=(e,t)=>new Fe({shape:()=>e,unknownKeys:"strip",catchall:lt.create(),typeName:j.ZodObject,...H(t)});Fe.strictCreate=(e,t)=>new Fe({shape:()=>e,unknownKeys:"strict",catchall:lt.create(),typeName:j.ZodObject,...H(t)});Fe.lazycreate=(e,t)=>new Fe({shape:e,unknownKeys:"strip",catchall:lt.create(),typeName:j.ZodObject,...H(t)});var fr=class extends F{_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new Be(a.ctx.common.issues));return 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 Be(c));return E(n,{code:S.invalid_union,unionErrors:a}),D}}get options(){return this._def.options}};fr.create=(e,t)=>new fr({options:e,typeName:j.ZodUnion,...H(t)});var Yt=e=>e instanceof pr?Yt(e.schema):e instanceof Xe?Yt(e.innerType()):e instanceof gr?[e.value]:e instanceof hr?e.options:e instanceof yr?V.objectValues(e.enum):e instanceof br?Yt(e._def.innerType):e instanceof ur?[void 0]:e instanceof dr?[null]:e instanceof Je?[void 0,...Yt(e.unwrap())]:e instanceof Et?[null,...Yt(e.unwrap())]:e instanceof uo||e instanceof vr?Yt(e.unwrap()):e instanceof _r?Yt(e._def.innerType):[],Oi=class e extends F{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==T.object)return E(n,{code:S.invalid_type,expected:T.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=Yt(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,...H(r)})}};function ll(e,t){let n=xt(e),r=xt(t);if(e===t)return{valid:!0,data:e};if(n===T.object&&r===T.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=ll(e[a],t[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===T.array&&r===T.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=ll(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===T.date&&r===T.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var mr=class extends F{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=(o,i)=>{if($i(o)||$i(i))return D;let a=ll(o.value,i.value);return a.valid?((Ni(o)||Ni(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}))}};mr.create=(e,t,n)=>new mr({left:e,right:t,typeName:j.ZodIntersection,...H(n)});var Ct=class e extends F{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==T.array)return E(r,{code:S.invalid_type,expected:T.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,...H(t)})};var Mi=class e extends F{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!==T.object)return E(r,{code:S.invalid_type,expected:T.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 F?new e({keyType:t,valueType:n,typeName:j.ZodRecord,...H(r)}):new e({keyType:kn.create(),valueType:t,typeName:j.ZodRecord,...H(n)})}},as=class extends F{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!==T.map)return E(r,{code:S.invalid_type,expected:T.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}}}};as.create=(e,t,n)=>new as({valueType:t,keyType:e,typeName:j.ZodMap,...H(n)});var cs=class e extends F{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==T.set)return E(r,{code:S.invalid_type,expected:T.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:O.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:O.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};cs.create=(e,t)=>new cs({valueType:e,minSize:null,maxSize:null,typeName:j.ZodSet,...H(t)});var Li=class e extends F{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==T.function)return E(n,{code:S.invalid_type,expected:T.function,received:n.parsedType}),D;function r(a,c){return lo({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,ns(),Wt].filter(l=>!!l),issueData:{code:S.invalid_arguments,argumentsError:c}})}function s(a,c){return lo({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,ns(),Wt].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 Rn){let a=this;return $e(async function(...c){let l=new Be([]),u=await a._def.args.parseAsync(c,o).catch(m=>{throw l.addIssue(r(c,m)),l}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,o).catch(m=>{throw l.addIssue(s(d,m)),l})})}else{let a=this;return $e(function(...c){let l=a._def.args.safeParse(c,o);if(!l.success)throw new Be([r(c,l.error)]);let u=Reflect.apply(i,this,l.data),d=a._def.returns.safeParse(u,o);if(!d.success)throw new Be([s(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Ct.create(t).rest(Jt.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(Jt.create()),returns:n||Jt.create(),typeName:j.ZodFunction,...H(r)})}},pr=class extends F{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})}};pr.create=(e,t)=>new pr({getter:e,typeName:j.ZodLazy,...H(t)});var gr=class extends F{_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}};gr.create=(e,t)=>new gr({value:e,typeName:j.ZodLiteral,...H(t)});function Qm(e,t){return new hr({values:e,typeName:j.ZodEnum,...H(t)})}var hr=class e extends F{_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 $e(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};hr.create=Qm;var yr=class extends F{_parse(t){let n=V.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==T.string&&r.parsedType!==T.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 $e(t.data)}get enum(){return this._def.values}};yr.create=(e,t)=>new yr({values:e,typeName:j.ZodNativeEnum,...H(t)});var Rn=class extends F{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==T.promise&&n.common.async===!1)return E(n,{code:S.invalid_type,expected:T.promise,received:n.parsedType}),D;let r=n.parsedType===T.promise?n.data:Promise.resolve(n.data);return $e(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Rn.create=(e,t)=>new Rn({type:e,typeName:j.ZodPromise,...H(t)});var Xe=class extends F{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"?or(c.value):n.value==="dirty"?or(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"?or(a.value):n.value==="dirty"?or(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(!An(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=>An(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:n.value,value:a})):D);V.assertNever(s)}};Xe.create=(e,t,n)=>new Xe({schema:e,typeName:j.ZodEffects,effect:t,...H(n)});Xe.createWithPreprocess=(e,t,n)=>new Xe({schema:t,effect:{type:"preprocess",transform:e},typeName:j.ZodEffects,...H(n)});var Je=class extends F{_parse(t){return this._getType(t)===T.undefined?$e(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Je.create=(e,t)=>new Je({innerType:e,typeName:j.ZodOptional,...H(t)});var Et=class extends F{_parse(t){return this._getType(t)===T.null?$e(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Et.create=(e,t)=>new Et({innerType:e,typeName:j.ZodNullable,...H(t)});var br=class extends F{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===T.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};br.create=(e,t)=>new br({innerType:e,typeName:j.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...H(t)});var _r=class extends F{_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 rs(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Be(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Be(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};_r.create=(e,t)=>new _r({innerType:e,typeName:j.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...H(t)});var ls=class extends F{_parse(t){if(this._getType(t)!==T.nan){let r=this._getOrReturnCtx(t);return E(r,{code:S.invalid_type,expected:T.nan,received:r.parsedType}),D}return{status:"valid",value:t.data}}};ls.create=e=>new ls({typeName:j.ZodNaN,...H(e)});var zv=Symbol("zod_brand"),uo=class extends F{_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}},fo=class e extends F{_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(),or(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})}},vr=class extends F{_parse(t){let n=this._def.innerType._parse(t),r=s=>(An(s)&&(s.value=Object.freeze(s.value)),s);return rs(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};vr.create=(e,t)=>new vr({innerType:e,typeName:j.ZodReadonly,...H(t)});function Jm(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function ep(e,t={},n){return e?Tn.create().superRefine((r,s)=>{let o=e(r);if(o instanceof Promise)return o.then(i=>{if(!i){let a=Jm(t,r),c=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=Jm(t,r),a=i.fatal??n??!0;s.addIssue({code:"custom",...i,fatal:a})}}):Tn.create()}var Xv={object:Fe.lazycreate},j;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(j||(j={}));var Zv=(e,t={message:`Input not instance of ${e.name}`})=>ep(n=>n instanceof e,t),tp=kn.create,np=ir.create,Qv=ls.create,ew=ar.create,rp=cr.create,tw=lr.create,nw=os.create,rw=ur.create,sw=dr.create,ow=Tn.create,iw=Jt.create,aw=lt.create,cw=is.create,lw=zt.create,uw=Fe.create,dw=Fe.strictCreate,fw=fr.create,mw=Oi.create,pw=mr.create,gw=Ct.create,hw=Mi.create,yw=as.create,bw=cs.create,_w=Li.create,vw=pr.create,ww=gr.create,Sw=hr.create,xw=yr.create,Cw=Rn.create,Ew=Xe.create,Aw=Je.create,kw=Et.create,Tw=Xe.createWithPreprocess,Rw=fo.create,Iw=()=>tp().optional(),Pw=()=>np().optional(),$w=()=>rp().optional(),Nw={string:(e=>kn.create({...e,coerce:!0})),number:(e=>ir.create({...e,coerce:!0})),boolean:(e=>cr.create({...e,coerce:!0})),bigint:(e=>ar.create({...e,coerce:!0})),date:(e=>lr.create({...e,coerce:!0}))};var Ow=D;var Mw=/^[A-Za-z0-9._-]+$/,Lw=/^[A-Za-z0-9._-]+(\|[A-Za-z0-9._-]+)*$/,sp=new Set([".",".."]),je=class extends Error{pattern;constructor(t,n){super(`Invalid freeReadPathPattern ${JSON.stringify(n)}: ${t}`),this.pattern=n,this.name="FreePathPatternError"}};function Uw(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(!Lw.test(s))throw new je(`malformed alternation segment ${JSON.stringify(e)}`,t);let o=s.split("|");if(o.some(i=>sp.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(Mw.test(e)){if(sp.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 Dw(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=>Uw(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 ul(e){Dw(e)}var op=["tempo","mpp_self","merchant_self"],ip=["catalog_static","fal_direct","fal_queue","openrouter_chat","openrouter_image","platform_proxy","tempo_gateway","x402_gateway"],ap=["image","audio","queued_audio","video","queued_video","model_3d","llm","transcription","utility"],cp=["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 fl=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()}),jw=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:fl.optional()}).passthrough(),ml=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")})]),pl=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()}),lp=C.object({attestation:C.boolean().optional(),rateLimitMs:C.number().positive().optional()}),up=C.object({displayName:C.string().optional(),feedbackEligible:C.boolean().optional(),suggestionEligible:C.boolean().optional(),batchable:C.boolean().optional()}),dp=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(),Hw=C.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),Bw=120,Fw=120,Vw=1200,qw=/^[^\u0000-\u001F\u007F]+$/;function dl(e,t){return C.string().min(1).max(e).regex(qw,`${t} must not contain control characters`)}var gl={id:C.string().min(1),name:dl(Bw,"name"),description:dl(Vw,"description"),provider:C.string().min(1),model:C.string().min(1),category:Hw,priceCents:C.number().nonnegative(),inputSchema:C.record(C.unknown()),gatewayUrl:C.string().min(1),merchantName:dl(Fw,"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:fl.optional(),priceDisplay:C.string().optional(),pricingModel:C.enum(["per-call","per-token","band"]).optional(),pricingInfo:jw.optional(),status:C.enum(["available","unavailable"]).optional(),handler:ml.optional(),pricing:pl.optional(),security:lp.optional(),engagement:up.optional(),gatewayConfig:dp.optional(),freeReadPathPattern:C.string().optional().superRefine((e,t)=>{if(e!==void 0)try{ul(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(op).optional(),executionKind:C.enum(ip).optional(),resultKind:C.enum(ap).optional(),extractionMode:C.enum(cp).optional(),pricingStrategy:C.enum(["flat","token","band"]).optional()},fp=C.object({...gl,dispatch:C.literal("routed"),routedPath:C.string().min(1).startsWith("/")}).strict(),mp=C.object({...gl,dispatch:C.literal("enveloped")}).strict(),pp=C.object({...gl,handler:ml,pricing:pl}).strict(),gp=C.union([C.discriminatedUnion("dispatch",[fp,mp]),pp]);var Ww="https://fal.run",_p="https://openrouter.mpp.tempo.xyz",yl=1024,Di=8192,Yw=4096,Jw=10;function zw(e){return e>=Jw?Yw:Di}function vp(e,t){let n=typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):yl;return Math.min(n,t)}var Xw=["num_images","num_outputs","num_samples","num_videos","batch_size","n"];function wp(e){for(let t of Xw)delete e[t];return e}function Zw(e){let{attestation:t,tool_id:n,...r}=e;return wp(r)}var hp={"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 Ui(e){let{attestation:t,tool_id:n,aspect_ratio:r,image_size:s,...o}=e,i=wp({...o});return typeof s=="string"&&s.length>0?(i.image_size=s,i):(typeof r=="string"&&hp[r]&&(i.image_size=hp[r]),i)}function Qw(e){let{attestation:t,tool_id:n,...r}=e;return r}function yp(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 eS(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 tS(e,t,n,r,s,o,i,a){return eS(e,t,n,"suno-ai",r,s,o,i,{merchantName:"Suno AI",...a})}function be(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:`${Ww}/${r}`,merchantName:"fal.ai",buildBody:Zw,tags:[],...a}}function Sp(e,t=Di){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:vp(c??l,t),usage:{include:!0}}}}function xp(e,t=Di){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,_=[{type:"text",text:o}];return typeof i=="string"&&i.length>0&&_.push({type:"image_url",image_url:{url:i}}),{messages:Array.isArray(f)?f:[{role:"user",content:_}],temperature:p??.7,...h,model:e,...typeof a=="string"&&a.length>0?{image_config:{aspect_ratio:a}}:{},max_tokens:vp(c??l,t),usage:{include:!0}}}}function le(e,t,n,r,s,o,i){let a=i?.maxOutputTokens??zw(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: ${yl}); 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:`${_p}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:Sp(r,a),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:s,outputPerMillion:o,...c>0?{perRequestFeeCents:c}:{}},...p}}function hl(e,t,n,r,s,o){let i=o?.maxOutputTokens??Di,{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: ${yl}); 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:`${_p}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:xp(r,i),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...c}}var bl=[be("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"]}),be("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:Ui}),be("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:Ui}),be("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:Ui}),be("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"]}),hl("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),hl("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}}),hl("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}}),be("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"]}),be("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"]}),be("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"]}),be("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"]}),be("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"]}),be("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"]}),be("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"]}),be("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"]}),be("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"]}),tS("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}}}),be("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"]}),be("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"]}),be("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"]}),be("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:yp,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:Qw,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=>Ui({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"]},be("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"}),be("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:yp,tags:["onchain","prices","allium","crypto","legacy"]}];function mo(e){return bl.find(t=>t.id===e)}var sS=[{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 oS(e,t){let r=(Array.isArray(t.type)?t.type:t.type!==void 0?[t.type]:[]).flatMap(o=>sS.filter(i=>i.type===o)),s=new Set(r.filter(o=>o.matches(e)).map(o=>o.type));return{declared:r,matched:s}}function _l(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}=oS(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 Fa=A(ds());var Vi=require("child_process"),Up=require("util"),Dp=A(require("crypto")),ne=A(require("fs")),jp=A(require("os")),Ne=A(require("path"));Kt();var dt=(0,Up.promisify)(Vi.execFile),PS=6e4,$S=()=>process.platform==="darwin",In=()=>process.platform==="win32",Pn=Ne.join(jp.homedir(),".visa-mcp","bin"),wr=Ne.join(Pn,"Visa CLI"),Qt=Ne.join(Pn,"visa-keychain-win.exe"),Hp=Ne.join(__dirname,"..","native"),Tp="6",Rp=Ne.join(Pn,"visa-keychain.version"),Ip=Ne.join(Pn,"visa-keychain.sha256"),Pp="1",$p=Ne.join(Pn,"visa-keychain-win.version"),Np=Ne.join(Pn,"visa-keychain-win.sha256"),Bp=[Ne.join(Hp,"bin","win32-x64","visa-keychain-win.exe"),Ne.resolve(__dirname,"..","..","native","bin","win32-x64","visa-keychain-win.exe"),Ne.resolve(__dirname,"..","native","bin","win32-x64","visa-keychain-win.exe")];function Hi(e){let t=ne.readFileSync(e);return Dp.createHash("sha256").update(t).digest("hex")}function NS(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 Op(e){let t=typeof e?.message=="string"?e.message:"";return e?.code==="ETIMEDOUT"||e?.killed===!0||/timed out|timeout/i.test(t)}function Mp(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 vl(){try{if(ne.readFileSync(Rp,"utf-8").trim()===Tp&&ne.existsSync(wr)){let r=ne.readFileSync(Ip,"utf-8").trim();if(Hi(wr)!==r)g.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),ne.unlinkSync(wr);else return wr}}catch{}let e=Ne.join(Hp,"visa-keychain.m");if(ne.existsSync(e)||(e=Ne.resolve(__dirname,"..","..","native","visa-keychain.m")),ne.existsSync(e)||(e=Ne.resolve(__dirname,"..","native","visa-keychain.m")),!ne.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");ne.mkdirSync(Pn,{recursive:!0,mode:448});try{await dt("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",wr,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=Hi(wr);return ne.writeFileSync(Ip,t,{mode:384}),ne.writeFileSync(Rp,Tp,{mode:384}),wr}function Fp(){for(let e of Bp)if(ne.existsSync(e))return e;return null}async function fs(){try{if(ne.readFileSync($p,"utf-8").trim()===Pp&&ne.existsSync(Qt)){let r=ne.readFileSync(Np,"utf-8").trim();if(Hi(Qt)!==r)g.warn("binary:hash-mismatch:win32",{message:"Windows binary hash mismatch. Redeploying."}),ne.unlinkSync(Qt);else return Qt}}catch{}let e=Fp();if(!e)throw new Error(`visa-keychain-win.exe not found in package. Reinstall @visa/cli.
145
+ If building from source, run native/build-win.bat first.`);ne.mkdirSync(Pn,{recursive:!0}),ne.copyFileSync(e,Qt);let t=Hi(Qt);return ne.writeFileSync(Np,t,{mode:384}),ne.writeFileSync($p,Pp,{mode:384}),Qt}async function OS(){return In()?fs():vl()}var Bi="visa-cli",Fi="attestation-key";async function MS(e){try{await dt("security",["delete-generic-password","-s",Bi,"-a",Fi],{timeout:5e3})}catch{}await dt("security",["add-generic-password","-s",Bi,"-a",Fi,"-w",e],{timeout:5e3})}function LS(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 US(){try{let{stdout:e}=await dt("security",["find-generic-password","-s",Bi,"-a",Fi,"-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:LS(e)}}}async function wl(){let e=await US();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 Vp(e){let t=await OS(),n;try{n=(await dt(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 NS(n)}var Lp=!1;function DS(){if(!In())return!1;try{return ne.existsSync(Qt)||Fp()!==null?!0:(Lp||(Lp=!0,g.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:Qt,searchedPrebuiltPaths:Bp})),!1)}catch{return!1}}function fe(){return Kr()||$S()?!0:In()?DS():!1}async function qi(){if(In()){let s=await fs(),{stdout:o}=await dt(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 Vp(["generate-key"]);if(!e)throw new Error("Key generation returned no output");let t=e.indexOf(":");if(t<0)throw new Error("Unexpected generate-key output format");let n=e.slice(0,t),r=e.slice(t+1);return await MS(n),r}async function Ki(){if(In())try{let e=await fs(),{stdout:t}=await dt(e,["public-key"],{timeout:1e4});return t.trim().startsWith("OK:")}catch{return!1}return await wl()!==null}async function qp(){if(Kr())return"mock-public-key-spki";if(In()){let n=await fs(),{stdout:r}=await dt(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 wl();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await vl();return new Promise((n,r)=>{let s=(0,Vi.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 $n(e,t,n={}){if(Kr())return Promise.resolve(sf());let r=n.timeoutMs??PS;if(In()){let a=await fs(),c=["sign",e];t&&c.push(t);let l;try{l=(await dt(a,c,{timeout:r})).stdout}catch(d){throw Op(d)?Mp(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 wl();if(!s)throw new Error("Attestation key not found. Run setup to generate a new key.");let o=await vl(),i=["sign",e];return t&&i.push(t),new Promise((a,c)=>{let l=(0,Vi.execFile)(o,i,{timeout:r},(u,d)=>{let f=(d||"").trim();if(u){f.startsWith("ERROR:")?c(new Error(f.slice(6))):Op(u)?c(Mp(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 Gi(){if(In()){try{let e=await fs();await dt(e,["delete-key"],{timeout:1e4})}catch{}return}try{await dt("security",["delete-generic-password","-s",Bi,"-a",Fi],{timeout:5e3})}catch{}try{await Vp(["delete-key"])}catch{}}Kt();var jS=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],HS=[...jS.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 Sl(e,t=HS){for(let n of t)if(n.toolId===e.requestedTool)return n.targetToolId;return null}var Wi=require("node:crypto"),en=A(require("node:fs")),go=A(require("node:path"));Xc();var BS="agent-enroll-pending.json",FS="agent-credential.json",Kp=15*6e4;function xl(){return go.join(Sn.getConfigDir(),BS)}function VS(){return go.join(Sn.getConfigDir(),FS)}function Gp(e,t){en.mkdirSync(go.dirname(e),{recursive:!0,mode:448}),en.rmSync(e,{force:!0}),en.writeFileSync(e,t,{mode:384})}function Wp(e=Date.now()){let t=(0,Wi.randomBytes)(32).toString("base64url"),n=(0,Wi.createHash)("sha256").update(t,"utf8").digest("base64url"),r={verifier:t,challenge:n,createdAt:e};return Gp(xl(),JSON.stringify(r,null,2)),{challenge:n}}function qS(){try{let e=JSON.parse(en.readFileSync(xl(),"utf8"));return typeof e?.verifier=="string"&&typeof e?.challenge=="string"&&typeof e?.createdAt=="number"?e:null}catch{return null}}var KS=e=>new Promise(t=>setTimeout(t,e));async function Yp(e,t={}){let{attempts:n=5,delayMs:r=3e3,fetchImpl:s=fetch,sleep:o=KS,now:i=Date.now}=t,a=qS();if(!a)return{status:"no_pending"};let c=e;for(;c.endsWith("/");)c=c.slice(0,-1);let l=`${c}/api/vgs/cli-handoff/claim`;for(let u=1;u<=n;u++){let d;try{d=await s(l,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({verifier:a.verifier})})}catch(m){return{status:"error",message:`Could not reach the enrollment service to claim the credential: ${m.message}`}}if(d.ok){let p=(await d.json().catch(()=>null))?.payload;if(!p||typeof p.tokenId!="string"||p.assuranceData==null)return{status:"error",message:"Claim response was malformed \u2014 try enrolling again."};let h={name:typeof p.name=="string"?p.name:void 0,agentJkt:typeof p.agentJkt=="string"?p.agentJkt:void 0,tokenId:p.tokenId,assuranceData:p.assuranceData,claimedAt:new Date(i()).toISOString(),source:e},_=VS();return Gp(_,JSON.stringify(h,null,2)),en.rmSync(xl(),{force:!0}),{status:"claimed",name:h.name,tokenId:h.tokenId,credentialPath:_}}if(d.status===404){u<n&&await o(r);continue}return d.status===429?{status:"not_ready",likelyExpired:i()-a.createdAt>Kp}:{status:"error",message:(await d.json().catch(()=>({}))).error||`Claim failed (${d.status}).`}}return{status:"not_ready",likelyExpired:i()-a.createdAt>Kp}}function Cl(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function Jp(e=process.env){return Cl(e)!==null}var GS=new Set(["false","0","no","off","disable","disabled"]),WS=new Set(["true","1","yes","on","enable","enabled"]);function zp(e){let t=(e??"").trim().toLowerCase();return t?GS.has(t)?!1:!!WS.has(t):!0}function Xp(e=process.env){return zp(e.VISA_CLI_PARENTLESS_SINGLE_CALL)}function Zp(e=process.env){return zp(e.VISA_CLI_PARENTLESS_BATCH)}var Jy=require("child_process"),Ce=A(require("crypto")),gt=A(require("fs")),Uo=A(require("os")),Va=A(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"?Gr(s):null,i=Array.isArray(n.urls)?n.urls[0]:void 0,c=typeof i=="string"&&i.startsWith("data:")?Gr(i):null;if(!o&&!c)return e;let l=o??c,u=o?"content":"urls",d;try{d=Bs(l,{tag:YS(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 YS(e,t){let n=typeof t.transactionId=="string"?t.transactionId:typeof t.transaction_id=="string"?t.transaction_id:null;return n?`${e}-${n}`:e}Kt();var El=!1;async function Sr(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")||!fe())throw r;if(g.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(El)throw g.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;El=!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 qi();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 El=!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 Yi(e,t){if(!fe())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 Ki())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."}}ct();var Qp="4.0.0-rc.21";function Al(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function kl(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=Ri(t);return s!==void 0?{value:s,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function Ze(e){return e==null?"\u2014":e?"yes":"no"}function Ji(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function JS(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function zS(){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=rl("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:tl,source:{kind:"default"}}}async function ho(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(k){n=k?.message||"unknown error"}let r=[],s=process.env.VISA_AUTH_URL,o=nl("auth.serverUrl"),i=de(),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:Ze(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:Ze(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:Ze(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:fe(),formatted:Ze(fe()),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:Ji(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:Ji(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:Ji(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:Ji(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(k=>k.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=zS();r.push({key:"credit.sessionCapCents",value:m.value,formatted:JS(m.value),source:m.source});let p=Dm();p.length>0&&r.push({key:"settings.retired",value:p.map(k=>k.key),formatted:p.map(k=>k.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${p.map(k=>`visa-cli config unset ${k.key}`).join(" && ")}`});let h=kl("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:h.value,formatted:Ze(h.value),source:h.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let _=kl("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:_.value,formatted:Ze(_.value),source:_.source});let I=St(),b;process.env.VISA_CLI_NO_UPDATE_CHECK?b={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?b={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?b={kind:"env",var:"NODE_ENV"}:b={kind:"default"},r.push({key:"ui.updateCheck",value:!I,formatted:Ze(!I),source:b});let v=kl("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:v.value,formatted:Ze(v.value),source:v.source});let w=process.env.VISA_DRY_RUN,R=Jp();if(r.push({key:"tools.dryRun",value:R,formatted:Ze(R),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:Qp,formatted:Qp,source:{kind:"default"}}),e.includeDev){let k=process.env.VISA_MOCK_KEYCHAIN,y=mn();r.push({key:"dev.mockKeychain",value:y,formatted:Ze(y),source:Al("VISA_MOCK_KEYCHAIN",!!k),hint:pc()});let x=process.env.VISA_MOCK_TOUCHID,Y=Kr();r.push({key:"dev.mockTouchid",value:Y,formatted:Ze(Y),source:Al("VISA_MOCK_TOUCHID",!!x),hint:pc()});let X=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!X,formatted:Ze(!!X),source:Al("VISA_CLI_DEBUG",!!X)})}return{entries:r,statusError:n}}function XS(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 eg(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}(${XS(o.source)})`),t.verbose&&o.hint&&s.push(` ${"\u21B3".padStart(n)} ${o.hint}`)}return s.join(`
146
+ `)}function tg(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 ng(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"}]}}}ct();Kt();var Nn=require("fs"),sg=require("os"),Tl=require("path"),ZS=(0,Tl.join)((0,sg.homedir)(),".visa-mcp"),rg=(0,Tl.join)(ZS,"mcp-session-budget.json");function zi(){try{(0,Nn.existsSync)(rg)&&(0,Nn.unlinkSync)(rg)}catch{}}var Il=require("crypto"),ft=A(ds()),Cr=null,Ge=0,Mn=0,Ve=0,On=null,Pl=null,$l=null,xr=Promise.resolve();function QS(e){return Number((0,ft.fromCents)(e))}function ig(e){return(0,ft.toCents)((0,ft.micros)(BigInt(e)))}function og(e){return(0,ft.toWire)((0,ft.fromCents)(e))}function Rl(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Xi(e){return typeof e=="string"&&/^\d+$/.test(e)}var ex=43,tx=new RegExp(`^[A-Za-z0-9_-]{${ex}}$`);function nx(e){return typeof e=="string"&&tx.test(e)}function rx(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||Cr&&e.session_id!==Cr||typeof e.nonce!="string"||e.nonce.length===0||!nx(e.server_signature)||!Rl(e.cumulative)||!Rl(e.remaining)||!Rl(e.delta)||e.cumulative<Ge||Ve>0&&e.cumulative>Ve||Ve>0&&e.remaining>Ve||e.cumulative_micros!==void 0&&!Xi(e.cumulative_micros)||e.remaining_micros!==void 0&&!Xi(e.remaining_micros)||e.delta_micros!==void 0&&!Xi(e.delta_micros)||e.reserved_micros!==void 0&&!Xi(e.reserved_micros))}function tn(e){Cr=e,Ge=0,Mn=0,Ve=0,On=null,Pl=null,$l=null,xr=Promise.resolve()}function yo(e){Ve=Math.max(0,Math.floor(e))}function Nl(){return Cr}function Ol(e){if(!Cr)return null;let t=Ge+Mn;return Ve>0&&t>Ve&&(t=Ve),{session_budget_id:Cr,cumulative_micros:QS(t),nonce:(0,Il.randomUUID)(),idempotency_key:e||(0,Il.randomUUID)()}}function bo(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 rx(r)?(Ge=Math.max(Ge,r.cumulative),Mn=0,On=r,r):null}function ag(){return On}function Ml(e){let t=ig(e.cumulative_micros);Ge=Math.max(Ge,t),Mn=0;let n={status:"accepted",session_id:e.session_budget_id,cumulative:Ge,remaining:Math.max(0,Ve-Ge),delta:0,cumulative_micros:og(Ge),remaining_micros:og(Math.max(0,Ve-Ge)),delta_micros:"0",nonce:e.nonce};return On=n,n}function _o(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,ft.toCents)((0,ft.micros)(n));if(!Number.isFinite(r)||r<0)return;Pl=t;let s=e,o=typeof s.session_id=="string"?s.session_id:Cr??"";On?(typeof s.remaining_micros=="string"&&/^\d+$/.test(s.remaining_micros)&&(On.remaining_micros=s.remaining_micros),typeof s.charged_micros=="string"&&/^\d+$/.test(s.charged_micros)&&(On.delta_micros=s.charged_micros)):On={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 cg(e){let t=e.receipt??null;$l={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:ig(e.voucher.cumulative_micros),estimatedCumulativeCents:Zi(),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 lg(){return $l}function ug(){return Ge}function dg(){return Pl}function Zi(){let e=Ge+Mn;return Ve>0&&e>Ve&&(e=Ve),e}function Ll(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return xr=xr.then(()=>{Mn+=t}),xr}function vo(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return xr=xr.then(()=>{Mn=Math.max(0,Mn-t)}),xr}var sx=10,ox=1,me=null,fg=Promise.resolve();function Ul(e){let t=fg.catch(()=>{}).then(e);return fg=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 Dl(e,t,n){return Ul(()=>mg(e,t,n))}async function mg(e,t,n){if(zi(),me&&new Date(me.expiresAt).getTime()>Date.now())return Nl()!==me.budgetId&&(tn(me.budgetId),yo(me.totalCents)),g.info("mcp-session:active-hit",{budgetId:me.budgetId,tool:n.toolName,remainingEstimatedCents:me.totalCents-Zi()}),{budgetId:me.budgetId,isFresh:!1,totalCents:me.totalCents,requestedCapCents:me.totalCents,appliedCapCents:me.totalCents,clampedReason:null};me&&(me=null,tn(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"?ox:sx,i=Math.max(o,Math.ceil(n.minRequiredCents??o));if(r.balanceCents<i)throw new xe(r.balanceCents,i);let a=n.capCentsOverride??Bm(),c=Math.min(a,r.balanceCents),l=c<a?"balance":null,u=await t("session_create",c,"Visa CLI Session",`open credit-model session with $${(c/100).toFixed(2)} cap`,n.userContext),d=await e.createSessionBudget({total_cents:c,session_kind:s,...u?{attestation:u}:{}});if(!d.success||!d.budget){let m=d.error||"unknown error";throw new Error(`Failed to open credit session: ${m}`)}let f={budgetId:d.budget.id,expiresAt:d.budget.expiresAt,totalCents:d.budget.totalCents,createdAt:d.budget.createdAt};return me=f,tn(f.budgetId),yo(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 pg(e,t,n){return Ul(async()=>{let s=Ln()?await gg(e):null,o=await mg(e,t,n);return{budgetId:o.budgetId,totalCents:o.totalCents,closedPrevious:s,requestedCapCents:o.requestedCapCents,appliedCapCents:o.appliedCapCents,clampedReason:o.clampedReason}})}async function gg(e){let n=Ln()?.budgetId??Nl(),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 zi(),me=null,tn(null),{closedServerSide:r,budgetId:n,finalCumulativeCents:s,finalCumulativeMicros:o}}async function Qi(e){return Ul(()=>gg(e))}function Ln(){return zi(),me?new Date(me.expiresAt).getTime()<=Date.now()?(me=null,tn(null),null):{budgetId:me.budgetId,totalCents:me.totalCents,lastReceiptCumulative:ug(),lastReceiptCumulativeMicros:ag()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:dg(),estimatedCumulative:Zi(),lastToolSpend:lg(),expiresAt:me.expiresAt}:null}var yg=A(ds()),hg=10000n;function ix(e){return e<=0n?0:Number((e+hg-1n)/hg)}function bg(e){return ix((0,yg.fromUsd)(e))}var ea=A(ds()),ax=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;function ta(e){if(typeof e!="string"||!ax.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,ea.toDisplay)((0,ea.fromCents)(s),{symbol:""})}}var na="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.",_g="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.";ct();var Ly=Promise.resolve();function mA(e,t){if(e)try{let n=(0,Fa.fromWire)(e),r=n%10000n===0n?2:6;return(0,Fa.toDisplay)(n,{decimals:r})}catch{}return`$${(t/100).toFixed(2)}`}var Uy=!1,Dy=!1,jy=!1;function qa(e){let t=Ly.catch(()=>{}).then(e);return Ly=t.then(()=>{},()=>{}),t}async function zy(e){let t=await Ee(()=>Dl(U,nt,{toolName:e.toolId,userContext:e.userContext}));await Ll(e.estimatedAmountCents);let n=Ol(e.idempotencyKey);if(!n)throw await vo(e.estimatedAmountCents),new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await xA(),s,o,i=async()=>U.shortcutWithSession(e.toolId,n,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);try{try{({data:s,voucherReceiptHeader:o}=await i())}catch(u){if(u instanceof qt){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 vo(e.estimatedAmountCents),u instanceof Qr){if(g.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 jy||(jy=!0,console.error(`[visa-cli] Your session was closed by another process; reopened automatically as pay-as-you-go.
147
+ 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}),Xy(e)}throw u instanceof qt?(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=bo(o)??(n?Ml(n):null);if(_o(s?.receipt_v2),cg({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),id(s))return At(s);let c=await od();if(e.idempotencyKey&&ad(s,c,e.idempotencyKey))return At(s);let l=c?Mo(c):null;return At(cd(s,r,l))}function et(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function ja(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(ja).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${ja(r)}`).join(",")}}`}function rd(e,t,n,r){let s=Ce.createHash("sha256").update(`${n}:${ja(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${s}`}function pA(e,t){return`${e}:${t}`}function gA(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 Ha(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,s=pt(r),o=s!==null?s.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=gA(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),c=i!=null?String(i):a;return{batch_id:e,item_id:pA(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 Xy(e){return Ee(()=>yA(e))}async function Zy(e,t,n){if(id(e))return At(e);let r=await od();if(n&&ad(e,r,n))return At(e);let s=r?Mo(r):null;return At(cd(e,t,s))}async function hA(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 bo(i),_o(o?.receipt_v2),g.info("parentless-single-call:completed",{tool:e.toolId}),Zy(o,e.beforeBalanceMicros,e.idempotencyKey)}async function yA(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=Mo(n);if(Xp()&&!Uy){let u=e.idempotencyKey??Ce.randomUUID();try{return await hA({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 wt)Uy=!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;tn(c),yo(a.budget.totalCents),g.info("on-demand-session:opened",{budgetId:c,capCents:a.budget.totalCents,tool:e.toolId});let l=!1;try{await Ll(e.estimatedAmountCents);let u=Ol(e.idempotencyKey);if(!u)throw await vo(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(bo(f)||Ml(u),l=!0,_o(d?.receipt_v2),id(d))return At(d);let m=await od();if(e.idempotencyKey&&ad(d,m,e.idempotencyKey))return At(d);let p=m?Mo(m):null;return At(cd(d,s,p))}catch(u){throw l||await vo(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)})}tn(null),g.info("on-demand-session:closed",{budgetId:c,tool:e.toolId})}}async function Yn(e){return qa(async()=>Ln()?zy(e):Xy(e))}function Ka(){return de()}var bA="https://v4-verify-web-visa-code-preview.up.railway.app";function _A(e=ld){return/^\d+\.\d+\.\d+$/.test(e)&&e!=="0.0.0"}function sd(e=process.env,t=ld){return e.VISA_VERIFY_WEB_URL?e.VISA_VERIFY_WEB_URL:_A(t)?null:bA}var U=new Ke(()=>G.getSessionToken());function pt(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function Mo(e){return pt(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function vA(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 wA(e){let t=pt(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=pt(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=pt(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function Oo(e,t="INVALID_TOOL_PARAMS",n){return{success:!1,error_code:t,code:t,error:e,message:e,...n??{}}}function SA(e){return{success:!1,error_code:"TOOL_EXECUTION_FAILED",code:"TOOL_EXECUTION_FAILED",error:e.message||"Tool execution failed.",message:e.message||"Tool execution failed.",tool_id:e.toolId,surface:e.surface,merchantName:e.merchantName,amount:e.amount,payment_finalized:!1,charged:!1}}async function xA(){try{let e=await U.getBalance();return e.success?Mo(e):null}catch{return null}}async function od(){try{let e=await U.getBalance();return e.success?e:null}catch{return null}}function id(e){if(!e||e.success===!1)return!1;let t=pt(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=pt(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 ad(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=pt(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 cd(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 ld="4.0.0-rc.21",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(`
148
+ `);function tt(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=Gs(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(jm())return{opened:!1,url:t,blockedReason:"suppressed"};let n=Tc();if(n.headless)return g.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let s=[Ka(),sd()].filter(i=>!!i).map(i=>wf(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=xf(s);return o?((0,Jy.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 "${Uo.platform()}". URL: ${s}`),{opened:!1,url:s,blockedReason:"unsupported_platform"})}async function Ee(e){return Sr(U,e,ab)}var Qy="get_cards",eb="set_default_card";function CA(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 '${Qy}' to see enrolled cards and '${eb}' to switch, then retry the original request.`}function EA(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 '${Qy}' to see enrolled cards and '${eb}' to switch. Do not retry automatically.`}function ht(e,t){let n=e.retryable?CA(e.code,e.retryAfter):EA(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 AA(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 Is=null,kA=3e4;function tb(){Is=null}var Wn=class extends Error{constructor(n){super(`${Ba()} attestation is required for this action, but it is not available in this MCP process. `+ud());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function Ga(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. `+ud()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function TA(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:na,agent_guidance:_g}}function Ba(){return process.platform==="darwin"?"Touch ID":"local biometric"}function ud(){return process.platform==="darwin"?"Run the action from an interactive terminal with Touch ID access, or call auth_recovery to re-sync a drifted local attestation key, or use reset with confirm:true to clear stale server biometric state through GitHub re-authentication.":"This platform cannot create Visa CLI Touch ID attestations. Call auth_recovery to re-sync a drifted local attestation key, or use reset with confirm:true to clear stale server biometric state through GitHub re-authentication."}async function RA(e){let t=Date.now();if(Is&&Is.expiresAt>t)return{required:Is.required,hasRegisteredKey:Is.hasRegisteredKey};try{let n=await U.getStatus(e),r=kt(n),s=n.attestationRequired!==!1;return Is={required:s,hasRegisteredKey:r,expiresAt:t+kA},{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 RA(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(!fe())throw g.warn("attestation:unavailable",{context:e}),new Wn(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 $n(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 Hy="[dry-run] https://placeholder.visa-cli.dev/image.png",IA=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"]),PA=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 $A(e){return e.startsWith("or-")?"llm":IA.has(e)?"image":PA.has(e)?"video":NA(e)?"media":null}function NA(e){let t=mo(e);return t?!Wa(t):!1}function OA(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function MA(e){return e==="llm"?"OpenRouter":"fal.ai"}function Ps(e,t,n,r){let s={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:MA(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${OA(n)}`;return{...s,content:i,data:{content:i,model:t,dry_run:!0}}}return{...s,urls:[Hy],data:{[e==="video"?"videoUrl":e==="image"?"imageUrl":"url"]:Hy,metadata:{dry_run:!0}}}}async function ed(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 LA="https://openrouter.ai/api/v1/chat/completions",UA="openrouter/free",DA=50,jA=15e3;function HA(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 BA(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:Ps("llm",e,t,n),degraded:!0,resolvedModel:null};let s=HA(t),o;try{o=await vt(LA,{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:UA,messages:[{role:"user",content:s}],max_tokens:DA}),timeoutMs:jA})}catch(u){return g.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:Ps("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:Ps("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:Ps("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 Do(e,t,n,r){let s=Cl();if(!s)return null;let o=$A(e);if(!o)return null;let i=Date.now();if(s==="mock"){let l=Ps(o,e,t,r);return await ed({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=Ps(o,e,t,r);return await ed({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 BA(e,t,r);return await ed({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 un(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 dn(e){return bg(e.amount)}function FA(e,t,n){return n.has(e.resolvedTool)?0:Math.max(1,dn(t[e.resolvedTool]))}function VA(){return Va.join(Uo.homedir(),".visa-mcp","allium-results")}var n$=16*1024,r$=50*1024*1024;function qA(){let e=VA();try{if(!gt.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=gt.readdirSync(e),n=0,r=0;for(let s of t)try{let o=gt.statSync(Va.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 By=3600*1e3,td=0;function KA(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function jo(e){if(!Hm()&&!(Date.now()<td))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(KA(t)){let n=td===0;td=Date.now()+By,n&&g.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:By});return}g.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function GA(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 ye)return g.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:l.code,retryable:l.retryable}),ht(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 WA(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await Do("generate_image_card",e,t);if(n)return n;let r=await un("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 Yn({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:dn(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)),jo({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 ye)return g.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),ht(o,r);throw fn(o,{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName}),o}}async function YA(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 Do("generate_image_fast_card",e,t);if(n)return n;let r=await un("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 Yn({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:dn(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)),jo({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 ye)return g.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),ht(o,r);throw fn(o,{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName}),o}}async function JA(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 Do("generate_video_tempo_card",e,t);if(n)return n;let r=await un("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 Yn({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:dn(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)),jo({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 ye)return g.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),ht(o,r);throw fn(o,{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName}),o}}async function zA(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 un("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 Yn({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:dn(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)),jo({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 ye)return g.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),ht(s,n);throw fn(s,{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName}),s}}async function XA(e,t){let n=await un("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 Yn({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:dn(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 ye)return g.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),ht(s,n);throw fn(s,{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName}),s}}async function ZA(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 un("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 Yn({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:dn(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 ye)return g.warn("payment:declined",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),ht(s,n);throw fn(s,{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName}),s}}var QA=["generate_music_tempo_card"],Rs=10,Fy=5,Vy=new Map;function qy(e){let t=Vy.get(e);if(t!==void 0)return t;let r=mo(e)?.isAsync===!0||QA.includes(e);return Vy.set(e,r),r}var ek=36e4,tk=18e4,nk=15e3,rk=12e4,sk=2e3;function nd(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}function ok(e,t){return Ce.createHash("sha256").update(`${e}:${ja(t)}`).digest("hex")}function ik(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,...Ha(n,r,o)});let l=0,u=0n;if(o?.success!==!1){let d=pt(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 ak(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,_=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:_,mode:d,batchId:u}),{success:m>0,outcome:_,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 ck(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,_=await U.getBalance();if(!_.success)throw new Error(`Could not read balance: ${_.error||"unknown error"}`);if(_.balanceCents<h)throw new xe(_.balanceCents,h);let I=`batch-${m}`,b=`spend up to $${(h/100).toFixed(2)} across a batch of ${t.length}`,{batchParentId:v}=await Ee(async()=>{let y=await nt("batch_open",h,I,b,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:v});let w=[],R=0,k=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:Us}=await U.shortcutParentlessBatchItem(x.resolvedTool,{batch_parent_id:v,batch_id:m,batch_index:y,batch_request_hash:ok(x.resolvedTool,x.params),item_ceiling_cents:o[y],idempotency_key:rd(m,y,x.resolvedTool,x.params)},x.params,f,p,"batch");bo(Us),_o(Z?.receipt_v2),K=await Zy(Z,null,rd(m,y,x.resolvedTool,x.params))}let{deltaCharged:ve,deltaMicros:se}=ik({results:w,batchId:m,index:y,item:x,itemResult:K,preview:Y,isFree:X,catalogName:s[x.resolvedTool]?.name});R+=ve,k+=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,...Ha(m,y),error:K?.message||String(K)})}}return ak({results:w,resolvedItems:t,uniqueTools:a,isHomogeneous:c,primaryTool:l,merchantNames:u,totalAmount:d,totalCharged:R,totalChargedMicros:k,batchId:m,mode:"parentless"})}catch(y){if(y instanceof ye)return g.warn("payment:declined",{tool:"batch",batchTool:l,count:t.length,totalAmount:d,merchant:u,code:y.code,retryable:y.retryable}),ht(y,{amount:d,merchantName:u});throw fn(y,{tool:"batch",batchTool:l,count:t.length,totalAmount:d,merchant:u}),y}}async function lk(e,t){let n;if(Array.isArray(e.requests)&&e.requests.length>Rs)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${Rs} 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=Sl({requestedTool:x})??x,{tool:X,tool_id:K,tier:ve,params:se,...Z}=y,Us=se&&typeof se=="object"?{...se,...Z}:Z;return{resolvedTool:Y,params:Us}});else if(e.tool){let y=Sl({requestedTool:e.tool})??e.tool;if(e.count!==void 0){if(!Number.isSafeInteger(e.count)||e.count<1)return nd("BATCH_INVALID_COUNT","Batch count must be a positive integer.");if(e.count>Rs)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${Rs} 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 nd("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return nd("BATCH_EMPTY","Batch requires at least one item.");if(n.length>Rs)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${Rs} items. Please split into smaller batches.`};if([...new Set(n.map(y=>y.resolvedTool))].some(qy)&&n.length>Fy)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${Fy} 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 cb(y);let l=new Set(i.filter(y=>c[y]&&Wa(c[y]))),u={};for(let y of i)l.has(y)||(u[y]=await un(y,void 0,t));let d=0;for(let y of n)d+=u[y.resolvedTool]?.amount??0;let f=n.map(y=>FA(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 _=n.some(y=>qy(y.resolvedTool)),I=n.some(y=>y.resolvedTool.startsWith("or-")||y.resolvedTool==="run_llm"||y.resolvedTool==="execute_tool"),b=_?ek:I?tk+n.length*nk:rk+n.length*sk,v=Ce.randomUUID(),w=[],R=0,k=0n;return qa(async()=>{let y=!Ln();if(Zp()&&!Dy&&y&&m>0)try{return await ck({resolvedItems:n,previews:u,freeTools:l,catalogEntries:c,itemCeilingCents:f,batchCeilingCents:m,uniqueTools:i,isHomogeneous:a,primaryTool:h,merchantNames:p,totalAmount:d,timeoutMs:b,batchId:v,userContext:t})}catch(x){if(x instanceof wt)Dy=!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(()=>Dl(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],Us=u[Z.resolvedTool];try{let ue=l.has(Z.resolvedTool)?await U.shortcut(Z.resolvedTool,Z.params,b,t,"batch"):await zy({toolId:Z.resolvedTool,toolParams:Z.params,estimatedAmountCents:f[se],userContext:t,metaTool:"batch",timeoutMs:b,idempotencyKey:rd(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,...Ha(v,se,ue)}),ue?.success!==!1){let Ds=pt(ue?.amountMicros??ue?.amount_micros),Yd=typeof ue?.amount=="number"?ue.amount:Us?.amount??0;Ds!==null&&Ds>0n?k+=Ds:k+=BigInt(Math.round(Yd*1e6)),R+=Yd}ue?.urls&&ue.urls.forEach(Ds=>tt(Ds))}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,...Ha(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=k>0n?Number(k)/1e6:Math.round((R+Number.EPSILON)*100)/100,ve=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:ve,mode:"session",batchId:v}),{success:Y>0,outcome:ve,batch_id:v,tool:a?i[0]:h,count:n.length,successCount:Y,failedCount:x,totalCharged:K,...k>0n?{totalChargedMicros:k.toString(),amountMicros:k.toString(),amount_micros:k.toString()}:{},merchantName:p,results:w,...X.length?{urls:X}:{}}}catch(x){if(x instanceof ye)return g.warn("payment:declined",{tool:"batch",batchTool:h,count:n.length,totalAmount:d,merchant:p,code:x.code,retryable:x.retryable}),ht(x,{amount:d,merchantName:p});throw fn(x,{tool:"batch",batchTool:h,count:n.length,totalAmount:d,merchant:p}),x}finally{if(y){let x=await Qi(U);g.info("batch-session:closed",{budgetId:x.budgetId,closedServerSide:x.closedServerSide})}}})}function uk(){let e=!1,t;try{let r=Va.join(Uo.homedir(),".claude","settings.json");if(gt.existsSync(r)){let s=JSON.parse(gt.readFileSync(r,"utf-8")),o=typeof s.statusLine=="object"?s.statusLine.command:"";e=wn(o)}}catch{}let n=pi();return n||(t="visa-cli config hud enable"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function dk(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=qA();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=uk(),!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=ld,Array.isArray(t.cards)&&(t.cards=t.cards.map(o=>({...o,displayName:dd(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=Ln();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 dd(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 nb(e,t){try{let r=((await U.getStatus(t)).cards||[]).find(s=>s?.id===e);if(r)return dd(r)}catch(n){g.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function fk(e){let n=(await U.getStatus(e)).cards||[];return n.length===0?{cards:[],message:"No cards enrolled. Use the add_card tool to add a payment card."}:n.some(s=>!Number.isInteger(s?.id)||s.id<=0)?{success:!1,cards:[],message:"Card action handles are unavailable right now, so remove_card and set_default_card are temporarily disabled."}:{cards:n.map(s=>({...s,displayName:dd(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 mk(e,t){return await U.getTransactions({limit:e.limit,offset:e.offset},t)}async function pk(e,t){return await U.feedback(e.message,e.transaction_id,t)}async function gk(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Dr("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=ta(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=mA(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 Wn)return TA();if(i instanceof it)return g.warn("buy_credits:ambiguous",{amountCents:r,code:i.code,transactionId:i.transactionId}),AA(i);throw g.error("buy_credits:failure",{amountCents:r,error:i.message}),i}}function Dr(e,t){return{success:!1,error:t,code:e,message:t}}async function hk(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Dr("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 Dr("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 Dr("INVALID_VALUE","dailyLimit must be at least $1");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return Dr("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 Wn)return Ga(n,"update_spending_controls");if(String(n?.message||n).includes("Attestation required"))return Dr("ATTESTATION_REQUIRED","Changing spending controls requires local attestation, even when payment biometric prompts are disabled.");throw n}}async function yk(e){let t=await ho({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 fd=new Set(["auth.serverUrl"]);function Lo(){return Object.keys(sr).filter(e=>!fd.has(e)).sort()}function rb(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:Lo()}}async function bk(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(fd.has(e.key))return g.warn("config:set:rejected:mcp-forbidden",{key:e.key}),rb(e.key,"set");g.info("config:set",{key:e.key});try{let t=Ii(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 Gt?"SERVER_CONTROLLED":t instanceof xn?"RETIRED_KEY":"INVALID_VALUE",r=t instanceof at?`Unknown setting "${e.key}". MCP-settable keys: ${Lo().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:Lo()}}}async function _k(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(fd.has(e.key))return g.warn("config:unset:rejected:mcp-forbidden",{key:e.key}),rb(e.key,"unset");g.info("config:unset",{key:e.key});try{let t=Pi(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 Gt?"SERVER_CONTROLLED":t instanceof xn?"RETIRED_KEY":"INVALID_VALUE",r=t instanceof at?`Unknown setting "${e.key}". MCP-settable keys: ${Lo().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:Lo()}}}async function vk(e){let t=await U.getStatus(e),n=t.attestationRequired!==!1,r=kt(t),s=fe(),o=n?r?s?`${Ba()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${Ba()} is not available in this process. ${ud()}`:"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 wk(e){g.info("biometric:on");let t=await Yi(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?(tb(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:n.error||"unknown error"}}async function Sk(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Dr("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(`${Ba()} 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 tb(),{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 Wn)return Ga(n,"biometric_off");throw n}}var Ky=3e4,xk=3e5;async function sb(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"?ob(s,o,n):o.opened?{...await ib(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 ob(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 ib(e,t,n="login"){let r=Date.now()+xk;for(;Date.now()<r;)try{let o=await fetch(`${Ka()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:Ky,...t&&{user_context:t}}),signal:AbortSignal.timeout(Ky+5e3)});if(!o.ok){await bn(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=ng(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 bn(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 ab(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"?ob(n.recoveryUrl,r,"attestation-recovery"):r.opened?{...await ib(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 Ck(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 nb(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 Wn)return Ga(o,"remove_card");throw o}}async function Ek(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 nb(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 Wn)return Ga(o,"set_default_card");throw o}}async function Ak(e){return g.info("auth:login_attempt"),sb(`${Ka()}/login`,e)}async function kk(e=sd()){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."};let{challenge:t}=Wp(),n=`${e}${e.includes("?")?"&":"?"}cli=${t}`;g.info("agent:enroll_open",{url:e});let r=tt(n),s="sign in \u2192 pick your .visa name \u2192 wallet \u2192 card (secure fields) \u2192 bank verification with passkey \u2192 mint",o='When the final screen shows "Sent to your Visa CLI", call enroll_agent with {"action":"claim"} to store the enrollment credential on this device.';return r.opened?{success:!0,opened:!0,browserUrl:r.url,message:`Opened the Visa Verified Agent enrollment in your browser (${s}). ${o} 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:r.url??n,message:`Open this URL in a browser to enroll your agent (${s}): ${r.url??n} \u2014 ${o}`}}async function Tk(e=sd()){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."};let t=await Yp(e);switch(g.info("agent:enroll_claim",{status:t.status}),t.status){case"claimed":return{success:!0,name:t.name,tokenId:t.tokenId,credentialPath:t.credentialPath,message:`Enrollment credential${t.name?` for ${t.name}`:""} stored at ${t.credentialPath} (token id ${t.tokenId}). The CLI purchase leg will read it from there.`};case"no_pending":return{success:!1,message:"No enrollment hand-off is in progress on this device \u2014 run enroll_agent first, finish the browser flow, then claim."};case"not_ready":return{success:!1,message:t.likelyExpired?"The hand-off window (15 minutes) has likely expired \u2014 run enroll_agent again, finish the browser flow, then claim.":'The enrollment credential is not ready yet \u2014 finish the browser flow through the final "minted" screen (it will say "Sent to your Visa CLI"), then claim again.'};case"error":return{success:!1,message:t.message}}}function Rk(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 Ik(e={},t){let n;try{n=Rk(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return qa(async()=>{let r=await Ee(()=>pg(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 Pk(){let e=Ln();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 $k(){return qa(async()=>{let e=Ln();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);g.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=wA(e),r=pt(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 ${vA(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 Nk(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 sb(`${Ka()}/enroll-card?code=${encodeURIComponent(n)}`,e,"enrollment")}async function Gy(){if(await G.clearAll(),fe())try{await Gi()}catch{}}async function Ok(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 Gy(),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 ab(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 Gy(),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 Mk(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})
149
149
  ${f.description}
150
- Provider: ${f.provider} | Price: ${Dy(f)}${jy(f)}
150
+ Provider: ${f.provider} | Price: ${Wy(f)}${Yy(f)}
151
151
  Params: ${Object.keys(f.inputSchema?.properties||f.inputSchema||{}).join(", ")||"none"}`).join(`
152
152
 
153
153
  `);return`## ${l.length<=3?l.toUpperCase():l.charAt(0).toUpperCase()+l.slice(1)}
@@ -160,75 +160,75 @@ ${c}
160
160
 
161
161
  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})
162
162
  ${a.description}
163
- Provider: ${a.provider} | Category: ${a.category} | Price: ${Dy(a)}${jy(a)}
163
+ Provider: ${a.provider} | Category: ${a.category} | Price: ${Wy(a)}${Yy(a)}
164
164
  Params: ${Object.keys(a.inputSchema?.properties||a.inputSchema||{}).join(", ")||"none"}`).join(`
165
165
 
166
166
  `);return g.info("catalog:discovered",{count:o.length}),{content:[{type:"text",text:`Found ${o.length} tool(s):
167
167
 
168
168
  ${i}
169
169
 
170
- 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 Dy(e){return e.priceDisplay??`$${(e.priceCents/100).toFixed(2)}`}function jy(e){let t=e.protocol;return t==="mpp"||t==="x402"?" | Paid from your prepaid balance":""}function Sk(e,t){return t==="image"||t==="video"||t==="audio"?t:e?.match(/\.(mp4|webm|mov)/)?"video":"image"}function xk(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=gl(a,c,l);if(u)return u}return null}async function eb(e){let t=fo(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 qa(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 Ck(e){let t=e;return t.platformRoute===!0||typeof t.platformMerchantSlug=="string"||t.executionKind==="platform_proxy"}function Ak(e){let n=e.inputSchema?.properties;return!!n&&typeof n=="object"&&Object.keys(n).length>0}function Ek(e){return qa(e)&&Ck(e)&&!Ak(e)}function kk(e){return e.split(/[-_]/).filter(t=>t.length>0&&!/^[0-9a-f]{8,}$/i.test(t)).join(" ").trim()}async function Tk(e){let t=kk(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 Rk(e,t,n="execute_tool"){let{tool_id:r,params:s,...o}=e,i=s||o;if(!r)return $o("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 eb(r);if(!a){let p=await Tk(r),h=p.length?` Did you mean: ${p.map(v=>v.tool_id).join(", ")}?`:"";return $o(`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 $o(`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}),$o(v,"SURFACE_DISABLED",{tool_id:r,...p?{unavailable_reason:p}:{},...h?{flag:h}:{}})}let l=n&&n!=="execute_tool"?n:void 0,u=Ek(a)?null:xk(a,i,l);if(u)return g.info("catalog:execute:validation_failed",{tool:r,metaTool:n,error:u}),$o(u);let d=await Lo(r,i,t,n);if(d)return d;if(qa(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 ln(r,void 0,t,i),m=Ce.randomUUID();g.info("payment:attempt",{tool:r,amount:f.amount,merchant:f.merchantName});try{return await Ae(async()=>{let p;try{p=await Gn({toolId:r,toolParams:i,estimatedAmountCents:un(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=Sk(p.urls[0],p.mediaType);Uo({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 ye?(g.warn("payment:declined",{tool:r,amount:f.amount,merchant:f.merchantName,code:p.code,retryable:p.retryable}),ht(p,f)):(tb(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}),lE({toolId:r,surface:n,merchantName:f.merchantName,amount:f.amount,message:p?.message||"Tool execution failed."}))}}function tb(e){return e?/\b(task_id|polling?|timeout|timed out|queue|IN_QUEUE|aborted)\b/i.test(e):!1}function dn(e,t){let n={...t,error:e?.message};tb(e?.message)?g.warn("payment:ambiguous",n):g.error("payment:failure",n)}async function Ik(e){if(!e.name)return{success:!1,error:"name is required"};try{let{registerName:t,ensureMailbox:n}=await Promise.resolve().then(()=>(Es(),Po)),r=await t(e.name);return await n(e.name),{success:!0,...r}}catch(t){let{CardRequiredError:n}=await Promise.resolve().then(()=>(Ss(),uy));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 Pk(e){if(!e.name)return{success:!1,error:"name is required"};try{let{resolveMeshName:t}=await Promise.resolve().then(()=>(Es(),Po));return{success:!0,...await t(e.name)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async function $k(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(()=>(Es(),Po)),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 Nk(e){try{let{readInbox:t,resolveActingName:n,meshName:r}=await Promise.resolve().then(()=>(Es(),Po)),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 Mt=class{static async subwayRegister(t){return Ik(t||{})}static async subwayFind(t){return Pk(t||{})}static async subwaySend(t){return $k(t||{})}static async subwayInbox(t){return Nk(t||{})}static async getStatus(t){return ZE(t)}static async getVisaSmi(t,n){return NE(t,n)}static async getCards(t){return QE(t)}static async transactionHistory(t,n){return ek(t||{},n)}static async feedback(t,n){return tk(t,n)}static async updateSpendingControls(t,n){return rk(t,n)}static async configList(t){return sk(t||{})}static async configSet(t){return ok(t||{})}static async configUnset(t){return ik(t||{})}static async biometricStatus(t){return ak(t)}static async biometricOn(t){return ck(t)}static async biometricOff(t,n){return lk(t,n)}static async reset(t,n){return vk(t,n)}static async login(t){return mk(t)}static async enrollAgent(t){return pk()}static async closeSession(t){return bk()}static async startSession(t,n){return hk(t||{},n)}static async getSessionStatus(t){return yk()}static async addCard(t){return _k(t)}static async removeCard(t,n){return dk(t,n)}static async setDefaultCard(t,n){return fk(t,n)}static async buyCredits(t,n){return nk(t,n)}static async batch(t,n){return zE(t,n)}static async discoverTools(t){return wk(t)}static async executeTool(t,n,r="execute_tool"){return Rk(t,n,r)}static async shortcut(t,n,r){switch(t){case"generate_image_card":return OE(n,r);case"generate_image_fast_card":return ME(n,r);case"generate_video_tempo_card":return LE(n,r);case"generate_music_tempo_card":return UE(n,r);case"check_music_status_tempo_card":return DE(n,r);case"query_onchain_prices_card":return jE(n,r);default:{let s=await Lo(t,n,r);if(s)return s;let o=await ln(t,void 0,r,n);g.info("payment:attempt",{tool:t});try{let i=await Gn({toolId:t,toolParams:n,estimatedAmountCents:un(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 ye)return g.warn("payment:declined",{tool:t,code:i.code,retryable:i.retryable}),ht(i,o);throw dn(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}}};Kt();function nb(e,t=process.stderr){if(St()||!e?.updateAvailable)return!1;let{latestVersion:n}=e.updateAvailable;if(!n)return!1;let r=`Update available: v${n}. Run: visa-cli update`;return t.write(`
170
+ 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 Wy(e){return e.priceDisplay??`$${(e.priceCents/100).toFixed(2)}`}function Yy(e){let t=e.protocol;return t==="mpp"||t==="x402"?" | Paid from your prepaid balance":""}function Lk(e,t){return t==="image"||t==="video"||t==="audio"?t:e?.match(/\.(mp4|webm|mov)/)?"video":"image"}function Uk(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=_l(a,c,l);if(u)return u}return null}async function cb(e){let t=mo(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 Wa(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 Dk(e){let t=e;return t.platformRoute===!0||typeof t.platformMerchantSlug=="string"||t.executionKind==="platform_proxy"}function jk(e){let n=e.inputSchema?.properties;return!!n&&typeof n=="object"&&Object.keys(n).length>0}function Hk(e){return Wa(e)&&Dk(e)&&!jk(e)}function Bk(e){return e.split(/[-_]/).filter(t=>t.length>0&&!/^[0-9a-f]{8,}$/i.test(t)).join(" ").trim()}async function Fk(e){let t=Bk(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 Vk(e,t,n="execute_tool"){let{tool_id:r,params:s,...o}=e,i=s||o;if(!r)return Oo("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 cb(r);if(!a){let p=await Fk(r),h=p.length?` Did you mean: ${p.map(_=>_.tool_id).join(", ")}?`:"";return Oo(`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 Oo(`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,_=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}),Oo(_,"SURFACE_DISABLED",{tool_id:r,...p?{unavailable_reason:p}:{},...h?{flag:h}:{}})}let l=n&&n!=="execute_tool"?n:void 0,u=Hk(a)?null:Uk(a,i,l);if(u)return g.info("catalog:execute:validation_failed",{tool:r,metaTool:n,error:u}),Oo(u);let d=await Do(r,i,t,n);if(d)return d;if(Wa(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 un(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 Yn({toolId:r,toolParams:i,estimatedAmountCents:dn(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(_=>tt(_));let h=Lk(p.urls[0],p.mediaType);jo({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 ye?(g.warn("payment:declined",{tool:r,amount:f.amount,merchant:f.merchantName,code:p.code,retryable:p.retryable}),ht(p,f)):(lb(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}),SA({toolId:r,surface:n,merchantName:f.merchantName,amount:f.amount,message:p?.message||"Tool execution failed."}))}}function lb(e){return e?/\b(task_id|polling?|timeout|timed out|queue|IN_QUEUE|aborted)\b/i.test(e):!1}function fn(e,t){let n={...t,error:e?.message};lb(e?.message)?g.warn("payment:ambiguous",n):g.error("payment:failure",n)}async function qk(e){if(!e.name)return{success:!1,error:"name is required"};try{let{registerName:t,ensureMailbox:n}=await Promise.resolve().then(()=>(Ts(),No)),r=await t(e.name);return await n(e.name),{success:!0,...r}}catch(t){let{CardRequiredError:n}=await Promise.resolve().then(()=>(Cs(),_y));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 Kk(e){if(!e.name)return{success:!1,error:"name is required"};try{let{resolveMeshName:t}=await Promise.resolve().then(()=>(Ts(),No));return{success:!0,...await t(e.name)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async function Gk(e){if(!e.to||!e.text)return{success:!1,error:"to and text are required"};try{let{sendVia:t,resolveActingName:n}=await Promise.resolve().then(()=>(Ts(),No)),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 Wk(e){try{let{readInbox:t,resolveActingName:n,meshName:r}=await Promise.resolve().then(()=>(Ts(),No)),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 Mt=class{static async subwayRegister(t){return qk(t||{})}static async subwayFind(t){return Kk(t||{})}static async subwaySend(t){return Gk(t||{})}static async subwayInbox(t){return Wk(t||{})}static async getStatus(t){return dk(t)}static async getVisaSmi(t,n){return GA(t,n)}static async getCards(t){return fk(t)}static async transactionHistory(t,n){return mk(t||{},n)}static async feedback(t,n){return pk(t,n)}static async updateSpendingControls(t,n){return hk(t,n)}static async configList(t){return yk(t||{})}static async configSet(t){return bk(t||{})}static async configUnset(t){return _k(t||{})}static async biometricStatus(t){return vk(t)}static async biometricOn(t){return wk(t)}static async biometricOff(t,n){return Sk(t,n)}static async reset(t,n){return Ok(t,n)}static async login(t){return Ak(t)}static async enrollAgent(t={},n){let r=t?.action??"start";return r==="start"?kk():r==="claim"?Tk():{success:!1,message:`Unknown enroll_agent action ${JSON.stringify(r)}. Use "start" (default \u2014 opens the enrollment flow) or "claim" (stores the credential after the browser flow finishes).`}}static async closeSession(t){return $k()}static async startSession(t,n){return Ik(t||{},n)}static async getSessionStatus(t){return Pk()}static async addCard(t){return Nk(t)}static async removeCard(t,n){return Ck(t,n)}static async setDefaultCard(t,n){return Ek(t,n)}static async buyCredits(t,n){return gk(t,n)}static async batch(t,n){return lk(t,n)}static async discoverTools(t){return Mk(t)}static async executeTool(t,n,r="execute_tool"){return Vk(t,n,r)}static async shortcut(t,n,r){switch(t){case"generate_image_card":return WA(n,r);case"generate_image_fast_card":return YA(n,r);case"generate_video_tempo_card":return JA(n,r);case"generate_music_tempo_card":return zA(n,r);case"check_music_status_tempo_card":return XA(n,r);case"query_onchain_prices_card":return ZA(n,r);default:{let s=await Do(t,n,r);if(s)return s;let o=await un(t,void 0,r,n);g.info("payment:attempt",{tool:t});try{let i=await Yn({toolId:t,toolParams:n,estimatedAmountCents:dn(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 ye)return g.warn("payment:declined",{tool:t,code:i.code,retryable:i.retryable}),ht(i,o);throw fn(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}}};Kt();function ub(e,t=process.stderr){if(St()||!e?.updateAvailable)return!1;let{latestVersion:n}=e.updateAvailable;if(!n)return!1;let r=`Update available: v${n}. Run: visa-cli update`;return t.write(`
171
171
  \x1B[33m\u2191 ${r}\x1B[0m
172
- `),!0}function sb(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]=rb(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]=rb(o,n[o]?.description);return s}function rb(e,t){let n=e.toLowerCase();return n==="prompt"?"a lobster":n==="text"?"Hello from Visa CLI.":n.endsWith("image_url")||n==="image_url"?"https://example.com/sample.jpg":n.endsWith("audio_url")||n==="audio_url"?"https://example.com/sample.wav":n.endsWith("video_url")||n==="video_url"?"https://example.com/sample.mp4":n==="taskid"||n==="task_id"?"task_abc123":n==="request_id"||n==="requestid"?"req_abc123":n==="model_path"||n==="model"?"fal-ai/flux/schnell":n==="language"?"en":t&&/\bUR?L\b|https?:\/\//i.test(t)?"https://example.com/sample":"example"}function Ok(e){let t=Lt(e.referralCode,"");if(!t)return[];let n=["Referrals",` Your code ${t}`],r=Lt(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 Mk=20;function ib(e,t,n,r){let s=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=Fk(e.spendingControls).dailyLimit,a=Math.max(0,Do(e.dailyCardFundedTopupSpent??e.dailySpent)),c=i>0?Math.min(i,Math.max(0,Do(e.dailyCardFundedTopupRemaining??e.dailyRemaining??i-a))):0,l=i>0?Math.min(1,a/i):0,d=(Array.isArray(t)?t:[]).filter(Dk),f=d.slice(0,3),m=jk(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),b=Lt(e.status,e.enrolled?"approved":"not enrolled"),w=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${b} | touch id: ${n?"ready":"unavailable"}`,`Version: v${s} | ${v}`,`Top-up meter: ${ob(l)} ${String(I).padStart(3," ")}% | remaining ${Is(c)}/day | daily top-up cap ${Is(i)}`,"","Card top-ups",` Remaining ${Is(c)} / ${Is(i)}`,` Usage ${ob(l)} ${I}%`,` Top-ups today ${Is(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...p.length>0?p.map(E=>` ${Hk(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=>` ${Bk(E)}`):[" No receipts yet"]],R=Ok(e);return R.length>0&&w.push("",...R),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(`
172
+ `),!0}function fb(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]=db(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]=db(o,n[o]?.description);return s}function db(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 Yk(e){let t=Lt(e.referralCode,"");if(!t)return[];let n=["Referrals",` Your code ${t}`],r=Lt(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 Jk=20;function pb(e,t,n,r){let s=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=n1(e.spendingControls).dailyLimit,a=Math.max(0,Ho(e.dailyCardFundedTopupSpent??e.dailySpent)),c=i>0?Math.min(i,Math.max(0,Ho(e.dailyCardFundedTopupRemaining??e.dailyRemaining??i-a))):0,l=i>0?Math.min(1,a/i):0,d=(Array.isArray(t)?t:[]).filter(Zk),f=d.slice(0,3),m=Qk(d,3),p=(e.cards??[]).slice(0,3),h=r.latestVersion?jr(r.latestVersion):"",_=r.updateCheckDisabled?"update checks disabled":h?`update ready: v${h}`:"up to date",I=Math.round(l*100),b=Lt(e.status,e.enrolled?"approved":"not enrolled"),w=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${b} | touch id: ${n?"ready":"unavailable"}`,`Version: v${s} | ${_}`,`Top-up meter: ${mb(l)} ${String(I).padStart(3," ")}% | remaining ${$s(c)}/day | daily top-up cap ${$s(i)}`,"","Card top-ups",` Remaining ${$s(c)} / ${$s(i)}`,` Usage ${mb(l)} ${I}%`,` Top-ups today ${$s(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...p.length>0?p.map(k=>` ${t1(k)}`):[" No cards enrolled"],"","Last 3 services",...m.length>0?m.map((k,y)=>` ${y+1}. ${k}`):[" No paid services yet"],"","Recent receipts",...f.length>0?f.map(k=>` ${e1(k)}`):[" No receipts yet"]],R=Yk(e);return R.length>0&&w.push("",...R),h&&!r.updateCheckDisabled?(w.push("",`Update: v${h} ready \u2014 run \`visa-cli update\``),r.updateMessage&&w.push(` ${jr(r.updateMessage)}`)):r.updateMessage&&w.push("",`Update: ${jr(r.updateMessage)}`),`${w.join(`
173
173
  `)}
174
- `}function Lk(e){return e.tool_name!=null}function Uk(e){return Do(e.amount)===0&&e.status==="failed"}function Dk(e){return Lk(e)&&!Uk(e)}function jk(e,t=1/0){let n=new Set,r=[];for(let s of e){if(r.length>=t)break;let o=Lt(s.merchant_name,"Unknown merchant"),i=Lt(s.tool_name,"unknown_tool"),a=`${o} :: ${i}`;n.has(a)||(n.add(a),r.push(`${o} [${i}]`))}return r}function Bk(e){let t=Lt(e.merchant_name,"Unknown merchant"),n=Lt(e.tool_name,"unknown_tool"),r=Is(Do(e.amount)),s=Lt(e.status,"unknown"),o=Vk(e.created_at);return`${r} ${s.padEnd(9)} ${t} [${n}] ${o}`}function Hk(e){let t=Lt(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function Fk(e){return{dailyLimit:Do(e?.daily_limit??e?.dailyLimit??0)}}function Do(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function Is(e){return`$${e.toFixed(2)}`}function ob(e,t=Mk){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function Lt(e,t){let n=Ur(e??"").trim();return n.length>0?n:t}function Vk(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?Lt(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 qk=/^[1-9]\d{0,9}$/;function ad(e){if(!qk.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 ab(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 Ut=k(require("fs")),_e=k(require("path")),Kk=["npm","pnpm","yarn","bun"],Gk=/\s+/,Wk=process.platform==="win32"?"visa-cli.cmd":"visa-cli",cd=["node_modules","@visa","cli"];function Yk(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(Gk)[0]??"",r=n.indexOf("/"),s=r===-1?n:n.slice(0,r);return Kk.includes(s)?s:void 0}function ld(e){if(!e)return;let t=e;try{t=Ut.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 Jk(e=process.argv[1]){return Yk()??ld(process.env.npm_execpath)??ld(process.env.npm_node_execpath)??ld(e)}function zk(e=process.env.PATH??""){let t=[];for(let n of e.split(_e.delimiter))n&&t.push(n);return t}function Xk(e=process.env.PATH??""){let t=new Set,n=[];for(let r of zk(e))try{let s=_e.join(r,Wk);Ut.accessSync(s,Ut.constants.X_OK);let o=_e.resolve(s);t.has(o)||(t.add(o),n.push(s))}catch{}return n}function cb(e){try{let t=Ut.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 Zk(e){let t=_e.resolve(e).split(_e.sep);for(let n=t.length-cd.length;n>=0;n--)if(cd.every((r,s)=>t[n+s]===r)){let r=t.slice(0,n+cd.length).join(_e.sep)||_e.sep;if(cb(r))return r}}function Qk(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 e1(e,t){let n=_e.resolve(e);try{n=Ut.realpathSync(e)}catch{}let r=Zk(n);return{binPath:e,realPath:n,packageRoot:r,version:r?cb(r):void 0,prefix:Qk(r),isActive:n===t}}function t1(e,t=process.env.PATH??""){let n=e??process.argv[1],r=n?_e.resolve(n):"";try{n&&(r=Ut.realpathSync(n))}catch{}let s=e?[e]:[n,...Xk(t)].filter(Boolean),o=new Map;for(let d of s){let f=e1(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 n1(e,t=process.platform){return/^[A-Za-z0-9_./:@+-]+$/.test(e)?e:t==="win32"?`"${e.replace(/"/g,'""')}"`:`'${e.replace(/'/g,"'\\''")}'`}function ud(e,t,n,r={}){let s=t??Jk(n)??"npm",o=r.withDiagnostics?t1(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 ${n1(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 r1(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 dd(e,t){if(!e.hasConflictingInstalls)return null;let n=["Multiple Visa CLI installs detected.",...e.installs.map(r1)];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(`
175
- `)}var nc=k(ls());function s1(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function lb(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=s1(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 ub(){await G.deleteSessionToken()}var qe=k(require("fs")),_b=k(require("os")),jr=k(require("path")),yd=require("node:readline/promises");Ao();ct();Ss();var db=k(require("node:crypto")),We=k(require("node:fs")),fb=k(require("node:os")),Ka=k(require("node:path"));Ao();Ss();ct();var o1="4.0.0-rc.20",jo=Ka.join(fb.homedir(),".visa-cli","pairings");function fd(e,t,n=jo){return Ka.join(n,`${e}.${t}.json`)}function mb(e,t=jo){We.mkdirSync(t,{recursive:!0,mode:448}),We.writeFileSync(fd(e.pairingId,e.role,t),JSON.stringify(e,null,2),{mode:384})}function Ga(e,t,n=jo){We.rmSync(fd(e,t,n),{force:!0})}function Wa(e,t,n=jo){try{let r=JSON.parse(We.readFileSync(fd(e,t,n),"utf8"));return r?.pairingId===e&&r.role===t?r:null}catch{return null}}function md(e=jo){return We.existsSync(e)?We.readdirSync(e).filter(n=>n.endsWith(".human.json")).map(n=>{try{return JSON.parse(We.readFileSync(Ka.join(e,n),"utf8"))}catch{return null}}).filter(n=>n?.role==="human").sort((n,r)=>r.createdAt.localeCompare(n.createdAt))[0]??null:null}async function Dr(e,t,n){let r=await n(e,t),s=await r.json().catch(()=>({}));if(!r.ok&&r.status!==202)throw new Error(s.error??s.detail??`pairing server returned ${r.status}`);return{status:r.status,body:s}}async function pb(e={}){let t=(e.authUrl??de()).replace(/\/+$/,""),n=Qh(),{body:r}=await Dr(`${t}/v4/agent-pairings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cliChallenge:ey(n)})},e.fetchImpl??fetch);if(!r.pairingId||!r.skillUrl||!r.authorizationUrl||!r.expiresAt)throw new Error("pairing server returned an incomplete initiation response");let s={role:"human",pairingId:r.pairingId,verifier:n,authUrl:t,skillUrl:r.skillUrl,authorizationUrl:r.authorizationUrl,expiresAt:r.expiresAt,createdAt:new Date().toISOString()};return mb(s,e.pairingDir),s}async function pd(e){let{pairing:t}=e,{body:n}=await Dr(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({verifier:t.verifier,code:e.code})},e.fetchImpl??fetch);return n}async function gd(e){let t=(e.authUrl??de()).replace(/\/+$/,""),{body:n}=await Dr(`${t}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}`,{method:"GET",cache:"no-store"},e.fetchImpl??fetch);return n}function i1(){let e=db.default.createECDH("prime256v1");return e.generateKeys(),{publicKey:e.getPublicKey("hex","compressed"),privateKey:e.getPrivateKey("hex")}}function gb(e,t){return Buffer.from(ka(e,Buffer.from(t,"utf8"))).toString("base64url")}async function hb(e){let t=(e.authUrl??de()).replace(/\/+$/,""),n=e.fetchImpl??fetch,r=await gd({pairingId:e.pairingId,authUrl:t,fetchImpl:n});if(r.state!=="awaiting_agent"||!r.serverNonce)throw new Error(`pairing cannot be claimed from state ${r.state}`);let{secretKey:s,publicKey:o}=Su(),i=xu(s),a=Ta(o),c=ko(a),l=i1(),u=ty(),d={runtime:e.runtime,contextLabel:e.contextLabel,platform:`${process.platform}/${process.arch}`,cliVersion:o1},f=gb(s,ny({pairingId:e.pairingId,serverNonce:r.serverNonce,claimTokenHash:Eu(u),agentJkt:c,walletPublicKey:l.publicKey,runtime:d})),m={role:"runtime",pairingId:e.pairingId,authUrl:t,claimToken:u,agentJkt:c,publicKeyJwk:a,privateKeyJwk:i,walletPublicKey:l.publicKey,walletPrivateKey:l.privateKey,createdAt:new Date().toISOString()};mb(m,e.pairingDir);let{body:p}=await Dr(`${t}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentPublicJwk:a,walletPublicKey:l.publicKey,runtime:d,signature:f,claimToken:u})},n);if(!p.verificationCode||p.claimToken!==u)throw new Error("pairing server returned an incomplete claim response");if(p.verificationCode!==Ra(e.pairingId,u))throw new Error("pairing server returned a mismatched verification code");return{pending:m,verificationCode:p.verificationCode}}async function hd(e){let t=e.fetchImpl??fetch,n=e.wait??(o=>new Promise(i=>setTimeout(i,o))),r=e.maxPolls??450,s="";for(let o=0;o<r;o+=1){let{body:i,status:a}=await Dr(`${e.pending.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pending.pairingId)}/delivery`,{method:"GET",headers:{"X-Agent-Pairing-Token":e.pending.claimToken},cache:"no-store"},t);if(i.state!==s&&(s=i.state,e.onState?.(i.state)),a===202){if(["expired","cancelled","failed","revoked"].includes(i.state))throw new Error(`pairing ended in state ${i.state}`);await n(e.pollIntervalMs??2e3);continue}if(!i.artifacts||!i.artifactHash)throw new Error("pairing delivery omitted identity artifacts");let c=i.artifacts,l=c.terms?.name;if(c.agentJkt!==e.pending.agentJkt||typeof c.bindingJwt!="string"||typeof c.registrationJwt!="string"||typeof c.termsHash!="string"||typeof l!="string"||sy(i.artifacts)!==i.artifactHash)throw new Error("pairing artifact integrity check failed");let u=gb(Buffer.from(e.pending.privateKeyJwk.d,"base64url"),ry({pairingId:e.pending.pairingId,agentJkt:e.pending.agentJkt,termsHash:c.termsHash,artifactHash:i.artifactHash}));if((await Dr(`${e.pending.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pending.pairingId)}/activate`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Pairing-Token":e.pending.claimToken},body:JSON.stringify({signature:u})},t)).body.state!=="activated")throw new Error("pairing activation was not acknowledged");let f={agent_jkt:e.pending.agentJkt,name:l,public_key_jwk:e.pending.publicKeyJwk,private_key_jwk:e.pending.privateKeyJwk,binding_jwt:c.bindingJwt,registration_jwt:c.registrationJwt,wallet_public_key:e.pending.walletPublicKey,wallet_private_key:e.pending.walletPrivateKey,pairing_id:e.pending.pairingId,pairing_status:"activated",artifacts:i.artifacts,auth_url:e.pending.authUrl,created_at:new Date().toISOString()};return bb(f,e.agentDir),Ga(e.pending.pairingId,"runtime",e.pairingDir),{record:f,name:l,agentJkt:e.pending.agentJkt}}throw new Error("timed out waiting for human authorization")}async function yb(e){let{pairing:t}=e,{body:n}=await Dr(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({verifier:t.verifier})},e.fetchImpl??fetch);return n.state==="cancelled"&&Ga(t.pairingId,"human",e.pairingDir),n}var Bo=jr.join(_b.homedir(),".visa-cli","agents");function vb(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 a1(){return!0}function c1(e=Bo){qe.mkdirSync(e,{recursive:!0,mode:448})}function Ya(e,t=Bo){return jr.join(t,`${e}.json`)}function l1(e=Bo){return qe.existsSync(e)?qe.readdirSync(e).filter(t=>t.endsWith(".json")).map(t=>jr.join(e,t)):[]}function u1(e,t=Bo){let n=Ya(e,t);if(!qe.existsSync(n))return null;try{let r=JSON.parse(qe.readFileSync(n,"utf8"));return vb(r)?r:null}catch{return null}}function bb(e,t=Bo){c1(t);let n=Ya(e.agent_jkt,t);qe.writeFileSync(n,JSON.stringify(e,null,2),{mode:384})}function d1(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}}function wb(e){if(!a1())return;let t=e.command("agent").description("Connect and manage agent runtimes with human-approved Visa identities.");t.command("create").description("Create a secure runtime pairing and authorize it in the browser.").action(async()=>{try{let n=await pb();if(process.stdout.write(["Agent pairing ready.","","Give this skill link to the agent you want to connect:","",` ${n.skillUrl}`,"",`Pairing expires at ${n.expiresAt}.`].join(`
174
+ `}function zk(e){return e.tool_name!=null}function Xk(e){return Ho(e.amount)===0&&e.status==="failed"}function Zk(e){return zk(e)&&!Xk(e)}function Qk(e,t=1/0){let n=new Set,r=[];for(let s of e){if(r.length>=t)break;let o=Lt(s.merchant_name,"Unknown merchant"),i=Lt(s.tool_name,"unknown_tool"),a=`${o} :: ${i}`;n.has(a)||(n.add(a),r.push(`${o} [${i}]`))}return r}function e1(e){let t=Lt(e.merchant_name,"Unknown merchant"),n=Lt(e.tool_name,"unknown_tool"),r=$s(Ho(e.amount)),s=Lt(e.status,"unknown"),o=r1(e.created_at);return`${r} ${s.padEnd(9)} ${t} [${n}] ${o}`}function t1(e){let t=Lt(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function n1(e){return{dailyLimit:Ho(e?.daily_limit??e?.dailyLimit??0)}}function Ho(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function $s(e){return`$${e.toFixed(2)}`}function mb(e,t=Jk){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function Lt(e,t){let n=jr(e??"").trim();return n.length>0?n:t}function r1(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?Lt(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function jr(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 s1=/^[1-9]\d{0,9}$/;function md(e){if(!s1.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 gb(e){let t=jr(e.brand||"Visa"),n=jr(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 Ut=A(require("fs")),_e=A(require("path")),o1=["npm","pnpm","yarn","bun"],i1=/\s+/,a1=process.platform==="win32"?"visa-cli.cmd":"visa-cli",pd=["node_modules","@visa","cli"];function c1(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(i1)[0]??"",r=n.indexOf("/"),s=r===-1?n:n.slice(0,r);return o1.includes(s)?s:void 0}function gd(e){if(!e)return;let t=e;try{t=Ut.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 l1(e=process.argv[1]){return c1()??gd(process.env.npm_execpath)??gd(process.env.npm_node_execpath)??gd(e)}function u1(e=process.env.PATH??""){let t=[];for(let n of e.split(_e.delimiter))n&&t.push(n);return t}function d1(e=process.env.PATH??""){let t=new Set,n=[];for(let r of u1(e))try{let s=_e.join(r,a1);Ut.accessSync(s,Ut.constants.X_OK);let o=_e.resolve(s);t.has(o)||(t.add(o),n.push(s))}catch{}return n}function hb(e){try{let t=Ut.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 f1(e){let t=_e.resolve(e).split(_e.sep);for(let n=t.length-pd.length;n>=0;n--)if(pd.every((r,s)=>t[n+s]===r)){let r=t.slice(0,n+pd.length).join(_e.sep)||_e.sep;if(hb(r))return r}}function m1(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 p1(e,t){let n=_e.resolve(e);try{n=Ut.realpathSync(e)}catch{}let r=f1(n);return{binPath:e,realPath:n,packageRoot:r,version:r?hb(r):void 0,prefix:m1(r),isActive:n===t}}function g1(e,t=process.env.PATH??""){let n=e??process.argv[1],r=n?_e.resolve(n):"";try{n&&(r=Ut.realpathSync(n))}catch{}let s=e?[e]:[n,...d1(t)].filter(Boolean),o=new Map;for(let d of s){let f=p1(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 h1(e,t=process.platform){return/^[A-Za-z0-9_./:@+-]+$/.test(e)?e:t==="win32"?`"${e.replace(/"/g,'""')}"`:`'${e.replace(/'/g,"'\\''")}'`}function hd(e,t,n,r={}){let s=t??l1(n)??"npm",o=r.withDiagnostics?g1(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 ${h1(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 y1(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 yd(e,t){if(!e.hasConflictingInstalls)return null;let n=["Multiple Visa CLI installs detected.",...e.installs.map(y1)];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(`
175
+ `)}var oc=A(ds());function b1(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function yb(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=b1(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 bb(){await G.deleteSessionToken()}var qe=A(require("fs")),kb=A(require("os")),Br=A(require("path")),xd=require("node:readline/promises");ko();ct();Cs();var _b=A(require("node:crypto")),We=A(require("node:fs")),vb=A(require("node:os")),Ya=A(require("node:path"));ko();Cs();ct();var _1="4.0.0-rc.21",Bo=Ya.join(vb.homedir(),".visa-cli","pairings");function bd(e,t,n=Bo){return Ya.join(n,`${e}.${t}.json`)}function wb(e,t=Bo){We.mkdirSync(t,{recursive:!0,mode:448}),We.writeFileSync(bd(e.pairingId,e.role,t),JSON.stringify(e,null,2),{mode:384})}function Ja(e,t,n=Bo){We.rmSync(bd(e,t,n),{force:!0})}function za(e,t,n=Bo){try{let r=JSON.parse(We.readFileSync(bd(e,t,n),"utf8"));return r?.pairingId===e&&r.role===t?r:null}catch{return null}}function _d(e=Bo){return We.existsSync(e)?We.readdirSync(e).filter(n=>n.endsWith(".human.json")).map(n=>{try{return JSON.parse(We.readFileSync(Ya.join(e,n),"utf8"))}catch{return null}}).filter(n=>n?.role==="human").sort((n,r)=>r.createdAt.localeCompare(n.createdAt))[0]??null:null}async function Hr(e,t,n){let r=await n(e,t),s=await r.json().catch(()=>({}));if(!r.ok&&r.status!==202)throw new Error(s.error??s.detail??`pairing server returned ${r.status}`);return{status:r.status,body:s}}async function Sb(e={}){let t=(e.authUrl??de()).replace(/\/+$/,""),n=cy(),{body:r}=await Hr(`${t}/v4/agent-pairings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cliChallenge:ly(n)})},e.fetchImpl??fetch);if(!r.pairingId||!r.skillUrl||!r.authorizationUrl||!r.expiresAt)throw new Error("pairing server returned an incomplete initiation response");let s={role:"human",pairingId:r.pairingId,verifier:n,authUrl:t,skillUrl:r.skillUrl,authorizationUrl:r.authorizationUrl,expiresAt:r.expiresAt,createdAt:new Date().toISOString()};return wb(s,e.pairingDir),s}async function vd(e){let{pairing:t}=e,{body:n}=await Hr(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({verifier:t.verifier,code:e.code})},e.fetchImpl??fetch);return n}async function wd(e){let t=(e.authUrl??de()).replace(/\/+$/,""),{body:n}=await Hr(`${t}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}`,{method:"GET",cache:"no-store"},e.fetchImpl??fetch);return n}function v1(){let e=_b.default.createECDH("prime256v1");return e.generateKeys(),{publicKey:e.getPublicKey("hex","compressed"),privateKey:e.getPrivateKey("hex")}}function xb(e,t){return Buffer.from(Ia(e,Buffer.from(t,"utf8"))).toString("base64url")}async function Cb(e){let t=(e.authUrl??de()).replace(/\/+$/,""),n=e.fetchImpl??fetch,r=await wd({pairingId:e.pairingId,authUrl:t,fetchImpl:n});if(r.state!=="awaiting_agent"||!r.serverNonce)throw new Error(`pairing cannot be claimed from state ${r.state}`);let{secretKey:s,publicKey:o}=ku(),i=Tu(s),a=Pa(o),c=Ro(a),l=v1(),u=uy(),d={runtime:e.runtime,contextLabel:e.contextLabel,platform:`${process.platform}/${process.arch}`,cliVersion:_1},f=xb(s,dy({pairingId:e.pairingId,serverNonce:r.serverNonce,claimTokenHash:Pu(u),agentJkt:c,walletPublicKey:l.publicKey,runtime:d})),m={role:"runtime",pairingId:e.pairingId,authUrl:t,claimToken:u,agentJkt:c,publicKeyJwk:a,privateKeyJwk:i,walletPublicKey:l.publicKey,walletPrivateKey:l.privateKey,createdAt:new Date().toISOString()};wb(m,e.pairingDir);let{body:p}=await Hr(`${t}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentPublicJwk:a,walletPublicKey:l.publicKey,runtime:d,signature:f,claimToken:u})},n);if(!p.verificationCode||p.claimToken!==u)throw new Error("pairing server returned an incomplete claim response");if(p.verificationCode!==$a(e.pairingId,u))throw new Error("pairing server returned a mismatched verification code");return{pending:m,verificationCode:p.verificationCode}}async function Sd(e){let t=e.fetchImpl??fetch,n=e.wait??(o=>new Promise(i=>setTimeout(i,o))),r=e.maxPolls??450,s="";for(let o=0;o<r;o+=1){let{body:i,status:a}=await Hr(`${e.pending.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pending.pairingId)}/delivery`,{method:"GET",headers:{"X-Agent-Pairing-Token":e.pending.claimToken},cache:"no-store"},t);if(i.state!==s&&(s=i.state,e.onState?.(i.state)),a===202){if(["expired","cancelled","failed","revoked"].includes(i.state))throw new Error(`pairing ended in state ${i.state}`);await n(e.pollIntervalMs??2e3);continue}if(!i.artifacts||!i.artifactHash)throw new Error("pairing delivery omitted identity artifacts");let c=i.artifacts,l=c.terms?.name;if(c.agentJkt!==e.pending.agentJkt||typeof c.bindingJwt!="string"||typeof c.registrationJwt!="string"||typeof c.termsHash!="string"||typeof l!="string"||my(i.artifacts)!==i.artifactHash)throw new Error("pairing artifact integrity check failed");let u=xb(Buffer.from(e.pending.privateKeyJwk.d,"base64url"),fy({pairingId:e.pending.pairingId,agentJkt:e.pending.agentJkt,termsHash:c.termsHash,artifactHash:i.artifactHash}));if((await Hr(`${e.pending.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pending.pairingId)}/activate`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Pairing-Token":e.pending.claimToken},body:JSON.stringify({signature:u})},t)).body.state!=="activated")throw new Error("pairing activation was not acknowledged");let f={agent_jkt:e.pending.agentJkt,name:l,public_key_jwk:e.pending.publicKeyJwk,private_key_jwk:e.pending.privateKeyJwk,binding_jwt:c.bindingJwt,registration_jwt:c.registrationJwt,wallet_public_key:e.pending.walletPublicKey,wallet_private_key:e.pending.walletPrivateKey,pairing_id:e.pending.pairingId,pairing_status:"activated",artifacts:i.artifacts,auth_url:e.pending.authUrl,created_at:new Date().toISOString()};return Ab(f,e.agentDir),Ja(e.pending.pairingId,"runtime",e.pairingDir),{record:f,name:l,agentJkt:e.pending.agentJkt}}throw new Error("timed out waiting for human authorization")}async function Eb(e){let{pairing:t}=e,{body:n}=await Hr(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({verifier:t.verifier})},e.fetchImpl??fetch);return n.state==="cancelled"&&Ja(t.pairingId,"human",e.pairingDir),n}var Fo=Br.join(kb.homedir(),".visa-cli","agents");function Tb(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 w1(){return!0}function S1(e=Fo){qe.mkdirSync(e,{recursive:!0,mode:448})}function Xa(e,t=Fo){return Br.join(t,`${e}.json`)}function x1(e=Fo){return qe.existsSync(e)?qe.readdirSync(e).filter(t=>t.endsWith(".json")).map(t=>Br.join(e,t)):[]}function C1(e,t=Fo){let n=Xa(e,t);if(!qe.existsSync(n))return null;try{let r=JSON.parse(qe.readFileSync(n,"utf8"));return Tb(r)?r:null}catch{return null}}function Ab(e,t=Fo){S1(t);let n=Xa(e.agent_jkt,t);qe.writeFileSync(n,JSON.stringify(e,null,2),{mode:384})}function E1(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}}function Rb(e){if(!w1())return;let t=e.command("agent").description("Connect and manage agent runtimes with human-approved Visa identities.");t.command("create").description("Create a secure runtime pairing and authorize it in the browser.").action(async()=>{try{let n=await Sb();if(process.stdout.write(["Agent pairing ready.","","Give this skill link to the agent you want to connect:","",` ${n.skillUrl}`,"",`Pairing expires at ${n.expiresAt}.`].join(`
176
176
  `)),!process.stdin.isTTY){process.stdout.write(`
177
177
  When the agent returns a code, run:
178
178
 
179
179
  visa agent verify ${n.pairingId} CODE
180
- `);return}let r=(0,yd.createInterface)({input:process.stdin,output:process.stdout}),s;try{s=(await r.question(`
181
- Verification code from the agent: `)).trim()}finally{r.close()}let o=await pd({pairing:n,code:s});if(!o.authorizationUrl)throw new Error("authorization URL missing after verification");process.stdout.write(`
180
+ `);return}let r=(0,xd.createInterface)({input:process.stdin,output:process.stdout}),s;try{s=(await r.question(`
181
+ Verification code from the agent: `)).trim()}finally{r.close()}let o=await vd({pairing:n,code:s});if(!o.authorizationUrl)throw new Error("authorization URL missing after verification");process.stdout.write(`
182
182
  \u2713 Agent channel verified. Finish approval in your browser.
183
- `),await Kr(o.authorizationUrl);let i="";for(;i!=="activated";){await new Promise(c=>setTimeout(c,2e3));let a=await gd({pairingId:n.pairingId,authUrl:n.authUrl});if(a.state!==i&&(i=a.state,process.stdout.write(` ${i}
184
- `)),["expired","cancelled","failed","revoked"].includes(i))throw new Error(`pairing ended in state ${i}`)}Ga(n.pairingId,"human"),process.stdout.write(`\u2713 Agent activated.
183
+ `),await Wr(o.authorizationUrl);let i="";for(;i!=="activated";){await new Promise(c=>setTimeout(c,2e3));let a=await wd({pairingId:n.pairingId,authUrl:n.authUrl});if(a.state!==i&&(i=a.state,process.stdout.write(` ${i}
184
+ `)),["expired","cancelled","failed","revoked"].includes(i))throw new Error(`pairing ended in state ${i}`)}Ja(n.pairingId,"human"),process.stdout.write(`\u2713 Agent activated.
185
185
  `)}catch(n){process.stderr.write(`agent create failed: ${n instanceof Error?n.message:String(n)}
186
- `),process.exit(1)}}),t.command("verify [pairing-id] [code]").description("Verify the code returned by an agent (recovery path for a closed create prompt).").action(async(n,r)=>{try{let s=n?Wa(n,"human"):md();if(!s)throw new Error("pending pairing not found on this machine");let o=r?.trim();if(!o&&process.stdin.isTTY){let a=(0,yd.createInterface)({input:process.stdin,output:process.stdout});try{o=(await a.question("Verification code from the agent: ")).trim()}finally{a.close()}}if(!o)throw new Error("verification code required");let i=await pd({pairing:s,code:o});if(!i.authorizationUrl)throw new Error("authorization URL missing after verification");process.stdout.write(`\u2713 Agent channel verified.
187
- `),await Kr(i.authorizationUrl)}catch(s){process.stderr.write(`agent verify failed: ${s instanceof Error?s.message:String(s)}
188
- `),process.exitCode=1}}),t.command("claim <pairing-id>").description("Claim a pairing as this runtime, create local credentials, and wait for approval.").requiredOption("--runtime <runtime>","Runtime name, for example codex or claude-code").requiredOption("--context <label>","Short context label shown to the human").action(async(n,r)=>{try{let{pending:s,verificationCode:o}=await hb({pairingId:n,runtime:r.runtime,contextLabel:r.context});process.stdout.write(["","Ask the human to enter this verification code in their terminal:","",` ${o}`,"","Waiting for approval\u2026"].join(`
189
- `));let i=await hd({pending:s,onState:a=>process.stdout.write(` ${a}
186
+ `),process.exit(1)}}),t.command("verify [pairing-id] [code]").description("Verify the code returned by an agent (recovery path for a closed create prompt).").action(async(n,r)=>{try{let s=n?za(n,"human"):_d();if(!s)throw new Error("pending pairing not found on this machine");let o=r?.trim();if(!o&&process.stdin.isTTY){let a=(0,xd.createInterface)({input:process.stdin,output:process.stdout});try{o=(await a.question("Verification code from the agent: ")).trim()}finally{a.close()}}if(!o)throw new Error("verification code required");let i=await vd({pairing:s,code:o});if(!i.authorizationUrl)throw new Error("authorization URL missing after verification");process.stdout.write(`\u2713 Agent channel verified.
187
+ `),await Wr(i.authorizationUrl)}catch(s){process.stderr.write(`agent verify failed: ${s instanceof Error?s.message:String(s)}
188
+ `),process.exitCode=1}}),t.command("claim <pairing-id>").description("Claim a pairing as this runtime, create local credentials, and wait for approval.").requiredOption("--runtime <runtime>","Runtime name, for example codex or claude-code").requiredOption("--context <label>","Short context label shown to the human").action(async(n,r)=>{try{let{pending:s,verificationCode:o}=await Cb({pairingId:n,runtime:r.runtime,contextLabel:r.context});process.stdout.write(["","Ask the human to enter this verification code in their terminal:","",` ${o}`,"","Waiting for approval\u2026"].join(`
189
+ `));let i=await Sd({pending:s,onState:a=>process.stdout.write(` ${a}
190
190
  `)});process.stdout.write(`\u2713 Activated ${i.name} (${i.agentJkt}). Credentials are stored locally with mode 0600.
191
191
  `)}catch(s){process.stderr.write(`agent claim failed: ${s instanceof Error?s.message:String(s)}
192
- `),process.exitCode=1}}),t.command("resume <pairing-id>").description("Resume artifact delivery for a runtime pairing claimed on this machine.").action(async n=>{try{let r=Wa(n,"runtime");if(!r)throw new Error("runtime pairing not found on this machine");process.stdout.write(`Verification code for the human: ${Ra(n,r.claimToken)}
193
- `);let s=await hd({pending:r,onState:o=>process.stdout.write(` ${o}
192
+ `),process.exitCode=1}}),t.command("resume <pairing-id>").description("Resume artifact delivery for a runtime pairing claimed on this machine.").action(async n=>{try{let r=za(n,"runtime");if(!r)throw new Error("runtime pairing not found on this machine");process.stdout.write(`Verification code for the human: ${$a(n,r.claimToken)}
193
+ `);let s=await Sd({pending:r,onState:o=>process.stdout.write(` ${o}
194
194
  `)});process.stdout.write(`\u2713 Activated ${s.name} (${s.agentJkt}).
195
195
  `)}catch(r){process.stderr.write(`agent resume failed: ${r instanceof Error?r.message:String(r)}
196
- `),process.exitCode=1}}),t.command("cancel [pairing-id]").description("Cancel a pending pairing created on this machine.").action(async n=>{try{let r=n?Wa(n,"human"):md();if(!r)throw new Error("pending pairing not found on this machine");let s=await yb({pairing:r});if(s.state!=="cancelled")throw new Error(`pairing cannot be cancelled from state ${s.state}`);process.stdout.write(`\u2713 Pairing ${r.pairingId} cancelled.
196
+ `),process.exitCode=1}}),t.command("cancel [pairing-id]").description("Cancel a pending pairing created on this machine.").action(async n=>{try{let r=n?za(n,"human"):_d();if(!r)throw new Error("pending pairing not found on this machine");let s=await Eb({pairing:r});if(s.state!=="cancelled")throw new Error(`pairing cannot be cancelled from state ${s.state}`);process.stdout.write(`\u2713 Pairing ${r.pairingId} cancelled.
197
197
  `)}catch(r){process.stderr.write(`agent cancel failed: ${r instanceof Error?r.message:String(r)}
198
- `),process.exitCode=1}}),t.command("list").description("List locally stored agent identities.").action(()=>{let n=l1();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(qe.readFileSync(r,"utf8"))}catch{process.stderr.write(`Skipped unreadable agent record: ${jr.basename(r)}
199
- `);continue}if(!vb(s)){process.stderr.write(`Skipped legacy agent record: ${jr.basename(r)}; run \`visa-cli agent create\` to migrate it.
198
+ `),process.exitCode=1}}),t.command("list").description("List locally stored agent identities.").action(()=>{let n=x1();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(qe.readFileSync(r,"utf8"))}catch{process.stderr.write(`Skipped unreadable agent record: ${Br.basename(r)}
199
+ `);continue}if(!Tb(s)){process.stderr.write(`Skipped legacy agent record: ${Br.basename(r)}; run \`visa-cli agent create\` to migrate it.
200
200
  `);continue}let o=s;process.stdout.write(`${o.agent_jkt} ${o.name} ${o.pairing_status??"legacy-bound"} ${o.created_at}
201
- `)}}),t.command("show <jkt>").description("Show an agent record and the decoded (unverified) binding claims.").action(n=>{let r=u1(n);if(!r){let o=Ya(n);process.stderr.write(qe.existsSync(o)?`Legacy or unreadable agent record: ${n}; run \`visa-cli agent create\` to migrate it.
201
+ `)}}),t.command("show <jkt>").description("Show an agent record and the decoded (unverified) binding claims.").action(n=>{let r=C1(n);if(!r){let o=Xa(n);process.stderr.write(qe.existsSync(o)?`Legacy or unreadable agent record: ${n}; run \`visa-cli agent create\` to migrate it.
202
202
  `:`Agent not found: ${n}
203
- `),process.exit(1)}let s=r.binding_jwt?d1(r.binding_jwt):null;process.stdout.write([`agent jkt: ${r.agent_jkt}`,`name: ${r.name}`,`created: ${r.created_at}`,`auth server: ${r.auth_url}`,`pairing: ${r.pairing_id??"(legacy direct binding)"}`,`status: ${r.pairing_status??"legacy-bound"}`,`public key: ${r.public_key_jwk.x} (Ed25519, OKP)`,`wallet key: ${r.wallet_public_key??"(not paired)"}`,`registration:${r.registration_jwt?" stored":" not stored"}`,`key file: ${Ya(r.agent_jkt)}`,"binding claims (decoded locally, NOT verified):",s?JSON.stringify(s,null,2):" (no binding stored or malformed JWT)",""].join(`
204
- `))})}ou();Es();Ss();var f1="4.0.0-rc.20";async function Sb(e){let t=await qu(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: ${Io} (mesh="${t.mesh}")`),console.log(` chat: visa subway listen --as ${e} | visa subway send --as ${e} <to> "<text>"`)}var Ho=(e,t)=>{if(t instanceof Ot){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 xb(e){if(!Bu(f1))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 Sb(n)}catch(r){Ho("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 Sb(n)}catch(r){Ho("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=Ma(s.as),i=await Gu(o,n,r);console.log(`\u2713 sent to ${i.to} as ${i.as}`)}catch(o){Ho("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 Ku(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){Ho("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=Ma(n.as),s=Cs(r,{autoReconnect:!0});await As(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 ${kr(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){Ho("listen",r)}}),t.command("whoami").description("List names this CLI has registered on the relay.").action(()=>{let n=Wu();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}`)})}ct();Kt();ct();var m1=["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"],p1=["generate_image","generate_video","generate_music","generate_audio","generate_3d","upscale_image","transcribe_audio","run_llm"];function g1(){let e=new Set;for(let t of m1)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of p1)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var A$=g1();var bd=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 P$=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...bd]);ct();var W=k(require("fs")),H=k(require("path")),Cb=k(require("os")),pe=Cb.homedir(),h1=["Claude_","Anthropic.ClaudeDesktop_"],Ps=class extends Error{constructor(n,r,s){super(b1(n,r,s));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function Ab(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
205
- `)}function y1(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=Ab(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function b1(e,t,n){let r=t.replace(pe,"~"),s=Ab(n).split(`
206
- `).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 Fo(){return process.env.APPDATA||H.join(pe,"AppData","Roaming")}function _1(){return process.env.LOCALAPPDATA||H.join(pe,"AppData","Local")}function _d(e){return process.platform==="win32"?e.win32:e.posix}function Eb(){if(process.platform!=="win32")return;let e=H.join(_1(),"Packages");if(W.existsSync(e))try{let t=W.readdirSync(e,"utf-8");for(let n of h1){let r=t.filter(s=>s.startsWith(n)).sort()[0];if(r)return H.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function kb(){if(process.platform==="win32"){let e=Eb();return e?H.join(e,"claude_desktop_config.json"):H.join(Fo(),"Claude","claude_desktop_config.json")}return H.join(pe,"Library","Application Support","Claude","claude_desktop_config.json")}function Tb(){if(process.platform!=="win32")return[H.join(pe,"Library","Application Support","Claude")];let e=[H.join(Fo(),"Claude")],t=Eb();return t&&e.push(t),e}function Ja(e){return e.id==="claude-desktop"?kb():e.globalConfigPath}function v1(e){return e.id==="claude-desktop"?Tb():e.detectPaths}var yt=[{id:"claude",displayName:"Claude Code",globalConfigPath:H.join(pe,".claude.json"),configKey:"mcpServers",detectPaths:[H.join(pe,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:kb(),configKey:"mcpServers",detectPaths:Tb(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:H.join(pe,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[H.join(pe,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:H.join(pe,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[H.join(pe,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:H.join(pe,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[H.join(pe,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:_d({win32:H.join(Fo(),"Roo","mcp_settings.json"),posix:H.join(pe,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[H.join(pe,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:H.join(pe,".vscode","mcp.json"),configKey:"servers",detectPaths:[H.join(pe,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:_d({win32:H.join(Fo(),"Zed","settings.json"),posix:H.join(pe,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:_d({win32:[H.join(Fo(),"Zed")],posix:[H.join(pe,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:H.join(pe,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[H.join(pe,".codex")],postInstallHint:"Restart Codex to connect."}];function vd(e){return yt.find(t=>t.id===e)}function Vo(e){return v1(e).some(t=>{if(t.includes("*")){let n=H.dirname(t),r=H.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 Rb(){return{command:"node",args:[H.resolve(__dirname,"mcp-server/index.js")]}}function wd(e,t){return t==="project"?"json":e.configFormat??"json"}function w1(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 Sd(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 xd(e,t){let n=e.split(`
207
- `),r=Sd(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]]=w1(i[2]))}return Object.keys(s).length>0?s:void 0}function S1(e,t,n){let r=`[${n.args.map(c=>`"${c}"`).join(", ")}]`,s=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],o=e.split(`
208
- `),i=Sd(o,t);if(i){o.splice(i.start,i.end-i.start,...s);let c=o.join(`
203
+ `),process.exit(1)}let s=r.binding_jwt?E1(r.binding_jwt):null;process.stdout.write([`agent jkt: ${r.agent_jkt}`,`name: ${r.name}`,`created: ${r.created_at}`,`auth server: ${r.auth_url}`,`pairing: ${r.pairing_id??"(legacy direct binding)"}`,`status: ${r.pairing_status??"legacy-bound"}`,`public key: ${r.public_key_jwk.x} (Ed25519, OKP)`,`wallet key: ${r.wallet_public_key??"(not paired)"}`,`registration:${r.registration_jwt?" stored":" not stored"}`,`key file: ${Xa(r.agent_jkt)}`,"binding claims (decoded locally, NOT verified):",s?JSON.stringify(s,null,2):" (no binding stored or malformed JWT)",""].join(`
204
+ `))})}uu();Ts();Cs();var A1="4.0.0-rc.21";async function Ib(e){let t=await Ju(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: ${$o} (mesh="${t.mesh}")`),console.log(` chat: visa subway listen --as ${e} | visa subway send --as ${e} <to> "<text>"`)}var Vo=(e,t)=>{if(t instanceof Ot){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 Pb(e){if(!Ku(A1))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 Ib(n)}catch(r){Vo("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 Ib(n)}catch(r){Vo("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=Da(s.as),i=await Xu(o,n,r);console.log(`\u2713 sent to ${i.to} as ${i.as}`)}catch(o){Vo("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 zu(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){Vo("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=Da(n.as),s=As(r,{autoReconnect:!0});await ks(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 ${Rr(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){Vo("listen",r)}}),t.command("whoami").description("List names this CLI has registered on the relay.").action(()=>{let n=Zu();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}`)})}ct();Kt();ct();var k1=["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"],T1=["generate_image","generate_video","generate_music","generate_audio","generate_3d","upscale_image","transcribe_audio","run_llm"];function R1(){let e=new Set;for(let t of k1)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of T1)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var F$=R1();var Cd=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 Y$=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...Cd]);ct();var W=A(require("fs")),B=A(require("path")),$b=A(require("os")),pe=$b.homedir(),I1=["Claude_","Anthropic.ClaudeDesktop_"],Ns=class extends Error{constructor(n,r,s){super($1(n,r,s));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function Nb(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
205
+ `)}function P1(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=Nb(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function $1(e,t,n){let r=t.replace(pe,"~"),s=Nb(n).split(`
206
+ `).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 qo(){return process.env.APPDATA||B.join(pe,"AppData","Roaming")}function N1(){return process.env.LOCALAPPDATA||B.join(pe,"AppData","Local")}function Ed(e){return process.platform==="win32"?e.win32:e.posix}function Ob(){if(process.platform!=="win32")return;let e=B.join(N1(),"Packages");if(W.existsSync(e))try{let t=W.readdirSync(e,"utf-8");for(let n of I1){let r=t.filter(s=>s.startsWith(n)).sort()[0];if(r)return B.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function Mb(){if(process.platform==="win32"){let e=Ob();return e?B.join(e,"claude_desktop_config.json"):B.join(qo(),"Claude","claude_desktop_config.json")}return B.join(pe,"Library","Application Support","Claude","claude_desktop_config.json")}function Lb(){if(process.platform!=="win32")return[B.join(pe,"Library","Application Support","Claude")];let e=[B.join(qo(),"Claude")],t=Ob();return t&&e.push(t),e}function Za(e){return e.id==="claude-desktop"?Mb():e.globalConfigPath}function O1(e){return e.id==="claude-desktop"?Lb():e.detectPaths}var yt=[{id:"claude",displayName:"Claude Code",globalConfigPath:B.join(pe,".claude.json"),configKey:"mcpServers",detectPaths:[B.join(pe,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:Mb(),configKey:"mcpServers",detectPaths:Lb(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:B.join(pe,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[B.join(pe,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:B.join(pe,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[B.join(pe,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:B.join(pe,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[B.join(pe,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:Ed({win32:B.join(qo(),"Roo","mcp_settings.json"),posix:B.join(pe,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[B.join(pe,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:B.join(pe,".vscode","mcp.json"),configKey:"servers",detectPaths:[B.join(pe,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:Ed({win32:B.join(qo(),"Zed","settings.json"),posix:B.join(pe,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:Ed({win32:[B.join(qo(),"Zed")],posix:[B.join(pe,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:B.join(pe,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[B.join(pe,".codex")],postInstallHint:"Restart Codex to connect."}];function Ad(e){return yt.find(t=>t.id===e)}function Ko(e){return O1(e).some(t=>{if(t.includes("*")){let n=B.dirname(t),r=B.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 Ub(){return{command:"node",args:[B.resolve(__dirname,"mcp-server/index.js")]}}function kd(e,t){return t==="project"?"json":e.configFormat??"json"}function M1(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 Td(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(`
207
+ `),r=Td(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]]=M1(i[2]))}return Object.keys(s).length>0?s:void 0}function L1(e,t,n){let r=`[${n.args.map(c=>`"${c}"`).join(", ")}]`,s=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],o=e.split(`
208
+ `),i=Td(o,t);if(i){o.splice(i.start,i.end-i.start,...s);let c=o.join(`
209
209
  `);return c.endsWith(`
210
210
  `)?c:c+`
211
211
  `}let a=e.trimEnd();return a+(a.length>0?`
212
212
 
213
213
  `:"")+s.join(`
214
214
  `)+`
215
- `}function x1(e,t){let n=e.split(`
216
- `),r=Sd(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
215
+ `}function U1(e,t){let n=e.split(`
216
+ `),r=Td(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
217
217
  `).replace(/\n{3,}/g,`
218
218
 
219
- `)):e}function qo(e,t="global"){let n=t==="project"?H.join(process.cwd(),".mcp.json"):Ja(e);try{let r=H.dirname(n);W.existsSync(r)||W.mkdirSync(r,{recursive:!0});let s=wd(e,t),o=Rb();if(s==="toml"){let i=W.existsSync(n)?W.readFileSync(n,"utf-8"):"",a=S1(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)+`
220
- `)}}catch(r){throw y1(r)?new Ps(e,n,r):r}return{installed:!0,configPath:n,message:e.postInstallHint}}function Cd(e,t="global"){let n=t==="project"?H.join(process.cwd(),".mcp.json"):Ja(e);if(!W.existsSync(n))return{removed:!1,configPath:n};if(wd(e,t)==="toml"){let i=W.readFileSync(n,"utf-8");return xd(i,"visa-cli")?(W.writeFileSync(n,x1(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)+`
221
- `),{removed:!0,configPath:n})}function Ib(e,t="global"){let n=t==="project"?H.join(process.cwd(),".mcp.json"):Ja(e);if(!W.existsSync(n))return!1;if(wd(e,t)==="toml")try{let s=W.readFileSync(n,"utf-8");return!!xd(s,"visa-cli")}catch{return!1}try{return!!JSON.parse(W.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function C1(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 A1(e,t){if(e===t)return!0;let n=H.resolve(e),r=H.resolve(t);if(n===r)return!0;try{let s=W.realpathSync(n),o=W.realpathSync(r);return s===o}catch{return!1}}function Ko(){let e=Rb(),t=e.args[e.args.length-1],n=[];for(let r of yt){let s=Ja(r);if(!W.existsSync(s))continue;let o=r.configFormat??"json",i;if(o==="toml")try{let l=W.readFileSync(s,"utf-8");i=xd(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=C1(i);if(!a||A1(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 Ad(e){return{configPath:qo(e.client,"global").configPath}}var Rd=(0,Bb.promisify)(jb.execFile);function Ed(){let e=Ft();setImmediate(()=>{Mc(e,{getCommand:()=>bi(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 I1(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)})
222
- ${r}: ${n(e.currentPath)}`}function Hb(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(I1(n))}function Pb(e){console.log(` ! ${e.client.displayName} skipped: ${e.message}`)}function Dt(){this.help({error:!1})}var z=new Db.Command,P1=new Set(["pay",...bd]),Za=null,Go=!1;function ge(){return Za=new Ke(()=>G.getSessionToken()),Za}function $b(e){if(e instanceof er)return!0;let t=e instanceof Error?e.message:"";return/attestation required|invalid signature|rotate biometric key|biometric key/i.test(t)}var Nb=0,Ob="",$1="attestation-key-rotation",N1="api-keys-create",Mb=0,Lb="",O1=12e3;async function M1(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:Nb,merchant:Ob,context:$1})).toString("base64");return{signature:await In(n,"verify Visa CLI Touch ID setup"),nonce:t,amount:Nb,merchant:Ob}}async function L1(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:Mb,merchant:Lb,context:N1})).toString("base64");return{signature:await In(n,"create a Visa Key",{timeoutMs:O1}),nonce:t,amount:Mb,merchant:Lb}}async function U1(e){let t=await e.getStatus();return t.attestationRequired!==!1||kt(t)}async function D1(e){let t=await jp(),n=await M1(e);await e.registerAttestationKey(t,n)}async function Fb(e,t,n=!1){let r=await Fi();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 kd(e){if(!await $d(e))throw new Error("Could not clear stale server biometric state. Run `visa-cli config reset`, then `visa-cli setup`.");await Fb(e,!0,!0)}function rc(e){return async()=>{let t=await $d(e);return{success:t,...t?{}:{message:"Biometric recovery was not completed."}}}}async function j1(e){let r=Date.now()+3e5;for(;Date.now()<r;)try{let s=await globalThis.fetch(`${de()}/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 yn(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 yn(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 $d(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=tc.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 Kr(r.recoveryUrl),await j1(n),console.log(" Server biometric state cleared."),!0}function Wo(e){return`$${(e/100).toFixed(2)}`}function B1(e){return typeof e=="number"?Wo(e):"no cap"}function Qa(e,t,n=!1){if(!e){let i=Wo(t);return n&&t>=0?`+${i}`:i}let r=(0,nc.fromWire)(e),s=r%10000n===0n?2:6,o=(0,nc.toDisplay)(r,{decimals:s});return n&&r>=0n?`+${o}`:o}function H1(e){return Qa(e,0)}function F1(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 V1(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=>P1.has(o));if(s)throw new Error(`Tool id "${s}" is retired for direct API-key access. Use discover/execute instead.`);return n}var Id=!1;async function Vb(e){let t=(0,Pd.createInterface)({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function q1(e,t=!1){let n=bm(e,{json:t,isTTY:process.stdin.isTTY===!0});if(n!==void 0)return n;if(await Bc("Use recommended Visa Key caps ($5/day and $25 total)? Without caps, leaked keys can spend from prepaid balance until revoked.",!0))return Id=!0,500;let s=await Vb("Daily cap USD (1-100): ");if(!s)throw new Error("--daily-cap is required when declining the recommended daily cap.");return Fc(s)}async function K1(e,t=!1){let n=_m(e,{json:t,isTTY:process.stdin.isTTY===!0,recommendedCapsAccepted:Id});if(n!==void 0)return Id=!1,n;let r=await Vb("Cumulative cap USD (1-10000, default 25): ");return Vc(r||"25")}function G1(e){return e&&e.length>0?e.join(", "):"all tools"}function qb(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 sc(e,t={}){let n=t.format&&ii(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=qr(c);if(d){let f=typeof e?.merchantName=="string"?e.merchantName:"media",m=typeof e?.transactionId=="string"?`${f}-${e.transactionId}`:f,p=js(d,{tag:m}),h=wc(i,e);h.success&&(h.filePath=p.filePath,h.mime=p.mime,h.bytes=p.bytes,u&&u.startsWith("data:")&&(h.urls=void 0)),Vs(h,a);return}}catch(d){Vs(Bs(i,`Failed to save inline media: ${d instanceof Error?d.message:String(d)}`),a),process.exitCode=Gb;return}Vs(wc(i,e),a);return}if(e?.content?.[0]?.text&&typeof e.content[0].text=="string"){try{let i=qr(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=js(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(of(e)){console.log("In Queue"),vc(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(`
219
+ `)):e}function Go(e,t="global"){let n=t==="project"?B.join(process.cwd(),".mcp.json"):Za(e);try{let r=B.dirname(n);W.existsSync(r)||W.mkdirSync(r,{recursive:!0});let s=kd(e,t),o=Ub();if(s==="toml"){let i=W.existsSync(n)?W.readFileSync(n,"utf-8"):"",a=L1(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)+`
220
+ `)}}catch(r){throw P1(r)?new Ns(e,n,r):r}return{installed:!0,configPath:n,message:e.postInstallHint}}function Id(e,t="global"){let n=t==="project"?B.join(process.cwd(),".mcp.json"):Za(e);if(!W.existsSync(n))return{removed:!1,configPath:n};if(kd(e,t)==="toml"){let i=W.readFileSync(n,"utf-8");return Rd(i,"visa-cli")?(W.writeFileSync(n,U1(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)+`
221
+ `),{removed:!0,configPath:n})}function Db(e,t="global"){let n=t==="project"?B.join(process.cwd(),".mcp.json"):Za(e);if(!W.existsSync(n))return!1;if(kd(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 D1(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 j1(e,t){if(e===t)return!0;let n=B.resolve(e),r=B.resolve(t);if(n===r)return!0;try{let s=W.realpathSync(n),o=W.realpathSync(r);return s===o}catch{return!1}}function Wo(){let e=Ub(),t=e.args[e.args.length-1],n=[];for(let r of yt){let s=Za(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=D1(i);if(!a||j1(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 Pd(e){return{configPath:Go(e.client,"global").configPath}}var Md=(0,Yb.promisify)(Wb.execFile);function $d(){let e=Ft();setImmediate(()=>{Dc(e,{getCommand:()=>vi(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 q1(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)})
222
+ ${r}: ${n(e.currentPath)}`}function Jb(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(q1(n))}function jb(e){console.log(` ! ${e.client.displayName} skipped: ${e.message}`)}function Dt(){this.help({error:!1})}var z=new Gb.Command,K1=new Set(["pay",...Cd]),tc=null,Yo=!1;function ge(){return tc=new Ke(()=>G.getSessionToken()),tc}function Hb(e){if(e instanceof nr)return!0;let t=e instanceof Error?e.message:"";return/attestation required|invalid signature|rotate biometric key|biometric key/i.test(t)}var Bb=0,Fb="",G1="attestation-key-rotation",W1="api-keys-create",Vb=0,qb="",Y1=12e3;async function J1(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:Bb,merchant:Fb,context:G1})).toString("base64");return{signature:await $n(n,"verify Visa CLI Touch ID setup"),nonce:t,amount:Bb,merchant:Fb}}async function z1(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:Vb,merchant:qb,context:W1})).toString("base64");return{signature:await $n(n,"create a Visa Key",{timeoutMs:Y1}),nonce:t,amount:Vb,merchant:qb}}async function X1(e){let t=await e.getStatus();return t.attestationRequired!==!1||kt(t)}async function Z1(e){let t=await qp(),n=await J1(e);await e.registerAttestationKey(t,n)}async function zb(e,t,n=!1){let r=await qi();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 Nd(e){if(!await Dd(e))throw new Error("Could not clear stale server biometric state. Run `visa-cli config reset`, then `visa-cli setup`.");await zb(e,!0,!0)}function ic(e){return async()=>{let t=await Dd(e);return{success:t,...t?{}:{message:"Biometric recovery was not completed."}}}}async function Q1(e){let r=Date.now()+3e5;for(;Date.now()<r;)try{let s=await globalThis.fetch(`${de()}/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 bn(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 bn(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 Dd(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=sc.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 Wr(r.recoveryUrl),await Q1(n),console.log(" Server biometric state cleared."),!0}function Jo(e){return`$${(e/100).toFixed(2)}`}function eT(e){return typeof e=="number"?Jo(e):"no cap"}function nc(e,t,n=!1){if(!e){let i=Jo(t);return n&&t>=0?`+${i}`:i}let r=(0,oc.fromWire)(e),s=r%10000n===0n?2:6,o=(0,oc.toDisplay)(r,{decimals:s});return n&&r>=0n?`+${o}`:o}function tT(e){return nc(e,0)}function nT(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 rT(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=>K1.has(o));if(s)throw new Error(`Tool id "${s}" is retired for direct API-key access. Use discover/execute instead.`);return n}var Ld=!1;async function Xb(e){let t=(0,Ud.createInterface)({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function sT(e,t=!1){let n=Cm(e,{json:t,isTTY:process.stdin.isTTY===!0});if(n!==void 0)return n;if(await Vc("Use recommended Visa Key caps ($5/day and $25 total)? Without caps, leaked keys can spend from prepaid balance until revoked.",!0))return Ld=!0,500;let s=await Xb("Daily cap USD (1-100): ");if(!s)throw new Error("--daily-cap is required when declining the recommended daily cap.");return Kc(s)}async function oT(e,t=!1){let n=Em(e,{json:t,isTTY:process.stdin.isTTY===!0,recommendedCapsAccepted:Ld});if(n!==void 0)return Ld=!1,n;let r=await Xb("Cumulative cap USD (1-10000, default 25): ");return Gc(r||"25")}function iT(e){return e&&e.length>0?e.join(", "):"all tools"}function Zb(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 ac(e,t={}){let n=t.format&&ci(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=Gr(c);if(d){let f=typeof e?.merchantName=="string"?e.merchantName:"media",m=typeof e?.transactionId=="string"?`${f}-${e.transactionId}`:f,p=Bs(d,{tag:m}),h=Cc(i,e);h.success&&(h.filePath=p.filePath,h.mime=p.mime,h.bytes=p.bytes,u&&u.startsWith("data:")&&(h.urls=void 0)),Ks(h,a);return}}catch(d){Ks(Fs(i,`Failed to save inline media: ${d instanceof Error?d.message:String(d)}`),a),process.exitCode=e_;return}Ks(Cc(i,e),a);return}if(e?.content?.[0]?.text&&typeof e.content[0].text=="string"){try{let i=Gr(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=Bs(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(ff(e)){console.log("In Queue"),xc(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(`
223
223
  \u2139 Your request is processing. Poll for the result with:
224
224
  ${c}`);let l=JSON.stringify(e,null,2);l&&l!=="{}"&&(console.log(`
225
- Result:`),console.log(l));return}if(console.log("Done"),vc(e),s.length>0){console.log(`
225
+ Result:`),console.log(l));return}if(console.log("Done"),xc(e),s.length>0){console.log(`
226
226
  Result URLs:`);for(let i of s)console.log(` ${i}`);return}let o=JSON.stringify(e,null,2);o&&o!=="{}"&&(console.log(`
227
- Result:`),console.log(o))}var W1=new Set(["INVALID_TOOL_PARAMS","MISSING_TOOL_ID","UNKNOWN_TOOL"]),Kb=0,Gb=1,Y1=2;function J1(e){if(e?.success!==!1)return Kb;let n=(typeof e?.error_code=="string"?e.error_code:typeof e?.code=="string"?e.code:"").toUpperCase();return W1.has(n)?Y1:Gb}function oc(e){let t=J1(e);t!==Kb&&(process.exitCode=t)}function $s(e,t,n={}){let r=typeof n=="boolean"?{json:n}:n,s=t instanceof Error?t.message:String(t),o=r.format&&ii(r.format)?r.format:void 0;if(r.json||o!==void 0){let i=o??"json";Vs(Bs(e,s),i)}else console.error("Error:",s);process.exit(1)}async function z1(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 Nd=100,Od=200;function ec(e){let t=Number.parseInt(e,10);return Number.isNaN(t)?Number.NaN:t}function X1(e){let t=typeof e.limit=="number"&&Number.isInteger(e.limit)?Math.max(1,Math.min(e.limit,Od)):Nd,n=typeof e.offset=="number"&&Number.isInteger(e.offset)?Math.max(0,e.offset):0;return{limit:t,offset:n}}function Z1(e){let t=`
227
+ Result:`),console.log(o))}var aT=new Set(["INVALID_TOOL_PARAMS","MISSING_TOOL_ID","UNKNOWN_TOOL"]),Qb=0,e_=1,cT=2;function lT(e){if(e?.success!==!1)return Qb;let n=(typeof e?.error_code=="string"?e.error_code:typeof e?.code=="string"?e.code:"").toUpperCase();return aT.has(n)?cT:e_}function cc(e){let t=lT(e);t!==Qb&&(process.exitCode=t)}function Os(e,t,n={}){let r=typeof n=="boolean"?{json:n}:n,s=t instanceof Error?t.message:String(t),o=r.format&&ci(r.format)?r.format:void 0;if(r.json||o!==void 0){let i=o??"json";Ks(Fs(e,s),i)}else console.error("Error:",s);process.exit(1)}async function uT(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 jd=100,Hd=200;function rc(e){let t=Number.parseInt(e,10);return Number.isNaN(t)?Number.NaN:t}function dT(e){let t=typeof e.limit=="number"&&Number.isInteger(e.limit)?Math.max(1,Math.min(e.limit,Hd)):jd,n=typeof e.offset=="number"&&Number.isInteger(e.offset)?Math.max(0,e.offset):0;return{limit:t,offset:n}}function fT(e){let t=`
228
228
  Options:
229
229
  `,n=`
230
230
  Commands:
231
- `,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 Q1(e){if(!e.startsWith("Usage: "))return e;let t=e.indexOf(`
231
+ `,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 mT(e){if(!e.startsWith("Usage: "))return e;let t=e.indexOf(`
232
232
 
233
233
  `);if(t===-1)return e;let n=e.slice(0,t),r=e.slice(t+2),s=r.indexOf(`
234
234
 
@@ -236,18 +236,18 @@ Commands:
236
236
 
237
237
  ${n}
238
238
 
239
- ${i}`:e}function eT(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(`
240
- `).map(tT).join(`
241
- `);return`${n}${r}${o}`})}function tT(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 nT(e){return e.replace(/^(Usage: .+?) \[options\](?= |$)/gm,"$1")}function rT(e){return e.replace(/^Options:$/gm,"Flags:")}function Wb(e){let t=e.helpInformation.bind(e);e.helpInformation=()=>rT(nT(eT(Z1(Q1(t())))));for(let n of e.commands)Wb(n)}function sT(e){let t=new Map(e.map((r,s)=>[r,s]));z.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})}z.name("visa-cli").description("Visa CLI - set up MCP payments, manage credentials, and monitor AI spend").version(Ds().version).addHelpCommand(!1).action(Dt);z.hook("preAction",async()=>{await rf()});z.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(`
239
+ ${i}`:e}function pT(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(`
240
+ `).map(gT).join(`
241
+ `);return`${n}${r}${o}`})}function gT(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 hT(e){return e.replace(/^(Usage: .+?) \[options\](?= |$)/gm,"$1")}function yT(e){return e.replace(/^Options:$/gm,"Flags:")}function t_(e){let t=e.helpInformation.bind(e);e.helpInformation=()=>yT(hT(pT(fT(mT(t())))));for(let n of e.commands)t_(n)}function bT(e){let t=new Map(e.map((r,s)=>[r,s]));z.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})}z.name("visa-cli").description("Visa CLI - set up MCP payments, manage credentials, and monitor AI spend").version(Hs().version).addHelpCommand(!1).action(Dt);z.hook("preAction",async()=>{await uf()});z.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(`
242
242
 
243
- 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 _=Ko();Hb(_,"MCP config check:"),_.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=Ko(),o=new Map(s.map(_=>[_.client.id,_])),i=new Set,a=new Set,c=new Set;for(let _ of yt)if(Vo(_)){let w;try{w=qo(_)}catch(y){if(y instanceof Ps){Pb(y),a.add(_.displayName),c.add(_.id);continue}throw y}let R=o.get(_.id),E=R?` \u2014 repaired stale ${R.staleReason} entry`:"";console.log(` \u2713 ${_.displayName} (${w.configPath.replace(re.homedir(),"~")})${E}`),R&&i.add(_.id)}let l=s.filter(_=>!i.has(_.client.id)&&!c.has(_.client.id)),u=0;for(let _ of l){try{Ad(_)}catch(w){if(w instanceof Ps){Pb(w),a.add(_.client.displayName),c.add(_.client.id);continue}throw w}console.log(` \u2713 ${_.client.displayName} (${_.configPath.replace(re.homedir(),"~")}) \u2014 repaired stale ${_.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(`
244
- Step 2: Checking authentication...`);let f=await G.getSessionToken();if(f)try{await new Ke(()=>Promise.resolve(f)).getStatus(),console.log(" Already authenticated.")}catch(_){let w=_ instanceof Error?_.message:"";w.includes("session has expired")||w.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await ub(),f=null):console.log(` Couldn't verify session (${w||"unknown error"}) \u2014 continuing with existing token.`)}if(!f){let _=null;try{let{stdout:w}=await Rd("gh",["auth","token"],{timeout:5e3});_=w.trim()}catch{}if(_||(_=process.env.GITHUB_TOKEN||null),_)try{console.log(" Found GitHub token \u2014 attempting headless login...");let w=await globalThis.fetch(`${de()}/v1/auth/token-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({github_token:_}),signal:AbortSignal.timeout(1e4)});if(w.ok){let R=await w.json();if(R.success&&R.sessionToken){let E=R.sessionToken;f=E,await G.saveSessionToken(E),console.log(` Signed in as ${R.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(_,w)=>{let R=tc.randomUUID(),E=`${de()}/login?state=${R}`;await Kr(E);let y=3e4,x=300*1e3,Y=Date.now()+x;for(;Date.now()<Y;)try{let X=await globalThis.fetch(`${de()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:R,timeout:y}),signal:AbortSignal.timeout(y+5e3)});if(!X.ok){await yn(X,ve=>{g.warn("auth_status:retry_after_http_error",{status:X.status,delayMs:ve})});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}.`),_(K.sessionToken);return}}catch{await yn(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(`
245
- Step 3: Setting up authentication...`),fe()){try{await Rd("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 _=ge();try{let w=await _.getStatus(),R=!0;if(kt(w))if(await Vi())try{await D1(_),console.log(" Attestation key already registered with server."),console.log(" Existing local Touch ID key verified and preserved."),R=!1}catch(E){if(!$b(E))throw E;console.log(" Existing local Touch ID key does not match server biometric state."),await kd(_),R=!1}else console.log(" Server already has a biometric key, but this device has no local key."),await kd(_),R=!1;R&&await Fb(_,w.attestationRequired===!1)}catch(w){let R=w?.message||"unknown error";if($b(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 kd(_),E=!0}catch(y){console.error(` Biometric recovery failed: ${y?.message||"unknown error"}`)}if(!E){let y=w instanceof er&&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: ${R}`),process.exit(1)}}else{let _=ge(),w;try{w=await _.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 R=lb(w);R.canContinue||(console.error(` ${R.message}`),R.hint&&console.error(` ${R.hint}`),process.exit(1)),console.log(` ${R.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(`
246
- Step 4: Visa HUD`),console.log(" Pin balance, card, spend, model, and session activity below the Claude Code input."),console.log(dm()),h=await Bc(" Install the Visa HUD now?",!1)),h)if(!p)console.log(`
243
+ 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=Wo();Jb(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=Wo(),o=new Map(s.map(v=>[v.client.id,v])),i=new Set,a=new Set,c=new Set;for(let v of yt)if(Ko(v)){let w;try{w=Go(v)}catch(y){if(y instanceof Ns){jb(y),a.add(v.displayName),c.add(v.id);continue}throw y}let R=o.get(v.id),k=R?` \u2014 repaired stale ${R.staleReason} entry`:"";console.log(` \u2713 ${v.displayName} (${w.configPath.replace(re.homedir(),"~")})${k}`),R&&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{Pd(v)}catch(w){if(w instanceof Ns){jb(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(`
244
+ Step 2: Checking authentication...`);let f=await G.getSessionToken();if(f)try{await new Ke(()=>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 bb(),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 Md("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(`${de()}/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 R=await w.json();if(R.success&&R.sessionToken){let k=R.sessionToken;f=k,await G.saveSessionToken(k),console.log(` Signed in as ${R.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 R=sc.randomUUID(),k=`${de()}/login?state=${R}`;await Wr(k);let y=3e4,x=300*1e3,Y=Date.now()+x;for(;Date.now()<Y;)try{let X=await globalThis.fetch(`${de()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:R,timeout:y}),signal:AbortSignal.timeout(y+5e3)});if(!X.ok){await bn(X,ve=>{g.warn("auth_status:retry_after_http_error",{status:X.status,delayMs:ve})});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 bn(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(`
245
+ Step 3: Setting up authentication...`),fe()){try{await Md("clang",["--version"])}catch{console.error(" Xcode Command Line Tools are required for payment authentication."),console.error(" Install them by running: xcode-select --install"),console.error(" Then re-run: visa-cli setup"),process.exit(1)}let v=ge();try{let w=await v.getStatus(),R=!0;if(kt(w))if(await Ki())try{await Z1(v),console.log(" Attestation key already registered with server."),console.log(" Existing local Touch ID key verified and preserved."),R=!1}catch(k){if(!Hb(k))throw k;console.log(" Existing local Touch ID key does not match server biometric state."),await Nd(v),R=!1}else console.log(" Server already has a biometric key, but this device has no local key."),await Nd(v),R=!1;R&&await zb(v,w.attestationRequired===!1)}catch(w){let R=w?.message||"unknown error";if(Hb(w)){console.log(" Server already has a biometric key for this account, but this device cannot prove access to it.");let k=!1;try{await Nd(v),k=!0}catch(y){console.error(` Biometric recovery failed: ${y?.message||"unknown error"}`)}if(!k){let y=w instanceof nr&&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: ${R}`),process.exit(1)}}else{let v=ge(),w;try{w=await v.getStatus()}catch(k){console.error(" Biometric attestation (Touch ID or Windows Hello) is unavailable in this process."),console.error(` Could not verify server biometric policy: ${k?.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 R=yb(w);R.canContinue||(console.error(` ${R.message}`),R.hint&&console.error(` ${R.hint}`),process.exit(1)),console.log(` ${R.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(`
246
+ Step 4: Visa HUD`),console.log(" Pin balance, card, spend, model, and session activity below the Claude Code input."),console.log(ym()),h=await Vc(" Install the Visa HUD now?",!1)),h)if(!p)console.log(`
247
247
  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(`
248
- Step 4: Enabling the Visa spend HUD...`);let _=zs(m),w=_.installed==="new"||_.installed==="already-visa"||_.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${w}${_.message}`);try{let R=ge(),E=await R.getStatus(),y={currentVersion:R.getClientVersion(),latestVersion:R.lastSignals?.updateAvailable?.latestVersion,updateCheckDisabled:St()},x=Ic(E,y);Pc(x,E),console.log(` Preview: ${x.split(`
248
+ Step 4: Enabling the Visa spend HUD...`);let v=Zs(m),w=v.installed==="new"||v.installed==="already-visa"||v.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${w}${v.message}`);try{let R=ge(),k=await R.getStatus(),y={currentVersion:R.getClientVersion(),latestVersion:R.lastSignals?.updateAvailable?.latestVersion,updateCheckDisabled:St()},x=Nc(k,y);Oc(x,k),console.log(` Preview: ${x.split(`
249
249
  `)[0]}`)}catch{}}else e.hud!==!1&&(console.log(`
250
- Step 4: Visa HUD not installed.`),console.log(" Enable later with: visa-cli config hud enable"));let v="\x1B[1m",I="\x1B[2m",b="\x1B[0m";console.log(`
250
+ Step 4: Visa HUD not installed.`),console.log(" Enable later with: visa-cli config hud enable"));let _="\x1B[1m",I="\x1B[2m",b="\x1B[0m";console.log(`
251
251
  \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
252
252
  \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
253
253
  \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
@@ -255,15 +255,15 @@ Step 4: Visa HUD not installed.`),console.log(" Enable later with: visa-cli co
255
255
  \u255A\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551
256
256
  \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u2588 CLI
257
257
 
258
- ${v}Setup complete.${b} Restart Claude Code or run /mcp to connect.
258
+ ${_}Setup complete.${b} Restart Claude Code or run /mcp to connect.
259
259
 
260
- ${v}Try it out:${b}
260
+ ${_}Try it out:${b}
261
261
  \u2022 Ask Claude: "Generate an image of a neon cityscape"
262
262
  \u2022 Ask Claude: "What's the price of ETH on Base?"
263
263
  \u2022 Check balance: visa-cli balance show
264
264
 
265
265
  \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
266
- \u2502 ${v}Recommended: enable the spend HUD${b} \u2502
266
+ \u2502 ${_}Recommended: enable the spend HUD${b} \u2502
267
267
  \u2502 \u2502
268
268
  \u2502 Keep an eye on what your agents are spending. \u2502
269
269
  \u2502 Shows your balance, active card, and recent tool usage \u2502
@@ -273,72 +273,72 @@ Step 4: Visa HUD not installed.`),console.log(" Enable later with: visa-cli co
273
273
  \u2502 \u2502
274
274
  \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
275
275
 
276
- ${v}Verify:${b} visa-cli status
277
- ${v}Docs:${b} https://visacli.sh
278
- `),r()}catch(s){console.error("Error:",s.message),r(),process.exit(1)}});z.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=Ko();Hb(o,"MCP config check:"),o.length>0&&process.exit(1);return}if(t.repair){let o=Ko();if(o.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of o)Ad(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(re.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
276
+ ${_}Verify:${b} visa-cli status
277
+ ${_}Docs:${b} https://visacli.sh
278
+ `),r()}catch(s){console.error("Error:",s.message),r(),process.exit(1)}});z.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=Wo();Jb(o,"MCP config check:"),o.length>0&&process.exit(1);return}if(t.repair){let o=Wo();if(o.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of o)Pd(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(re.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
279
279
  Repaired ${o.length} stale MCP config ${o.length===1?"entry":"entries"}.`);return}if(t.list){console.log(`
280
280
  \x1B[1mSupported MCP Clients\x1B[0m
281
- `),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 yt){let c=Vo(a),l=Ib(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 yt){if(!Vo(a)){i.push(a.displayName);continue}qo(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(`
282
- Supported clients: ${yt.map(o=>o.id).join(", ")}`),process.exit(1));let r=vd(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${yt.map(o=>o.id).join(", ")}`),process.exit(1)),n==="global"&&!Vo(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let s=qo(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)}});z.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{Go=!1;try{let e=ge(),[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}
283
- `)}return{transactions:[]}})]),r={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:St()};process.stdout.write(ib(t,Array.isArray(n?.transactions)?n.transactions:[],fe(),r)),Go=!0}catch(e){Go=!1,console.error("Error:",e.message),process.exit(1)}});function oT(e){let t=e.map(ab),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(`
281
+ `),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 yt){let c=Ko(a),l=Db(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 yt){if(!Ko(a)){i.push(a.displayName);continue}Go(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(`
282
+ Supported clients: ${yt.map(o=>o.id).join(", ")}`),process.exit(1));let r=Ad(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${yt.map(o=>o.id).join(", ")}`),process.exit(1)),n==="global"&&!Ko(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let s=Go(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)}});z.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{Yo=!1;try{let e=ge(),[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}
283
+ `)}return{transactions:[]}})]),r={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:St()};process.stdout.write(pb(t,Array.isArray(n?.transactions)?n.transactions:[],fe(),r)),Yo=!0}catch(e){Yo=!1,console.error("Error:",e.message),process.exit(1)}});function _T(e){let t=e.map(gb),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(`
284
284
  Cards
285
285
  `),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(`
286
286
  Use:`),console.log(" visa-cli cards default <id>"),console.log(` visa-cli cards remove <id>
287
- `)}async function Yb(e,t){if(t.yes)return"confirmed";if(!process.stdin.isTTY)return"refused-non-tty";let n=(0,Pd.createInterface)({input:process.stdin,output:process.stdout});try{let r=(await n.question(`${e} [y/N] `)).trim();return/^y(es)?$/i.test(r)?"confirmed":"declined"}finally{n.close()}}var ic=z.command("cards").description("Manage enrolled payment cards").addHelpCommand(!1).action(Dt);ic.command("list").alias("ls").description("List enrolled payment cards").action(async()=>{try{let e=await Mt.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}oT(t)}catch(e){console.error("Error:",e.message),process.exit(1)}});ic.command("add").description("Add a new Visa card").action(async()=>{try{let e=await Mt.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)}});ic.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=ad(e),r=await Yb(`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 Mt.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)}});ic.command("default <card-id>").alias("set-default").description("Set the default payment card").action(async e=>{try{let t=ad(e),n=await Mt.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 iT(e){return/timed out waiting for touch id\/device approval|attestation[_\s-]?required/i.test(e)}function Md(e){let t=e instanceof Error?e.message:String(e);console.error("Error:",t),iT(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 aT(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 Ld(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 Ud=z.command("keys").description("Create and manage Visa Keys for apps and agents").addHelpCommand(!1).action(Dt);Ud.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 q1(t.dailyCap,t.json),r=await K1(t.totalCap,t.json),s=await Ld(async()=>{let o=ge(),i={label:F1(e),allowed_tools:V1(t.tools),daily_cap_cents:n,total_cap_cents:r};return await U1(o)?await vr(o,async()=>{let a=await L1(o);return o.createAppApiKey({...i,attestation:a})},rc(o)):await o.createAppApiKey(i)});if(t.json){console.log(JSON.stringify(s,null,2));return}process.stdout.write(hm(s,{authUrl:de()}))}catch(n){Md(n)}});Ud.command("list").description("List Visa Keys for the authenticated user").option("--json","Output raw JSON").action(async e=>{try{let t=await Ld(async()=>await ge().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: ${G1(r.allowed_tools)}`),console.log(` Daily cap: ${Wo(r.daily_cap_cents)}/day`),console.log(` Total cap: ${B1(r.total_cap_cents)}`),console.log(` Last used: ${r.last_used_at||"never"}`)}catch(t){Md(t)}});Ud.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 Ld(async()=>await ge().revokeAppApiKey(t));console.log(`Revoked Visa Key ${n.revoked}.`)}catch(t){Md(t)}});async function cT(){if(await G.clearAll(),console.log(" Keychain credentials cleared."),fe())try{await qi(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}}async function Jb(e={}){try{if(console.log(`Resetting Visa CLI...
288
- `),e.localOnly)console.log(" Local-only reset: skipping server logout and biometric recovery.");else{let t=ge();await $d(t);try{await t.logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}}await cT(),console.log(`
289
- 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)}}z.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(Jb);var Dd=z.command("balance").description("Manage prepaid balance").addHelpCommand(!1).action(Dt);Dd.command("show").description("Show prepaid balance + recent ledger entries").action(async()=>{try{let t=await new Ke(()=>G.getSessionToken()).getBalance();if(console.log(`
290
- Balance: ${Qa(t.balanceMicros,t.balanceCents)}
287
+ `)}async function n_(e,t){if(t.yes)return"confirmed";if(!process.stdin.isTTY)return"refused-non-tty";let n=(0,Ud.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 lc=z.command("cards").description("Manage enrolled payment cards").addHelpCommand(!1).action(Dt);lc.command("list").alias("ls").description("List enrolled payment cards").action(async()=>{try{let e=await Mt.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}_T(t)}catch(e){console.error("Error:",e.message),process.exit(1)}});lc.command("add").description("Add a new Visa card").action(async()=>{try{let e=await Mt.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)}});lc.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=md(e),r=await n_(`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 Mt.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)}});lc.command("default <card-id>").alias("set-default").description("Set the default payment card").action(async e=>{try{let t=md(e),n=await Mt.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 vT(e){return/timed out waiting for touch id\/device approval|attestation[_\s-]?required/i.test(e)}function Bd(e){let t=e instanceof Error?e.message:String(e);console.error("Error:",t),vT(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 wT(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 Fd(e){let t=Object.prototype.hasOwnProperty.call(process.env,"VISA_CLI_API_KEY"),n=process.env.VISA_CLI_API_KEY;delete process.env.VISA_CLI_API_KEY;try{return await e()}finally{t&&(process.env.VISA_CLI_API_KEY=n)}}var Vd=z.command("keys").description("Create and manage Visa Keys for apps and agents").addHelpCommand(!1).action(Dt);Vd.command("create [label]").description("Create a Visa Key for the authenticated approved user").option("--tools <ids>","Comma-separated allowed tool ids (default: all tools)").option("--daily-cap <usd>","Daily cap in USD, between 1 and 100").option("--total-cap <usd>","Cumulative cap in USD, between 1 and 10000").option("--no-total-cap","Create without a cumulative cap (higher risk; daily cap still applies)").option("--json","Output raw JSON").action(async(e,t)=>{try{let n=await sT(t.dailyCap,t.json),r=await oT(t.totalCap,t.json),s=await Fd(async()=>{let o=ge(),i={label:nT(e),allowed_tools:rT(t.tools),daily_cap_cents:n,total_cap_cents:r};return await X1(o)?await Sr(o,async()=>{let a=await z1(o);return o.createAppApiKey({...i,attestation:a})},ic(o)):await o.createAppApiKey(i)});if(t.json){console.log(JSON.stringify(s,null,2));return}process.stdout.write(Sm(s,{authUrl:de()}))}catch(n){Bd(n)}});Vd.command("list").description("List Visa Keys for the authenticated user").option("--json","Output raw JSON").action(async e=>{try{let t=await Fd(async()=>await ge().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: ${iT(r.allowed_tools)}`),console.log(` Daily cap: ${Jo(r.daily_cap_cents)}/day`),console.log(` Total cap: ${eT(r.total_cap_cents)}`),console.log(` Last used: ${r.last_used_at||"never"}`)}catch(t){Bd(t)}});Vd.command("revoke <id>").alias("delete").description("Revoke (or delete) a Visa Key by id").action(async e=>{try{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Error("Visa Key id must be a positive integer. Run `visa-cli keys list` first.");let n=await Fd(async()=>await ge().revokeAppApiKey(t));console.log(`Revoked Visa Key ${n.revoked}.`)}catch(t){Bd(t)}});async function ST(){if(await G.clearAll(),console.log(" Keychain credentials cleared."),fe())try{await Gi(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}}async function r_(e={}){try{if(console.log(`Resetting Visa CLI...
288
+ `),e.localOnly)console.log(" Local-only reset: skipping server logout and biometric recovery.");else{let t=ge();await Dd(t);try{await t.logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}}await ST(),console.log(`
289
+ 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)}}z.command("reset",{hidden:!0}).description("Deprecated alias for `config reset`").option("--local-only","Only clear local credentials and the local biometric key; skip server-side biometric recovery").action(r_);var qd=z.command("balance").description("Manage prepaid balance").addHelpCommand(!1).action(Dt);qd.command("show").description("Show prepaid balance + recent ledger entries").action(async()=>{try{let t=await new Ke(()=>G.getSessionToken()).getBalance();if(console.log(`
290
+ Balance: ${nc(t.balanceMicros,t.balanceCents)}
291
291
  `),t.ledger.length===0){console.log(` (no ledger entries \u2014 top up to begin: visa-cli balance topup --amount 5)
292
- `);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=H1(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)}});Dd.command("topup").description("Top up prepaid balance from your default card (same path as MCP buy_credits; Touch ID required)").requiredOption("-a, --amount <usd>","Amount in USD (e.g. 5 or 1.50)").action(async e=>{try{let t=Zi(e.amount);if(!t.ok)throw new Error(t.error);let n=t.cents,r=n/100,s=new Ke(()=>G.getSessionToken());if(!fe())throw new Error(Qi);let o=tc.randomUUID(),i=await vr(s,async()=>{let a;if(fe()){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 In(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})},rc(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}`),Of();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 zb=Dd.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(Dt);zb.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(`
292
+ `);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=nc(u.deltaMicros,u.deltaCents,!0),p=tT(r[d]),h=(u.reason??"").slice(0,l),_=u.toolName??"";console.log(` ${f.padEnd(i)} ${m.padStart(a)} ${p.padStart(c)} ${h.padEnd(l)} ${_}`)}),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)}});qd.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=ta(e.amount);if(!t.ok)throw new Error(t.error);let n=t.cents,r=n/100,s=new Ke(()=>G.getSessionToken());if(!fe())throw new Error(na);let o=sc.randomUUID(),i=await Sr(s,async()=>{let a;if(fe()){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 $n(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})},ic(s));if(i.success)console.log(`Top-up complete: +$${(n/100).toFixed(2)} \u2192 balance now ${nc(i.balanceMicros,i.balanceCents??0)}`),i.transactionId&&console.log(`Transaction: ${i.transactionId}`),Hf();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 s_=qd.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(Dt);s_.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(`
293
293
  Auto-topup: disabled
294
- `);return}let n=Wo(t.targetCents),r=Wo(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)}});zb.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 lT=z.command("session",{hidden:!0}).description("Inspect session budgets");lT.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(`
294
+ `);return}let n=Jo(t.targetCents),r=Jo(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 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 xT=z.command("session",{hidden:!0}).description("Inspect session budgets");xT.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(`
295
295
  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(`
296
296
  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(`
297
- (no PSP references yet \u2014 no holds placed)`);console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});async function Xb(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 ge().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}}z.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action(Xb);z.command("update").description("Update Visa CLI to the latest stable version").action(async()=>{let e=ud(void 0,void 0,void 0,{withDiagnostics:!0}),t=e.diagnostics?dd(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 Rd(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=Mc(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 jt=z.command("config").description("Manage CLI configuration and local integrations").addHelpCommand(!1).action(Dt);function Zb(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 uT(e){let t=new Map;for(let n of Zb(e))try{ce.existsSync(n)&&t.set(n,ce.readFileSync(n,"utf-8"))}catch{}return t}function dT(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 fT(e){let t=[];for(let n of Zb(e))try{if(!ce.existsSync(n))continue;let r=ce.readFileSync(n,"utf-8");Ys(r)!==r.trimEnd()&&t.push(n)}catch{}return t}jt.command("feedback",{hidden:!0}).description("Deprecated alias for `feedback`").argument("[message]","Your feedback message").action(Xb);jt.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=ge(),n=await po({api:t,includeDev:!!e.dev});if(e.json){console.log(Gp(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(Kp(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});jt.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=ge(),s=(await po({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 mT(){return Object.entries(nr).map(([e,t])=>` ${e.padEnd(22)} (${t.type}) ${t.description}`).join(`
297
+ (no PSP references yet \u2014 no holds placed)`);console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});async function o_(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 ge().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}}z.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action(o_);z.command("update").description("Update Visa CLI to the latest stable version").action(async()=>{let e=hd(void 0,void 0,void 0,{withDiagnostics:!0}),t=e.diagnostics?yd(e.diagnostics,e.display):null;try{t&&console.warn(`Warning: ${t}`),console.log(`Updating Visa CLI with ${e.packageManager}: ${e.display}`);let{stdout:n,stderr:r}=await Md(e.command,e.args,{timeout:5*6e4,maxBuffer:10*1024*1024});n.trim()&&process.stdout.write(n),r.trim()&&process.stderr.write(r);let s=Dc(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 jt=z.command("config").description("Manage CLI configuration and local integrations").addHelpCommand(!1).action(Dt);function i_(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 CT(e){let t=new Map;for(let n of i_(e))try{ce.existsSync(n)&&t.set(n,ce.readFileSync(n,"utf-8"))}catch{}return t}function ET(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 AT(e){let t=[];for(let n of i_(e))try{if(!ce.existsSync(n))continue;let r=ce.readFileSync(n,"utf-8");zs(r)!==r.trimEnd()&&t.push(n)}catch{}return t}jt.command("feedback",{hidden:!0}).description("Deprecated alias for `feedback`").argument("[message]","Your feedback message").action(o_);jt.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=ge(),n=await ho({api:t,includeDev:!!e.dev});if(e.json){console.log(tg(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(eg(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});jt.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=ge(),s=(await ho({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 kT(){return Object.entries(sr).map(([e,t])=>` ${e.padEnd(22)} (${t.type}) ${t.description}`).join(`
298
298
  `)}jt.command("set <key> <value>").description("Persist a CLI setting to ~/.visa-mcp/settings.json").addHelpText("after",`
299
299
  Settable keys:
300
- ${mT()}`).action((e,t)=>{try{let n=Ti(e,t);console.log(`Saved ${n.key}=${JSON.stringify(n.value)} \u2192 ${n.path}`),n.requiresRestart&&console.log("Restart Claude Code (or your MCP-enabled client) for the change to take effect.")}catch(n){n instanceof at||n instanceof Gt||n instanceof wn?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});jt.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=Ri(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)}});jt.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(Jb);var jd=jt.command("biometric").description("Manage Touch ID / biometric attestation enforcement").addHelpCommand(!1).action(Dt);jd.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 ge().getStatus(),r=n.attestationRequired!==!1,s=!!n.hasAttestationKey,o=fe();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)}});jd.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=ge(),n=await Ki(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)}});jd.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=ge(),n=await t.getStatus();if(n.attestationRequired===!1){console.log("Touch ID is already disabled.");return}n.hasAttestationKey&&!fe()&&(console.error("Touch ID is unavailable on this device but the server has a registered key."),console.error("Disable Touch ID from a device that can sign, or contact support."),process.exit(1));let r=await vr(t,async()=>{let s;if(n.hasAttestationKey&&fe())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 In(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})},rc(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)}});z.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=ge();(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)),fe()||(console.error("Touch ID is unavailable on this device but the server has a registered key."),console.error("Run this from a device that can sign with your registered key."),process.exit(1));let{pending:r}=await t.getPendingWebAuthenticators();if(!r||r.length===0){console.log("No passkeys are awaiting authorization."),console.log("Register a passkey at https://app.visacli.sh/account first, then re-run this.");return}console.log(`${r.length} passkey${r.length===1?"":"s"} awaiting authorization.`);let s=0;for(let o of r){let i=o.deviceLabel?` (${o.deviceLabel})`:"",a=await vr(t,async()=>{let{nonce:c}=await t.getAttestationChallenge(),l=0,u=o.credentialId,d=Buffer.from(JSON.stringify({nonce:c,amount:l,merchant:u,context:"web-authenticator-enrollment"})).toString("base64"),f=await In(d,`authorize web passkey${i}`);return t.authorizeWebAuthenticator({credentialId:o.credentialId,attestation:{signature:f,nonce:c,amount:l,merchant:u}})},rc(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 Br=jt.command("shell-hud").description("Manage the shell prompt HUD (opt-in \u2014 prefer: visa-cli config hud enable)").addHelpCommand(!1).action(Dt);function Qb(){let e=mi();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 pT(){e_(jc(void 0,{homeDir:re.homedir(),installVisaStatusLine:zs,installShellHud:mi}))}function t_(){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"),pT()}function ac(){let e=Ht();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}Br.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Qb);Br.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(t_);Br.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(ac);Br.command("disable").description("Disable the persistent shell HUD").action(ac);Br.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${pi()}
301
- `)});Br.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
302
- `);let s=zr();if(r("Shell detected",!!s,s??"none (zsh, bash, or PowerShell required)"),s){let d=Ws(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=bn(),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=Gs(),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 ge().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?`
300
+ ${kT()}`).action((e,t)=>{try{let n=Ii(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 Gt||n instanceof xn?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});jt.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=Pi(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)}});jt.command("reset").description("Log out and clear all credentials").option("--local-only","Only clear local credentials and the local biometric key; skip server-side biometric recovery").action(r_);var Kd=jt.command("biometric").description("Manage Touch ID / biometric attestation enforcement").addHelpCommand(!1).action(Dt);Kd.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 ge().getStatus(),r=n.attestationRequired!==!1,s=!!n.hasAttestationKey,o=fe();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)}});Kd.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=ge(),n=await Yi(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)}});Kd.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=ge(),n=await t.getStatus();if(n.attestationRequired===!1){console.log("Touch ID is already disabled.");return}n.hasAttestationKey&&!fe()&&(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 Sr(t,async()=>{let s;if(n.hasAttestationKey&&fe())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 $n(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})},ic(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)}});z.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=ge();(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)),fe()||(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 Sr(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 $n(d,`authorize web passkey${i}`);return t.authorizeWebAuthenticator({credentialId:o.credentialId,attestation:{signature:f,nonce:c,amount:l,merchant:u}})},ic(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 Fr=jt.command("shell-hud").description("Manage the shell prompt HUD (opt-in \u2014 prefer: visa-cli config hud enable)").addHelpCommand(!1).action(Dt);function a_(){let e=gi();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function c_(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 TT(){c_(Fc(void 0,{homeDir:re.homedir(),installVisaStatusLine:Zs,installShellHud:gi}))}function l_(){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"),TT()}function uc(){let e=Bt();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}Fr.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(a_);Fr.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(l_);Fr.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(uc);Fr.command("disable").description("Disable the persistent shell HUD").action(uc);Fr.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${hi()}
301
+ `)});Fr.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
302
+ `);let s=Zr();if(r("Shell detected",!!s,s??"none (zsh, bash, or PowerShell required)"),s){let d=Js(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=_n(),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=Ys(),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 ge().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?`
303
303
  All checks passed.`:`
304
- Some checks failed \u2014 see above.`),n||process.exit(1)});async function n_(e){if(!(!e.force&&$f()))try{await Ec();let t=ge(),[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"&&aT(s.reason)&&(i.apiKeyStatus="rollout_locked"),o.status==="fulfilled"){let u=o.value,f=(Array.isArray(u)?u:Array.isArray(u.transactions)?u.transactions:[]).find(m=>m&&typeof m.tool_name=="string"&&m.tool_name.length>0);f&&f.created_at&&(i.lastService={toolName:f.tool_name,createdAt:f.created_at})}let c={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:St()},l=Ic(i,c);Pc(l,i)}catch(t){let n=t instanceof Error?t.message:"unknown refresh failure";Nf(n)}finally{zn()}}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(n_);var Hr=z.command("shell-hud",{hidden:!0}).description("Deprecated alias for `config shell-hud`");Hr.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Qb);Hr.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(t_);Hr.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(ac);Hr.command("disable").description("Disable the persistent shell HUD").action(ac);Hr.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${pi()}
305
- `)});Hr.command("doctor").description("Show the new shell HUD doctor command").action(()=>{console.log("Run: visa-cli config shell-hud doctor")});Hr.command("refresh").description("Refresh the shell HUD cache (no-op if cache is fresh unless --force)").option("--force","Bypass the cache freshness gate and always refresh").action(n_);async function r_(e){try{await Ec();let t=await Yf(),n=pi(),r=n,s=n.split(`
306
- `)[0],o=Mf();if(!t&&s.includes("loading")){process.stdout.write(`VISA | HUD not initialized \u2014 run: visa-cli config hud enable
307
- `),Ed();return}if(e.json){let a=await em(r,t,o);process.stdout.write(`${JSON.stringify(a,null,2)}
308
- `),Ed();return}let i=await Xf(r,t,o);process.stdout.write(`${i}
309
- `),Ed()}catch(t){let n=t instanceof Error?t.message:"unknown error";console.error(`Failed to render Visa HUD: ${n}`),process.exit(1)}}jt.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_);z.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 Ns=jt.command("hud").description("Manage the Visa spend HUD \u2014 one command for all surfaces").addHelpCommand(!1);Ns.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(`
304
+ Some checks failed \u2014 see above.`),n||process.exit(1)});async function u_(e){if(!(!e.force&&Df()))try{await Rc();let t=ge(),[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"&&wT(s.reason)&&(i.apiKeyStatus="rollout_locked"),o.status==="fulfilled"){let u=o.value,f=(Array.isArray(u)?u:Array.isArray(u.transactions)?u.transactions:[]).find(m=>m&&typeof m.tool_name=="string"&&m.tool_name.length>0);f&&f.created_at&&(i.lastService={toolName:f.tool_name,createdAt:f.created_at})}let c={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:St()},l=Nc(i,c);Oc(l,i)}catch(t){let n=t instanceof Error?t.message:"unknown refresh failure";jf(n)}finally{Zn()}}Fr.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(u_);var Vr=z.command("shell-hud",{hidden:!0}).description("Deprecated alias for `config shell-hud`");Vr.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(a_);Vr.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(l_);Vr.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(uc);Vr.command("disable").description("Disable the persistent shell HUD").action(uc);Vr.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${hi()}
305
+ `)});Vr.command("doctor").description("Show the new shell HUD doctor command").action(()=>{console.log("Run: visa-cli config shell-hud doctor")});Vr.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(u_);async function d_(e){try{await Rc();let t=await em(),n=hi(),r=n,s=n.split(`
306
+ `)[0],o=Bf();if(!t&&s.includes("loading")){process.stdout.write(`VISA | HUD not initialized \u2014 run: visa-cli config hud enable
307
+ `),$d();return}if(e.json){let a=await im(r,t,o);process.stdout.write(`${JSON.stringify(a,null,2)}
308
+ `),$d();return}let i=await rm(r,t,o);process.stdout.write(`${i}
309
+ `),$d()}catch(t){let n=t instanceof Error?t.message:"unknown error";console.error(`Failed to render Visa HUD: ${n}`),process.exit(1)}}jt.command("statusline").description("Output the Visa HUD for agent statusline integrations").option("--json","Output structured JSON for clients that render their own HUD").action(d_);z.command("statusline",{hidden:!0}).description("Deprecated alias for `config statusline`").option("--json","Output structured JSON for clients that render their own HUD").action(d_);var Ms=jt.command("hud").description("Manage the Visa spend HUD \u2014 one command for all surfaces").addHelpCommand(!1);Ms.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(`
310
310
  ${e}Visa HUD Status${s}
311
- `);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=vn(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=Zn(re.homedir()),d=u.length>0||fi(),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(`
312
- ${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()});Ns.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_(jc(e,{homeDir:re.homedir(),installVisaStatusLine:zs,installShellHud:mi}))});Ns.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=Ht();o.removed||(console.error(o.message),process.exit(1)),console.log(o.message);return}let n=Si(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=Lc(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&&!vi()&&Zn(re.homedir()).length>0){let l=Ht();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=Ht();console.log(o.message),o.removed&&(s=!0),!o.removed&&n!=="all"&&(r=!0)}n==="all"&&!s&&(r=!0),r&&process.exit(1)});Ns.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
313
- `);let r=[],s=ud(void 0,void 0,void 0,{withDiagnostics:!0}),o=s.diagnostics?dd(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=vn(p)}}catch{}n("Claude Code statusLine",a,a?"registered":"not registered \u2014 run: visa-cli config hud enable");let c=fT(re.homedir()),l=zr();if(n("Shell detected",!!l,l??"none (zsh, bash, or PowerShell required)"),l){let m=Ws(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 Yb(`Remove shell prompt HUD block from ${m}?`,{})==="confirmed"),p){let h=uT(re.homedir());Ht();let v=dT(h);if(v.length>0){let I=v.map(b=>b.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=bn(),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:"",b=I.length>0&&gi(I);if(console.log(` ${v?"\u2713":"\u26A0"} Cache freshness: ${h}s old${v?"":" (stale \u2014 will refresh on next prompt)"}`),b&&console.log(' \u26A0 Cache content: legacy placeholder (HUD will display "VISA | HUD not ready" until next successful refresh)'),e.fix&&(!v||b)){let _=!1;try{ce.rmSync(u,{force:!0}),_=!0}catch{}try{let w=Gs();ce.existsSync(w)&&(ce.rmSync(w,{force:!0}),_=!0)}catch{}if(_){let w=b?"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 R=rt.join(re.homedir(),".visa-cli","shell-hud.lock");ce.existsSync(R)&&(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 ge().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(`
311
+ `);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=wn(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=er(re.homedir()),d=u.length>0||pi(),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(`
312
+ ${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()});Ms.command("enable").description("Enable the Visa HUD \u2014 claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{c_(Fc(e,{homeDir:re.homedir(),installVisaStatusLine:Zs,installShellHud:gi}))});Ms.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=Ci(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=jc(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&&!Si()&&er(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)});Ms.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
313
+ `);let r=[],s=hd(void 0,void 0,void 0,{withDiagnostics:!0}),o=s.diagnostics?yd(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=wn(p)}}catch{}n("Claude Code statusLine",a,a?"registered":"not registered \u2014 run: visa-cli config hud enable");let c=AT(re.homedir()),l=Zr();if(n("Shell detected",!!l,l??"none (zsh, bash, or PowerShell required)"),l){let m=Js(l),p=ce.existsSync(m);if(n("RC file exists",p,m.replace(re.homedir(),"~")),p){let _=ce.readFileSync(m,"utf-8").includes("visa-cli shell hud v2");console.log(` ${_?"\u2713":"\u2013"} Shell HUD block: ${_?"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 n_(`Remove shell prompt HUD block from ${m}?`,{})==="confirmed"),p){let h=CT(re.homedir());Bt();let _=ET(h);if(_.length>0){let I=_.map(b=>b.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=_n(),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),_=h<=30,I=typeof m.line=="string"?m.line:"",b=I.length>0&&yi(I);if(console.log(` ${_?"\u2713":"\u26A0"} Cache freshness: ${h}s old${_?"":" (stale \u2014 will refresh on next prompt)"}`),b&&console.log(' \u26A0 Cache content: legacy placeholder (HUD will display "VISA | HUD not ready" until next successful refresh)'),e.fix&&(!_||b)){let v=!1;try{ce.rmSync(u,{force:!0}),v=!0}catch{}try{let w=Ys();ce.existsSync(w)&&(ce.rmSync(w,{force:!0}),v=!0)}catch{}if(v){let w=b?"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 R=rt.join(re.homedir(),".visa-cli","shell-hud.lock");ce.existsSync(R)&&(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 ge().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(`
314
314
  --fix: no locally fixable issues found.`):console.log(`
315
315
  --fix: applied ${r.length} change${r.length===1?"":"s"} \u2014 ${r.join("; ")}.`)),console.log(t?`
316
316
  All checks passed.`:`
317
- Some checks failed \u2014 see above.`),t||process.exit(1)});Ns.command("enable-claude").description("Alias for: hud enable claude").action(()=>{let e=Ft(),t=zs(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});Ns.command("disable-claude").description("Alias for: hud disable claude").action(()=>{let e=Ft(),t=Lc(e);console.log(t.message),t.removed||process.exit(1)});var Os=z.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||gT.has(e)){Os.help({error:!1});return}await yT(e,t,n)});Os.command("list").description("List live platform merchants").option("--json","Print machine-readable JSON").action(async e=>{try{let n=await new Ke(()=>G.getSessionToken()).listPublicMerchants();if(n.length===0){e.json?console.log(JSON.stringify({merchants:[]},null,2)):console.log(`
317
+ Some checks failed \u2014 see above.`),t||process.exit(1)});Ms.command("enable-claude").description("Alias for: hud enable claude").action(()=>{let e=Ft(),t=Zs(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});Ms.command("disable-claude").description("Alias for: hud disable claude").action(()=>{let e=Ft(),t=jc(e);console.log(t.message),t.removed||process.exit(1)});var Ls=z.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||RT.has(e)){Ls.help({error:!1});return}await PT(e,t,n)});Ls.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(`
318
318
  No live platform merchants on this auth server.
319
319
  `);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(`
320
320
  ${s}Run 'visa-cli merchants tools' to browse tools by merchant.${o}
321
- `)}catch(t){console.error("Error:",t.message),process.exit(1)}});var gT=new Set(["list","tools","describe","run","refresh"]);async function Bd(e){try{let n=await ge().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(`
321
+ `)}catch(t){console.error("Error:",t.message),process.exit(1)}});var RT=new Set(["list","tools","describe","run","refresh"]);async function Gd(e){try{let n=await ge().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(`
322
322
  ${n.id}
323
323
  `),console.log(n.description),console.log(`
324
- Price`),console.log(` ${ao(n.priceCents,n.priceDisplay)}`),console.log(`
324
+ Price`),console.log(` ${co(n.priceCents,n.priceDisplay)}`),console.log(`
325
325
  Provider`),console.log(` ${n.provider} \xB7 ${n.category}`),console.log(`
326
- 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=cm(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(`
327
- Examples`);let s=sb(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 Hd(e){try{let t=ge();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?tl(l):Hm(i,l);return}let{limit:n,offset:r}=X1(e),{tools:s,hidden:o}=await z1(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){nl(o);return}console.log("No merchant tools found. Try: visa-cli tools --category image");return}e.verbose?tl(s):Bm(s),o&&o.count>0&&nl(o)}catch(t){console.error("Error:",t.message),process.exit(1)}}Os.command("tools").description("List available merchant tools").option("--category <category>","Filter by category (image, video, audio, 3d, llm)").option("--query <query>","Search by intent or keyword").option("--merchant <slug>","Scope to a single merchant (e.g. fal, openrouter)").option("--verbose","Show grouped cards with descriptions").option("--json","Print machine-readable JSON").option("--limit <n>",`Maximum tools to return (default ${Nd}, max ${Od})`,ec).option("--offset <n>","Pagination offset (default 0)",ec).action(Hd);Os.command("describe <tool>").description("Show tool schema, price, and examples").action(async e=>{await Bd(e)});function hT(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 cc(e,t,n){return hT(e)?Mt.shortcut(e,t,n):Mt.executeTool({tool_id:e,params:t},n,"execute_tool")}Os.command("run <tool>").description("Run any merchant tool by id").option("--json <json>","Tool parameters as a JSON object").option("--prompt <prompt>","Prompt parameter for prompt-shaped tools").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=qb(t.json,"--json");t.prompt&&(n.prompt=t.prompt),Hs({yes:t.yes}),console.log(`Running ${e}`);let r=await cc(e,n,`visa-cli merchants run ${e}`);sc(r),oc(r)}catch(n){console.error("Error:",n.message),process.exit(1)}});Os.command("refresh").description("Hint: restart the MCP server (Claude/Cursor) to refresh discovered tools \u2014 discovery is in-process").action(()=>{console.log(`
326
+ 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=pm(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(`
327
+ Examples`);let s=fb(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=ge();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?ol(l):Gm(i,l);return}let{limit:n,offset:r}=dT(e),{tools:s,hidden:o}=await uT(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){il(o);return}console.log("No merchant tools found. Try: visa-cli tools --category image");return}e.verbose?ol(s):Km(s),o&&o.count>0&&il(o)}catch(t){console.error("Error:",t.message),process.exit(1)}}Ls.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 ${jd}, max ${Hd})`,rc).option("--offset <n>","Pagination offset (default 0)",rc).action(Wd);Ls.command("describe <tool>").description("Show tool schema, price, and examples").action(async e=>{await Gd(e)});function IT(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 dc(e,t,n){return IT(e)?Mt.shortcut(e,t,n):Mt.executeTool({tool_id:e,params:t},n,"execute_tool")}Ls.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=Zb(t.json,"--json");t.prompt&&(n.prompt=t.prompt),Vs({yes:t.yes}),console.log(`Running ${e}`);let r=await dc(e,n,`visa-cli merchants run ${e}`);ac(r),cc(r)}catch(n){console.error("Error:",n.message),process.exit(1)}});Ls.command("refresh").description("Hint: restart the MCP server (Claude/Cursor) to refresh discovered tools \u2014 discovery is in-process").action(()=>{console.log(`
328
328
  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.
329
- `)});async function yT(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 Hd({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=ge(),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(`
329
+ `)});async function PT(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=ge(),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(`
330
330
  ${r}
331
331
  `),a.description&&console.log(a.description),console.log(`
332
- Price`),console.log(` ${ao(a.price_cents)}`),console.log(`
332
+ Price`),console.log(` ${co(a.price_cents)}`),console.log(`
333
333
  Examples`),console.log(` visa-cli merchants run ${r} --json '${JSON.stringify(a.request?.body_example??{})}'`),console.log(` visa-cli merchants ${e} run ${r}
334
- `);return}await Bd(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=qb(i,"--json"),c=s("--prompt");c&&(a.prompt=c),Hs({yes:o}),console.log(`Running ${r}`);let l=await cc(r,a,`visa-cli merchants ${e} run ${r}`);sc(l),oc(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)}z.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 ${Nd}, max ${Od})`,ec).option("--offset <n>","Pagination offset (default 0)",ec).action(Hd);z.command("describe <tool>").description("Show schema, price, and examples for a tool (alias for: merchants describe)").action(async e=>{await Bd(e)});var Yo=z.command("generate").description("Generate media with merchant tools").addHelpCommand(!1).action(Dt);async function Jo(e){Hs({yes:e.yes}),e.json||e.format&&ii(e.format)||(console.log(`
334
+ `);return}await Gd(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=Zb(i,"--json"),c=s("--prompt");c&&(a.prompt=c),Vs({yes:o}),console.log(`Running ${r}`);let l=await dc(r,a,`visa-cli merchants ${e} run ${r}`);ac(l),cc(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)}z.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 ${jd}, max ${Hd})`,rc).option("--offset <n>","Pagination offset (default 0)",rc).action(Wd);z.command("describe <tool>").description("Show schema, price, and examples for a tool (alias for: merchants describe)").action(async e=>{await Gd(e)});var zo=z.command("generate").description("Generate media with merchant tools").addHelpCommand(!1).action(Dt);async function Xo(e){Vs({yes:e.yes}),e.json||e.format&&ci(e.format)||(console.log(`
335
335
  ${e.kind}
336
336
  `),console.log(`Using: ${e.toolId}`),console.log(`Prompt: ${e.prompt}
337
- `));let n=await cc(e.toolId,e.params,`visa-cli generate ${e.kind.toLowerCase()}: ${e.prompt}`);sc(n,{json:e.json,format:e.format,command:e.command??`generate.${e.kind.toLowerCase().replace(/\s+/g,"_")}`}),oc(n)}var Wn=(e,t)=>n=>(t.includes(n)||z.error(`error: option '${e}' accepts ${t.map(r=>`'${r}'`).join(", ")} (got '${n}')`,{exitCode:2}),n);Yo.command("image [prompt]").description("Generate an image from a prompt (accepts stdin via `-` or --stdin)").option("--quality <quality>","Image quality: standard or high",Wn("--quality",["standard","high"]),"standard").option("--fast","Use the fast image tool").option("--tool <tool>","Exact tool id override").option("--image-ref <url>","Optional source image URL for edit/style-transfer tools").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Wn("--format",hn)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await Yn(e,t),r=t.tool??(t.fast||t.quality!=="high"?"fal-flux-pro":"fal-flux-pro-ultra"),s={prompt:n};t.imageRef&&(s.image_url=t.imageRef),await Jo({kind:"Image generation",toolId:r,params:s,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.image"})}catch(n){$s("generate.image",n,{json:t.json,format:t.format})}});Yo.command("video [prompt]").description("Generate a video from a prompt (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--aspect-ratio <ratio>","Aspect ratio, when supported by the selected tool").option("--duration <seconds>","Duration in seconds, when supported by the selected tool").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Wn("--format",hn)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await Yn(e,t),r={prompt:n};t.aspectRatio&&(r.aspect_ratio=t.aspectRatio),t.duration&&(r.duration=Number(t.duration)),await Jo({kind:"Video generation",toolId:t.tool??"fal-minimax-video",params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.video"})}catch(n){$s("generate.video",n,{json:t.json,format:t.format})}});Yo.command("music [prompt]").description("Generate music from a prompt (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--instrumental","Generate instrumental music").option("--duration <seconds>","Duration in seconds, when supported by the selected tool").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Wn("--format",hn)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await Yn(e,t),r={prompt:n};t.instrumental&&(r.instrumental=!0),t.duration&&(r.duration=Number(t.duration)),await Jo({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){$s("generate.music",n,{json:t.json,format:t.format})}});Yo.command("speech [text]").description("Generate speech from text using a voice sample (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--audio-url <url>","Voice sample audio URL for voice cloning").option("--ref-audio-url <url>","Alias for --audio-url").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Wn("--format",hn)).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||z.error("error: option '--audio-url <url>' is required for visa-cli generate speech",{exitCode:2});let r=await Yn(e,t),s={text:r,audio_url:n};await Jo({kind:"Speech generation",toolId:t.tool??"fal-metavoice",params:s,prompt:r,json:t.json,format:t.format,yes:t.yes,command:"generate.speech"})}catch(n){$s("generate.speech",n,{json:t.json,format:t.format})}});Yo.command("3d [image-url]").alias("model").description("Generate a 3D model from an image URL (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Wn("--format",hn)).option("--stdin","Read image URL from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await Yn(e,t),r={image_url:n};await Jo({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){$s("generate.3d",n,{json:t.json,format:t.format})}});var Td="reasoning",s_={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"},Ub=Object.keys(s_);z.command("run-llm [prompt]").description(`Run a chat-completion against an OpenRouter-backed LLM (default tier: ${Td})`).option("--tier <tier>",`LLM tier: ${Ub.join(" | ")} (resolves to a catalog tool id)`,Wn("--tier",Ub),Td).option("--model <id>","Exact catalog tool id (e.g. or-claude-haiku, or-gemini-3-flash). Overrides --tier.").option("--system <prompt>","System prompt (inline string or @./path to a file)").option("--max-tokens <n>","Maximum completion tokens").option("--temperature <n>","Sampling temperature 0-2").option("--image-url <url>","Image URL for vision-capable models (or-gemini-nano-banana-pro, etc.)").option("--from-stdin <field>","Read upstream JSON envelope from stdin and bind .field to a flag value (e.g. --image-url --from-stdin .urls[0])").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Wn("--format",hn)).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 xc(),u=JSON.parse(l),d=lf(u,t.fromStdin);n=n??d}let r=await Yn(e,{stdin:t.stdin&&!t.fromStdin});Hs({yes:t.yes});let s={prompt:r},o=await df(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??Td,a=t.model??s_[i],c=await cc(a,s,"visa-cli run-llm");if(!t.json&&c?.success!==!1){console.log(`
337
+ `));let n=await dc(e.toolId,e.params,`visa-cli generate ${e.kind.toLowerCase()}: ${e.prompt}`);ac(n,{json:e.json,format:e.format,command:e.command??`generate.${e.kind.toLowerCase().replace(/\s+/g,"_")}`}),cc(n)}var Jn=(e,t)=>n=>(t.includes(n)||z.error(`error: option '${e}' accepts ${t.map(r=>`'${r}'`).join(", ")} (got '${n}')`,{exitCode:2}),n);zo.command("image [prompt]").description("Generate an image from a prompt (accepts stdin via `-` or --stdin)").option("--quality <quality>","Image quality: standard or high",Jn("--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)",Jn("--format",yn)).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 zn(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 Xo({kind:"Image generation",toolId:r,params:s,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.image"})}catch(n){Os("generate.image",n,{json:t.json,format:t.format})}});zo.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)",Jn("--format",yn)).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 zn(e,t),r={prompt:n};t.aspectRatio&&(r.aspect_ratio=t.aspectRatio),t.duration&&(r.duration=Number(t.duration)),await Xo({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){Os("generate.video",n,{json:t.json,format:t.format})}});zo.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)",Jn("--format",yn)).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 zn(e,t),r={prompt:n};t.instrumental&&(r.instrumental=!0),t.duration&&(r.duration=Number(t.duration)),await Xo({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){Os("generate.music",n,{json:t.json,format:t.format})}});zo.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)",Jn("--format",yn)).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||z.error("error: option '--audio-url <url>' is required for visa-cli generate speech",{exitCode:2});let r=await zn(e,t),s={text:r,audio_url:n};await Xo({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){Os("generate.speech",n,{json:t.json,format:t.format})}});zo.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)",Jn("--format",yn)).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 zn(e,t),r={image_url:n};await Xo({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){Os("generate.3d",n,{json:t.json,format:t.format})}});var Od="reasoning",f_={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"},Kb=Object.keys(f_);z.command("run-llm [prompt]").description(`Run a chat-completion against an OpenRouter-backed LLM (default tier: ${Od})`).option("--tier <tier>",`LLM tier: ${Kb.join(" | ")} (resolves to a catalog tool id)`,Jn("--tier",Kb),Od).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)",Jn("--format",yn)).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 Ac(),u=JSON.parse(l),d=gf(u,t.fromStdin);n=n??d}let r=await zn(e,{stdin:t.stdin&&!t.fromStdin});Vs({yes:t.yes});let s={prompt:r},o=await yf(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??Od,a=t.model??f_[i],c=await dc(a,s,"visa-cli run-llm");if(!t.json&&c?.success!==!1){console.log(`
338
338
  LLM completion
339
339
  `),console.log(`Using: ${a}`);let l=r.length>200?`${r.slice(0,200)}\u2026`:r;console.log(`Prompt: ${l}
340
- `)}sc(c,{json:t.json,format:t.format,command:"run-llm"}),oc(c)}catch(n){$s("run-llm",n,{json:t.json,format:t.format})}});z.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 yt)Cd(i,n).removed&&o.push(i.displayName);o.length>0?console.log(`Removed visa-cli from: ${o.join(", ")}.`):console.log("visa-cli was not installed in any client.");return}e||(console.error("Usage: visa-cli uninstall <client>"),console.error(" visa-cli uninstall --all"),console.error(`
341
- Supported clients: ${yt.map(o=>o.id).join(", ")}`),process.exit(1));let r=vd(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${yt.map(o=>o.id).join(", ")}`),process.exit(1));let s=Cd(r,n);s.removed?console.log(`Removed visa-cli from ${s.configPath}`):console.log(`visa-cli was not installed for ${r.displayName}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});z.hook("postAction",()=>{if(Go){Go=!1;return}Za&&nb(Za.lastSignals)});wb(z);xb(z);sT(["setup","install","status","cards","keys","balance","tools","describe","merchants","generate","run-llm","config","feedback","update","uninstall"]);Wb(z);z.parseAsync().catch(async e=>{console.error("Error:",e instanceof Error?e.message:String(e));let{reportFatal:t}=await Promise.resolve().then(()=>(Xa(),za));await t(e)});process.on("uncaughtException",async e=>{console.error("Uncaught exception:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(Xa(),za));await t(e)});process.on("unhandledRejection",async e=>{console.error("Unhandled rejection:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(Xa(),za));await t(e)});0&&(module.exports={printGroupHelpAndExit});
340
+ `)}ac(c,{json:t.json,format:t.format,command:"run-llm"}),cc(c)}catch(n){Os("run-llm",n,{json:t.json,format:t.format})}});z.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 yt)Id(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(`
341
+ Supported clients: ${yt.map(o=>o.id).join(", ")}`),process.exit(1));let r=Ad(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${yt.map(o=>o.id).join(", ")}`),process.exit(1));let s=Id(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)}});z.hook("postAction",()=>{if(Yo){Yo=!1;return}tc&&ub(tc.lastSignals)});Rb(z);Pb(z);bT(["setup","install","status","cards","keys","balance","tools","describe","merchants","generate","run-llm","config","feedback","update","uninstall"]);t_(z);z.parseAsync().catch(async e=>{console.error("Error:",e instanceof Error?e.message:String(e));let{reportFatal:t}=await Promise.resolve().then(()=>(ec(),Qa));await t(e)});process.on("uncaughtException",async e=>{console.error("Uncaught exception:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(ec(),Qa));await t(e)});process.on("unhandledRejection",async e=>{console.error("Unhandled rejection:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(ec(),Qa));await t(e)});0&&(module.exports={printGroupHelpAndExit});
342
342
  /*! Bundled license information:
343
343
 
344
344
  @noble/ed25519/index.js: