@visa/cli 3.3.1-rc.3 → 3.4.0-rc.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,16 +1,16 @@
1
- "use strict";var Yy=Object.create;var No=Object.defineProperty;var zy=Object.getOwnPropertyDescriptor;var Jy=Object.getOwnPropertyNames;var Xy=Object.getPrototypeOf,Zy=Object.prototype.hasOwnProperty;var Nt=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Zu=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},Lo=(e,t)=>{for(var n in t)No(e,n,{get:t[n],enumerable:!0})},Qu=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Jy(t))!Zy.call(e,s)&&s!==n&&No(e,s,{get:()=>t[s],enumerable:!(r=zy(t,s))||r.enumerable});return e};var R=(e,t,n)=>(n=e!=null?Yy(Xy(e)):{},Qu(t||!e||!e.__esModule?No(n,"default",{value:e,enumerable:!0}):n,e)),Qy=e=>Qu(No({},"__esModule",{value:!0}),e);var Is=Zu((rA,f_)=>{f_.exports={name:"@visa/cli",version:"3.3.1-rc.3",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{"sync:server-json":"node scripts/sync-server-json.mjs","check:server-json":"node scripts/sync-server-json.mjs --check",prebuild:"node scripts/sync-server-json.mjs && pnpm --filter @visa/money build && pnpm --filter @visa/crypto build && pnpm --filter subway-sdk build && pnpm --filter @visa-cli/tools build",build:"tsc --noEmit && node esbuild.config.js",prepack:"node scripts/sync-server-json.mjs --check",dev:"tsc --watch",pretest:"pnpm build",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0",commander:"^12.1.0",zod:"^3.23.0"},devDependencies:{"@visa/crypto":"workspace:*","subway-sdk":"workspace:*","@visa/money":"workspace:*","@visa/observability":"workspace:*","@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.31.0","@types/jest":"^30.0.0","@types/node":"^25.9.3","@typescript-eslint/eslint-plugin":"^8.62.0","@typescript-eslint/parser":"^8.62.0","@types/express":"^5.0.0",esbuild:"^0.28.1",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.4","ts-jest":"^29.4.11",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","native/visa-keychain-win.cpp","native/build-win.bat","native/bin/win32-x64/visa-keychain-win.exe","server.json","README.md","LICENSE"]}});function Nb(){je.existsSync(Cc)||je.mkdirSync(Cc,{recursive:!0,mode:448})}function Lb(){if(!Tc){if(Nb(),je.existsSync(Gs)&&je.statSync(Gs).size>Mb){let t=Gs+".1";je.existsSync(t)&&je.unlinkSync(t),je.renameSync(Gs,t)}Tc=je.createWriteStream(Gs,{flags:"a"})}return Tc}function Ub(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function ui(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
- `;Ub(e)&&process.stderr.write(s),Lb().write(s)}var je,kc,If,Cc,Gs,Mb,Tc,g,_t=Nt(()=>{"use strict";je=R(require("fs")),kc=R(require("path")),If=R(require("os")),Cc=kc.join(If.homedir(),".visa-mcp"),Gs=kc.join(Cc,"mcp-server.log"),Mb=5*1024*1024,Tc=null;g={debug:(...e)=>ui("DEBUG",...e),info:(...e)=>ui("INFO",...e),warn:(...e)=>ui("WARN",...e),error:(...e)=>ui("ERROR",...e)}});var di,Mf,Nf,Ec,Ws,Lf=Nt(()=>{"use strict";di=R(require("fs")),Mf=R(require("path")),Nf=R(require("os")),Ec=Mf.join(Nf.homedir(),".visa-mcp"),Ws=class{static ensureConfigDir(){di.existsSync(Ec)||di.mkdirSync(Ec,{recursive:!0,mode:448})}static getConfigDir(){return Ec}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 Uf(e){let t=Df.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function Ys(){return jf.join(Ws.getConfigDir(),Bb)}function Bf(e){if((0,Ic.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function Hb(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 Bf(s)}function Vb(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,Ic.isIP)(t);return n===4?Bf(t):n===6?t==="::1"||Hb(t):!1}function Ac(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:"&&Vb(n.hostname)))throw new Error(`${t} ${Fb}`)}function Xn(){let e=Ys();if(!yn.existsSync(e))return{};try{let t=yn.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?(g.warn("settings:corrupt",{path:Uf(e),reason:"not_object"}),{}):n}catch(t){return g.warn("settings:corrupt",{path:Uf(e),error:t?.message||String(t)}),{}}}function Rc(e){Ws.ensureConfigDir();let t=Ys(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
3
- `;yn.writeFileSync(n,r,{mode:384}),yn.renameSync(n,t)}function Pc(e){let t=Xn()[e];return typeof t=="string"?t:void 0}function pi(e){let t=Xn()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function Oc(e){let t=Xn()[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 mi(e,t){if(Ff.some(o=>e.startsWith(o)))throw new Ft(e);if(e in fi)throw new hn(e);let n=Zn[e];if(!n)throw new rt(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=Xn();return s[e]=r,Rc(s),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:Ys()}}function gi(e){if(Ff.some(o=>e.startsWith(o)))throw new Ft(e);let t=Zn[e];if(e in fi){let o=Xn(),i=e in o;return i&&(delete o[e],Rc(o)),{key:e,removed:i,requiresRestart:!1,path:Ys()}}if(!t)throw new rt(e);let r=Xn(),s=e in r;return s&&(delete r[e],Rc(r)),{key:e,removed:s,requiresRestart:s&&!!t.requiresRestart,path:Ys()}}function Hf(){let e=Xn();return Object.entries(fi).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}function Gb(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function Wb(){try{let e=Is();return Gb(e.version)}catch{return!1}}function Yb(e){return e.envVar!==void 0&&e.envVar!==""?(Ac(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(Ac(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?Kb:qb}function Ue(){return Yb({envVar:process.env.VISA_AUTH_URL,settingValue:Pc("auth.serverUrl"),isPrerelease:Wb()})}function Vf(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":pi("ui.suppressBrowser")??!1}function qf(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":pi("ui.suppressFeed")??!1}function Kf(){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=Oc("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):$c}var yn,Ic,Df,jf,Bb,Fb,Zn,$c,fi,rt,Ft,hn,Ff,qb,Kb,Ht=Nt(()=>{"use strict";yn=R(require("fs")),Ic=require("node:net"),Df=R(require("os")),jf=R(require("path"));Lf();_t();Bb="settings.json",Fb="must use https unless it points at localhost/loopback for local development";Zn={"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");Ac(e)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."},"ui.suppressFeed":{type:"boolean",description:"When true, generated images/music are not auto-submitted to the public Made-with-Visa feed."},"tools.meta":{type:"boolean",description:"Show category meta-tools (generate_image, generate_video, generate_music, run_llm, ...). Restart required.",requiresRestart:!0},"tools.discover":{type:"boolean",description:"Show the dynamic-catalog tools (discover_tools, execute_tool). Restart required.",requiresRestart:!0},"merchants.discover":{type:"string",description:'Platform-merchant JIT tool discovery: "all" = every live merchant, "off" = none, comma-separated slugs = exactly those. Equivalent to VISA_MERCHANT_DISCOVER / VISA_MERCHANT_SLUGS env. Restart required.',requiresRestart:!0,validate:e=>{if(typeof e!="string")throw new Error("merchants.discover must be a string");let t=e.trim().toLowerCase();if(t===""||t==="all"||t==="off"||t==="*")return;let n=/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/,r=e.split(",").map(s=>s.trim()).filter(Boolean);for(let s of r)if(!n.test(s))throw new Error(`merchants.discover: "${s}" is not a valid merchant slug`)}},"credit.sessionCapCents":{type:"number",description:"Default cap (in cents) for start_session and pay-as-you-go one-shot approvals. Server clamps to [10, 10000] = $0.10\u2013$100. Default 500 ($5).",validate:e=>{if(typeof e!="number"||!Number.isFinite(e))throw new Error("credit.sessionCapCents must be a number");if(!Number.isInteger(e))throw new Error("credit.sessionCapCents must be a whole number of cents (no fractional cents)");if(e<10||e>1e4)throw new Error("credit.sessionCapCents must be between 10 ($0.10) and 10000 ($100)")}}},$c=500,fi={"tools.specific":"Legacy direct _card MCP tools are retired. Use category meta-tools or discover_tools/execute_tool.","credit.sessionMode":"The session-mode toggle is retired. Use start_session, close_session, and get_session_status."};rt=class extends Error{constructor(t){let n=Object.keys(Zn).sort().join(", ");super(`Unknown setting "${t}". Settable keys: ${n}. For server-controlled values (biometric.*, spending.*) use the dedicated tools (biometric_on/off, update_spending_controls).`),this.name="UnknownSettingKeyError"}},Ft=class extends Error{constructor(t){let n="";t.startsWith("biometric.")?n="biometric_on / biometric_off":t.startsWith("spending.")?n="update_spending_controls":t.startsWith("cards.")?n="add_card / remove_card / set_default_card":t.startsWith("account.")&&(n="login / reset"),super(`"${t}" is a server-controlled value and cannot be set via config set. `+(n?`Use ${n} instead.`:"No client-side override is supported.")),this.name="ServerOnlySettingError"}},hn=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+fi[t]),this.name="RetiredSettingKeyError"}},Ff=["biometric.","spending.","account.","cards.","biometric"];qb="https://auth.visacli.sh",Kb="https://auth-visa-code-preview.up.railway.app"});var ts=Zu(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.micros=Wv;be.fromCents=Yv;be.fromUsdc=zv;be.fromUsd=Jv;be.toCents=Xv;be.toCentsForAcquirer=Zv;be.toUsdc=Qv;be.toWire=ew;be.fromWire=tw;be.toDisplay=nw;be.toUsdRounded2dp=rw;be.add=sw;be.sub=ow;be.clampNonNegative=iw;be.isNonNegative=aw;be.max=cw;be.min=lw;var Wt=10000n,Pp=1000000n;function Wv(e){return e}function Yv(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*Wt}function zv(e){return e}function Jv(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function Xv(e){if(e>=0n)return Number(e/Wt);let t=e/Wt,n=e%Wt;return Number(n===0n?t:t-1n)}function Zv(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/Wt)}function Qv(e){return e}function ew(e){return e.toString()}function tw(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 nw(e,t={}){let n=t.decimals??2,r=t.symbol??"$",s=e<0n,o=s?-e:e,i=o/Pp,a=o%Pp,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 rw(e){let t=e<0n,n=t?-e:e,r=n/Wt,o=n%Wt*2n,i;o<Wt?i=r:o>Wt?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function sw(e,t){return e+t}function ow(e,t){return e-t}function iw(e){return e<0n?0n:e}function aw(e){return e>=0n}function cw(e,t){return e>t?e:t}function lw(e,t){return e<t?e:t}});function fl(e,t){switch(e){case"name_not_found":return new Cm(t);case"delivery_failed":return new km(t);case"timeout":return new lo(t);case"not_registered":return new Em;case"register_failed":return new Bi(t);case"invalid_message":return new Am(t);case"rate_limited":return new Rm(t);default:return new Ct(e,t)}}var Tm,Ct,Cm,km,lo,Em,Pe,Am,Bi,Rm,pl=Nt(()=>{"use strict";Tm=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Ct=class extends Error{code;constructor(e,t){super(t),this.name="SubwayError",this.code=e}},Cm=class extends Ct{constructor(e){super("name_not_found",`Agent not registered: ${e}`),this.name="NameNotFoundError"}},km=class extends Ct{constructor(e){super("delivery_failed",e),this.name="DeliveryFailedError"}},lo=class extends Ct{constructor(e="RPC call timed out"){super("timeout",e),this.name="TimeoutError"}},Em=class extends Ct{constructor(){super("not_registered","Client has not registered with the bridge"),this.name="NotRegisteredError"}},Pe=class extends Ct{constructor(e){super("connection_failed",e),this.name="ConnectionError"}},Am=class extends Ct{constructor(e){super("invalid_message",e),this.name="InvalidMessageError"}},Bi=class extends Ct{constructor(e){super("register_failed",e),this.name="RegisterFailedError"}},Rm=class extends Ct{constructor(e="Rate limited"){super("rate_limited",e),this.name="RateLimitedError"}}});function xr(e){return e.includes(".")?e:`${e}.relay`}function ml(){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 Hw(){if(typeof WebSocket<"u")return WebSocket;try{let e=Tm("ws");return e.default??e}catch{return}}function Vw(e,t,n){return Math.min(Math.max(e,t),n)}function mS(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function mg(e,t,n=""){let r=mS(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 Um(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 gS(e,t){mg(e,void 0,"digestInto() output");let n=t.outputLen;if(e.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function uo(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function _l(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Et(e,t){return e<<32-t|e>>>t}function gg(e,t={}){let n=(s,o)=>e(o).update(s).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=s=>e(s),Object.assign(n,t),Object.freeze(n)}function hS(e,t,n){return e&t^~e&n}function yS(e,t,n){return e&t^e&n^t&n}function _S(e,t=!1){return t?{h:Number(e&Fi),l:Number(e>>Dm&Fi)}:{h:Number(e>>Dm&Fi)|0,l:Number(e&Fi)|0}}function bS(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}=_S(e[o],t);[r[o],s[o]]=[i,a]}return[r,s]}function Xt(e,t,n,r){let s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}function NS(e){return aS(e)}function LS(e,t){return uS(t,e)}function DS(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function FS(e){let t=US(OS(e.payload)),n=`${e.messageId}
1
+ "use strict";var r_=Object.create;var Do=Object.defineProperty;var s_=Object.getOwnPropertyDescriptor;var o_=Object.getOwnPropertyNames;var i_=Object.getPrototypeOf,a_=Object.prototype.hasOwnProperty;var Lt=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Ya=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},jo=(e,t)=>{for(var n in t)Do(e,n,{get:t[n],enumerable:!0})},od=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of o_(t))!a_.call(e,s)&&s!==n&&Do(e,s,{get:()=>t[s],enumerable:!(r=s_(t,s))||r.enumerable});return e};var R=(e,t,n)=>(n=e!=null?r_(i_(e)):{},od(t||!e||!e.__esModule?Do(n,"default",{value:e,enumerable:!0}):n,e)),c_=e=>od(Do({},"__esModule",{value:!0}),e);var Os=Ya((vE,w_)=>{w_.exports={name:"@visa/cli",version:"3.4.0-rc.5",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js",visa:"./bin/visa-cli.js"},scripts:{"sync:server-json":"node scripts/sync-server-json.mjs","check:server-json":"node scripts/sync-server-json.mjs --check",prebuild:"node scripts/sync-server-json.mjs && pnpm --filter @visa/money build && pnpm --filter @visa/crypto build && pnpm --filter subway-sdk build && pnpm --filter @visa-cli/tools build",build:"tsc --noEmit && node esbuild.config.js",prepack:"node scripts/sync-server-json.mjs --check",dev:"tsc --watch",pretest:"pnpm build",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0",commander:"^12.1.0",zod:"^3.23.0"},devDependencies:{"@visa/crypto":"workspace:*","subway-sdk":"workspace:*","@visa/money":"workspace:*","@visa/observability":"workspace:*","@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.31.0","@types/jest":"^30.0.0","@types/node":"^25.9.3","@typescript-eslint/eslint-plugin":"^8.62.0","@typescript-eslint/parser":"^8.62.1","@types/express":"^5.0.0",esbuild:"^0.28.1",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.9.3","ts-jest":"^29.4.11",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","native/visa-keychain-win.cpp","native/build-win.bat","native/bin/win32-x64/visa-keychain-win.exe","server.json","README.md","LICENSE"]}});function qb(){je.existsSync($c)||je.mkdirSync($c,{recursive:!0,mode:448})}function Kb(){if(!Ic){if(qb(),je.existsSync(zs)&&je.statSync(zs).size>Vb){let t=zs+".1";je.existsSync(t)&&je.unlinkSync(t),je.renameSync(zs,t)}Ic=je.createWriteStream(zs,{flags:"a"})}return Ic}function Gb(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function mi(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
+ `;Gb(e)&&process.stderr.write(s),Kb().write(s)}var je,Pc,Uf,$c,zs,Vb,Ic,g,bt=Lt(()=>{"use strict";je=R(require("fs")),Pc=R(require("path")),Uf=R(require("os")),$c=Pc.join(Uf.homedir(),".visa-mcp"),zs=Pc.join($c,"mcp-server.log"),Vb=5*1024*1024,Ic=null;g={debug:(...e)=>mi("DEBUG",...e),info:(...e)=>mi("INFO",...e),warn:(...e)=>mi("WARN",...e),error:(...e)=>mi("ERROR",...e)}});var pi,Ff,Hf,Oc,Js,Vf=Lt(()=>{"use strict";pi=R(require("fs")),Ff=R(require("path")),Hf=R(require("os")),Oc=Ff.join(Hf.homedir(),".visa-mcp"),Js=class{static ensureConfigDir(){pi.existsSync(Oc)||pi.mkdirSync(Oc,{recursive:!0,mode:448})}static getConfigDir(){return Oc}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 qf(e){let t=Kf.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function Xs(){return Gf.join(Js.getConfigDir(),zb)}function Wf(e){if((0,Lc.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function Xb(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 Wf(s)}function Zb(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,Lc.isIP)(t);return n===4?Wf(t):n===6?t==="::1"||Xb(t):!1}function Mc(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:"&&Zb(n.hostname)))throw new Error(`${t} ${Jb}`)}function Qn(){let e=Xs();if(!bn.existsSync(e))return{};try{let t=bn.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?(g.warn("settings:corrupt",{path:qf(e),reason:"not_object"}),{}):n}catch(t){return g.warn("settings:corrupt",{path:qf(e),error:t?.message||String(t)}),{}}}function Nc(e){Js.ensureConfigDir();let t=Xs(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
3
+ `;bn.writeFileSync(n,r,{mode:384}),bn.renameSync(n,t)}function Dc(e){let t=Qn()[e];return typeof t=="string"?t:void 0}function hi(e){let t=Qn()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function jc(e){let t=Qn()[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 yi(e,t){if(Yf.some(o=>e.startsWith(o)))throw new Ht(e);if(e in gi)throw new _n(e);let n=er[e];if(!n)throw new rt(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=Qn();return s[e]=r,Nc(s),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:Xs()}}function _i(e){if(Yf.some(o=>e.startsWith(o)))throw new Ht(e);let t=er[e];if(e in gi){let o=Qn(),i=e in o;return i&&(delete o[e],Nc(o)),{key:e,removed:i,requiresRestart:!1,path:Xs()}}if(!t)throw new rt(e);let r=Qn(),s=e in r;return s&&(delete r[e],Nc(r)),{key:e,removed:s,requiresRestart:s&&!!t.requiresRestart,path:Xs()}}function zf(){let e=Qn();return Object.entries(gi).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}function t0(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function n0(){try{let e=Os();return t0(e.version)}catch{return!1}}function r0(e){return e.envVar!==void 0&&e.envVar!==""?(Mc(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(Mc(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?e0:Qb}function Ue(){return r0({envVar:process.env.VISA_AUTH_URL,settingValue:Dc("auth.serverUrl"),isPrerelease:n0()})}function Jf(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":hi("ui.suppressBrowser")??!1}function Xf(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":hi("ui.suppressFeed")??!1}function Zf(){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=jc("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):Uc}var bn,Lc,Kf,Gf,zb,Jb,er,Uc,gi,rt,Ht,_n,Yf,Qb,e0,Vt=Lt(()=>{"use strict";bn=R(require("fs")),Lc=require("node:net"),Kf=R(require("os")),Gf=R(require("path"));Vf();bt();zb="settings.json",Jb="must use https unless it points at localhost/loopback for local development";er={"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");Mc(e)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."},"ui.suppressFeed":{type:"boolean",description:"When true, generated images/music are not auto-submitted to the public Made-with-Visa feed."},"tools.meta":{type:"boolean",description:"Show category meta-tools (generate_image, generate_video, generate_music, run_llm, ...). Restart required.",requiresRestart:!0},"tools.discover":{type:"boolean",description:"Show the dynamic-catalog tools (discover_tools, execute_tool). Restart required.",requiresRestart:!0},"merchants.discover":{type:"string",description:'Platform-merchant JIT tool discovery: "all" = every live merchant, "off" = none, comma-separated slugs = exactly those. Equivalent to VISA_MERCHANT_DISCOVER / VISA_MERCHANT_SLUGS env. Restart required.',requiresRestart:!0,validate:e=>{if(typeof e!="string")throw new Error("merchants.discover must be a string");let t=e.trim().toLowerCase();if(t===""||t==="all"||t==="off"||t==="*")return;let n=/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/,r=e.split(",").map(s=>s.trim()).filter(Boolean);for(let s of r)if(!n.test(s))throw new Error(`merchants.discover: "${s}" is not a valid merchant slug`)}},"credit.sessionCapCents":{type:"number",description:"Default cap (in cents) for start_session and pay-as-you-go one-shot approvals. Server clamps to [10, 10000] = $0.10\u2013$100. Default 500 ($5).",validate:e=>{if(typeof e!="number"||!Number.isFinite(e))throw new Error("credit.sessionCapCents must be a number");if(!Number.isInteger(e))throw new Error("credit.sessionCapCents must be a whole number of cents (no fractional cents)");if(e<10||e>1e4)throw new Error("credit.sessionCapCents must be between 10 ($0.10) and 10000 ($100)")}}},Uc=500,gi={"tools.specific":"Legacy direct _card MCP tools are retired. Use category meta-tools or discover_tools/execute_tool.","credit.sessionMode":"The session-mode toggle is retired. Use start_session, close_session, and get_session_status."};rt=class extends Error{constructor(t){let n=Object.keys(er).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"}},Ht=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"}},_n=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+gi[t]),this.name="RetiredSettingKeyError"}},Yf=["biometric.","spending.","account.","cards.","biometric"];Qb="https://auth.visacli.sh",e0="https://auth-visa-code-preview.up.railway.app"});var Fm=Ya(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.formatCents=Bm;ot.formatUsd=rw;ot.formatMicros=Ci;ot.formatMicrosWire=sw;ot.formatTxAmount=ow;ot.formatDate=iw;ot.formatRelativeTime=aw;ot.formatTime=cw;ot.formatAge=lw;var jm=1e6,nw=100;function Bm(e,t={}){let n=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return n;let s=(e/nw).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${s}`:s}function rw(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 Ci(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/jm).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??6});return t.showPlusSign&&r>0?`+${o}`:o}function sw(e,t,n={}){return e&&/^-?\d+$/.test(e)?Ci(e,n):t!=null&&Number.isFinite(t)?Bm(t,n):n.fallback??"\u2014"}function ow(e,t={}){let n=Number(e.amount_micros);if(Number.isFinite(n)&&e.amount_micros!=null&&e.amount_micros!=="")return Ci(n,t);let r=Number(String(e.amount).replace(/^\$/,""));return Number.isFinite(r)?Ci(r*jm,t):t.fallback??"\u2014"}function iw(e,t={}){let n=t.fallback??"\u2014";if(!e)return n;let r=new Date(e);return Number.isNaN(r.getTime())?n:r.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:t.timeZone??"UTC"})}function aw(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),m=Math.floor(l/365);return i<45?"just now":a<1?s?"a minute ago":"in a minute":a<60?rs(r,s,a,"minute"):c<24?rs(r,s,c,"hour"):l===1?s?"yesterday":"tomorrow":l<7?rs(r,s,l,"day"):u<4?rs(r,s,u,"week"):d<12?rs(r,s,d,"month"):rs(r,s,m,"year")}function rs(e,t,n,r){let s=n!==1?"s":"";return t?`${n} ${r}${s} ago`:`in ${n} ${r}${s}`}function cw(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 lw(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 ss=Ya(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.formatAge=K.formatTime=K.formatRelativeTime=K.formatDate=K.formatTxAmount=K.formatMicrosWire=K.formatMicros=K.formatUsd=K.formatCents=void 0;K.micros=uw;K.fromCents=dw;K.fromUsdc=fw;K.fromUsd=mw;K.toCents=pw;K.toCentsForAcquirer=gw;K.toUsdc=hw;K.toWire=yw;K.fromWire=_w;K.toDisplay=bw;K.toUsdRounded2dp=vw;K.add=ww;K.sub=Sw;K.clampNonNegative=xw;K.isNonNegative=Tw;K.max=kw;K.min=Cw;var Yt=10000n,Hm=1000000n;function uw(e){return e}function dw(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*Yt}function fw(e){return e}function mw(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function pw(e){if(e>=0n)return Number(e/Yt);let t=e/Yt,n=e%Yt;return Number(n===0n?t:t-1n)}function gw(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/Yt)}function hw(e){return e}function yw(e){return e.toString()}function _w(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 bw(e,t={}){let n=t.decimals??2,r=t.symbol??"$",s=e<0n,o=s?-e:e,i=o/Hm,a=o%Hm,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 vw(e){let t=e<0n,n=t?-e:e,r=n/Yt,o=n%Yt*2n,i;o<Yt?i=r:o>Yt?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function ww(e,t){return e+t}function Sw(e,t){return e-t}function xw(e){return e<0n?0n:e}function Tw(e){return e>=0n}function kw(e,t){return e>t?e:t}function Cw(e,t){return e<t?e:t}var zt=Fm();Object.defineProperty(K,"formatCents",{enumerable:!0,get:function(){return zt.formatCents}});Object.defineProperty(K,"formatUsd",{enumerable:!0,get:function(){return zt.formatUsd}});Object.defineProperty(K,"formatMicros",{enumerable:!0,get:function(){return zt.formatMicros}});Object.defineProperty(K,"formatMicrosWire",{enumerable:!0,get:function(){return zt.formatMicrosWire}});Object.defineProperty(K,"formatTxAmount",{enumerable:!0,get:function(){return zt.formatTxAmount}});Object.defineProperty(K,"formatDate",{enumerable:!0,get:function(){return zt.formatDate}});Object.defineProperty(K,"formatRelativeTime",{enumerable:!0,get:function(){return zt.formatRelativeTime}});Object.defineProperty(K,"formatTime",{enumerable:!0,get:function(){return zt.formatTime}});Object.defineProperty(K,"formatAge",{enumerable:!0,get:function(){return zt.formatAge}})});function bl(e,t){switch(e){case"name_not_found":return new Mp(t);case"delivery_failed":return new Np(t);case"timeout":return new mo(t);case"not_registered":return new Lp;case"register_failed":return new qi(t);case"invalid_message":return new Up(t);case"rate_limited":return new Dp(t);default:return new Ct(e,t)}}var Op,Ct,Mp,Np,mo,Lp,Pe,Up,qi,Dp,vl=Lt(()=>{"use strict";Op=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Ct=class extends Error{code;constructor(e,t){super(t),this.name="SubwayError",this.code=e}},Mp=class extends Ct{constructor(e){super("name_not_found",`Agent not registered: ${e}`),this.name="NameNotFoundError"}},Np=class extends Ct{constructor(e){super("delivery_failed",e),this.name="DeliveryFailedError"}},mo=class extends Ct{constructor(e="RPC call timed out"){super("timeout",e),this.name="TimeoutError"}},Lp=class extends Ct{constructor(){super("not_registered","Client has not registered with the bridge"),this.name="NotRegisteredError"}},Pe=class extends Ct{constructor(e){super("connection_failed",e),this.name="ConnectionError"}},Up=class extends Ct{constructor(e){super("invalid_message",e),this.name="InvalidMessageError"}},qi=class extends Ct{constructor(e){super("register_failed",e),this.name="RegisterFailedError"}},Dp=class extends Ct{constructor(e="Rate limited"){super("rate_limited",e),this.name="RateLimitedError"}}});function kr(e){return e.includes(".")?e:`${e}.relay`}function wl(){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 oS(){if(typeof WebSocket<"u")return WebSocket;try{let e=Op("ws");return e.default??e}catch{return}}function iS(e,t,n){return Math.min(Math.max(e,t),n)}function $S(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function xg(e,t,n=""){let r=$S(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 Gp(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 PS(e,t){xg(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 po(...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 Et(e,t){return e<<32-t|e>>>t}function Tg(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 OS(e,t,n){return e&t^~e&n}function MS(e,t,n){return e&t^e&n^t&n}function NS(e,t=!1){return t?{h:Number(e&Ki),l:Number(e>>Wp&Ki)}:{h:Number(e>>Wp&Ki)|0,l:Number(e&Ki)|0}}function LS(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}=NS(e[o],t);[r[o],s[o]]=[i,a]}return[r,s]}function Qt(e,t,n,r){let s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}function ZS(e){return TS(e)}function QS(e,t){return AS(t,e)}function tx(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function sx(e){let t=ex(JS(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 jS.encode(n)}function HS(e,t,n,r,s,o,i){return FS({messageId:e,senderPeerId:t,senderName:n,timestampMs:r,messageType:s,payload:o,nonce:i})}function VS(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 fx(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Pg(e,t,n=""){let r=fx(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 zm(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function px(e,t){Pg(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 Al(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Sl(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function mx(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 yx(e,t=!1){return t?{h:Number(e&qi),l:Number(e>>Jm&qi)}:{h:Number(e>>Jm&qi)|0,l:Number(e&qi)|0}}function _x(e,t=!1){let n=e.length,r=new Uint32Array(n),s=new Uint32Array(n);for(let o=0;o<n;o++){let{h:i,l:a}=yx(e[o],t);[r[o],s[o]]=[i,a]}return[r,s]}function Qt(e,t,n,r){let s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}function Ix(){return cx.randomSecretKey()}function Mg(e){return ix(e)}function $x(){let e=Ix();return{secretKey:e,publicKey:Mg(e)}}function Px(e){if((0,Un.existsSync)(e)){let n=(0,Un.readFileSync)(e),r=new Uint8Array(n.buffer.slice(n.byteOffset,n.byteOffset+32));return{secretKey:r,publicKey:Mg(r)}}let t=$x();return(0,Un.mkdirSync)((0,tg.dirname)(e),{recursive:!0}),(0,Un.writeFileSync)(e,new Uint8Array(t.secretKey)),t}function Ox(e){let{secretKey:t,publicKey:n}=Px(e);return{privateKey:t,publicKey:n}}async function Mx(e,t,n,r,s,o,i,a){let c=HS(t,n,r,s,o,i,a);return{signature:await LS(e,c),signatureInput:BS.subwayAgentMsgV1}}function eg(e){return DS(e)}var Un,tg,qw,Kw,Gw,Ww,Yw,ng,zi,Wi,Im,$m,gl,hl,zw,ta,Jw,Ce,Xw,Zw,Qw,en,na,Rl,rg,Il,Jt,Pm,$l,sg,eS,as,tS,Ji,br,se,Om,$,og,ig,ag,cg,yl,xl,fo,kr,Tr,lg,ug,kt,nS,Mm,rS,Tl,Pl,sS,dg,oS,iS,aS,cS,lS,uS,Ol,fg,Xi,dS,pg,Cl,fS,Nm,Lm,pS,hg,yg,$n,Oe,Fi,Dm,jm,Bm,rs,ss,Hi,Vi,vS,wS,SS,xS,TS,CS,kS,Pn,ES,AS,_g,RS,IS,On,Mn,$S,PS,OS,MS,Fm,US,bg,jS,BS,vg,Zi,Yi,Hm,Vm,bl,vl,qS,cs,KS,ke,GS,WS,YS,Dn,ra,Ml,wg,Sg,Zt,qm,xg,Tg,zS,Nl,JS,Qi,wr,ie,Km,P,XS,ZS,Cg,kg,wl,kl,po,ls,Cr,QS,Eg,At,ex,Gm,tx,nx,rx,sx,Ag,ox,Rg,ix,Ig,ax,cx,ea,lx,$g,El,ux,Wm,Ym,dx,gx,hx,Me,qi,Jm,Xm,Zm,os,is,Ki,Gi,bx,vx,wx,Sx,xx,Tx,Og,Cx,kx,Nn,Ln,Ex,Ax,Rx,Qm,Nx,Lx,Ng,Ll=Nt(()=>{"use strict";pl();pl();Un=require("fs"),tg=require("path");qw=1e3,Kw=10,Gw=3e4,Ww=3e4,Yw=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??qw,this.maxReconnectAttempts=e.maxReconnectAttempts??Kw,this.pingInterval=e.pingInterval??Gw}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=Hw();if(!n){t(new Pe('No WebSocket implementation available. Install the "ws" package for Node.js.'));return}this.setStatus("connecting");try{this.ws=new n(this.url)}catch(s){t(new Pe(`Failed to create WebSocket: ${s}`));return}let r=!1;this.ws.onopen=()=>{this.reconnectAttempt=0,this.setStatus("connected"),this.startPing(),r||(r=!0,e())},this.ws.onmessage=s=>{let o;try{o=JSON.parse(typeof s.data=="string"?s.data:s.data.toString())}catch{return}for(let i of this.messageHandlers)i(o)},this.ws.onclose=()=>{this.ws=null,this.stopPing(),!this.stopped&&this.autoReconnect?this.scheduleReconnect():this.setStatus("disconnected"),r||(r=!0,t(new Pe("WebSocket closed before connection established")))},this.ws.onerror=()=>{r||(r=!0,t(new Pe(`WebSocket connection failed: ${this.url}`)))}})}disconnect(){this.stopped=!0,this.clearReconnectTimer(),this.stopPing(),this.ws&&(this.ws.onclose=null,this.ws.onerror=null,this.ws.onmessage=null,this.ws.close(),this.ws=null),this.setStatus("disconnected")}send(e){if(!this.ws||this.ws.readyState!==1)throw new Pe("WebSocket is not connected");this.ws.send(JSON.stringify(e))}startPing(){this.stopPing(),this.pingInterval>0&&(this.pingTimer=setInterval(()=>{try{this.send({type:"ping"})}catch{}},this.pingInterval))}stopPing(){this.pingTimer!==null&&(clearInterval(this.pingTimer),this.pingTimer=null)}scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts){this.setStatus("disconnected");return}this.setStatus("reconnecting");let e=Vw(this.reconnectInterval*Math.pow(2,this.reconnectAttempt),this.reconnectInterval,Ww);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)}}},ng=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:zi,n:Wi,Gx:Im,Gy:$m,a:gl,d:hl,h:zw}=ng,ta=32,Jw=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},Ce=(e="")=>{let t=new Error(e);throw Jw(t,Ce),t},Xw=e=>typeof e=="bigint",Zw=e=>typeof e=="string",Qw=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,en=(e,t,n="")=>{let r=Qw(e),s=e?.length,o=t!==void 0;if(!r||o&&s!==t){let i=n&&`"${n}" `,a=o?` of length ${t}`:"",c=r?`length=${s}`:`type=${typeof e}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):new TypeError(l)}return e},na=e=>new Uint8Array(e),Rl=e=>Uint8Array.from(e),rg=(e,t)=>e.toString(16).padStart(t,"0"),Il=e=>Array.from(en(e)).map(t=>rg(t,2)).join(""),Jt={_0:48,_9:57,A:65,F:70,a:97,f:102},Pm=e=>{if(e>=Jt._0&&e<=Jt._9)return e-Jt._0;if(e>=Jt.A&&e<=Jt.F)return e-(Jt.A-10);if(e>=Jt.a&&e<=Jt.f)return e-(Jt.a-10)},$l=e=>{let t="hex invalid";if(!Zw(e))return Ce(t);let n=e.length,r=n/2;if(n%2)return Ce(t);let s=na(r);for(let o=0,i=0;o<r;o++,i+=2){let a=Pm(e.charCodeAt(i)),c=Pm(e.charCodeAt(i+1));if(a===void 0||c===void 0)return Ce(t);s[o]=a*16+c}return s},sg=()=>globalThis?.crypto,eS=()=>sg()?.subtle??Ce("crypto.subtle must be defined, consider polyfill"),as=(...e)=>{let t=0;for(let s of e)t+=en(s).length;let n=na(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},tS=(e=ta)=>sg().getRandomValues(na(e)),Ji=BigInt,br=(e,t,n,r="bad number: out of range")=>{if(!Xw(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},se=(e,t=zi)=>{let n=e%t;return n>=0n?n:t+n},Om=(1n<<255n)-1n,$=e=>{e<0n&&Ce("negative coordinate");let t=(e>>255n)*19n+(e&Om);return t=(t>>255n)*19n+(t&Om),t%zi},og=e=>se(e,Wi),ig=(e,t)=>{(e===0n||t<=0n)&&Ce("no inverse n="+e+" mod="+t);let n=se(e,t),r=t,s=0n,o=1n;for(;n!==0n;){let i=r/n,a=r%n,c=s-o*i;r=n,n=a,s=o,o=c}return r===1n?se(s,t):Ce("no inverse")},ag=e=>{let t=fg[e];return typeof t!="function"&&Ce("hashes."+e+" not set"),t},cg=e=>en(e,64,"digest"),yl=e=>e instanceof fo?e:Ce("Point expected"),xl=2n**256n,fo=class vr{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=xl;this.X=br(t,0n,o),this.Y=br(n,0n,o),this.Z=br(r,1n,o),this.T=br(s,0n,o),Object.freeze(this)}static CURVE(){return ng}static fromAffine(t){return new vr(t.x,t.y,1n,$(t.x*t.y))}static fromBytes(t,n=!1){let r=hl,s=Rl(en(t,ta)),o=t[31];s[31]=o&-129;let i=ug(s);br(i,0n,n?xl:zi);let c=$(i*i),l=se(c-1n),u=$(r*c+1n),{isValid:d,value:p}=rS(l,u);d||Ce("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!n&&p===0n&&m&&Ce("bad point: x==0, isLastByteOdd"),m!==f&&(p=se(-p)),new vr(p,i,1n,$(p*i))}static fromHex(t,n){return vr.fromBytes($l(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=gl,n=hl,r=this;if(r.is0())return Ce("bad point: ZERO");let{X:s,Y:o,Z:i,T:a}=r,c=$(s*s),l=$(o*o),u=$(i*i),d=$(u*u),p=$(c*t),f=$(u*(p+l)),m=se(d+$(n*$(c*l)));if(f!==m)return Ce("bad point: equation left != right (1)");let h=$(s*o),w=$(i*a);return h!==w?Ce("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=yl(t),c=$(n*a),l=$(o*s),u=$(r*a),d=$(i*s);return c===l&&u===d}is0(){return this.equals(Tr)}negate(){return new vr(se(-this.X),this.Y,this.Z,se(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=gl,o=$(t*t),i=$(n*n),a=$(2n*r*r),c=$(s*o),l=se(t+n),u=se($(l*l)-o-i),d=se(c+i),p=se(d-a),f=se(c-i),m=$(u*p),h=$(d*f),w=$(u*f),C=$(p*d);return new vr(m,h,C,w)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=yl(t),u=gl,d=hl,p=$(n*i),f=$(r*a),m=$($(o*d)*l),h=$(s*c),w=se($(se(n+r)*se(i+a))-p-f),C=se(h-m),b=se(h+m),v=se(f-$(u*p)),S=$(w*C),A=$(b*v),I=$(w*v),y=$(C*b);return new vr(S,A,y,I)}subtract(t){return this.add(yl(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(br(t,1n,Wi),!n&&this.is0()))return Tr;if(t===1n)return this;if(this.equals(kr))return pS(t).p;let r=Tr,s=kr;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=ig(r,zi);$(r*s)!==1n&&Ce("invalid inverse");let o=$(t*s),i=$(n*s);return{x:o,y:i}}toBytes(){let{x:t,y:n}=this.toAffine(),r=lg(n);return r[31]|=t&1n?128:0,r}toHex(){return Il(this.toBytes())}clearCofactor(){return this.multiply(Ji(zw),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Wi/2n,!1).double();return Wi%2n&&(t=t.add(this)),t.is0()}},kr=new fo(Im,$m,1n,se(Im*$m)),Tr=new fo(0n,1n,1n,0n);fo.BASE=kr;fo.ZERO=Tr;lg=e=>$l(rg(br(e,0n,xl),64)).reverse(),ug=e=>Ji("0x"+Il(Rl(en(e)).reverse())),kt=(e,t)=>{let n=e;for(;t-- >0n;)n=$(n*n);return n},nS=e=>{let t=$(e*e),n=$(t*e),r=$(kt(n,2n)*n),s=$(kt(r,1n)*e),o=$(kt(s,5n)*s),i=$(kt(o,10n)*o),a=$(kt(i,20n)*i),c=$(kt(a,40n)*a),l=$(kt(c,80n)*c),u=$(kt(l,80n)*c),d=$(kt(u,10n)*o);return{pow_p_5_8:$(kt(d,2n)*e),b2:n}},Mm=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,rS=(e,t)=>{let n=$(t*$(t*t)),r=$($(n*n)*t),s=nS($(e*r)).pow_p_5_8,o=$(e*$(n*s)),i=$(t*$(o*o)),a=o,c=$(o*Mm),l=i===e,u=i===se(-e),d=i===se(-e*Mm);return l&&(o=a),(u||d)&&(o=c),(se(o)&1n)===1n&&(o=se(-o)),{isValid:l||u,value:o}},Tl=e=>og(ug(e)),Pl=(...e)=>Promise.resolve(ag("sha512Async")(as(...e))).then(cg),sS=(...e)=>cg(ag("sha512")(as(...e))),dg=e=>{let t=Rl(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=Tl(n),o=kr.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},oS=e=>Pl(en(e,ta)).then(dg),iS=e=>dg(sS(en(e,ta))),aS=e=>iS(e).pointBytes,cS=e=>Pl(e.hashable).then(e.finish),lS=(e,t,n)=>{let{pointBytes:r,scalar:s}=e,o=Tl(t),i=kr.multiply(o).toBytes();return{hashable:as(i,r,n),finish:l=>{let u=og(o+Tl(l)*s);return en(as(i,lg(u)),64)}}},uS=async(e,t)=>{let n=en(e),r=await oS(t),s=await Pl(r.prefix,n);return cS(lS(r,s,n))},Ol=Object.freeze({bytesToHex:Il,hexToBytes:$l,concatBytes:as,mod:se,invert:ig,randomBytes:tS}),fg={sha512Async:async e=>{let t=eS(),n=as(e);return na(await t.digest("SHA-512",n.buffer))},sha512:void 0},Xi=8,dS=256,pg=Math.ceil(dS/Xi)+1,Cl=2**(Xi-1),fS=()=>{let e=[],t=kr,n=t;for(let r=0;r<pg;r++){n=t,e.push(n);for(let s=1;s<Cl;s++)n=n.add(t),e.push(n);t=n.double()}return e},Nm=void 0,Lm=(e,t)=>{let n=t.negate();return e?n:t},pS=e=>{let t=Nm||(Nm=fS()),n=Tr,r=kr,s=2**Xi,o=s,i=Ji(s-1),a=Ji(Xi);for(let c=0;c<pg;c++){let l=Number(e&i);e>>=a,l>Cl&&(l-=o,e+=1n);let u=c*Cl,d=u,p=u+Math.abs(l)-1,f=c%2!==0,m=l<0;l===0?r=r.add(Lm(f,t[d])):n=n.add(Lm(m,t[p]))}return e!==0n&&Ce("invalid wnaf"),{p:n,f:r}};hg=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});yg=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=_l(this.buffer)}update(e){Um(this),mg(e);let{view:t,buffer:n,blockLen:r}=this,s=e.length;for(let o=0;o<s;){let i=Math.min(r-this.pos,s-o);if(i===r){let a=_l(e);for(;r<=s-o;o+=r)this.process(a,o);continue}n.set(e.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Um(this),gS(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,uo(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let u=o;u<r;u++)t[u]=0;n.setBigUint64(r-8,BigInt(this.length*8),s),this.process(n,0);let i=_l(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<c;u++)i.setUint32(4*u,l[u],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:s,destroyed:o,pos:i}=this;return e.destroyed=o,e.finished=s,e.length=r,e.pos=i,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},$n=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Oe=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Fi=BigInt(2**32-1),Dm=BigInt(32);jm=(e,t,n)=>e>>>n,Bm=(e,t,n)=>e<<32-n|t>>>n,rs=(e,t,n)=>e>>>n|t<<32-n,ss=(e,t,n)=>e<<32-n|t>>>n,Hi=(e,t,n)=>e<<64-n|t>>>n-32,Vi=(e,t,n)=>e>>>n-32|t<<64-n;vS=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),wS=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,SS=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),xS=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,TS=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),CS=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,kS=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]),Pn=new Uint32Array(64),ES=class extends yg{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:r,E:s,F:o,G:i,H:a}=this;return[e,t,n,r,s,o,i,a]}set(e,t,n,r,s,o,i,a){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=s|0,this.F=o|0,this.G=i|0,this.H=a|0}process(e,t){for(let u=0;u<16;u++,t+=4)Pn[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let d=Pn[u-15],p=Pn[u-2],f=Et(d,7)^Et(d,18)^d>>>3,m=Et(p,17)^Et(p,19)^p>>>10;Pn[u]=m+Pn[u-7]+f+Pn[u-16]|0}let{A:n,B:r,C:s,D:o,E:i,F:a,G:c,H:l}=this;for(let u=0;u<64;u++){let d=Et(i,6)^Et(i,11)^Et(i,25),p=l+d+hS(i,a,c)+kS[u]+Pn[u]|0,m=(Et(n,2)^Et(n,13)^Et(n,22))+yS(n,r,s)|0;l=c,c=a,a=i,i=o+p|0,o=s,s=r,r=n,n=p+m|0}n=n+this.A|0,r=r+this.B|0,s=s+this.C|0,o=o+this.D|0,i=i+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,s,o,i,a,c,l)}roundClean(){uo(Pn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),uo(this.buffer)}},AS=class extends ES{A=$n[0]|0;B=$n[1]|0;C=$n[2]|0;D=$n[3]|0;E=$n[4]|0;F=$n[5]|0;G=$n[6]|0;H=$n[7]|0;constructor(){super(32)}},_g=bS(["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))),RS=_g[0],IS=_g[1],On=new Uint32Array(80),Mn=new Uint32Array(80),$S=class extends yg{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:s,Cl:o,Dh:i,Dl:a,Eh:c,El:l,Fh:u,Fl:d,Gh:p,Gl:f,Hh:m,Hl:h}=this;return[e,t,n,r,s,o,i,a,c,l,u,d,p,f,m,h]}set(e,t,n,r,s,o,i,a,c,l,u,d,p,f,m,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=s|0,this.Cl=o|0,this.Dh=i|0,this.Dl=a|0,this.Eh=c|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=p|0,this.Gl=f|0,this.Hh=m|0,this.Hl=h|0}process(e,t){for(let b=0;b<16;b++,t+=4)On[b]=e.getUint32(t),Mn[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let v=On[b-15]|0,S=Mn[b-15]|0,A=rs(v,S,1)^rs(v,S,8)^jm(v,S,7),I=ss(v,S,1)^ss(v,S,8)^Bm(v,S,7),y=On[b-2]|0,T=Mn[b-2]|0,Y=rs(y,T,19)^Hi(y,T,61)^jm(y,T,6),X=ss(y,T,19)^Vi(y,T,61)^Bm(y,T,6),H=SS(I,X,Mn[b-7],Mn[b-16]),_e=xS(H,A,Y,On[b-7],On[b-16]);On[b]=_e|0,Mn[b]=H|0}let{Ah:n,Al:r,Bh:s,Bl:o,Ch:i,Cl:a,Dh:c,Dl:l,Eh:u,El:d,Fh:p,Fl:f,Gh:m,Gl:h,Hh:w,Hl:C}=this;for(let b=0;b<80;b++){let v=rs(u,d,14)^rs(u,d,18)^Hi(u,d,41),S=ss(u,d,14)^ss(u,d,18)^Vi(u,d,41),A=u&p^~u&m,I=d&f^~d&h,y=TS(C,S,I,IS[b],Mn[b]),T=CS(y,w,v,A,RS[b],On[b]),Y=y|0,X=rs(n,r,28)^Hi(n,r,34)^Hi(n,r,39),H=ss(n,r,28)^Vi(n,r,34)^Vi(n,r,39),_e=n&s^n&i^s&i,re=r&o^r&a^o&a;w=m|0,C=h|0,m=p|0,h=f|0,p=u|0,f=d|0,{h:u,l:d}=Xt(c|0,l|0,T|0,Y|0),c=i|0,l=a|0,i=s|0,a=o|0,s=n|0,o=r|0;let J=vS(Y,H,re);n=wS(J,T,X,_e),r=J|0}({h:n,l:r}=Xt(this.Ah|0,this.Al|0,n|0,r|0)),{h:s,l:o}=Xt(this.Bh|0,this.Bl|0,s|0,o|0),{h:i,l:a}=Xt(this.Ch|0,this.Cl|0,i|0,a|0),{h:c,l}=Xt(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=Xt(this.Eh|0,this.El|0,u|0,d|0),{h:p,l:f}=Xt(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=Xt(this.Gh|0,this.Gl|0,m|0,h|0),{h:w,l:C}=Xt(this.Hh|0,this.Hl|0,w|0,C|0),this.set(n,r,s,o,i,a,c,l,u,d,p,f,m,h,w,C)}roundClean(){uo(On,Mn)}destroy(){this.destroyed=!0,uo(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},PS=class extends $S{Ah=Oe[0]|0;Al=Oe[1]|0;Bh=Oe[2]|0;Bl=Oe[3]|0;Ch=Oe[4]|0;Cl=Oe[5]|0;Dh=Oe[6]|0;Dl=Oe[7]|0;Eh=Oe[8]|0;El=Oe[9]|0;Fh=Oe[10]|0;Fl=Oe[11]|0;Gh=Oe[12]|0;Gl=Oe[13]|0;Hh=Oe[14]|0;Hl=Oe[15]|0;constructor(){super(64)}},OS=gg(()=>new AS,hg(1)),MS=gg(()=>new PS,hg(3)),Fm=fg;Fm.sha512||(Fm.sha512=e=>MS(e));US=Ol.bytesToHex,bg=Ol.hexToBytes;Ol.concatBytes;jS=new TextEncoder,BS={subwayAgentMsgV1:"message_id;sender_peer_id;sender_name;timestamp_ms;message_type;payload_hash;nonce"};bg("302e020100300506032b657004220420");bg("302a300506032b6570032100");vg=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:Zi,n:Yi,Gx:Hm,Gy:Vm,a:bl,d:vl,h:qS}=vg,cs=32,KS=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},ke=(e="")=>{let t=new Error(e);throw KS(t,ke),t},GS=e=>typeof e=="bigint",WS=e=>typeof e=="string",YS=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,Dn=(e,t,n="")=>{let r=YS(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},ra=e=>new Uint8Array(e),Ml=e=>Uint8Array.from(e),wg=(e,t)=>e.toString(16).padStart(t,"0"),Sg=e=>Array.from(Dn(e)).map(t=>wg(t,2)).join(""),Zt={_0:48,_9:57,A:65,F:70,a:97,f:102},qm=e=>{if(e>=Zt._0&&e<=Zt._9)return e-Zt._0;if(e>=Zt.A&&e<=Zt.F)return e-(Zt.A-10);if(e>=Zt.a&&e<=Zt.f)return e-(Zt.a-10)},xg=e=>{let t="hex invalid";if(!WS(e))return ke(t);let n=e.length,r=n/2;if(n%2)return ke(t);let s=ra(r);for(let o=0,i=0;o<r;o++,i+=2){let a=qm(e.charCodeAt(i)),c=qm(e.charCodeAt(i+1));if(a===void 0||c===void 0)return ke(t);s[o]=a*16+c}return s},Tg=()=>globalThis?.crypto,zS=()=>Tg()?.subtle??ke("crypto.subtle must be defined, consider polyfill"),Nl=(...e)=>{let t=0;for(let s of e)t+=Dn(s).length;let n=ra(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},JS=(e=cs)=>Tg().getRandomValues(ra(e)),Qi=BigInt,wr=(e,t,n,r="bad number: out of range")=>{if(!GS(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},ie=(e,t=Zi)=>{let n=e%t;return n>=0n?n:t+n},Km=(1n<<255n)-1n,P=e=>{e<0n&&ke("negative coordinate");let t=(e>>255n)*19n+(e&Km);return t=(t>>255n)*19n+(t&Km),t%Zi},XS=e=>ie(e,Yi),ZS=(e,t)=>{(e===0n||t<=0n)&&ke("no inverse n="+e+" mod="+t);let n=ie(e,t),r=t,s=0n,o=1n;for(;n!==0n;){let i=r/n,a=r%n,c=s-o*i;r=n,n=a,s=o,o=c}return r===1n?ie(s,t):ke("no inverse")},Cg=e=>{let t=Ig[e];return typeof t!="function"&&ke("hashes."+e+" not set"),t},kg=e=>Dn(e,64,"digest"),wl=e=>e instanceof po?e:ke("Point expected"),kl=2n**256n,po=class Sr{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=kl;this.X=wr(t,0n,o),this.Y=wr(n,0n,o),this.Z=wr(r,1n,o),this.T=wr(s,0n,o),Object.freeze(this)}static CURVE(){return vg}static fromAffine(t){return new Sr(t.x,t.y,1n,P(t.x*t.y))}static fromBytes(t,n=!1){let r=vl,s=Ml(Dn(t,cs)),o=t[31];s[31]=o&-129;let i=Eg(s);wr(i,0n,n?kl:Zi);let c=P(i*i),l=ie(c-1n),u=P(r*c+1n),{isValid:d,value:p}=tx(l,u);d||ke("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!n&&p===0n&&m&&ke("bad point: x==0, isLastByteOdd"),m!==f&&(p=ie(-p)),new Sr(p,i,1n,P(p*i))}static fromHex(t,n){return Sr.fromBytes(xg(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=bl,n=vl,r=this;if(r.is0())return ke("bad point: ZERO");let{X:s,Y:o,Z:i,T:a}=r,c=P(s*s),l=P(o*o),u=P(i*i),d=P(u*u),p=P(c*t),f=P(u*(p+l)),m=ie(d+P(n*P(c*l)));if(f!==m)return ke("bad point: equation left != right (1)");let h=P(s*o),w=P(i*a);return h!==w?ke("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=wl(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(Cr)}negate(){return new Sr(ie(-this.X),this.Y,this.Z,ie(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=bl,o=P(t*t),i=P(n*n),a=P(2n*r*r),c=P(s*o),l=ie(t+n),u=ie(P(l*l)-o-i),d=ie(c+i),p=ie(d-a),f=ie(c-i),m=P(u*p),h=P(d*f),w=P(u*f),C=P(p*d);return new Sr(m,h,C,w)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=wl(t),u=bl,d=vl,p=P(n*i),f=P(r*a),m=P(P(o*d)*l),h=P(s*c),w=ie(P(ie(n+r)*ie(i+a))-p-f),C=ie(h-m),b=ie(h+m),v=ie(f-P(u*p)),S=P(w*C),A=P(b*v),I=P(w*v),y=P(C*b);return new Sr(S,A,y,I)}subtract(t){return this.add(wl(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(wr(t,1n,Yi),!n&&this.is0()))return Cr;if(t===1n)return this;if(this.equals(ls))return dx(t).p;let r=Cr,s=ls;for(let o=this;t>0n;o=o.double(),t>>=1n)t&1n?r=r.add(o):n&&(s=s.add(o));return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(this.equals(Cr))return{x:0n,y:1n};let s=ZS(r,Zi);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=QS(n);return r[31]|=t&1n?128:0,r}toHex(){return Sg(this.toBytes())}clearCofactor(){return this.multiply(Qi(qS),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Yi/2n,!1).double();return Yi%2n&&(t=t.add(this)),t.is0()}},ls=new po(Hm,Vm,1n,ie(Hm*Vm)),Cr=new po(0n,1n,1n,0n);po.BASE=ls;po.ZERO=Cr;QS=e=>xg(wg(wr(e,0n,kl),64)).reverse(),Eg=e=>Qi("0x"+Sg(Ml(Dn(e)).reverse())),At=(e,t)=>{let n=e;for(;t-- >0n;)n=P(n*n);return n},ex=e=>{let t=P(e*e),n=P(t*e),r=P(At(n,2n)*n),s=P(At(r,1n)*e),o=P(At(s,5n)*s),i=P(At(o,10n)*o),a=P(At(i,20n)*i),c=P(At(a,40n)*a),l=P(At(c,80n)*c),u=P(At(l,80n)*c),d=P(At(u,10n)*o);return{pow_p_5_8:P(At(d,2n)*e),b2:n}},Gm=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,tx=(e,t)=>{let n=P(t*P(t*t)),r=P(P(n*n)*t),s=ex(P(e*r)).pow_p_5_8,o=P(e*P(n*s)),i=P(t*P(o*o)),a=o,c=P(o*Gm),l=i===e,u=i===ie(-e),d=i===ie(-e*Gm);return l&&(o=a),(u||d)&&(o=c),(ie(o)&1n)===1n&&(o=ie(-o)),{isValid:l||u,value:o}},nx=e=>XS(Eg(e)),rx=(...e)=>Promise.resolve(Cg("sha512Async")(Nl(...e))).then(kg),sx=(...e)=>kg(Cg("sha512")(Nl(...e))),Ag=e=>{let t=Ml(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=nx(n),o=ls.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},ox=e=>rx(Dn(e,cs)).then(Ag),Rg=e=>Ag(sx(Dn(e,cs))),ix=e=>Rg(e).pointBytes,Ig={sha512Async:async e=>{let t=zS(),n=Nl(e);return ra(await t.digest("SHA-512",n.buffer))},sha512:void 0},ax=e=>(e=e===void 0?JS(cs):e,Dn(e,cs)),cx=Object.freeze({getExtendedPublicKeyAsync:ox,getExtendedPublicKey:Rg,randomSecretKey:ax}),ea=8,lx=256,$g=Math.ceil(lx/ea)+1,El=2**(ea-1),ux=()=>{let e=[],t=ls,n=t;for(let r=0;r<$g;r++){n=t,e.push(n);for(let s=1;s<El;s++)n=n.add(t),e.push(n);t=n.double()}return e},Wm=void 0,Ym=(e,t)=>{let n=t.negate();return e?n:t},dx=e=>{let t=Wm||(Wm=ux()),n=Cr,r=ls,s=2**ea,o=s,i=Qi(s-1),a=Qi(ea);for(let c=0;c<$g;c++){let l=Number(e&i);e>>=a,l>El&&(l-=o,e+=1n);let u=c*El,d=u,p=u+Math.abs(l)-1,f=c%2!==0,m=l<0;l===0?r=r.add(Ym(f,t[d])):n=n.add(Ym(m,t[p]))}return e!==0n&&ke("invalid wnaf"),{p:n,f:r}};gx=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),hx=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=Sl(this.buffer)}update(e){zm(this),Pg(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=Sl(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){zm(this),px(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,Al(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=Sl(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<c;u++)i.setUint32(4*u,l[u],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:s,destroyed:o,pos:i}=this;return e.destroyed=o,e.finished=s,e.length=r,e.pos=i,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Me=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),qi=BigInt(2**32-1),Jm=BigInt(32);Xm=(e,t,n)=>e>>>n,Zm=(e,t,n)=>e<<32-n|t>>>n,os=(e,t,n)=>e>>>n|t<<32-n,is=(e,t,n)=>e<<32-n|t>>>n,Ki=(e,t,n)=>e<<64-n|t>>>n-32,Gi=(e,t,n)=>e>>>n-32|t<<64-n;bx=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),vx=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,wx=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Sx=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,xx=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),Tx=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,Og=_x(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),Cx=Og[0],kx=Og[1],Nn=new Uint32Array(80),Ln=new Uint32Array(80),Ex=class extends hx{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:s,Cl:o,Dh:i,Dl:a,Eh:c,El:l,Fh:u,Fl:d,Gh:p,Gl:f,Hh:m,Hl:h}=this;return[e,t,n,r,s,o,i,a,c,l,u,d,p,f,m,h]}set(e,t,n,r,s,o,i,a,c,l,u,d,p,f,m,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=s|0,this.Cl=o|0,this.Dh=i|0,this.Dl=a|0,this.Eh=c|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=p|0,this.Gl=f|0,this.Hh=m|0,this.Hl=h|0}process(e,t){for(let b=0;b<16;b++,t+=4)Nn[b]=e.getUint32(t),Ln[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let v=Nn[b-15]|0,S=Ln[b-15]|0,A=os(v,S,1)^os(v,S,8)^Xm(v,S,7),I=is(v,S,1)^is(v,S,8)^Zm(v,S,7),y=Nn[b-2]|0,T=Ln[b-2]|0,Y=os(y,T,19)^Ki(y,T,61)^Xm(y,T,6),X=is(y,T,19)^Gi(y,T,61)^Zm(y,T,6),H=wx(I,X,Ln[b-7],Ln[b-16]),_e=Sx(H,A,Y,Nn[b-7],Nn[b-16]);Nn[b]=_e|0,Ln[b]=H|0}let{Ah:n,Al:r,Bh:s,Bl:o,Ch:i,Cl:a,Dh:c,Dl:l,Eh:u,El:d,Fh:p,Fl:f,Gh:m,Gl:h,Hh:w,Hl:C}=this;for(let b=0;b<80;b++){let v=os(u,d,14)^os(u,d,18)^Ki(u,d,41),S=is(u,d,14)^is(u,d,18)^Gi(u,d,41),A=u&p^~u&m,I=d&f^~d&h,y=xx(C,S,I,kx[b],Ln[b]),T=Tx(y,w,v,A,Cx[b],Nn[b]),Y=y|0,X=os(n,r,28)^Ki(n,r,34)^Ki(n,r,39),H=is(n,r,28)^Gi(n,r,34)^Gi(n,r,39),_e=n&s^n&i^s&i,re=r&o^r&a^o&a;w=m|0,C=h|0,m=p|0,h=f|0,p=u|0,f=d|0,{h:u,l:d}=Qt(c|0,l|0,T|0,Y|0),c=i|0,l=a|0,i=s|0,a=o|0,s=n|0,o=r|0;let J=bx(Y,H,re);n=vx(J,T,X,_e),r=J|0}({h:n,l:r}=Qt(this.Ah|0,this.Al|0,n|0,r|0)),{h:s,l:o}=Qt(this.Bh|0,this.Bl|0,s|0,o|0),{h:i,l:a}=Qt(this.Ch|0,this.Cl|0,i|0,a|0),{h:c,l}=Qt(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=Qt(this.Eh|0,this.El|0,u|0,d|0),{h:p,l:f}=Qt(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=Qt(this.Gh|0,this.Gl|0,m|0,h|0),{h:w,l:C}=Qt(this.Hh|0,this.Hl|0,w|0,C|0),this.set(n,r,s,o,i,a,c,l,u,d,p,f,m,h,w,C)}roundClean(){Al(Nn,Ln)}destroy(){this.destroyed=!0,Al(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Ax=class extends Ex{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)}},Rx=mx(()=>new Ax,gx(3)),Qm=Ig;Qm.sha512||(Qm.sha512=e=>Rx(e));Nx="ws://localhost:9001/ws",Lx=3e4,Ng=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=xr(e.name),e.keyPath)try{this._keypair=Ox(e.keyPath)}catch{}this.options={name:this._name,url:e.url??Nx,relay:e.relay??"",autoReconnect:e.autoReconnect??!0,reconnectInterval:e.reconnectInterval??1e3,maxReconnectAttempts:e.maxReconnectAttempts??10,rpcTimeout:e.rpcTimeout??Lx,pingInterval:e.pingInterval??3e4,binding:e.binding??""},this.transport=new Yw({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=VS(new Uint8Array(t));n&&(this._keypair={privateKey:n,publicKey:NS(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=eg(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 Pe(String(r)))}})}disconnect(){for(let[,e]of this.pendingCalls)clearTimeout(e.timer),e.reject(new Pe("Client disconnected"));this.pendingCalls.clear();for(let[,e]of this.pendingSend)e.reject(new Pe("Client disconnected"));this.pendingSend.clear();for(let[,e]of this.pendingResolve)e.reject(new Pe("Client disconnected"));this.pendingResolve.clear(),this.registerPromise&&(this.registerPromise.reject(new Pe("Client disconnected")),this.registerPromise=null),this.transport.disconnect(),this._peerId=null,this.hasConnectedOnce=!1}async send(e,t,n,r){let s=xr(e),o=ml();return new Promise((i,a)=>{this.pendingSend.set(s,{resolve:i,reject:a});try{this.transport.send({type:"send",to:s,message_type:t,payload:n,metadata:r})}catch(c){this.pendingSend.delete(s),a(c instanceof Error?c:new Pe(String(c)))}setTimeout(()=>{this.pendingSend.has(s)&&(this.pendingSend.delete(s),i({messageId:o,to:s}))},5e3)})}async sendSigned(e,t,n,r){if(!this._keypair||!this._peerId)return this.send(e,t,n,r);let s=xr(e),o=ml(),i=Date.now(),a=Math.floor(Math.random()*2**32),c=new TextEncoder().encode(n),{signature:l,signatureInput:u}=await Mx(this._keypair.privateKey,o,this._peerId,this._name,i,t,c,a);return new Promise((d,p)=>{this.pendingSend.set(s,{resolve:d,reject:p});try{this.transport.send({type:"send_signed",to:s,message_id:o,sender_peer_id:this._peerId,sender_name:this._name,timestamp_ms:i,message_type:t,payload:n,metadata:r,signature:Buffer.from(l).toString("base64"),signature_input:u,nonce:a})}catch(f){this.pendingSend.delete(s),p(f instanceof Error?f:new Pe(String(f)))}setTimeout(()=>{this.pendingSend.has(s)&&(this.pendingSend.delete(s),d({messageId:o,to:s}))},5e3)})}async call(e,t,n,r){let s=xr(e),o=r?.correlationId??ml(),i=r?.timeout??this.options.rpcTimeout;return new Promise((a,c)=>{let l=setTimeout(()=>{this.pendingCalls.delete(o),c(new lo(`RPC call to ${s}.${t} timed out after ${i}ms`))},i);this.pendingCalls.set(o,{resolve:a,reject:c,timer:l});try{this.transport.send({type:"call",to:s,method:t,payload:n??"",correlation_id:o})}catch(u){clearTimeout(l),this.pendingCalls.delete(o),c(u instanceof Error?u:new Pe(String(u)))}})}async broadcast(e,t,n){this.transport.send({type:"broadcast",topic:e,message_type:t,payload:n})}subscribe(e,t){let n=this.topicHandlers.get(e);if(!n){n=new Set,this.topicHandlers.set(e,n);try{this.transport.send({type:"subscribe",topic:e})}catch{}}return n.add(t),()=>{n.delete(t),n.size===0&&this.topicHandlers.delete(e)}}onMessage(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}onCall(e,t){return this.rpcHandlers.set(e,t),()=>this.rpcHandlers.delete(e)}onAnyCall(e){return this.defaultRpcHandler=e,()=>{this.defaultRpcHandler=null}}async resolve(e){let t=xr(e);return new Promise((n,r)=>{this.pendingResolve.set(t,{resolve:n,reject:r});try{this.transport.send({type:"resolve",name:t})}catch(s){this.pendingResolve.delete(t),r(s instanceof Error?s:new Pe(String(s)))}setTimeout(()=>{this.pendingResolve.has(t)&&(this.pendingResolve.delete(t),r(new lo(`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=fl(e.code,e.message);this.registerPromise&&e.code==="register_failed"&&(this.registerPromise.reject(new Bi(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=eg(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 nT(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function ah(e,t,n=""){let r=nT(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 Vg(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 rT(e,t){ah(e,void 0,"digestInto() output");let n=t.outputLen;if(e.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function ql(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Bl(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function sT(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 aT(e,t=!1){return t?{h:Number(e&sa),l:Number(e>>qg&sa)}:{h:Number(e>>qg&sa)|0,l:Number(e&sa)|0}}function cT(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}=aT(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 vT(){return Zx.randomSecretKey()}function fa(e){return Wx(e)}function lh(){let e=vT();return{secretKey:e,publicKey:fa(e)}}function go(e,t){return Jx(t,e)}function wT(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function ST(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 ms(e){return wT(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function xT(e){let t=e.length%4===0?0:4-e.length%4,n=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return ST(n)}function TT(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function dh(e){let t=fa(e);return{kty:"OKP",crv:"Ed25519",x:ms(t),d:ms(e)}}function fh(e){return{kty:"OKP",crv:"Ed25519",x:ms(e)}}function ho(e){if(TT(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return xT(e.d)}var Yg,ca,aa,Lg,Ug,Ul,Dl,Ux,fs,Dx,Ee,jx,Bx,Fx,It,da,Kl,zg,Gl,tn,Dg,Wl,Jg,Hx,ps,Xg,la,Er,oe,jg,O,Zg,Qg,eh,th,jl,Fl,mo,Ir,Rr,nh,rh,Rt,Vx,Bg,qx,Hl,Kx,Yl,sh,Gx,zl,Wx,Yx,zx,Jx,Jl,oh,Xx,Zx,ua,Qx,ih,Vl,eT,Fg,Hg,tT,oT,iT,Ne,sa,qg,Kg,Gg,us,ds,oa,ia,lT,uT,dT,fT,pT,mT,ch,gT,hT,jn,Bn,yT,_T,bT,Wg,LI,uh,UI,DI,jI,BI,pa=Nt(()=>{"use strict";Yg=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:ca,n:aa,Gx:Lg,Gy:Ug,a:Ul,d:Dl,h:Ux}=Yg,fs=32,Dx=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},Ee=(e="")=>{let t=new Error(e);throw Dx(t,Ee),t},jx=e=>typeof e=="bigint",Bx=e=>typeof e=="string",Fx=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,It=(e,t,n="")=>{let r=Fx(e),s=e?.length,o=t!==void 0;if(!r||o&&s!==t){let i=n&&`"${n}" `,a=o?` of length ${t}`:"",c=r?`length=${s}`:`type=${typeof e}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):new TypeError(l)}return e},da=e=>new Uint8Array(e),Kl=e=>Uint8Array.from(e),zg=(e,t)=>e.toString(16).padStart(t,"0"),Gl=e=>Array.from(It(e)).map(t=>zg(t,2)).join(""),tn={_0:48,_9:57,A:65,F:70,a:97,f:102},Dg=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)},Wl=e=>{let t="hex invalid";if(!Bx(e))return Ee(t);let n=e.length,r=n/2;if(n%2)return Ee(t);let s=da(r);for(let o=0,i=0;o<r;o++,i+=2){let a=Dg(e.charCodeAt(i)),c=Dg(e.charCodeAt(i+1));if(a===void 0||c===void 0)return Ee(t);s[o]=a*16+c}return s},Jg=()=>globalThis?.crypto,Hx=()=>Jg()?.subtle??Ee("crypto.subtle must be defined, consider polyfill"),ps=(...e)=>{let t=0;for(let s of e)t+=It(s).length;let n=da(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},Xg=(e=fs)=>Jg().getRandomValues(da(e)),la=BigInt,Er=(e,t,n,r="bad number: out of range")=>{if(!jx(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},oe=(e,t=ca)=>{let n=e%t;return n>=0n?n:t+n},jg=(1n<<255n)-1n,O=e=>{e<0n&&Ee("negative coordinate");let t=(e>>255n)*19n+(e&jg);return t=(t>>255n)*19n+(t&jg),t%ca},Zg=e=>oe(e,aa),Qg=(e,t)=>{(e===0n||t<=0n)&&Ee("no inverse n="+e+" mod="+t);let n=oe(e,t),r=t,s=0n,o=1n,i=1n,a=0n;for(;n!==0n;){let c=r/n,l=r%n,u=s-i*c,d=o-a*c;r=n,n=l,s=i,o=a,i=u,a=d}return r===1n?oe(s,t):Ee("no inverse")},eh=e=>{let t=oh[e];return typeof t!="function"&&Ee("hashes."+e+" not set"),t},th=e=>It(e,64,"digest"),jl=e=>e instanceof mo?e:Ee("Point expected"),Fl=2n**256n,mo=class Ar{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=Fl;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 Yg}static fromAffine(t){return new Ar(t.x,t.y,1n,O(t.x*t.y))}static fromBytes(t,n=!1){let r=Dl,s=Kl(It(t,fs)),o=t[31];s[31]=o&-129;let i=rh(s);Er(i,0n,n?Fl:ca);let c=O(i*i),l=oe(c-1n),u=O(r*c+1n),{isValid:d,value:p}=qx(l,u);d||Ee("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!n&&p===0n&&m&&Ee("bad point: x==0, isLastByteOdd"),m!==f&&(p=oe(-p)),new Ar(p,i,1n,O(p*i))}static fromHex(t,n){return Ar.fromBytes(Wl(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Ul,n=Dl,r=this;if(r.is0())return Ee("bad point: ZERO");let{X:s,Y:o,Z:i,T:a}=r,c=O(s*s),l=O(o*o),u=O(i*i),d=O(u*u),p=O(c*t),f=O(u*(p+l)),m=oe(d+O(n*O(c*l)));if(f!==m)return Ee("bad point: equation left != right (1)");let h=O(s*o),w=O(i*a);return h!==w?Ee("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=jl(t),c=O(n*a),l=O(o*s),u=O(r*a),d=O(i*s);return c===l&&u===d}is0(){return this.equals(Rr)}negate(){return new Ar(oe(-this.X),this.Y,this.Z,oe(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=Ul,o=O(t*t),i=O(n*n),a=O(2n*r*r),c=O(s*o),l=oe(t+n),u=oe(O(l*l)-o-i),d=oe(c+i),p=oe(d-a),f=oe(c-i),m=O(u*p),h=O(d*f),w=O(u*f),C=O(p*d);return new Ar(m,h,C,w)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=jl(t),u=Ul,d=Dl,p=O(n*i),f=O(r*a),m=O(O(o*d)*l),h=O(s*c),w=oe(O(oe(n+r)*oe(i+a))-p-f),C=oe(h-m),b=oe(h+m),v=oe(f-O(u*p)),S=O(w*C),A=O(b*v),I=O(w*v),y=O(C*b);return new Ar(S,A,y,I)}subtract(t){return this.add(jl(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(Er(t,1n,aa),!n&&this.is0()))return Rr;if(t===1n)return this;if(this.equals(Ir))return tT(t).p;let r=Rr,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(Rr))return{x:0n,y:1n};let s=Qg(r,ca);O(r*s)!==1n&&Ee("invalid inverse");let o=O(t*s),i=O(n*s);return{x:o,y:i}}toBytes(){let{x:t,y:n}=this.toAffine(),r=nh(n);return r[31]|=t&1n?128:0,r}toHex(){return Gl(this.toBytes())}clearCofactor(){return this.multiply(la(Ux),!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 mo(Lg,Ug,1n,oe(Lg*Ug)),Rr=new mo(0n,1n,1n,0n);mo.BASE=Ir;mo.ZERO=Rr;nh=e=>Wl(zg(Er(e,0n,Fl),64)).reverse(),rh=e=>la("0x"+Gl(Kl(It(e)).reverse())),Rt=(e,t)=>{let n=e;for(;t-- >0n;)n=O(n*n);return n},Vx=e=>{let t=O(e*e),n=O(t*e),r=O(Rt(n,2n)*n),s=O(Rt(r,1n)*e),o=O(Rt(s,5n)*s),i=O(Rt(o,10n)*o),a=O(Rt(i,20n)*i),c=O(Rt(a,40n)*a),l=O(Rt(c,80n)*c),u=O(Rt(l,80n)*c),d=O(Rt(u,10n)*o);return{pow_p_5_8:O(Rt(d,2n)*e),b2:n}},Bg=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,qx=(e,t)=>{let n=O(t*O(t*t)),r=O(O(n*n)*t),s=Vx(O(e*r)).pow_p_5_8,o=O(e*O(n*s)),i=O(t*O(o*o)),a=o,c=O(o*Bg),l=i===e,u=i===oe(-e),d=i===oe(-e*Bg);return l&&(o=a),(u||d)&&(o=c),(oe(o)&1n)===1n&&(o=oe(-o)),{isValid:l||u,value:o}},Hl=e=>Zg(rh(e)),Kx=(...e)=>Promise.resolve(eh("sha512Async")(ps(...e))).then(th),Yl=(...e)=>th(eh("sha512")(ps(...e))),sh=e=>{let t=Kl(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=Hl(n),o=Ir.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},Gx=e=>Kx(It(e,fs)).then(sh),zl=e=>sh(Yl(It(e,fs))),Wx=e=>zl(e).pointBytes,Yx=e=>e.finish(Yl(e.hashable)),zx=(e,t,n)=>{let{pointBytes:r,scalar:s}=e,o=Hl(t),i=Ir.multiply(o).toBytes();return{hashable:ps(i,r,n),finish:l=>{let u=Zg(o+Hl(l)*s);return It(ps(i,nh(u)),64)}}},Jx=(e,t)=>{let n=It(e),r=zl(t),s=Yl(r.prefix,n);return Yx(zx(r,s,n))},Jl=Object.freeze({bytesToHex:Gl,hexToBytes:Wl,concatBytes:ps,mod:oe,invert:Qg,randomBytes:Xg}),oh={sha512Async:async e=>{let t=Hx(),n=ps(e);return da(await t.digest("SHA-512",n.buffer))},sha512:void 0},Xx=e=>(e=e===void 0?Xg(fs):e,It(e,fs)),Zx=Object.freeze({getExtendedPublicKeyAsync:Gx,getExtendedPublicKey:zl,randomSecretKey:Xx}),ua=8,Qx=256,ih=Math.ceil(Qx/ua)+1,Vl=2**(ua-1),eT=()=>{let e=[],t=Ir,n=t;for(let r=0;r<ih;r++){n=t,e.push(n);for(let s=1;s<Vl;s++)n=n.add(t),e.push(n);t=n.double()}return e},Fg=void 0,Hg=(e,t)=>{let n=t.negate();return e?n:t},tT=e=>{let t=Fg||(Fg=eT()),n=Rr,r=Ir,s=2**ua,o=s,i=la(s-1),a=la(ua);for(let c=0;c<ih;c++){let l=Number(e&i);e>>=a,l>Vl&&(l-=o,e+=1n);let u=c*Vl,d=u,p=u+Math.abs(l)-1,f=c%2!==0,m=l<0;l===0?r=r.add(Hg(f,t[d])):n=n.add(Hg(m,t[p]))}return e!==0n&&Ee("invalid wnaf"),{p:n,f:r}};oT=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),iT=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=Bl(this.buffer)}update(e){Vg(this),ah(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=Bl(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){Vg(this),rT(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,ql(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let u=o;u<r;u++)t[u]=0;n.setBigUint64(r-8,BigInt(this.length*8),s),this.process(n,0);let i=Bl(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<c;u++)i.setUint32(4*u,l[u],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:s,destroyed:o,pos:i}=this;return e.destroyed=o,e.finished=s,e.length=r,e.pos=i,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Ne=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),sa=BigInt(2**32-1),qg=BigInt(32);Kg=(e,t,n)=>e>>>n,Gg=(e,t,n)=>e<<32-n|t>>>n,us=(e,t,n)=>e>>>n|t<<32-n,ds=(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;lT=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),uT=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,dT=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),fT=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,pT=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),mT=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,ch=cT(["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))),gT=ch[0],hT=ch[1],jn=new Uint32Array(80),Bn=new Uint32Array(80),yT=class extends iT{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:s,Cl:o,Dh:i,Dl:a,Eh:c,El:l,Fh:u,Fl:d,Gh:p,Gl:f,Hh:m,Hl:h}=this;return[e,t,n,r,s,o,i,a,c,l,u,d,p,f,m,h]}set(e,t,n,r,s,o,i,a,c,l,u,d,p,f,m,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=s|0,this.Cl=o|0,this.Dh=i|0,this.Dl=a|0,this.Eh=c|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=p|0,this.Gl=f|0,this.Hh=m|0,this.Hl=h|0}process(e,t){for(let b=0;b<16;b++,t+=4)jn[b]=e.getUint32(t),Bn[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let v=jn[b-15]|0,S=Bn[b-15]|0,A=us(v,S,1)^us(v,S,8)^Kg(v,S,7),I=ds(v,S,1)^ds(v,S,8)^Gg(v,S,7),y=jn[b-2]|0,T=Bn[b-2]|0,Y=us(y,T,19)^oa(y,T,61)^Kg(y,T,6),X=ds(y,T,19)^ia(y,T,61)^Gg(y,T,6),H=dT(I,X,Bn[b-7],Bn[b-16]),_e=fT(H,A,Y,jn[b-7],jn[b-16]);jn[b]=_e|0,Bn[b]=H|0}let{Ah:n,Al:r,Bh:s,Bl:o,Ch:i,Cl:a,Dh:c,Dl:l,Eh:u,El:d,Fh:p,Fl:f,Gh:m,Gl:h,Hh:w,Hl:C}=this;for(let b=0;b<80;b++){let v=us(u,d,14)^us(u,d,18)^oa(u,d,41),S=ds(u,d,14)^ds(u,d,18)^ia(u,d,41),A=u&p^~u&m,I=d&f^~d&h,y=pT(C,S,I,hT[b],Bn[b]),T=mT(y,w,v,A,gT[b],jn[b]),Y=y|0,X=us(n,r,28)^oa(n,r,34)^oa(n,r,39),H=ds(n,r,28)^ia(n,r,34)^ia(n,r,39),_e=n&s^n&i^s&i,re=r&o^r&a^o&a;w=m|0,C=h|0,m=p|0,h=f|0,p=u|0,f=d|0,{h:u,l:d}=nn(c|0,l|0,T|0,Y|0),c=i|0,l=a|0,i=s|0,a=o|0,s=n|0,o=r|0;let J=lT(Y,H,re);n=uT(J,T,X,_e),r=J|0}({h:n,l:r}=nn(this.Ah|0,this.Al|0,n|0,r|0)),{h:s,l:o}=nn(this.Bh|0,this.Bl|0,s|0,o|0),{h:i,l:a}=nn(this.Ch|0,this.Cl|0,i|0,a|0),{h:c,l}=nn(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=nn(this.Eh|0,this.El|0,u|0,d|0),{h:p,l:f}=nn(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=nn(this.Gh|0,this.Gl|0,m|0,h|0),{h:w,l:C}=nn(this.Hh|0,this.Hl|0,w|0,C|0),this.set(n,r,s,o,i,a,c,l,u,d,p,f,m,h,w,C)}roundClean(){ql(jn,Bn)}destroy(){this.destroyed=!0,ql(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},_T=class extends yT{Ah=Ne[0]|0;Al=Ne[1]|0;Bh=Ne[2]|0;Bl=Ne[3]|0;Ch=Ne[4]|0;Cl=Ne[5]|0;Dh=Ne[6]|0;Dl=Ne[7]|0;Eh=Ne[8]|0;El=Ne[9]|0;Fh=Ne[10]|0;Fl=Ne[11]|0;Gh=Ne[12]|0;Gl=Ne[13]|0;Hh=Ne[14]|0;Hl=Ne[15]|0;constructor(){super(64)}},bT=sT(()=>new _T,oT(3)),Wg=oh;Wg.sha512||(Wg.sha512=e=>bT(e));LI=Jl.bytesToHex,uh=Jl.hexToBytes,UI=Jl.concatBytes;DI=new TextEncoder;jI=uh("302e020100300506032b657004220420"),BI=uh("302a300506032b6570032100");});function CT(e){let t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return ph.createHash("sha256").update(t,"utf8").digest("base64url")}function kT(e,t,n){return`visa-agent-binding:v1:${e}:${t}:${n}`}function ET(e,t,n="visa",r=Math.floor(Date.now()/1e3)){let s=fh(fa(e)),o=Buffer.from(kT(t,CT(s),r),"utf8"),i=Buffer.from(go(e,o)).toString("base64url");return{name:t,mesh:n,agent_pubkey:s,proof:{ts:r,sig:i}}}async function gh(e){let t=ET(e.seed,e.name,e.mesh??"visa",e.nowSec),n=e.fetchImpl??fetch,r=`${e.authUrl.replace(/\/+$/,"")}/v2/harness/agents`,s=await n(r,{method:"POST",headers:{"content-type":"application/json","x-api-key":e.apiKey},body:JSON.stringify(t)});if(!s.ok){let o="";try{o=(await s.json())?.error??""}catch{}throw new Error(`Visa binding issuance failed (${s.status})${o?`: ${o}`:""}`)}return await s.json()}function hh(e){return new Uint8Array(mh.readFileSync(e))}var ph,mh,yh=Nt(()=>{"use strict";ph=R(require("crypto")),mh=R(require("fs"));pa()});var ya={};Lo(ya,{MESH:()=>Xe,RELAY_URL:()=>_o,connectOrThrow:()=>_s,ensureMailbox:()=>ou,isSubwayEnabled:()=>Ql,listRegistered:()=>su,loadBindingFor:()=>tu,loadRegistry:()=>gs,makeClient:()=>ys,maybeMintVisaBinding:()=>Sh,meshName:()=>$t,readInbox:()=>IT,registerName:()=>nu,resolveActingName:()=>ha,seedSubwayKeyFromTapAgent:()=>wh,sendMessage:()=>ru,sendVia:()=>$T,subwayKeyPath:()=>ga});function $t(e){return e.includes(".")?e:`${e}.${Xe}`}function Ql(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 vh(){Ae.mkdirSync(eu,{recursive:!0,mode:448})}function AT(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function ga(e){return hs.join(eu,`${AT(e)}.key`)}function gs(){if(!Ae.existsSync(Zl))return{};try{return JSON.parse(Ae.readFileSync(Zl,"utf8"))}catch{return{}}}function _h(e){vh(),Ae.writeFileSync(Zl,JSON.stringify(e,null,2),{mode:384})}function bh(){try{return yo.userInfo().username}catch{return"local"}}function wh(e){if(Ae.existsSync(e)||!Ae.existsSync(Xl))return null;let t=Ae.readdirSync(Xl).filter(r=>r.endsWith(".json"));if(t.length===0)return null;let n=t.map(r=>hs.join(Xl,r)).sort((r,s)=>Ae.statSync(s).mtimeMs-Ae.statSync(r).mtimeMs)[0];try{let r=JSON.parse(Ae.readFileSync(n,"utf8"));if(!r.private_key_jwk)return null;let s=ho(r.private_key_jwk);return vh(),Ae.writeFileSync(e,Buffer.from(s),{mode:384}),r.agent_id??null}catch{return null}}function ys(e,t={}){return new Ng({name:$t(e),url:_o,keyPath:ga(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function tu(e){if(Xe!=="visa")return;let t=gs()[e];if(t?.binding&&!(t.bindingExpiresAt&&Date.parse(t.bindingExpiresAt)<=Date.now()))return t.binding}async function _s(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 ha(e){if(e)return e;let t=Object.keys(gs());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 Sh(e){if(Xe!=="visa")return null;let t=process.env.VISA_CLI_API_KEY?.trim();if(!t)return console.warn("[subway] .visa mesh needs a Visa Key (VISA_CLI_API_KEY) with a card on file to mint a binding; registering without one."),null;try{return await gh({authUrl:Ue(),apiKey:t,seed:hh(ga(e)),name:$t(e)})}catch(n){return console.warn(`[subway] Visa binding not minted: ${n instanceof Error?n.message:String(n)}`),null}}async function nu(e){let t=ga(e),n=wh(t),r=$t(e),s=await Sh(e),o=s?{binding:s.binding,bindingExpiresAt:new Date(Date.now()+s.expires_in*1e3).toISOString()}:{};if(Xe==="visa"&&!process.env.SUBWAY_RELAY){let a=gs();return a[e]={relayName:r,mesh:Xe,peerId:null,owner:bh(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},_h(a),{relayName:r,mesh:Xe,peerId:null,tapAgentId:n,...s?{binding:s.binding}:{},note:s?"Visa binding minted; relay admission pending a .visa relay (set SUBWAY_RELAY).":"No Visa binding minted; set VISA_CLI_API_KEY (card on file) and SUBWAY_RELAY for a .visa relay."}}let i=ys(e,{autoReconnect:!1,binding:s?.binding});try{await _s(i);let a=gs();return a[e]={relayName:r,mesh:Xe,peerId:i.peerId,owner:bh(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},_h(a),{relayName:r,mesh:Xe,peerId:i.peerId,tapAgentId:n,...s?{binding:s.binding}:{}}}finally{i.disconnect()}}async function ru(e,t,n){let r=ys(e,{autoReconnect:!1,binding:tu(e)});try{await _s(r);let s=$t(t);return await r.sendSigned(s,"chat",n),{to:s,as:$t(e)}}finally{r.disconnect()}}function su(){let e=gs();return Object.entries(e).map(([t,n])=>({name:t,...n}))}async function ou(e){let t=ma.get(e);if(t)return{relayName:$t(e),peerId:t.client.peerId};let n=ys(e,{autoReconnect:!0,binding:tu(e)}),r=[];return n.onMessage(s=>{r.push({from:s.fromName,text:s.payload,ts:s.timestampMs,verified:!!s.verified}),r.length>RT&&r.shift()}),ma.set(e,{client:n,buffer:r}),await _s(n),{relayName:$t(e),peerId:n.peerId}}async function IT(e,t=20,n=!1){await ou(e);let r=ma.get(e);if(!r)return[];let s=r.buffer.slice(-t);return n&&(r.buffer.length=0),s}async function $T(e,t,n){await ou(e);let r=ma.get(e);if(!r)throw new Error(`mailbox for ${e} unavailable`);let s=$t(t);return await r.client.sendSigned(s,"chat",n),{to:s,as:$t(e)}}var Ae,yo,hs,Xe,_o,eu,Zl,Xl,ma,RT,bo=Nt(()=>{"use strict";Ll();pa();Ae=R(require("fs")),yo=R(require("os")),hs=R(require("path"));Ht();yh();Xe=process.env.SUBWAY_MESH??"relay",_o=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";eu=hs.join(yo.homedir(),".visa-cli","subway"),Zl=hs.join(eu,"registry.json"),Xl=hs.join(yo.homedir(),".visa-cli","agents");ma=new Map,RT=200});var $a={};Lo($a,{initSentry:()=>iE,isSentryConfigured:()=>oE,reportFatal:()=>aE});function oE(){return!1}async function iE(){return null}async function aE(e,t){process.exit(t?.exitCode??1)}var Pa=Nt(()=>{});var JE={};Lo(JE,{printGroupHelpAndExit:()=>pt});module.exports=Qy(JE);var Ay=require("commander"),La=R(require("crypto")),ae=R(require("fs")),ne=R(require("os")),et=R(require("path")),Ry=require("child_process"),Bu=require("node:readline/promises"),Iy=require("util");var jo=require("child_process"),ld=require("util"),ln=R(require("fs")),Bo=R(require("os")),za=R(require("path"));var rd=R(require("crypto"));var Lt="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";var sd="VISA_ALLOW_INSECURE_MOCKS",ed,td,nd;function qa(e){return`${e}-${rd.randomBytes(24).toString("base64url")}`}function od(e=process.env){return e.NODE_ENV==="test"||e[sd]==="true"}function an(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&od(e)}function Lr(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&od(e)}function Ka(){return`Set ${sd}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function id(){return ed??=qa("mock-session"),ed}function ad(e=process.env){return e.NODE_ENV==="test"?Lt:(td??=qa("mock-rc"),td)}function cd(){return nd??=qa("mock-signature"),nd}var mt=(0,ld.promisify)(jo.execFile),Ja=za.join(Bo.homedir(),".visa-mcp"),Rs=za.join(Ja,"session-token"),We="visa-cli",cn="session-token",Uo="rc-access",e_=5e3,Do=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function t_(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
10
- `)}function ud(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=t_(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function n_(){try{let{stdout:e}=await mt("security",["find-generic-password","-s",We,"-a",cn,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(ud(e))throw new Do("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 r_(e){try{try{await mt("security",["delete-generic-password","-s",We,"-a",cn],{timeout:5e3})}catch{}return await mt("security",["add-generic-password","-s",We,"-a",cn,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function s_(){try{await mt("security",["delete-generic-password","-s",We,"-a",cn],{timeout:5e3})}catch{}}async function o_(){if(!Xa())return null;try{let{stdout:e}=await mt("secret-tool",["lookup","service",We,"account",cn],{timeout:5e3});return e.trim()||null}catch{return null}}async function i_(e){if(!Xa())return!1;try{let t=(0,jo.execFile)("secret-tool",["store","--label",`${We} ${cn}`,"service",We,"account",cn]);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"))},e_))]),!0):!1}catch{return!1}}async function a_(){if(Xa())try{await mt("secret-tool",["clear","service",We,"account",cn],{timeout:5e3})}catch{}}function Xa(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function c_(){try{let{stdout:e}=await mt("security",["find-generic-password","-s",We,"-a",Uo,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function l_(e){try{try{await mt("security",["delete-generic-password","-s",We,"-a",Uo],{timeout:5e3})}catch{}await mt("security",["add-generic-password","-s",We,"-a",Uo,"-w",e],{timeout:5e3})}catch{}}async function u_(){try{await mt("security",["delete-generic-password","-s",We,"-a",Uo],{timeout:5e3})}catch{}}function Wa(){try{return ln.readFileSync(Rs,"utf-8").trim()||null}catch(e){if(ud(e))throw new Do(`Unable to read Visa CLI credentials from ${Rs}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function dd(e){ln.mkdirSync(Ja,{recursive:!0,mode:448}),ln.writeFileSync(Rs,e,{mode:384}),process.platform==="win32"&&d_(Rs)}function Ya(){try{ln.unlinkSync(Rs)}catch{}}function d_(e){try{let t=Bo.userInfo().username;(0,jo.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 Ga(){switch(process.platform){case"darwin":return{get:n_,store:r_,delete:s_};case"linux":return{get:o_,store:i_,delete:a_};default:return{get:async()=>Wa(),store:async e=>{try{return dd(e),!0}catch{return!1}},delete:async()=>Ya(),storesInSessionFile:!0}}}var K=class{static async getSessionToken(){if(an())return Promise.resolve(id());let t=Ga(),n=await t.get();if(n)return n;let r=Wa();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(an())return;let n=Ga();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||Ya();return}await n.delete()}if(dd(t),Wa()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${Ja} is writable.`))}static async getRcAccessToken(){return an()?ad():c_()}static async saveRcAccessToken(t){an()||await l_(t)}static async deleteSessionToken(){if(an())return;await Ga().delete(),Ya()}static async clearAll(){await this.deleteSessionToken(),await u_()}};var Fo=R(require("crypto")),Ho=R(require("tty")),Vo=R(require("fs"));function p_(e){return/-rc\.|-beta\./.test(e)}function Za(e){return Fo.createHash("sha256").update(e.trim()).digest("hex")}function fd(e){return Lt==="SKIP"?!0:Fo.timingSafeEqual(Buffer.from(Za(e)),Buffer.from(Lt))}function m_(){try{let e=Vo.openSync("/dev/tty","r+"),t=new Ho.ReadStream(e),n=new Ho.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{Vo.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 g_(e){return new Promise((t,n)=>{let r;try{r=m_()}catch(u){n(u);return}let{input:s,output:o,cleanupStreams:i}=r,a=()=>{s.off("data",l);try{s.setRawMode?.(!1)}catch{}i()};o.write(e),s.setRawMode?.(!0),s.resume(),s.setEncoding("utf8");let c="",l=u=>{u==="\r"||u===`
9
+ ${e.nonce}`;return nx.encode(n)}function ox(e,t,n,r,s,o,i){return sx({messageId:e,senderPeerId:t,senderName:n,timestampMs:r,messageType:s,payload:o,nonce:i})}function ix(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 Rx(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Fg(e,t,n=""){let r=Rx(e),s=e?.length;if(!r||t!==void 0){let i=n&&`"${n}" `,a="",c=r?`length=${s}`:`type=${typeof e}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):new TypeError(l)}return e}function sg(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Ix(e,t){Fg(e,void 0,"digestInto() output");let n=t.outputLen;if(e.length<n)throw new RangeError('"digestInto() output" expected to be of length >='+n)}function Nl(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Rl(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function $x(e,t={}){let n=(s,o)=>e(o).update(s).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=s=>e(s),Object.assign(n,t),Object.freeze(n)}function Mx(e,t=!1){return t?{h:Number(e&Yi),l:Number(e>>og&Yi)}:{h:Number(e>>og&Yi)|0,l:Number(e&Yi)|0}}function Nx(e,t=!1){let n=e.length,r=new Uint32Array(n),s=new Uint32Array(n);for(let o=0;o<n;o++){let{h:i,l:a}=Mx(e[o],t);[r[o],s[o]]=[i,a]}return[r,s]}function tn(e,t,n,r){let s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}function Wx(){return kx.randomSecretKey()}function Vg(e){return xx(e)}function Yx(){let e=Wx();return{secretKey:e,publicKey:Vg(e)}}function zx(e){if((0,jn.existsSync)(e)){let n=(0,jn.readFileSync)(e),r=new Uint8Array(n.buffer.slice(n.byteOffset,n.byteOffset+32));return{secretKey:r,publicKey:Vg(r)}}let t=Yx();return(0,jn.mkdirSync)((0,ug.dirname)(e),{recursive:!0}),(0,jn.writeFileSync)(e,new Uint8Array(t.secretKey)),t}function Jx(e){let{secretKey:t,publicKey:n}=zx(e);return{privateKey:t,publicKey:n}}async function Xx(e,t,n,r,s,o,i,a){let c=ox(t,n,r,s,o,i,a);return{signature:await QS(e,c),signatureInput:rx.subwayAgentMsgV1}}function lg(e){return tx(e)}var jn,ug,aS,cS,lS,uS,dS,dg,Qi,Xi,jp,Bp,Sl,xl,fS,oa,mS,ke,pS,gS,hS,nn,ia,Ll,fg,Ul,Zt,Fp,Dl,mg,yS,us,_S,ea,wr,oe,Hp,$,pg,gg,hg,yg,Tl,Il,go,Er,Cr,_g,bg,At,bS,Vp,vS,$l,jl,wS,vg,SS,xS,TS,kS,CS,AS,Bl,wg,ta,ES,Sg,Pl,RS,qp,Kp,IS,kg,Cg,On,Oe,Ki,Wp,Yp,zp,is,as,Gi,Wi,US,DS,jS,BS,FS,HS,VS,Mn,qS,KS,Ag,GS,WS,Nn,Ln,YS,zS,JS,XS,Jp,ex,Eg,nx,rx,Rg,na,Zi,Xp,Zp,Cl,Al,ax,ds,cx,Ce,lx,ux,dx,Bn,aa,Fl,Ig,$g,en,Qp,Pg,Og,fx,Hl,mx,ra,xr,ae,eg,P,px,gx,Mg,Ng,El,Ol,ho,fs,Ar,hx,Lg,Rt,yx,tg,_x,bx,vx,wx,Ug,Sx,Dg,xx,jg,Tx,kx,sa,Cx,Bg,Ml,Ax,ng,rg,Ex,Px,Ox,Me,Yi,og,ig,ag,cs,ls,zi,Ji,Lx,Ux,Dx,jx,Bx,Fx,Hg,Hx,Vx,Un,Dn,qx,Kx,Gx,cg,Zx,Qx,qg,Vl=Lt(()=>{"use strict";vl();vl();jn=require("fs"),ug=require("path");aS=1e3,cS=10,lS=3e4,uS=3e4,dS=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??aS,this.maxReconnectAttempts=e.maxReconnectAttempts??cS,this.pingInterval=e.pingInterval??lS}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=oS();if(!n){t(new Pe('No WebSocket implementation available. Install the "ws" package for Node.js.'));return}this.setStatus("connecting");try{this.ws=new n(this.url)}catch(s){t(new Pe(`Failed to create WebSocket: ${s}`));return}let r=!1;this.ws.onopen=()=>{this.reconnectAttempt=0,this.setStatus("connected"),this.startPing(),r||(r=!0,e())},this.ws.onmessage=s=>{let o;try{o=JSON.parse(typeof s.data=="string"?s.data:s.data.toString())}catch{return}for(let i of this.messageHandlers)i(o)},this.ws.onclose=()=>{this.ws=null,this.stopPing(),!this.stopped&&this.autoReconnect?this.scheduleReconnect():this.setStatus("disconnected"),r||(r=!0,t(new Pe("WebSocket closed before connection established")))},this.ws.onerror=()=>{r||(r=!0,t(new Pe(`WebSocket connection failed: ${this.url}`)))}})}disconnect(){this.stopped=!0,this.clearReconnectTimer(),this.stopPing(),this.ws&&(this.ws.onclose=null,this.ws.onerror=null,this.ws.onmessage=null,this.ws.close(),this.ws=null),this.setStatus("disconnected")}send(e){if(!this.ws||this.ws.readyState!==1)throw new Pe("WebSocket is not connected");this.ws.send(JSON.stringify(e))}startPing(){this.stopPing(),this.pingInterval>0&&(this.pingTimer=setInterval(()=>{try{this.send({type:"ping"})}catch{}},this.pingInterval))}stopPing(){this.pingTimer!==null&&(clearInterval(this.pingTimer),this.pingTimer=null)}scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts){this.setStatus("disconnected");return}this.setStatus("reconnecting");let e=iS(this.reconnectInterval*Math.pow(2,this.reconnectAttempt),this.reconnectInterval,uS);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)}}},dg=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:Qi,n:Xi,Gx:jp,Gy:Bp,a:Sl,d:xl,h:fS}=dg,oa=32,mS=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},ke=(e="")=>{let t=new Error(e);throw mS(t,ke),t},pS=e=>typeof e=="bigint",gS=e=>typeof e=="string",hS=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,nn=(e,t,n="")=>{let r=hS(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},ia=e=>new Uint8Array(e),Ll=e=>Uint8Array.from(e),fg=(e,t)=>e.toString(16).padStart(t,"0"),Ul=e=>Array.from(nn(e)).map(t=>fg(t,2)).join(""),Zt={_0:48,_9:57,A:65,F:70,a:97,f:102},Fp=e=>{if(e>=Zt._0&&e<=Zt._9)return e-Zt._0;if(e>=Zt.A&&e<=Zt.F)return e-(Zt.A-10);if(e>=Zt.a&&e<=Zt.f)return e-(Zt.a-10)},Dl=e=>{let t="hex invalid";if(!gS(e))return ke(t);let n=e.length,r=n/2;if(n%2)return ke(t);let s=ia(r);for(let o=0,i=0;o<r;o++,i+=2){let a=Fp(e.charCodeAt(i)),c=Fp(e.charCodeAt(i+1));if(a===void 0||c===void 0)return ke(t);s[o]=a*16+c}return s},mg=()=>globalThis?.crypto,yS=()=>mg()?.subtle??ke("crypto.subtle must be defined, consider polyfill"),us=(...e)=>{let t=0;for(let s of e)t+=nn(s).length;let n=ia(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},_S=(e=oa)=>mg().getRandomValues(ia(e)),ea=BigInt,wr=(e,t,n,r="bad number: out of range")=>{if(!pS(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},oe=(e,t=Qi)=>{let n=e%t;return n>=0n?n:t+n},Hp=(1n<<255n)-1n,$=e=>{e<0n&&ke("negative coordinate");let t=(e>>255n)*19n+(e&Hp);return t=(t>>255n)*19n+(t&Hp),t%Qi},pg=e=>oe(e,Xi),gg=(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")},hg=e=>{let t=wg[e];return typeof t!="function"&&ke("hashes."+e+" not set"),t},yg=e=>nn(e,64,"digest"),Tl=e=>e instanceof go?e:ke("Point expected"),Il=2n**256n,go=class Sr{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=Il;this.X=wr(t,0n,o),this.Y=wr(n,0n,o),this.Z=wr(r,1n,o),this.T=wr(s,0n,o),Object.freeze(this)}static CURVE(){return dg}static fromAffine(t){return new Sr(t.x,t.y,1n,$(t.x*t.y))}static fromBytes(t,n=!1){let r=xl,s=Ll(nn(t,oa)),o=t[31];s[31]=o&-129;let i=bg(s);wr(i,0n,n?Il:Qi);let c=$(i*i),l=oe(c-1n),u=$(r*c+1n),{isValid:d,value:m}=vS(l,u);d||ke("bad point: y not sqrt");let f=(m&1n)===1n,p=(o&128)!==0;return!n&&m===0n&&p&&ke("bad point: x==0, isLastByteOdd"),p!==f&&(m=oe(-m)),new Sr(m,i,1n,$(m*i))}static fromHex(t,n){return Sr.fromBytes(Dl(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Sl,n=xl,r=this;if(r.is0())return ke("bad point: ZERO");let{X:s,Y:o,Z:i,T:a}=r,c=$(s*s),l=$(o*o),u=$(i*i),d=$(u*u),m=$(c*t),f=$(u*(m+l)),p=oe(d+$(n*$(c*l)));if(f!==p)return ke("bad point: equation left != right (1)");let h=$(s*o),w=$(i*a);return h!==w?ke("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=Tl(t),c=$(n*a),l=$(o*s),u=$(r*a),d=$(i*s);return c===l&&u===d}is0(){return this.equals(Cr)}negate(){return new Sr(oe(-this.X),this.Y,this.Z,oe(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=Sl,o=$(t*t),i=$(n*n),a=$(2n*r*r),c=$(s*o),l=oe(t+n),u=oe($(l*l)-o-i),d=oe(c+i),m=oe(d-a),f=oe(c-i),p=$(u*m),h=$(d*f),w=$(u*f),k=$(m*d);return new Sr(p,h,k,w)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=Tl(t),u=Sl,d=xl,m=$(n*i),f=$(r*a),p=$($(o*d)*l),h=$(s*c),w=oe($(oe(n+r)*oe(i+a))-m-f),k=oe(h-p),b=oe(h+p),v=oe(f-$(u*m)),S=$(w*k),E=$(b*v),I=$(w*v),y=$(k*b);return new Sr(S,E,y,I)}subtract(t){return this.add(Tl(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(wr(t,1n,Xi),!n&&this.is0()))return Cr;if(t===1n)return this;if(this.equals(Er))return IS(t).p;let r=Cr,s=Er;for(let o=this;t>0n;o=o.double(),t>>=1n)t&1n?r=r.add(o):n&&(s=s.add(o));return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(this.equals(Cr))return{x:0n,y:1n};let s=gg(r,Qi);$(r*s)!==1n&&ke("invalid inverse");let o=$(t*s),i=$(n*s);return{x:o,y:i}}toBytes(){let{x:t,y:n}=this.toAffine(),r=_g(n);return r[31]|=t&1n?128:0,r}toHex(){return Ul(this.toBytes())}clearCofactor(){return this.multiply(ea(fS),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Xi/2n,!1).double();return Xi%2n&&(t=t.add(this)),t.is0()}},Er=new go(jp,Bp,1n,oe(jp*Bp)),Cr=new go(0n,1n,1n,0n);go.BASE=Er;go.ZERO=Cr;_g=e=>Dl(fg(wr(e,0n,Il),64)).reverse(),bg=e=>ea("0x"+Ul(Ll(nn(e)).reverse())),At=(e,t)=>{let n=e;for(;t-- >0n;)n=$(n*n);return n},bS=e=>{let t=$(e*e),n=$(t*e),r=$(At(n,2n)*n),s=$(At(r,1n)*e),o=$(At(s,5n)*s),i=$(At(o,10n)*o),a=$(At(i,20n)*i),c=$(At(a,40n)*a),l=$(At(c,80n)*c),u=$(At(l,80n)*c),d=$(At(u,10n)*o);return{pow_p_5_8:$(At(d,2n)*e),b2:n}},Vp=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,vS=(e,t)=>{let n=$(t*$(t*t)),r=$($(n*n)*t),s=bS($(e*r)).pow_p_5_8,o=$(e*$(n*s)),i=$(t*$(o*o)),a=o,c=$(o*Vp),l=i===e,u=i===oe(-e),d=i===oe(-e*Vp);return l&&(o=a),(u||d)&&(o=c),(oe(o)&1n)===1n&&(o=oe(-o)),{isValid:l||u,value:o}},$l=e=>pg(bg(e)),jl=(...e)=>Promise.resolve(hg("sha512Async")(us(...e))).then(yg),wS=(...e)=>yg(hg("sha512")(us(...e))),vg=e=>{let t=Ll(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=$l(n),o=Er.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},SS=e=>jl(nn(e,oa)).then(vg),xS=e=>vg(wS(nn(e,oa))),TS=e=>xS(e).pointBytes,kS=e=>jl(e.hashable).then(e.finish),CS=(e,t,n)=>{let{pointBytes:r,scalar:s}=e,o=$l(t),i=Er.multiply(o).toBytes();return{hashable:us(i,r,n),finish:l=>{let u=pg(o+$l(l)*s);return nn(us(i,_g(u)),64)}}},AS=async(e,t)=>{let n=nn(e),r=await SS(t),s=await jl(r.prefix,n);return kS(CS(r,s,n))},Bl=Object.freeze({bytesToHex:Ul,hexToBytes:Dl,concatBytes:us,mod:oe,invert:gg,randomBytes:_S}),wg={sha512Async:async e=>{let t=yS(),n=us(e);return ia(await t.digest("SHA-512",n.buffer))},sha512:void 0},ta=8,ES=256,Sg=Math.ceil(ES/ta)+1,Pl=2**(ta-1),RS=()=>{let e=[],t=Er,n=t;for(let r=0;r<Sg;r++){n=t,e.push(n);for(let s=1;s<Pl;s++)n=n.add(t),e.push(n);t=n.double()}return e},qp=void 0,Kp=(e,t)=>{let n=t.negate();return e?n:t},IS=e=>{let t=qp||(qp=RS()),n=Cr,r=Er,s=2**ta,o=s,i=ea(s-1),a=ea(ta);for(let c=0;c<Sg;c++){let l=Number(e&i);e>>=a,l>Pl&&(l-=o,e+=1n);let u=c*Pl,d=u,m=u+Math.abs(l)-1,f=c%2!==0,p=l<0;l===0?r=r.add(Kp(f,t[d])):n=n.add(Kp(p,t[m]))}return e!==0n&&ke("invalid wnaf"),{p:n,f:r}};kg=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});Cg=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){Gp(this),xg(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){Gp(this),PS(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,po(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()}},On=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Oe=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Ki=BigInt(2**32-1),Wp=BigInt(32);Yp=(e,t,n)=>e>>>n,zp=(e,t,n)=>e<<32-n|t>>>n,is=(e,t,n)=>e>>>n|t<<32-n,as=(e,t,n)=>e<<32-n|t>>>n,Gi=(e,t,n)=>e<<64-n|t>>>n-32,Wi=(e,t,n)=>e>>>n-32|t<<64-n;US=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),DS=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,jS=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),BS=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,FS=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),HS=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,VS=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Mn=new Uint32Array(64),qS=class extends Cg{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:r,E:s,F:o,G:i,H:a}=this;return[e,t,n,r,s,o,i,a]}set(e,t,n,r,s,o,i,a){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=s|0,this.F=o|0,this.G=i|0,this.H=a|0}process(e,t){for(let u=0;u<16;u++,t+=4)Mn[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let d=Mn[u-15],m=Mn[u-2],f=Et(d,7)^Et(d,18)^d>>>3,p=Et(m,17)^Et(m,19)^m>>>10;Mn[u]=p+Mn[u-7]+f+Mn[u-16]|0}let{A:n,B:r,C:s,D:o,E:i,F:a,G:c,H:l}=this;for(let u=0;u<64;u++){let d=Et(i,6)^Et(i,11)^Et(i,25),m=l+d+OS(i,a,c)+VS[u]+Mn[u]|0,p=(Et(n,2)^Et(n,13)^Et(n,22))+MS(n,r,s)|0;l=c,c=a,a=i,i=o+m|0,o=s,s=r,r=n,n=m+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(){po(Mn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),po(this.buffer)}},KS=class extends qS{A=On[0]|0;B=On[1]|0;C=On[2]|0;D=On[3]|0;E=On[4]|0;F=On[5]|0;G=On[6]|0;H=On[7]|0;constructor(){super(32)}},Ag=LS(["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))),GS=Ag[0],WS=Ag[1],Nn=new Uint32Array(80),Ln=new Uint32Array(80),YS=class extends Cg{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:m,Gl:f,Hh:p,Hl:h}=this;return[e,t,n,r,s,o,i,a,c,l,u,d,m,f,p,h]}set(e,t,n,r,s,o,i,a,c,l,u,d,m,f,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=m|0,this.Gl=f|0,this.Hh=p|0,this.Hl=h|0}process(e,t){for(let b=0;b<16;b++,t+=4)Nn[b]=e.getUint32(t),Ln[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let v=Nn[b-15]|0,S=Ln[b-15]|0,E=is(v,S,1)^is(v,S,8)^Yp(v,S,7),I=as(v,S,1)^as(v,S,8)^zp(v,S,7),y=Nn[b-2]|0,T=Ln[b-2]|0,z=is(y,T,19)^Gi(y,T,61)^Yp(y,T,6),Z=as(y,T,19)^Wi(y,T,61)^zp(y,T,6),H=jS(I,Z,Ln[b-7],Ln[b-16]),be=BS(H,E,z,Nn[b-7],Nn[b-16]);Nn[b]=be|0,Ln[b]=H|0}let{Ah:n,Al:r,Bh:s,Bl:o,Ch:i,Cl:a,Dh:c,Dl:l,Eh:u,El:d,Fh:m,Fl:f,Gh:p,Gl:h,Hh:w,Hl:k}=this;for(let b=0;b<80;b++){let v=is(u,d,14)^is(u,d,18)^Gi(u,d,41),S=as(u,d,14)^as(u,d,18)^Wi(u,d,41),E=u&m^~u&p,I=d&f^~d&h,y=FS(k,S,I,WS[b],Ln[b]),T=HS(y,w,v,E,GS[b],Nn[b]),z=y|0,Z=is(n,r,28)^Gi(n,r,34)^Gi(n,r,39),H=as(n,r,28)^Wi(n,r,34)^Wi(n,r,39),be=n&s^n&i^s&i,se=r&o^r&a^o&a;w=p|0,k=h|0,p=m|0,h=f|0,m=u|0,f=d|0,{h:u,l:d}=Qt(c|0,l|0,T|0,z|0),c=i|0,l=a|0,i=s|0,a=o|0,s=n|0,o=r|0;let X=US(z,H,se);n=DS(X,T,Z,be),r=X|0}({h:n,l:r}=Qt(this.Ah|0,this.Al|0,n|0,r|0)),{h:s,l:o}=Qt(this.Bh|0,this.Bl|0,s|0,o|0),{h:i,l:a}=Qt(this.Ch|0,this.Cl|0,i|0,a|0),{h:c,l}=Qt(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=Qt(this.Eh|0,this.El|0,u|0,d|0),{h:m,l:f}=Qt(this.Fh|0,this.Fl|0,m|0,f|0),{h:p,l:h}=Qt(this.Gh|0,this.Gl|0,p|0,h|0),{h:w,l:k}=Qt(this.Hh|0,this.Hl|0,w|0,k|0),this.set(n,r,s,o,i,a,c,l,u,d,m,f,p,h,w,k)}roundClean(){po(Nn,Ln)}destroy(){this.destroyed=!0,po(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},zS=class extends YS{Ah=Oe[0]|0;Al=Oe[1]|0;Bh=Oe[2]|0;Bl=Oe[3]|0;Ch=Oe[4]|0;Cl=Oe[5]|0;Dh=Oe[6]|0;Dl=Oe[7]|0;Eh=Oe[8]|0;El=Oe[9]|0;Fh=Oe[10]|0;Fl=Oe[11]|0;Gh=Oe[12]|0;Gl=Oe[13]|0;Hh=Oe[14]|0;Hl=Oe[15]|0;constructor(){super(64)}},JS=Tg(()=>new KS,kg(1)),XS=Tg(()=>new zS,kg(3)),Jp=wg;Jp.sha512||(Jp.sha512=e=>XS(e));ex=Bl.bytesToHex,Eg=Bl.hexToBytes;Bl.concatBytes;nx=new TextEncoder,rx={subwayAgentMsgV1:"message_id;sender_peer_id;sender_name;timestamp_ms;message_type;payload_hash;nonce"};Eg("302e020100300506032b657004220420");Eg("302a300506032b6570032100");Rg=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:na,n:Zi,Gx:Xp,Gy:Zp,a:Cl,d:Al,h:ax}=Rg,ds=32,cx=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},Ce=(e="")=>{let t=new Error(e);throw cx(t,Ce),t},lx=e=>typeof e=="bigint",ux=e=>typeof e=="string",dx=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,Bn=(e,t,n="")=>{let r=dx(e),s=e?.length,o=t!==void 0;if(!r||o&&s!==t){let i=n&&`"${n}" `,a=o?` of length ${t}`:"",c=r?`length=${s}`:`type=${typeof e}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):new TypeError(l)}return e},aa=e=>new Uint8Array(e),Fl=e=>Uint8Array.from(e),Ig=(e,t)=>e.toString(16).padStart(t,"0"),$g=e=>Array.from(Bn(e)).map(t=>Ig(t,2)).join(""),en={_0:48,_9:57,A:65,F:70,a:97,f:102},Qp=e=>{if(e>=en._0&&e<=en._9)return e-en._0;if(e>=en.A&&e<=en.F)return e-(en.A-10);if(e>=en.a&&e<=en.f)return e-(en.a-10)},Pg=e=>{let t="hex invalid";if(!ux(e))return Ce(t);let n=e.length,r=n/2;if(n%2)return Ce(t);let s=aa(r);for(let o=0,i=0;o<r;o++,i+=2){let a=Qp(e.charCodeAt(i)),c=Qp(e.charCodeAt(i+1));if(a===void 0||c===void 0)return Ce(t);s[o]=a*16+c}return s},Og=()=>globalThis?.crypto,fx=()=>Og()?.subtle??Ce("crypto.subtle must be defined, consider polyfill"),Hl=(...e)=>{let t=0;for(let s of e)t+=Bn(s).length;let n=aa(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},mx=(e=ds)=>Og().getRandomValues(aa(e)),ra=BigInt,xr=(e,t,n,r="bad number: out of range")=>{if(!lx(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},ae=(e,t=na)=>{let n=e%t;return n>=0n?n:t+n},eg=(1n<<255n)-1n,P=e=>{e<0n&&Ce("negative coordinate");let t=(e>>255n)*19n+(e&eg);return t=(t>>255n)*19n+(t&eg),t%na},px=e=>ae(e,Zi),gx=(e,t)=>{(e===0n||t<=0n)&&Ce("no inverse n="+e+" mod="+t);let n=ae(e,t),r=t,s=0n,o=1n;for(;n!==0n;){let i=r/n,a=r%n,c=s-o*i;r=n,n=a,s=o,o=c}return r===1n?ae(s,t):Ce("no inverse")},Mg=e=>{let t=jg[e];return typeof t!="function"&&Ce("hashes."+e+" not set"),t},Ng=e=>Bn(e,64,"digest"),El=e=>e instanceof ho?e:Ce("Point expected"),Ol=2n**256n,ho=class Tr{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=Ol;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 Rg}static fromAffine(t){return new Tr(t.x,t.y,1n,P(t.x*t.y))}static fromBytes(t,n=!1){let r=Al,s=Fl(Bn(t,ds)),o=t[31];s[31]=o&-129;let i=Lg(s);xr(i,0n,n?Ol:na);let c=P(i*i),l=ae(c-1n),u=P(r*c+1n),{isValid:d,value:m}=_x(l,u);d||Ce("bad point: y not sqrt");let f=(m&1n)===1n,p=(o&128)!==0;return!n&&m===0n&&p&&Ce("bad point: x==0, isLastByteOdd"),p!==f&&(m=ae(-m)),new Tr(m,i,1n,P(m*i))}static fromHex(t,n){return Tr.fromBytes(Pg(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Cl,n=Al,r=this;if(r.is0())return Ce("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),m=P(c*t),f=P(u*(m+l)),p=ae(d+P(n*P(c*l)));if(f!==p)return Ce("bad point: equation left != right (1)");let h=P(s*o),w=P(i*a);return h!==w?Ce("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=El(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(Ar)}negate(){return new Tr(ae(-this.X),this.Y,this.Z,ae(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=Cl,o=P(t*t),i=P(n*n),a=P(2n*r*r),c=P(s*o),l=ae(t+n),u=ae(P(l*l)-o-i),d=ae(c+i),m=ae(d-a),f=ae(c-i),p=P(u*m),h=P(d*f),w=P(u*f),k=P(m*d);return new Tr(p,h,k,w)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=El(t),u=Cl,d=Al,m=P(n*i),f=P(r*a),p=P(P(o*d)*l),h=P(s*c),w=ae(P(ae(n+r)*ae(i+a))-m-f),k=ae(h-p),b=ae(h+p),v=ae(f-P(u*m)),S=P(w*k),E=P(b*v),I=P(w*v),y=P(k*b);return new Tr(S,E,y,I)}subtract(t){return this.add(El(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(xr(t,1n,Zi),!n&&this.is0()))return Ar;if(t===1n)return this;if(this.equals(fs))return Ex(t).p;let r=Ar,s=fs;for(let o=this;t>0n;o=o.double(),t>>=1n)t&1n?r=r.add(o):n&&(s=s.add(o));return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(this.equals(Ar))return{x:0n,y:1n};let s=gx(r,na);P(r*s)!==1n&&Ce("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=hx(n);return r[31]|=t&1n?128:0,r}toHex(){return $g(this.toBytes())}clearCofactor(){return this.multiply(ra(ax),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Zi/2n,!1).double();return Zi%2n&&(t=t.add(this)),t.is0()}},fs=new ho(Xp,Zp,1n,ae(Xp*Zp)),Ar=new ho(0n,1n,1n,0n);ho.BASE=fs;ho.ZERO=Ar;hx=e=>Pg(Ig(xr(e,0n,Ol),64)).reverse(),Lg=e=>ra("0x"+$g(Fl(Bn(e)).reverse())),Rt=(e,t)=>{let n=e;for(;t-- >0n;)n=P(n*n);return n},yx=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}},tg=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,_x=(e,t)=>{let n=P(t*P(t*t)),r=P(P(n*n)*t),s=yx(P(e*r)).pow_p_5_8,o=P(e*P(n*s)),i=P(t*P(o*o)),a=o,c=P(o*tg),l=i===e,u=i===ae(-e),d=i===ae(-e*tg);return l&&(o=a),(u||d)&&(o=c),(ae(o)&1n)===1n&&(o=ae(-o)),{isValid:l||u,value:o}},bx=e=>px(Lg(e)),vx=(...e)=>Promise.resolve(Mg("sha512Async")(Hl(...e))).then(Ng),wx=(...e)=>Ng(Mg("sha512")(Hl(...e))),Ug=e=>{let t=Fl(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),s=bx(n),o=fs.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},Sx=e=>vx(Bn(e,ds)).then(Ug),Dg=e=>Ug(wx(Bn(e,ds))),xx=e=>Dg(e).pointBytes,jg={sha512Async:async e=>{let t=fx(),n=Hl(e);return aa(await t.digest("SHA-512",n.buffer))},sha512:void 0},Tx=e=>(e=e===void 0?mx(ds):e,Bn(e,ds)),kx=Object.freeze({getExtendedPublicKeyAsync:Sx,getExtendedPublicKey:Dg,randomSecretKey:Tx}),sa=8,Cx=256,Bg=Math.ceil(Cx/sa)+1,Ml=2**(sa-1),Ax=()=>{let e=[],t=fs,n=t;for(let r=0;r<Bg;r++){n=t,e.push(n);for(let s=1;s<Ml;s++)n=n.add(t),e.push(n);t=n.double()}return e},ng=void 0,rg=(e,t)=>{let n=t.negate();return e?n:t},Ex=e=>{let t=ng||(ng=Ax()),n=Ar,r=fs,s=2**sa,o=s,i=ra(s-1),a=ra(sa);for(let c=0;c<Bg;c++){let l=Number(e&i);e>>=a,l>Ml&&(l-=o,e+=1n);let u=c*Ml,d=u,m=u+Math.abs(l)-1,f=c%2!==0,p=l<0;l===0?r=r.add(rg(f,t[d])):n=n.add(rg(p,t[m]))}return e!==0n&&Ce("invalid wnaf"),{p:n,f:r}};Px=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),Ox=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=Rl(this.buffer)}update(e){sg(this),Fg(e);let{view:t,buffer:n,blockLen:r}=this,s=e.length;for(let o=0;o<s;){let i=Math.min(r-this.pos,s-o);if(i===r){let a=Rl(e);for(;r<=s-o;o+=r)this.process(a,o);continue}n.set(e.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){sg(this),Ix(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:s}=this,{pos:o}=this;t[o++]=128,Nl(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=Rl(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<c;u++)i.setUint32(4*u,l[u],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:s,destroyed:o,pos:i}=this;return e.destroyed=o,e.finished=s,e.length=r,e.pos=i,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Me=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Yi=BigInt(2**32-1),og=BigInt(32);ig=(e,t,n)=>e>>>n,ag=(e,t,n)=>e<<32-n|t>>>n,cs=(e,t,n)=>e>>>n|t<<32-n,ls=(e,t,n)=>e<<32-n|t>>>n,zi=(e,t,n)=>e<<64-n|t>>>n-32,Ji=(e,t,n)=>e>>>n-32|t<<64-n;Lx=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Ux=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Dx=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),jx=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,Bx=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),Fx=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,Hg=Nx(["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))),Hx=Hg[0],Vx=Hg[1],Un=new Uint32Array(80),Dn=new Uint32Array(80),qx=class extends Ox{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:m,Gl:f,Hh:p,Hl:h}=this;return[e,t,n,r,s,o,i,a,c,l,u,d,m,f,p,h]}set(e,t,n,r,s,o,i,a,c,l,u,d,m,f,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=m|0,this.Gl=f|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 v=Un[b-15]|0,S=Dn[b-15]|0,E=cs(v,S,1)^cs(v,S,8)^ig(v,S,7),I=ls(v,S,1)^ls(v,S,8)^ag(v,S,7),y=Un[b-2]|0,T=Dn[b-2]|0,z=cs(y,T,19)^zi(y,T,61)^ig(y,T,6),Z=ls(y,T,19)^Ji(y,T,61)^ag(y,T,6),H=Dx(I,Z,Dn[b-7],Dn[b-16]),be=jx(H,E,z,Un[b-7],Un[b-16]);Un[b]=be|0,Dn[b]=H|0}let{Ah:n,Al:r,Bh:s,Bl:o,Ch:i,Cl:a,Dh:c,Dl:l,Eh:u,El:d,Fh:m,Fl:f,Gh:p,Gl:h,Hh:w,Hl:k}=this;for(let b=0;b<80;b++){let v=cs(u,d,14)^cs(u,d,18)^zi(u,d,41),S=ls(u,d,14)^ls(u,d,18)^Ji(u,d,41),E=u&m^~u&p,I=d&f^~d&h,y=Bx(k,S,I,Vx[b],Dn[b]),T=Fx(y,w,v,E,Hx[b],Un[b]),z=y|0,Z=cs(n,r,28)^zi(n,r,34)^zi(n,r,39),H=ls(n,r,28)^Ji(n,r,34)^Ji(n,r,39),be=n&s^n&i^s&i,se=r&o^r&a^o&a;w=p|0,k=h|0,p=m|0,h=f|0,m=u|0,f=d|0,{h:u,l:d}=tn(c|0,l|0,T|0,z|0),c=i|0,l=a|0,i=s|0,a=o|0,s=n|0,o=r|0;let X=Lx(z,H,se);n=Ux(X,T,Z,be),r=X|0}({h:n,l:r}=tn(this.Ah|0,this.Al|0,n|0,r|0)),{h:s,l:o}=tn(this.Bh|0,this.Bl|0,s|0,o|0),{h:i,l:a}=tn(this.Ch|0,this.Cl|0,i|0,a|0),{h:c,l}=tn(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=tn(this.Eh|0,this.El|0,u|0,d|0),{h:m,l:f}=tn(this.Fh|0,this.Fl|0,m|0,f|0),{h:p,l:h}=tn(this.Gh|0,this.Gl|0,p|0,h|0),{h:w,l:k}=tn(this.Hh|0,this.Hl|0,w|0,k|0),this.set(n,r,s,o,i,a,c,l,u,d,m,f,p,h,w,k)}roundClean(){Nl(Un,Dn)}destroy(){this.destroyed=!0,Nl(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Kx=class extends qx{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)}},Gx=$x(()=>new Kx,Px(3)),cg=jg;cg.sha512||(cg.sha512=e=>Gx(e));Zx="ws://localhost:9001/ws",Qx=3e4,qg=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=Jx(e.keyPath)}catch{}this.options={name:this._name,url:e.url??Zx,relay:e.relay??"",autoReconnect:e.autoReconnect??!0,reconnectInterval:e.reconnectInterval??1e3,maxReconnectAttempts:e.maxReconnectAttempts??10,rpcTimeout:e.rpcTimeout??Qx,pingInterval:e.pingInterval??3e4,binding:e.binding??""},this.transport=new dS({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=ix(new Uint8Array(t));n&&(this._keypair={privateKey:n,publicKey:ZS(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=lg(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 Pe(String(r)))}})}disconnect(){for(let[,e]of this.pendingCalls)clearTimeout(e.timer),e.reject(new Pe("Client disconnected"));this.pendingCalls.clear();for(let[,e]of this.pendingSend)e.reject(new Pe("Client disconnected"));this.pendingSend.clear();for(let[,e]of this.pendingResolve)e.reject(new Pe("Client disconnected"));this.pendingResolve.clear(),this.registerPromise&&(this.registerPromise.reject(new Pe("Client disconnected")),this.registerPromise=null),this.transport.disconnect(),this._peerId=null,this.hasConnectedOnce=!1}async send(e,t,n,r){let s=kr(e),o=wl();return new Promise((i,a)=>{this.pendingSend.set(s,{resolve:i,reject:a});try{this.transport.send({type:"send",to:s,message_type:t,payload:n,metadata:r})}catch(c){this.pendingSend.delete(s),a(c instanceof Error?c:new Pe(String(c)))}setTimeout(()=>{this.pendingSend.has(s)&&(this.pendingSend.delete(s),i({messageId:o,to:s}))},5e3)})}async sendSigned(e,t,n,r){if(!this._keypair||!this._peerId)return this.send(e,t,n,r);let s=kr(e),o=wl(),i=Date.now(),a=Math.floor(Math.random()*2**32),c=new TextEncoder().encode(n),{signature:l,signatureInput:u}=await Xx(this._keypair.privateKey,o,this._peerId,this._name,i,t,c,a);return new Promise((d,m)=>{this.pendingSend.set(s,{resolve:d,reject:m});try{this.transport.send({type:"send_signed",to:s,message_id:o,sender_peer_id:this._peerId,sender_name:this._name,timestamp_ms:i,message_type:t,payload:n,metadata:r,signature:Buffer.from(l).toString("base64"),signature_input:u,nonce:a})}catch(f){this.pendingSend.delete(s),m(f instanceof Error?f:new Pe(String(f)))}setTimeout(()=>{this.pendingSend.has(s)&&(this.pendingSend.delete(s),d({messageId:o,to:s}))},5e3)})}async call(e,t,n,r){let s=kr(e),o=r?.correlationId??wl(),i=r?.timeout??this.options.rpcTimeout;return new Promise((a,c)=>{let l=setTimeout(()=>{this.pendingCalls.delete(o),c(new mo(`RPC call to ${s}.${t} timed out after ${i}ms`))},i);this.pendingCalls.set(o,{resolve:a,reject:c,timer:l});try{this.transport.send({type:"call",to:s,method:t,payload:n??"",correlation_id:o})}catch(u){clearTimeout(l),this.pendingCalls.delete(o),c(u instanceof Error?u:new Pe(String(u)))}})}async broadcast(e,t,n){this.transport.send({type:"broadcast",topic:e,message_type:t,payload:n})}subscribe(e,t){let n=this.topicHandlers.get(e);if(!n){n=new Set,this.topicHandlers.set(e,n);try{this.transport.send({type:"subscribe",topic:e})}catch{}}return n.add(t),()=>{n.delete(t),n.size===0&&this.topicHandlers.delete(e)}}onMessage(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}onCall(e,t){return this.rpcHandlers.set(e,t),()=>this.rpcHandlers.delete(e)}onAnyCall(e){return this.defaultRpcHandler=e,()=>{this.defaultRpcHandler=null}}async resolve(e){let t=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 Pe(String(s)))}setTimeout(()=>{this.pendingResolve.has(t)&&(this.pendingResolve.delete(t),r(new mo(`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=bl(e.code,e.message);this.registerPromise&&e.code==="register_failed"&&(this.registerPromise.reject(new qi(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=lg(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 bT(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function hh(e,t,n=""){let r=bT(e),s=e?.length,o=t!==void 0;if(!r||o&&s!==t){let i=n&&`"${n}" `,a=o?` of length ${t}`:"",c=r?`length=${s}`:`type=${typeof e}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):new TypeError(l)}return e}function Zg(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 vT(e,t){hh(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 Wl(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function wT(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 TT(e,t=!1){return t?{h:Number(e&ca),l:Number(e>>Qg&ca)}:{h:Number(e>>Qg&ca)|0,l:Number(e&ca)|0}}function kT(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}=TT(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 UT(){return gT.randomSecretKey()}function ha(e){return uT(e)}function _h(){let e=UT();return{secretKey:e,publicKey:ha(e)}}function _o(e,t){return mT(t,e)}function DT(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function jT(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 ys(e){return DT(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function BT(e){let t=e.length%4===0?0:4-e.length%4,n=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return jT(n)}function FT(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function vh(e){let t=ha(e);return{kty:"OKP",crv:"Ed25519",x:ys(t),d:ys(e)}}function wh(e){return{kty:"OKP",crv:"Ed25519",x:ys(e)}}function bo(e){if(FT(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return BT(e.d)}var rh,fa,da,Kg,Gg,ql,Kl,eT,gs,tT,Ae,nT,rT,sT,$t,ga,Zl,sh,Ql,rn,Wg,eu,oh,oT,hs,ih,ma,Rr,ie,Yg,O,ah,ch,lh,uh,Gl,Yl,yo,Pr,$r,dh,fh,It,iT,zg,aT,zl,cT,tu,mh,lT,nu,uT,dT,fT,mT,ru,ph,pT,gT,pa,hT,gh,Jl,yT,Jg,Xg,_T,ST,xT,Ne,ca,Qg,eh,th,ms,ps,la,ua,CT,AT,ET,RT,IT,$T,yh,PT,OT,Fn,Hn,MT,NT,LT,nh,t2,bh,n2,r2,s2,o2,ya=Lt(()=>{"use strict";rh=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:fa,n:da,Gx:Kg,Gy:Gg,a:ql,d:Kl,h:eT}=rh,gs=32,tT=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},Ae=(e="")=>{let t=new Error(e);throw tT(t,Ae),t},nT=e=>typeof e=="bigint",rT=e=>typeof e=="string",sT=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,$t=(e,t,n="")=>{let r=sT(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},ga=e=>new Uint8Array(e),Zl=e=>Uint8Array.from(e),sh=(e,t)=>e.toString(16).padStart(t,"0"),Ql=e=>Array.from($t(e)).map(t=>sh(t,2)).join(""),rn={_0:48,_9:57,A:65,F:70,a:97,f:102},Wg=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)},eu=e=>{let t="hex invalid";if(!rT(e))return Ae(t);let n=e.length,r=n/2;if(n%2)return Ae(t);let s=ga(r);for(let o=0,i=0;o<r;o++,i+=2){let a=Wg(e.charCodeAt(i)),c=Wg(e.charCodeAt(i+1));if(a===void 0||c===void 0)return Ae(t);s[o]=a*16+c}return s},oh=()=>globalThis?.crypto,oT=()=>oh()?.subtle??Ae("crypto.subtle must be defined, consider polyfill"),hs=(...e)=>{let t=0;for(let s of e)t+=$t(s).length;let n=ga(t),r=0;return e.forEach(s=>{n.set(s,r),r+=s.length}),n},ih=(e=gs)=>oh().getRandomValues(ga(e)),ma=BigInt,Rr=(e,t,n,r="bad number: out of range")=>{if(!nT(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},ie=(e,t=fa)=>{let n=e%t;return n>=0n?n:t+n},Yg=(1n<<255n)-1n,O=e=>{e<0n&&Ae("negative coordinate");let t=(e>>255n)*19n+(e&Yg);return t=(t>>255n)*19n+(t&Yg),t%fa},ah=e=>ie(e,da),ch=(e,t)=>{(e===0n||t<=0n)&&Ae("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):Ae("no inverse")},lh=e=>{let t=ph[e];return typeof t!="function"&&Ae("hashes."+e+" not set"),t},uh=e=>$t(e,64,"digest"),Gl=e=>e instanceof yo?e:Ae("Point expected"),Yl=2n**256n,yo=class Ir{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,s){let o=Yl;this.X=Rr(t,0n,o),this.Y=Rr(n,0n,o),this.Z=Rr(r,1n,o),this.T=Rr(s,0n,o),Object.freeze(this)}static CURVE(){return rh}static fromAffine(t){return new Ir(t.x,t.y,1n,O(t.x*t.y))}static fromBytes(t,n=!1){let r=Kl,s=Zl($t(t,gs)),o=t[31];s[31]=o&-129;let i=fh(s);Rr(i,0n,n?Yl:fa);let c=O(i*i),l=ie(c-1n),u=O(r*c+1n),{isValid:d,value:m}=aT(l,u);d||Ae("bad point: y not sqrt");let f=(m&1n)===1n,p=(o&128)!==0;return!n&&m===0n&&p&&Ae("bad point: x==0, isLastByteOdd"),p!==f&&(m=ie(-m)),new Ir(m,i,1n,O(m*i))}static fromHex(t,n){return Ir.fromBytes(eu(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=ql,n=Kl,r=this;if(r.is0())return Ae("bad point: ZERO");let{X:s,Y:o,Z:i,T:a}=r,c=O(s*s),l=O(o*o),u=O(i*i),d=O(u*u),m=O(c*t),f=O(u*(m+l)),p=ie(d+O(n*O(c*l)));if(f!==p)return Ae("bad point: equation left != right (1)");let h=O(s*o),w=O(i*a);return h!==w?Ae("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:s}=this,{X:o,Y:i,Z:a}=Gl(t),c=O(n*a),l=O(o*s),u=O(r*a),d=O(i*s);return c===l&&u===d}is0(){return this.equals($r)}negate(){return new Ir(ie(-this.X),this.Y,this.Z,ie(-this.T))}double(){let{X:t,Y:n,Z:r}=this,s=ql,o=O(t*t),i=O(n*n),a=O(2n*r*r),c=O(s*o),l=ie(t+n),u=ie(O(l*l)-o-i),d=ie(c+i),m=ie(d-a),f=ie(c-i),p=O(u*m),h=O(d*f),w=O(u*f),k=O(m*d);return new Ir(p,h,k,w)}add(t){let{X:n,Y:r,Z:s,T:o}=this,{X:i,Y:a,Z:c,T:l}=Gl(t),u=ql,d=Kl,m=O(n*i),f=O(r*a),p=O(O(o*d)*l),h=O(s*c),w=ie(O(ie(n+r)*ie(i+a))-m-f),k=ie(h-p),b=ie(h+p),v=ie(f-O(u*m)),S=O(w*k),E=O(b*v),I=O(w*v),y=O(k*b);return new Ir(S,E,y,I)}subtract(t){return this.add(Gl(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(Rr(t,1n,da),!n&&this.is0()))return $r;if(t===1n)return this;if(this.equals(Pr))return _T(t).p;let r=$r,s=Pr;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($r))return{x:0n,y:1n};let s=ch(r,fa);O(r*s)!==1n&&Ae("invalid inverse");let o=O(t*s),i=O(n*s);return{x:o,y:i}}toBytes(){let{x:t,y:n}=this.toAffine(),r=dh(n);return r[31]|=t&1n?128:0,r}toHex(){return Ql(this.toBytes())}clearCofactor(){return this.multiply(ma(eT),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(da/2n,!1).double();return da%2n&&(t=t.add(this)),t.is0()}},Pr=new yo(Kg,Gg,1n,ie(Kg*Gg)),$r=new yo(0n,1n,1n,0n);yo.BASE=Pr;yo.ZERO=$r;dh=e=>eu(sh(Rr(e,0n,Yl),64)).reverse(),fh=e=>ma("0x"+Ql(Zl($t(e)).reverse())),It=(e,t)=>{let n=e;for(;t-- >0n;)n=O(n*n);return n},iT=e=>{let t=O(e*e),n=O(t*e),r=O(It(n,2n)*n),s=O(It(r,1n)*e),o=O(It(s,5n)*s),i=O(It(o,10n)*o),a=O(It(i,20n)*i),c=O(It(a,40n)*a),l=O(It(c,80n)*c),u=O(It(l,80n)*c),d=O(It(u,10n)*o);return{pow_p_5_8:O(It(d,2n)*e),b2:n}},zg=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,aT=(e,t)=>{let n=O(t*O(t*t)),r=O(O(n*n)*t),s=iT(O(e*r)).pow_p_5_8,o=O(e*O(n*s)),i=O(t*O(o*o)),a=o,c=O(o*zg),l=i===e,u=i===ie(-e),d=i===ie(-e*zg);return l&&(o=a),(u||d)&&(o=c),(ie(o)&1n)===1n&&(o=ie(-o)),{isValid:l||u,value:o}},zl=e=>ah(fh(e)),cT=(...e)=>Promise.resolve(lh("sha512Async")(hs(...e))).then(uh),tu=(...e)=>uh(lh("sha512")(hs(...e))),mh=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=zl(n),o=Pr.multiply(s),i=o.toBytes();return{head:n,prefix:r,scalar:s,point:o,pointBytes:i}},lT=e=>cT($t(e,gs)).then(mh),nu=e=>mh(tu($t(e,gs))),uT=e=>nu(e).pointBytes,dT=e=>e.finish(tu(e.hashable)),fT=(e,t,n)=>{let{pointBytes:r,scalar:s}=e,o=zl(t),i=Pr.multiply(o).toBytes();return{hashable:hs(i,r,n),finish:l=>{let u=ah(o+zl(l)*s);return $t(hs(i,dh(u)),64)}}},mT=(e,t)=>{let n=$t(e),r=nu(t),s=tu(r.prefix,n);return dT(fT(r,s,n))},ru=Object.freeze({bytesToHex:Ql,hexToBytes:eu,concatBytes:hs,mod:ie,invert:ch,randomBytes:ih}),ph={sha512Async:async e=>{let t=oT(),n=hs(e);return ga(await t.digest("SHA-512",n.buffer))},sha512:void 0},pT=e=>(e=e===void 0?ih(gs):e,$t(e,gs)),gT=Object.freeze({getExtendedPublicKeyAsync:lT,getExtendedPublicKey:nu,randomSecretKey:pT}),pa=8,hT=256,gh=Math.ceil(hT/pa)+1,Jl=2**(pa-1),yT=()=>{let e=[],t=Pr,n=t;for(let r=0;r<gh;r++){n=t,e.push(n);for(let s=1;s<Jl;s++)n=n.add(t),e.push(n);t=n.double()}return e},Jg=void 0,Xg=(e,t)=>{let n=t.negate();return e?n:t},_T=e=>{let t=Jg||(Jg=yT()),n=$r,r=Pr,s=2**pa,o=s,i=ma(s-1),a=ma(pa);for(let c=0;c<gh;c++){let l=Number(e&i);e>>=a,l>Jl&&(l-=o,e+=1n);let u=c*Jl,d=u,m=u+Math.abs(l)-1,f=c%2!==0,p=l<0;l===0?r=r.add(Xg(f,t[d])):n=n.add(Xg(p,t[m]))}return e!==0n&&Ae("invalid wnaf"),{p:n,f:r}};ST=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),xT=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=Wl(this.buffer)}update(e){Zg(this),hh(e);let{view:t,buffer:n,blockLen:r}=this,s=e.length;for(let o=0;o<s;){let i=Math.min(r-this.pos,s-o);if(i===r){let a=Wl(e);for(;r<=s-o;o+=r)this.process(a,o);continue}n.set(e.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Zg(this),vT(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=Wl(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<c;u++)i.setUint32(4*u,l[u],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:s,destroyed:o,pos:i}=this;return e.destroyed=o,e.finished=s,e.length=r,e.pos=i,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Ne=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),ca=BigInt(2**32-1),Qg=BigInt(32);eh=(e,t,n)=>e>>>n,th=(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,la=(e,t,n)=>e<<64-n|t>>>n-32,ua=(e,t,n)=>e>>>n-32|t<<64-n;CT=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),AT=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,ET=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),RT=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0,IT=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0),$T=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0,yh=kT(["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))),PT=yh[0],OT=yh[1],Fn=new Uint32Array(80),Hn=new Uint32Array(80),MT=class extends xT{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:m,Gl:f,Hh:p,Hl:h}=this;return[e,t,n,r,s,o,i,a,c,l,u,d,m,f,p,h]}set(e,t,n,r,s,o,i,a,c,l,u,d,m,f,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=m|0,this.Gl=f|0,this.Hh=p|0,this.Hl=h|0}process(e,t){for(let b=0;b<16;b++,t+=4)Fn[b]=e.getUint32(t),Hn[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let v=Fn[b-15]|0,S=Hn[b-15]|0,E=ms(v,S,1)^ms(v,S,8)^eh(v,S,7),I=ps(v,S,1)^ps(v,S,8)^th(v,S,7),y=Fn[b-2]|0,T=Hn[b-2]|0,z=ms(y,T,19)^la(y,T,61)^eh(y,T,6),Z=ps(y,T,19)^ua(y,T,61)^th(y,T,6),H=ET(I,Z,Hn[b-7],Hn[b-16]),be=RT(H,E,z,Fn[b-7],Fn[b-16]);Fn[b]=be|0,Hn[b]=H|0}let{Ah:n,Al:r,Bh:s,Bl:o,Ch:i,Cl:a,Dh:c,Dl:l,Eh:u,El:d,Fh:m,Fl:f,Gh:p,Gl:h,Hh:w,Hl:k}=this;for(let b=0;b<80;b++){let v=ms(u,d,14)^ms(u,d,18)^la(u,d,41),S=ps(u,d,14)^ps(u,d,18)^ua(u,d,41),E=u&m^~u&p,I=d&f^~d&h,y=IT(k,S,I,OT[b],Hn[b]),T=$T(y,w,v,E,PT[b],Fn[b]),z=y|0,Z=ms(n,r,28)^la(n,r,34)^la(n,r,39),H=ps(n,r,28)^ua(n,r,34)^ua(n,r,39),be=n&s^n&i^s&i,se=r&o^r&a^o&a;w=p|0,k=h|0,p=m|0,h=f|0,m=u|0,f=d|0,{h:u,l:d}=sn(c|0,l|0,T|0,z|0),c=i|0,l=a|0,i=s|0,a=o|0,s=n|0,o=r|0;let X=CT(z,H,se);n=AT(X,T,Z,be),r=X|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:m,l:f}=sn(this.Fh|0,this.Fl|0,m|0,f|0),{h:p,l:h}=sn(this.Gh|0,this.Gl|0,p|0,h|0),{h:w,l:k}=sn(this.Hh|0,this.Hl|0,w|0,k|0),this.set(n,r,s,o,i,a,c,l,u,d,m,f,p,h,w,k)}roundClean(){Xl(Fn,Hn)}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)}},NT=class extends MT{Ah=Ne[0]|0;Al=Ne[1]|0;Bh=Ne[2]|0;Bl=Ne[3]|0;Ch=Ne[4]|0;Cl=Ne[5]|0;Dh=Ne[6]|0;Dl=Ne[7]|0;Eh=Ne[8]|0;El=Ne[9]|0;Fh=Ne[10]|0;Fl=Ne[11]|0;Gh=Ne[12]|0;Gl=Ne[13]|0;Hh=Ne[14]|0;Hl=Ne[15]|0;constructor(){super(64)}},LT=wT(()=>new NT,ST(3)),nh=ph;nh.sha512||(nh.sha512=e=>LT(e));t2=ru.bytesToHex,bh=ru.hexToBytes,n2=ru.concatBytes;r2=new TextEncoder;s2=bh("302e020100300506032b657004220420"),o2=bh("302a300506032b6570032100");});function HT(e){let t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return Sh.createHash("sha256").update(t,"utf8").digest("base64url")}function VT(e,t,n){return`visa-agent-binding:v1:${e}:${t}:${n}`}function qT(e,t,n="visa",r=Math.floor(Date.now()/1e3)){let s=wh(ha(e)),o=Buffer.from(VT(t,HT(s),r),"utf8"),i=Buffer.from(_o(e,o)).toString("base64url");return{name:t,mesh:n,agent_pubkey:s,proof:{ts:r,sig:i}}}async function Th(e){let t=qT(e.seed,e.name,e.mesh??"visa",e.nowSec),n=e.fetchImpl??fetch,r=`${e.authUrl.replace(/\/+$/,"")}/v2/harness/agents`,s=await n(r,{method:"POST",headers:{"content-type":"application/json","x-api-key":e.apiKey},body:JSON.stringify(t)});if(!s.ok){let o="";try{o=(await s.json())?.error??""}catch{}throw new Error(`Visa binding issuance failed (${s.status})${o?`: ${o}`:""}`)}return await s.json()}function kh(e){return new Uint8Array(xh.readFileSync(e))}var Sh,xh,Ch=Lt(()=>{"use strict";Sh=R(require("crypto")),xh=R(require("fs"));ya()});var wa={};jo(wa,{MESH:()=>Xe,RELAY_URL:()=>wo,connectOrThrow:()=>ws,ensureMailbox:()=>fu,isSubwayEnabled:()=>iu,listRegistered:()=>du,loadBindingFor:()=>cu,loadRegistry:()=>_s,makeClient:()=>vs,maybeMintVisaBinding:()=>$h,meshName:()=>Pt,readInbox:()=>WT,registerName:()=>lu,resolveActingName:()=>va,seedSubwayKeyFromTapAgent:()=>Ih,sendMessage:()=>uu,sendVia:()=>YT,subwayKeyPath:()=>ba});function Pt(e){return e.includes(".")?e:`${e}.${Xe}`}function iu(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 Rh(){Ee.mkdirSync(au,{recursive:!0,mode:448})}function KT(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function ba(e){return bs.join(au,`${KT(e)}.key`)}function _s(){if(!Ee.existsSync(ou))return{};try{return JSON.parse(Ee.readFileSync(ou,"utf8"))}catch{return{}}}function Ah(e){Rh(),Ee.writeFileSync(ou,JSON.stringify(e,null,2),{mode:384})}function Eh(){try{return vo.userInfo().username}catch{return"local"}}function Ih(e){if(Ee.existsSync(e)||!Ee.existsSync(su))return null;let t=Ee.readdirSync(su).filter(r=>r.endsWith(".json"));if(t.length===0)return null;let n=t.map(r=>bs.join(su,r)).sort((r,s)=>Ee.statSync(s).mtimeMs-Ee.statSync(r).mtimeMs)[0];try{let r=JSON.parse(Ee.readFileSync(n,"utf8"));if(!r.private_key_jwk)return null;let s=bo(r.private_key_jwk);return Rh(),Ee.writeFileSync(e,Buffer.from(s),{mode:384}),r.agent_id??null}catch{return null}}function vs(e,t={}){return new qg({name:Pt(e),url:wo,keyPath:ba(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function cu(e){if(Xe!=="visa")return;let t=_s()[e];if(t?.binding&&!(t.bindingExpiresAt&&Date.parse(t.bindingExpiresAt)<=Date.now()))return t.binding}async function ws(e,t=15e3){await Promise.race([e.connect(),new Promise((n,r)=>setTimeout(()=>r(new Error(`Subway relay connect timed out after ${t}ms (${wo})`)),t))])}function va(e){if(e)return e;let t=Object.keys(_s());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 $h(e){if(Xe!=="visa")return null;let t=process.env.VISA_CLI_API_KEY?.trim();if(!t)return console.warn("[subway] .visa mesh needs a Visa Key (VISA_CLI_API_KEY) with a card on file to mint a binding; registering without one."),null;try{return await Th({authUrl:Ue(),apiKey:t,seed:kh(ba(e)),name:Pt(e)})}catch(n){return console.warn(`[subway] Visa binding not minted: ${n instanceof Error?n.message:String(n)}`),null}}async function lu(e){let t=ba(e),n=Ih(t),r=Pt(e),s=await $h(e),o=s?{binding:s.binding,bindingExpiresAt:new Date(Date.now()+s.expires_in*1e3).toISOString()}:{};if(Xe==="visa"&&!process.env.SUBWAY_RELAY){let a=_s();return a[e]={relayName:r,mesh:Xe,peerId:null,owner:Eh(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},Ah(a),{relayName:r,mesh:Xe,peerId:null,tapAgentId:n,...s?{binding:s.binding}:{},note:s?"Visa binding minted; relay admission pending a .visa relay (set SUBWAY_RELAY).":"No Visa binding minted; set VISA_CLI_API_KEY (card on file) and SUBWAY_RELAY for a .visa relay."}}let i=vs(e,{autoReconnect:!1,binding:s?.binding});try{await ws(i);let a=_s();return a[e]={relayName:r,mesh:Xe,peerId:i.peerId,owner:Eh(),tapAgentId:n,registeredAt:new Date().toISOString(),...o},Ah(a),{relayName:r,mesh:Xe,peerId:i.peerId,tapAgentId:n,...s?{binding:s.binding}:{}}}finally{i.disconnect()}}async function uu(e,t,n){let r=vs(e,{autoReconnect:!1,binding:cu(e)});try{await ws(r);let s=Pt(t);return await r.sendSigned(s,"chat",n),{to:s,as:Pt(e)}}finally{r.disconnect()}}function du(){let e=_s();return Object.entries(e).map(([t,n])=>({name:t,...n}))}async function fu(e){let t=_a.get(e);if(t)return{relayName:Pt(e),peerId:t.client.peerId};let n=vs(e,{autoReconnect:!0,binding:cu(e)}),r=[];return n.onMessage(s=>{r.push({from:s.fromName,text:s.payload,ts:s.timestampMs,verified:!!s.verified}),r.length>GT&&r.shift()}),_a.set(e,{client:n,buffer:r}),await ws(n),{relayName:Pt(e),peerId:n.peerId}}async function WT(e,t=20,n=!1){await fu(e);let r=_a.get(e);if(!r)return[];let s=r.buffer.slice(-t);return n&&(r.buffer.length=0),s}async function YT(e,t,n){await fu(e);let r=_a.get(e);if(!r)throw new Error(`mailbox for ${e} unavailable`);let s=Pt(t);return await r.client.sendSigned(s,"chat",n),{to:s,as:Pt(e)}}var Ee,vo,bs,Xe,wo,au,ou,su,_a,GT,So=Lt(()=>{"use strict";Vl();ya();Ee=R(require("fs")),vo=R(require("os")),bs=R(require("path"));Vt();Ch();Xe=process.env.SUBWAY_MESH??"relay",wo=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";au=bs.join(vo.homedir(),".visa-cli","subway"),ou=bs.join(au,"registry.json"),su=bs.join(vo.homedir(),".visa-cli","agents");_a=new Map,GT=200});var Na={};jo(Na,{initSentry:()=>xA,isSentryConfigured:()=>SA,reportFatal:()=>TA});function SA(){return!1}async function xA(){return null}async function TA(e,t){process.exit(t?.exitCode??1)}var La=Lt(()=>{});var mE={};jo(mE,{printGroupHelpAndExit:()=>pt});module.exports=c_(mE);var Uy=require("commander"),Ba=R(require("crypto")),ce=R(require("fs")),re=R(require("os")),et=R(require("path")),Dy=require("child_process"),Wu=require("node:readline/promises"),jy=require("util");var Ho=require("child_process"),gd=require("util"),dn=R(require("fs")),Vo=R(require("os")),ec=R(require("path"));var ld=R(require("crypto"));var Ut="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";var ud="VISA_ALLOW_INSECURE_MOCKS",id,ad,cd;function za(e){return`${e}-${ld.randomBytes(24).toString("base64url")}`}function dd(e=process.env){return e.NODE_ENV==="test"||e[ud]==="true"}function ln(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&dd(e)}function Dr(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&dd(e)}function Ja(){return`Set ${ud}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function fd(){return id??=za("mock-session"),id}function md(e=process.env){return e.NODE_ENV==="test"?Ut:(ad??=za("mock-rc"),ad)}function pd(){return cd??=za("mock-signature"),cd}var gt=(0,gd.promisify)(Ho.execFile),tc=ec.join(Vo.homedir(),".visa-mcp"),Ps=ec.join(tc,"session-token"),We="visa-cli",un="session-token",Bo="rc-access",l_=5e3,Fo=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function u_(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
10
+ `)}function hd(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=u_(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function d_(){try{let{stdout:e}=await gt("security",["find-generic-password","-s",We,"-a",un,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(hd(e))throw new Fo("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 f_(e){try{try{await gt("security",["delete-generic-password","-s",We,"-a",un],{timeout:5e3})}catch{}return await gt("security",["add-generic-password","-s",We,"-a",un,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function m_(){try{await gt("security",["delete-generic-password","-s",We,"-a",un],{timeout:5e3})}catch{}}async function p_(){if(!nc())return null;try{let{stdout:e}=await gt("secret-tool",["lookup","service",We,"account",un],{timeout:5e3});return e.trim()||null}catch{return null}}async function g_(e){if(!nc())return!1;try{let t=(0,Ho.execFile)("secret-tool",["store","--label",`${We} ${un}`,"service",We,"account",un]);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"))},l_))]),!0):!1}catch{return!1}}async function h_(){if(nc())try{await gt("secret-tool",["clear","service",We,"account",un],{timeout:5e3})}catch{}}function nc(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function y_(){try{let{stdout:e}=await gt("security",["find-generic-password","-s",We,"-a",Bo,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function __(e){try{try{await gt("security",["delete-generic-password","-s",We,"-a",Bo],{timeout:5e3})}catch{}await gt("security",["add-generic-password","-s",We,"-a",Bo,"-w",e],{timeout:5e3})}catch{}}async function b_(){try{await gt("security",["delete-generic-password","-s",We,"-a",Bo],{timeout:5e3})}catch{}}function Za(){try{return dn.readFileSync(Ps,"utf-8").trim()||null}catch(e){if(hd(e))throw new Fo(`Unable to read Visa CLI credentials from ${Ps}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function yd(e){dn.mkdirSync(tc,{recursive:!0,mode:448}),dn.writeFileSync(Ps,e,{mode:384}),process.platform==="win32"&&v_(Ps)}function Qa(){try{dn.unlinkSync(Ps)}catch{}}function v_(e){try{let t=Vo.userInfo().username;(0,Ho.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 Xa(){switch(process.platform){case"darwin":return{get:d_,store:f_,delete:m_};case"linux":return{get:p_,store:g_,delete:h_};default:return{get:async()=>Za(),store:async e=>{try{return yd(e),!0}catch{return!1}},delete:async()=>Qa(),storesInSessionFile:!0}}}var G=class{static async getSessionToken(){if(ln())return Promise.resolve(fd());let t=Xa(),n=await t.get();if(n)return n;let r=Za();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(ln())return;let n=Xa();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||Qa();return}await n.delete()}if(yd(t),Za()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${tc} is writable.`))}static async getRcAccessToken(){return ln()?md():y_()}static async saveRcAccessToken(t){ln()||await __(t)}static async deleteSessionToken(){if(ln())return;await Xa().delete(),Qa()}static async clearAll(){await this.deleteSessionToken(),await b_()}};var qo=R(require("crypto")),Ko=R(require("tty")),Go=R(require("fs"));function S_(e){return/-rc\.|-beta\./.test(e)}function rc(e){return qo.createHash("sha256").update(e.trim()).digest("hex")}function _d(e){return Ut==="SKIP"?!0:qo.timingSafeEqual(Buffer.from(rc(e)),Buffer.from(Ut))}function x_(){try{let e=Go.openSync("/dev/tty","r+"),t=new Ko.ReadStream(e),n=new Ko.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{Go.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 T_(e){return new Promise((t,n)=>{let r;try{r=x_()}catch(u){n(u);return}let{input:s,output:o,cleanupStreams:i}=r,a=()=>{s.off("data",l);try{s.setRawMode?.(!1)}catch{}i()};o.write(e),s.setRawMode?.(!0),s.resume(),s.setEncoding("utf8");let c="",l=u=>{u==="\r"||u===`
11
11
  `?(o.write(`
12
12
  `),a(),t(c)):u===""?(o.write(`
13
- `),a(),n(new Error("Cancelled"))):u==="\x7F"||u==="\b"?c.length>0&&(c=c.slice(0,-1),o.write("\b \b")):(c+=u,o.write("\u2022"))};s.on("data",l)})}var h_=`
13
+ `),a(),n(new Error("Cancelled"))):u==="\x7F"||u==="\b"?c.length>0&&(c=c.slice(0,-1),o.write("\b \b")):(c+=u,o.write("\u2022"))};s.on("data",l)})}var k_=`
14
14
  \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
15
15
  \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557
16
16
  \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551
@@ -19,25 +19,25 @@ ${e.nonce}`;return jS.encode(n)}function HS(e,t,n,r,s,o,i){return FS({messageId:
19
19
  \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D
20
20
 
21
21
  This is a Release Candidate build. Access is restricted to Visa employees.
22
- `;async function pd(e={}){let t=e.version??Is().version;if(!p_(t))return;let n=process.env.VISA_RC_CODE;if(n&&fd(n)){await K.saveRcAccessToken(Za(n));return}if(e.isMcp??!1){let i=await K.getRcAccessToken();if(i&&(Lt==="SKIP"||i===Lt))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
23
- `),process.exit(1)}let s=await K.getRcAccessToken();if(s&&(Lt==="SKIP"||s===Lt))return;console.log(h_);let o=3;for(let i=1;i<=o;i++){let a;try{a=await g_(" Enter RC access code: ")}catch{process.exit(1)}if(fd(a)){await K.saveRcAccessToken(Za(a)),console.log(`
22
+ `;async function bd(e={}){let t=e.version??Os().version;if(!S_(t))return;let n=process.env.VISA_RC_CODE;if(n&&_d(n)){await G.saveRcAccessToken(rc(n));return}if(e.isMcp??!1){let i=await G.getRcAccessToken();if(i&&(Ut==="SKIP"||i===Ut))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
23
+ `),process.exit(1)}let s=await G.getRcAccessToken();if(s&&(Ut==="SKIP"||s===Ut))return;console.log(k_);let o=3;for(let i=1;i<=o;i++){let a;try{a=await T_(" Enter RC access code: ")}catch{process.exit(1)}if(_d(a)){await G.saveRcAccessToken(rc(a)),console.log(`
24
24
  Access granted. Welcome.
25
25
  `);return}i<o&&console.log(`
26
26
  Invalid code. ${o-i} attempt(s) remaining.
27
27
  `)}console.log(`
28
28
  Invalid code. Contact your team lead.
29
- `),process.exit(1)}var qo=R(require("fs")),md=R(require("os")),Qa=R(require("path")),y_=[{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"}}],__=/^data:(image\/(png|jpeg|jpg|gif|webp));base64,([A-Za-z0-9+/=]+)$/;function Ur(e){if(typeof e!="string"||e.length===0)return null;let t=e.trim(),n=__.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 y_)if(r.startsWith(s))return{base64:r,sig:o};return null}function $s(e,t={}){let n=t.outputDir??Qa.join(md.tmpdir(),"visa-cli");qo.mkdirSync(n,{recursive:!0});let r=(t.tag??"media").toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"media",s=new Date().toISOString().replace(/[:.]/g,"-"),o=Qa.join(n,`${r}-${s}.${e.sig.ext}`),i=Buffer.from(e.base64,"base64");return qo.writeFileSync(o,i,{mode:384}),{filePath:o,bytes:i.length,mime:e.sig.mime}}function b_(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 Ps(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 ec(e,t){if(!t||typeof t!="object")return Ps(e,"No result payload from tool");let n=t;if(n.success===!1)return Ps(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 b_(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 tc=require("process");async function nc(){let e="";tc.stdin.setEncoding("utf8");for await(let t of tc.stdin)e+=t;return e.endsWith(`
30
- `)?e.slice(0,-1):e}async function qn(e,t){if(e==="-"||t.stdin===!0&&!e){let s=(await nc()).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 Os(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 _d=R(require("fs")),Ko=R(require("path"));var un=class extends Error{constructor(t){super(t),this.name="FromStdinFieldError"}},gd=new Set;function v_(e){gd.add(e)}function hd(e){return gd.has(e)}function yd(e,t){if(!t.startsWith("."))throw new un(`--from-stdin path must start with "." (got: "${t}")`);let n=w_(t),r=e;for(let o of n){if(r==null)throw new un(`--from-stdin path "${t}" failed: hit ${r===null?"null":"undefined"} at segment "${o}"`);if(typeof r!="object")throw new un(`--from-stdin path "${t}" failed: cannot descend into primitive at segment "${o}"`);if(typeof o=="number"){if(!Array.isArray(r))throw new un(`--from-stdin path "${t}" failed: expected array at segment [${o}], got object`);r=r[o]}else r=r[o]}if(r==null)throw new un(`--from-stdin path "${t}" resolved to ${r===null?"null":"undefined"}`);if(typeof r=="object")throw new un(`--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 v_(s),s}function w_(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 rc=class extends Error{constructor(t){super(t),this.name="FileShorthandStdinSourceError"}};async function bd(e){if(e===void 0)return;if(!e.startsWith("@"))return e;if(hd(e))throw new rc("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("~")?Ko.join(process.env.HOME??"",t.slice(1)):Ko.resolve(process.cwd(),t),r=await _d.promises.readFile(n,"utf8");return r.endsWith(`
31
- `)?r.slice(0,-1):r}var Ms=require("process"),dn=["json","yaml","tsv","table"];function Go(e){return dn.includes(e)}function Ns(e,t){switch(t){case"json":Ms.stdout.write(JSON.stringify(e)+`
32
- `);return;case"yaml":Ms.stdout.write(S_(e)+`
33
- `);return;case"tsv":Ms.stdout.write(x_(e)+`
34
- `);return;case"table":Ms.stdout.write(T_(e)+`
35
- `);return}}function S_(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(` - ${vd(s)}`)}else r!==null&&typeof r=="object"?t.push(`${n}: ${JSON.stringify(r)}`):t.push(`${n}: ${vd(r)}`);return t.join(`
36
- `)}function vd(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 x_(e){let t=[];for(let[n,r]of Object.entries(e)){if(r===void 0)continue;let s=Array.isArray(r)||r!==null&&typeof r=="object"?JSON.stringify(r):String(r);t.push(`${n} ${s}`)}return t.join(`
37
- `)}function T_(e){let t=[];for(let[r,s]of Object.entries(e)){if(s===void 0)continue;let o=Array.isArray(s)||s!==null&&typeof s=="object"?JSON.stringify(s):String(s);t.push([r,o])}let n=Math.max(...t.map(([r])=>r.length),1);return t.map(([r,s])=>`${r.padEnd(n)} ${s}`).join(`
38
- `)}var Sd=require("child_process");function sc(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 C_(e){let n=e.length+4;return[`\u250C${"\u2500".repeat(n)}\u2510`,`\u2502${" ".repeat(2)}${e}${" ".repeat(2)}\u2502`,`\u2514${"\u2500".repeat(n)}\u2518`].join(`
39
- `)}function Ls(e){if(typeof e!="string"||e.length===0)return null;let t;try{t=new URL(e)}catch{return null}return t.protocol!=="https:"&&t.protocol!=="http:"?null:t.toString()}function xd(e,t){let n=Ls(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 Td(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 Cd(e,t=process.platform){let n=Ls(e);return n?Td(n,t):null}function wd(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function oc(e,t={}){let n=t.log??(l=>console.log(l)),r=t.env??process.env,s=t.platform??process.platform,o=Ls(e),i=t.spawn??((l,u,d)=>{(0,Sd.execFile)(l,u,p=>d(p))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let l of C_(o??e).split(`
40
- `))n(` ${l}`);if(n(""),!o){n(" (Auth URL is not a valid absolute http(s) URL \u2014 skipping browser auto-open.)"),n(" Open the URL above manually to continue."),n("");return}let a=sc(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=Td(o,s);if(!c){n(` No known browser-open command for platform "${s}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(l=>{let u=d=>{d?wd(n,d):(n(" Opened browser. Waiting for you to sign in..."),n("")),l()};try{i(c.cmd,c.args,u)}catch(d){wd(n,d instanceof Error?d:new Error(String(d))),l()}})}function k_(e){return new Promise(t=>setTimeout(t,e))}function kd(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 Ed(e){return!Number.isFinite(e)||e===null||e<=0?1e3:Math.min(Math.max(Math.ceil(e),1e3),3e4)}async function E_(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=kd(e.headers?.get("Retry-After"));if(r!==null)return n(Ed(r));if(typeof e.json=="function")try{let s=await e.json();return n(Ed(kd(s?.retryAfter)))}catch{return n(1e3)}return n(1e3)}async function fn(e,t){let n=await E_(e);return t?.(n),await k_(n),n}var Gd=R(require("crypto")),Wd=require("child_process"),ve=R(require("fs")),Yd=R(require("os")),Le=R(require("path"));var W=R(require("fs")),Wn=R(require("os")),Z=R(require("path")),Md=require("child_process"),cc=require("crypto");var jr=R(require("fs")),Wo=R(require("tty"));function Rd(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 Id(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 $d(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 Ad(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 A_=80,R_="/dev/tty";function I_(e=R_){if(process.platform==="win32")return null;let t,n;try{t=jr.openSync(e,"r"),n=jr.openSync(e,"w");let r=new Wo.ReadStream(t),s=new Wo.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 $_(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??I_)(e.ttyPath);return o?.stdout.isTTY&&o.stdin.isTTY&&typeof o.stdin.setRawMode=="function"?o:(o?.close?.(),null)}async function P_(e={}){let t=$_(e);if(!t)return null;let{stdin:n,stdout:r}=t,s=e.timeoutMs??A_,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 w=Ad(l),C=l.includes("\x07")||l.includes("\x1B\\");w!==null&&C&&f(w>.5?"light":"dark")},p=()=>{try{n.removeListener("data",d)}catch{}try{i(m)}catch{}try{!u&&typeof n.setRawMode=="function"&&n.setRawMode(!1)}catch{}try{n.pause?.()}catch{}try{n.unref?.()}catch{}try{t.close?.()}catch{}},f=h=>{c||(c=!0,p(),a(h))},m=o(()=>{let h=Ad(l);f(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{f(null)}})}var Kn,Us;function O_(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=$d(e.COLORFGBG);return n||"dark"}function Yo(e=process.env){return Kn!==void 0||(Kn=O_(e)),Kn}function Re(e=process.env){if(Us!==void 0)return Us;let t=Yo(e),n=Rd(e);return Us=Id(t==="light"?"light":"dark",n),Us}function zo(e=process.env){return Yo(e)==="no-color"}async function ic(e={}){if(Kn!==void 0)return Kn;let t=e.env??process.env;if((t.NO_COLOR??"")!=="")return Dr("no-color",t);let n=(t.VISA_CLI_HUD_THEME??"").toLowerCase().trim();if(n==="light")return Dr("light",t);if(n==="dark")return Dr("dark",t);let r=$d(t.COLORFGBG);if(r)return Dr(r,t);let s=await P_(e);return Dr(s||"dark",t)}function Dr(e,t){Kn=e;let n=Rd(t);return Us=Id(e==="light"?"light":"dark",n),e}var M_=2,Jo="# >>> visa-cli shell hud v2 >>>",Xo="# <<< visa-cli shell hud v2 <<<",N_="# >>> visa-cli shell hud >>>",L_="# <<< visa-cli shell hud <<<",Nd=3e4,U_=6e4,D_="VISA | HUD not ready \u2014 run: visa-cli config hud doctor",j_={currentVersion:"0.0.0"},B_=15e3;function lc(){try{return Z.join(fc(),".visa-cli")}catch{return Z.join(Wn.tmpdir(),".visa-cli")}}function pn(){return Z.join(lc(),"shell-hud.json")}function Ds(){return Z.join(lc(),"shell-hud.line")}function Ld(){return Z.join(lc(),"shell-hud.lock")}function Hr(e){let t=e??process.env.SHELL;if(!t)return null;let n=Z.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=fc();if(e==="zsh")return Z.join(t,".zshrc");if(e==="bash")return Z.join(t,".bashrc");let n=(process.platform==="win32","PowerShell");return Z.join(t,"Documents",n,"Microsoft.PowerShell_profile.ps1")}function Ud(e,t){let n=t??fc(),r=[{shell:"zsh",rcPath:Z.join(n,".zshrc")},{shell:"bash",rcPath:Z.join(n,".bashrc")},{shell:"bash",rcPath:Z.join(n,".bash_profile")},{shell:"powershell",rcPath:Z.join(n,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:Z.join(n,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:Z.join(n,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:Z.join(n,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:Z.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 F_(e){let t="$HOME/.visa-cli/shell-hud.line",n=ob(e),r=ib(e);if(e==="zsh")return`${Jo}
29
+ `),process.exit(1)}var Wo=R(require("fs")),vd=R(require("os")),sc=R(require("path")),C_=[{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"}}],A_=/^data:(image\/(png|jpeg|jpg|gif|webp));base64,([A-Za-z0-9+/=]+)$/;function jr(e){if(typeof e!="string"||e.length===0)return null;let t=e.trim(),n=A_.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 C_)if(r.startsWith(s))return{base64:r,sig:o};return null}function Ms(e,t={}){let n=t.outputDir??sc.join(vd.tmpdir(),"visa-cli");Wo.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 Wo.writeFileSync(o,i,{mode:384}),{filePath:o,bytes:i.length,mime:e.sig.mime}}function wd(e){return typeof e?.status=="string"&&(e.status==="IN_QUEUE"||e.status==="PENDING")}function oc(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 E_(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 Ns(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 ic(e,t){if(!t||typeof t!="object")return Ns(e,"No result payload from tool");let n=t;if(n.success===!1)return Ns(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 E_(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 ac=require("process");async function cc(){let e="";ac.stdin.setEncoding("utf8");for await(let t of ac.stdin)e+=t;return e.endsWith(`
30
+ `)?e.slice(0,-1):e}async function Gn(e,t){if(e==="-"||t.stdin===!0&&!e){let s=(await cc()).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 Ls(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 kd=R(require("fs")),Yo=R(require("path"));var fn=class extends Error{constructor(t){super(t),this.name="FromStdinFieldError"}},Sd=new Set;function R_(e){Sd.add(e)}function xd(e){return Sd.has(e)}function Td(e,t){if(!t.startsWith("."))throw new fn(`--from-stdin path must start with "." (got: "${t}")`);let n=I_(t),r=e;for(let o of n){if(r==null)throw new fn(`--from-stdin path "${t}" failed: hit ${r===null?"null":"undefined"} at segment "${o}"`);if(typeof r!="object")throw new fn(`--from-stdin path "${t}" failed: cannot descend into primitive at segment "${o}"`);if(typeof o=="number"){if(!Array.isArray(r))throw new fn(`--from-stdin path "${t}" failed: expected array at segment [${o}], got object`);r=r[o]}else r=r[o]}if(r==null)throw new fn(`--from-stdin path "${t}" resolved to ${r===null?"null":"undefined"}`);if(typeof r=="object")throw new fn(`--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 R_(s),s}function I_(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 lc=class extends Error{constructor(t){super(t),this.name="FileShorthandStdinSourceError"}};async function Cd(e){if(e===void 0)return;if(!e.startsWith("@"))return e;if(xd(e))throw new lc("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("~")?Yo.join(process.env.HOME??"",t.slice(1)):Yo.resolve(process.cwd(),t),r=await kd.promises.readFile(n,"utf8");return r.endsWith(`
31
+ `)?r.slice(0,-1):r}var Us=require("process"),mn=["json","yaml","tsv","table"];function zo(e){return mn.includes(e)}function Ds(e,t){switch(t){case"json":Us.stdout.write(JSON.stringify(e)+`
32
+ `);return;case"yaml":Us.stdout.write($_(e)+`
33
+ `);return;case"tsv":Us.stdout.write(P_(e)+`
34
+ `);return;case"table":Us.stdout.write(O_(e)+`
35
+ `);return}}function $_(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(` - ${Ad(s)}`)}else r!==null&&typeof r=="object"?t.push(`${n}: ${JSON.stringify(r)}`):t.push(`${n}: ${Ad(r)}`);return t.join(`
36
+ `)}function Ad(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 P_(e){let t=[];for(let[n,r]of Object.entries(e)){if(r===void 0)continue;let s=Array.isArray(r)||r!==null&&typeof r=="object"?JSON.stringify(r):String(r);t.push(`${n} ${s}`)}return t.join(`
37
+ `)}function O_(e){let t=[];for(let[r,s]of Object.entries(e)){if(s===void 0)continue;let o=Array.isArray(s)||s!==null&&typeof s=="object"?JSON.stringify(s):String(s);t.push([r,o])}let n=Math.max(...t.map(([r])=>r.length),1);return t.map(([r,s])=>`${r.padEnd(n)} ${s}`).join(`
38
+ `)}var Rd=require("child_process");function uc(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 M_(e){let n=e.length+4;return[`\u250C${"\u2500".repeat(n)}\u2510`,`\u2502${" ".repeat(2)}${e}${" ".repeat(2)}\u2502`,`\u2514${"\u2500".repeat(n)}\u2518`].join(`
39
+ `)}function js(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 Id(e,t){let n=js(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 $d(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 Pd(e,t=process.platform){let n=js(e);return n?$d(n,t):null}function Ed(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function dc(e,t={}){let n=t.log??(l=>console.log(l)),r=t.env??process.env,s=t.platform??process.platform,o=js(e),i=t.spawn??((l,u,d)=>{(0,Rd.execFile)(l,u,m=>d(m))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let l of M_(o??e).split(`
40
+ `))n(` ${l}`);if(n(""),!o){n(" (Auth URL is not a valid absolute http(s) URL \u2014 skipping browser auto-open.)"),n(" Open the URL above manually to continue."),n("");return}let a=uc(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=$d(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?Ed(n,d):(n(" Opened browser. Waiting for you to sign in..."),n("")),l()};try{i(c.cmd,c.args,u)}catch(d){Ed(n,d instanceof Error?d:new Error(String(d))),l()}})}function N_(e){return new Promise(t=>setTimeout(t,e))}function Od(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 Md(e){return!Number.isFinite(e)||e===null||e<=0?1e3:Math.min(Math.max(Math.ceil(e),1e3),3e4)}async function L_(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=Od(e.headers?.get("Retry-After"));if(r!==null)return n(Md(r));if(typeof e.json=="function")try{let s=await e.json();return n(Md(Od(s?.retryAfter)))}catch{return n(1e3)}return n(1e3)}async function pn(e,t){let n=await L_(e);return t?.(n),await N_(n),n}var Qd=R(require("crypto")),ef=require("child_process"),ve=R(require("fs")),tf=R(require("os")),Le=R(require("path"));var Y=R(require("fs")),zn=R(require("os")),Q=R(require("path")),Fd=require("child_process"),pc=require("crypto");var Fr=R(require("fs")),Jo=R(require("tty"));function Ld(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 Ud(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 Dd(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 Nd(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 U_=80,D_="/dev/tty";function j_(e=D_){if(process.platform==="win32")return null;let t,n;try{t=Fr.openSync(e,"r"),n=Fr.openSync(e,"w");let r=new Jo.ReadStream(t),s=new Jo.WriteStream(n);return{stdin:r,stdout:s,close:()=>{try{r.destroy?.()}catch{}try{s.destroy?.()}catch{}}}}catch{try{t!==void 0&&Fr.closeSync(t)}catch{}try{n!==void 0&&Fr.closeSync(n)}catch{}return null}}function B_(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 F_(e={}){let t=B_(e);if(!t)return null;let{stdin:n,stdout:r}=t,s=e.timeoutMs??U_,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 w=Nd(l),k=l.includes("\x07")||l.includes("\x1B\\");w!==null&&k&&f(w>.5?"light":"dark")},m=()=>{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{}},f=h=>{c||(c=!0,m(),a(h))},p=o(()=>{let h=Nd(l);f(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{f(null)}})}var Wn,Bs;function H_(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=Dd(e.COLORFGBG);return n||"dark"}function Xo(e=process.env){return Wn!==void 0||(Wn=H_(e)),Wn}function Re(e=process.env){if(Bs!==void 0)return Bs;let t=Xo(e),n=Ld(e);return Bs=Ud(t==="light"?"light":"dark",n),Bs}function Zo(e=process.env){return Xo(e)==="no-color"}async function fc(e={}){if(Wn!==void 0)return Wn;let t=e.env??process.env;if((t.NO_COLOR??"")!=="")return Br("no-color",t);let n=(t.VISA_CLI_HUD_THEME??"").toLowerCase().trim();if(n==="light")return Br("light",t);if(n==="dark")return Br("dark",t);let r=Dd(t.COLORFGBG);if(r)return Br(r,t);let s=await F_(e);return Br(s||"dark",t)}function Br(e,t){Wn=e;let n=Ld(t);return Bs=Ud(e==="light"?"light":"dark",n),e}var V_=2,Qo="# >>> visa-cli shell hud v2 >>>",ei="# <<< visa-cli shell hud v2 <<<",q_="# >>> visa-cli shell hud >>>",K_="# <<< visa-cli shell hud <<<",Hd=3e4,G_=6e4,W_="VISA | HUD not ready \u2014 run: visa-cli config hud doctor",Y_={currentVersion:"0.0.0"},z_=15e3;function gc(){try{return Q.join(_c(),".visa-cli")}catch{return Q.join(zn.tmpdir(),".visa-cli")}}function gn(){return Q.join(gc(),"shell-hud.json")}function Fs(){return Q.join(gc(),"shell-hud.line")}function Vd(){return Q.join(gc(),"shell-hud.lock")}function qr(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 Hs(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 qd(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 J_(e){let t="$HOME/.visa-cli/shell-hud.line",n=pb(e),r=gb(e);if(e==="zsh")return`${Qo}
41
41
  _visa_cli_shell_hud_precmd() {
42
42
  setopt localoptions no_bg_nice
43
43
  if [[ -f "${t}" ]]; then
@@ -54,7 +54,7 @@ autoload -Uz add-zsh-hook
54
54
  if [[ -z "\${precmd_functions[(r)_visa_cli_shell_hud_precmd]}" ]]; then
55
55
  add-zsh-hook precmd _visa_cli_shell_hud_precmd
56
56
  fi
57
- ${Xo}`;if(e==="powershell"){let s="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${Jo}
57
+ ${ei}`;if(e==="powershell"){let s="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${Qo}
58
58
  if (-not (Test-Path Function:\\global:__visa_cli_original_prompt)) {
59
59
  $function:global:__visa_cli_original_prompt = if (Test-Path Function:\\prompt) { $function:prompt } else { { '' } }
60
60
  }
@@ -73,7 +73,7 @@ function global:prompt {
73
73
  }
74
74
  & $function:global:__visa_cli_original_prompt
75
75
  }
76
- ${Xo}`}return`${Jo}
76
+ ${ei}`}return`${Qo}
77
77
  __visa_cli_shell_hud_precmd() {
78
78
  if [ -f "${t}" ]; then
79
79
  cat "${t}"
@@ -90,62 +90,62 @@ case ";$PROMPT_COMMAND;" in
90
90
  *";__visa_cli_shell_hud_precmd;"*) ;;
91
91
  *) PROMPT_COMMAND="__visa_cli_shell_hud_precmd\${PROMPT_COMMAND:+;$PROMPT_COMMAND}" ;;
92
92
  esac
93
- ${Xo}`}function H_(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 V_(e,t,n){let r=new RegExp(`(^|\\n)([ \\t]*${Od(t)}[ \\t]*\\r?\\n)([\\s\\S]*?)(\\r?\\n[ \\t]*${Od(n)}[ \\t]*)(?=\\r?\\n|$)(\\r?\\n)?`,"g");return e.replace(r,(s,o,i,a,c,l,u)=>{if(!H_(a))return s;let d=u>0?e[u-1]:"";return o===`
93
+ ${ei}`}function X_(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 Z_(e,t,n){let r=new RegExp(`(^|\\n)([ \\t]*${Bd(t)}[ \\t]*\\r?\\n)([\\s\\S]*?)(\\r?\\n[ \\t]*${Bd(n)}[ \\t]*)(?=\\r?\\n|$)(\\r?\\n)?`,"g");return e.replace(r,(s,o,i,a,c,l,u)=>{if(!X_(a))return s;let d=u>0?e[u-1]:"";return o===`
94
94
  `&&d!==`
95
95
  `?`
96
- `:""})}function Bs(e){let t=e;for(let[n,r]of[[Jo,Xo],[N_,L_]])t=V_(t,n,r);return t.trimEnd()}function Dd(e){return Bs(e)!==e.trimEnd()}function q_(e,t){let n=Bs(e).trimEnd(),r=F_(t);return n.length>0?`${n}
96
+ `:""})}function Vs(e){let t=e;for(let[n,r]of[[Qo,ei],[q_,K_]])t=Z_(t,n,r);return t.trimEnd()}function Kd(e){return Vs(e)!==e.trimEnd()}function Q_(e,t){let n=Vs(e).trimEnd(),r=J_(t);return n.length>0?`${n}
97
97
 
98
98
  ${r}
99
99
  `:`${r}
100
- `}function Zo(e=Hr()){if(!e)return!1;try{let t=js(e),n=W.readFileSync(t,"utf-8");return Dd(n)}catch{return!1}}function Yn(e=Wn.homedir()){let t=[],n=K_(e);for(let r of n)try{if(!W.existsSync(r))continue;let s=W.readFileSync(r,"utf-8");Dd(s)&&t.push(r)}catch{}return t}function K_(e){return Ud(null,e).map(t=>t.rcPath)}function Qo(e=Hr()){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=W.existsSync(t)?W.readFileSync(t,"utf-8"):"",r=q_(n,e),s=r!==n;return s&&Fr(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}: ${ac(n)}`}}}function Ut(e=Hr(),t){let n=[],r=[],s=[];try{for(let o of Ud(e,t))if(r.push(o.rcPath),!!W.existsSync(o.rcPath))try{let i=W.readFileSync(o.rcPath,"utf-8"),a=Bs(i);if(a===i.trimEnd())continue;Fr(o.rcPath,a.length>0?`${a}
101
- `:""),n.push(o.rcPath)}catch(i){s.push(`${o.rcPath}: ${ac(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: ${ac(o)}`}}}function uc(e,t){let n=t??j_,r=n.currentVersion==="0.0.0"&&e.version?e.version:n.currentVersion,s=mn(r),o=` ${ee("\u2502",Q.chrome)} `,i=jd(n),a=J_(n,i),c=n.updateCheckDisabled?"":i,l=z_(s,c);if(!e.enrolled)return[l,ee("setup needed",Q.visaGold),a].filter(Boolean).join(o);let u=sb(e),d=Y_(e),p=mn(Wn.hostname().split(".")[0]),f=[l,p?ee(p,Q.muted):"",ee(u,Q.visaGold),a].filter(Boolean).join(o),m=[d,G_(e)].filter(Boolean),h=m.length>0?m.join(o):"";return h?`${f}
102
- ${h}`:f}function G_(e){let t=` ${ee("\u2502",Q.chrome)} `,n=[];if(typeof e.spentToday=="number"&&Number.isFinite(e.spentToday)&&n.push(ee(`spent today ${Br(Math.max(0,e.spentToday))}`,Q.muted)),e.lastService&&typeof e.lastService.toolName=="string"&&e.lastService.toolName.length>0){let r=rb(mn(e.lastService.toolName)),s=W_(e.lastService.createdAt),o=ee(s?`last ${r} ${s}`:`last ${r}`,Q.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(ee(`${r} ${s}`,Q.muted))}else e.apiKeyStatus==="rollout_locked"&&n.push(ee("VISA Key \u{1F51C}",Q.muted));return n.join(t)}function W_(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 Y_(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 ee("balance unknown",Q.muted);let r=t/100;if(n){let i=Math.max(0,n.capCents),a=Math.max(0,n.estimatedRemainingCents),c=Math.max(0,i-a),l=i>0?Math.max(0,Math.min(1,c/i)):0;return`${nb(l)} ${ee(`${Br(a/100)} in session`,Q.green)} ${ee(`(${Br(c/100)}/${Br(i/100)} cap)`,Q.muted)} ${ee("\xB7",Q.chrome)} ${ee(`${Br(r)} balance`,Q.muted)}`}let s=10,o=`balance ${Br(r)}`;return t>=s?ee(o,Q.green):ee(`${o} \u2014 top up via buy_credits`,Q.visaGold)}function z_(e,t){let n=e,r=`${ee("VISA CLI",Q.visaBlue)} ${ee(`v${n}`,Q.visaBlueSoft)}`;if(!t)return r;let s=t;return`${r} ${ee("\u2B06 update",Q.visaGold)} ${ee(`v${s}`,Q.visaGold)}`}function J_(e,t){return t&&!e.updateCheckDisabled?ee("run: visa-cli update",Q.visaGold):t?null:X_(e)}function jd(e){return e.latestVersion?mn(e.latestVersion):""}function X_(e){let t=jd(e);return t?ee(`update ready v${t}`,Q.visaGold):null}function Bd(){let e=Fs();return!(!e||Date.now()-e.renderedAt>Nd||e.cwd&&e.cwd!==process.cwd())}function ei(){let e=Fs(),t=Date.now();if(e&&t-e.renderedAt<=Nd||(Q_(),e?.line))return Pd(e.line,e,t);try{let n=Ds();if(W.existsSync(n)){let r=W.readFileSync(n,"utf-8").trimEnd();if(r&&!ti(r))return r}}catch{}return D_}function Pd(e,t,n){let r=n-t.renderedAt,s=typeof t.refreshFailedAt=="number"&&t.refreshFailedAt>t.renderedAt,o=[];if(r>=U_&&o.push(`stale ${Z_(r)}`),s&&o.push("\u26A0 refresh failed"),o.length===0)return e;let i=` ${ee("\xB7",Q.chrome)} ${ee(o.join(" \xB7 "),Q.visaGold)}`,a=e.split(`
100
+ `}function ti(e=qr()){if(!e)return!1;try{let t=Hs(e),n=Y.readFileSync(t,"utf-8");return Kd(n)}catch{return!1}}function Jn(e=zn.homedir()){let t=[],n=eb(e);for(let r of n)try{if(!Y.existsSync(r))continue;let s=Y.readFileSync(r,"utf-8");Kd(s)&&t.push(r)}catch{}return t}function eb(e){return qd(null,e).map(t=>t.rcPath)}function ni(e=qr()){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=Hs(e);let n=Y.existsSync(t)?Y.readFileSync(t,"utf-8"):"",r=Q_(n,e),s=r!==n;return s&&Vr(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}: ${mc(n)}`}}}function Dt(e=qr(),t){let n=[],r=[],s=[];try{for(let o of qd(e,t))if(r.push(o.rcPath),!!Y.existsSync(o.rcPath))try{let i=Y.readFileSync(o.rcPath,"utf-8"),a=Vs(i);if(a===i.trimEnd())continue;Vr(o.rcPath,a.length>0?`${a}
101
+ `:""),n.push(o.rcPath)}catch(i){s.push(`${o.rcPath}: ${mc(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: ${mc(o)}`}}}function hc(e,t){let n=t??Y_,r=n.currentVersion==="0.0.0"&&e.version?e.version:n.currentVersion,s=hn(r),o=` ${te("\u2502",ee.chrome)} `,i=Gd(n),a=ob(n,i),c=n.updateCheckDisabled?"":i,l=sb(s,c);if(!e.enrolled)return[l,te("setup needed",ee.visaGold),a].filter(Boolean).join(o);let u=mb(e),d=rb(e),m=hn(zn.hostname().split(".")[0]),f=[l,m?te(m,ee.muted):"",te(u,ee.visaGold),a].filter(Boolean).join(o),p=[d,tb(e)].filter(Boolean),h=p.length>0?p.join(o):"";return h?`${f}
102
+ ${h}`:f}function tb(e){let t=` ${te("\u2502",ee.chrome)} `,n=[];if(typeof e.spentToday=="number"&&Number.isFinite(e.spentToday)&&n.push(te(`spent today ${Hr(Math.max(0,e.spentToday))}`,ee.muted)),e.lastService&&typeof e.lastService.toolName=="string"&&e.lastService.toolName.length>0){let r=fb(hn(e.lastService.toolName)),s=nb(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 nb(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 rb(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`${db(l)} ${te(`${Hr(a/100)} in session`,ee.green)} ${te(`(${Hr(c/100)}/${Hr(i/100)} cap)`,ee.muted)} ${te("\xB7",ee.chrome)} ${te(`${Hr(r)} balance`,ee.muted)}`}let s=10,o=`balance ${Hr(r)}`;return t>=s?te(o,ee.green):te(`${o} \u2014 top up via buy_credits`,ee.visaGold)}function sb(e,t){let n=e,r=`${te("VISA CLI",ee.visaBlue)} ${te(`v${n}`,ee.visaBlueSoft)}`;if(!t)return r;let s=t;return`${r} ${te("\u2B06 update",ee.visaGold)} ${te(`v${s}`,ee.visaGold)}`}function ob(e,t){return t&&!e.updateCheckDisabled?te("run: visa-cli update",ee.visaGold):t?null:ib(e)}function Gd(e){return e.latestVersion?hn(e.latestVersion):""}function ib(e){let t=Gd(e);return t?te(`update ready v${t}`,ee.visaGold):null}function Wd(){let e=qs();return!(!e||Date.now()-e.renderedAt>Hd||e.cwd&&e.cwd!==process.cwd())}function ri(){let e=qs(),t=Date.now();if(e&&t-e.renderedAt<=Hd||(cb(),e?.line))return jd(e.line,e,t);try{let n=Fs();if(Y.existsSync(n)){let r=Y.readFileSync(n,"utf-8").trimEnd();if(r&&!si(r))return r}}catch{}return W_}function jd(e,t,n){let r=n-t.renderedAt,s=typeof t.refreshFailedAt=="number"&&t.refreshFailedAt>t.renderedAt,o=[];if(r>=G_&&o.push(`stale ${ab(r)}`),s&&o.push("\u26A0 refresh failed"),o.length===0)return e;let i=` ${te("\xB7",ee.chrome)} ${te(o.join(" \xB7 "),ee.visaGold)}`,a=e.split(`
103
103
  `);for(let c=a.length-1;c>=0;c--)if(a[c].length>0)return a[c]=`${a[c]}${i}`,a.join(`
104
- `);return`${e}${i}`}function Z_(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 dc(e,t){try{let n=Z.dirname(pn());W.mkdirSync(n,{recursive:!0});let r=e.split(`
105
- `).map(o=>tb(o)).filter(o=>o.length>0).join(`
106
- `),s={hudVersion:M_,renderedAt:Date.now(),line:r,cwd:process.cwd(),status:t};Fr(pn(),JSON.stringify(s)+`
107
- `),Fr(Ds(),r+`
108
- `)}catch{}}function Fd(e){try{let t=Fs();if(!t)return;let n=Math.max(Date.now(),t.renderedAt+1),r={...t,refreshFailedAt:n,refreshErrorReason:mn(e).slice(0,200)};Fr(pn(),JSON.stringify(r)+`
109
- `)}catch{}}function Hd(){try{let e=Fs();if(!e)return;let t={...e,renderedAt:0};Fr(pn(),JSON.stringify(t)+`
110
- `)}catch{}}function Gn(){try{W.unlinkSync(Ld())}catch{}}function Fs(){let e=pn();if(!W.existsSync(e))return null;try{let t=JSON.parse(W.readFileSync(e,"utf-8"));return typeof t?.line=="string"&&ti(t.line)?null:t}catch{return null}}function ti(e){for(let t of e.split(`
111
- `)){let n=t.trim();if(n.length===0)continue;let r=n.replace(/\[[0-?]*[ -/]*[@-~]/g,"").trim();if(/^VISA\s*\|\s*loading\b/i.test(r)||/^VISA\s*\|\s*HUD\s+not\s+(ready|initialized)\b/i.test(r))return!0}return!1}function Vd(){return Fs()?.status??null}function Q_(){if(process.env.JEST_WORKER_ID)return;let e=Ld();try{if(W.mkdirSync(Z.dirname(e),{recursive:!0}),!ab(e))return;let t=process.argv[1]?Z.resolve(process.argv[1]):"";if(!t){Gn();return}let n=Yo(),r=(process.env.VISA_CLI_HUD_THEME??"").toLowerCase().trim(),s=n==="no-color"||r==="light"||r==="dark"?{}:{VISA_CLI_HUD_THEME:n},o=(0,Md.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,...s,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});o.once("error",Gn),o.unref()}catch{Gn()}}function mn(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 eb=/^\u001B\[(?:0|38;2;\d{1,3};\d{1,3};\d{1,3}|38;5;\d{1,3})m$/;function tb(e){let t=[],n=`__VISA_CLI_HUD_SGR_${(0,cc.randomBytes)(8).toString("hex")}_`,r=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,o=>{if(!eb.test(o))return"";let i=`${n}${t.length}__`;return t.push(o),i}),s=new RegExp(`${n}(\\d+)__`,"g");return mn(r).replace(s,(o,i)=>t[Number(i)]??"")}function nb(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${ee(r||"",Q.green)}${ee(s||"",Q.chrome)}`}function Br(e){return`$${e.toFixed(2)}`}function rb(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 sb(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=mn(n.toUpperCase()),o=mn(r);return`${t.isDefault?"default":"active"} ${s} ****${o}`}var Q={get reset(){return Re().reset},get visaBlue(){return Re().visaBlue},get visaBlueSoft(){return Re().visaBlueSoft},get visaGold(){return Re().visaGold},get green(){return Re().green},get muted(){return Re().muted},get chrome(){return Re().chrome}};function ee(e,t){return e.length===0||process.env.NO_COLOR||zo()?e:`${t}${e}${Q.reset}`}function Od(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fc(){let e=Wn.homedir();if(!e||!Z.isAbsolute(e))throw new Error("unable to determine a valid home directory");return Z.resolve(e)}function ob(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function ib(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function ab(e){for(let t=0;t<2;t+=1){let n;try{return n=W.openSync(e,"wx"),W.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=W.statSync(e);if(Date.now()-s.mtimeMs<=B_)return!1;W.unlinkSync(e)}catch{}}finally{n!==void 0&&W.closeSync(n)}}return!1}function ac(e){return e instanceof Error?e.message:"unknown file system error"}function Fr(e,t){W.mkdirSync(Z.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${(0,cc.randomBytes)(8).toString("hex")}.tmp`;try{W.writeFileSync(n,t),W.renameSync(n,e)}catch(r){try{W.unlinkSync(n)}catch{}throw r}}var cb=1440*60*1e3;function ri(e,t){ve.mkdirSync(Le.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Gd.randomBytes(8).toString("hex")}.tmp`;try{ve.writeFileSync(n,JSON.stringify(t,null,2)+`
112
- `),ve.renameSync(n,e)}catch(r){try{ve.unlinkSync(n)}catch{}throw r}}function qd(e){return`'${e.replace(/'/g,"'\\''")}'`}var mc="# visa-cli-hud-v1";function si(e,t){if(!e&&!t&&lb())return`visa-cli config statusline ${mc}`;let n=e??process.execPath,r=t??process.argv[1]??"",s=r?Le.resolve(r):"";return`${s?`${qd(n)} ${qd(s)} config statusline`:"visa-cli config statusline"} ${mc}`}function lb(){try{return(0,Wd.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function gn(e){return typeof e!="string"?!1:e.includes(mc)?!0:e.includes("visa-cli")&&e.includes("statusline")}function ub(){return"3.3.1-rc.3"}function oi(e){let t=Le.dirname(Le.resolve(e));return Le.basename(t)===".claude"?Le.dirname(t):Yd.homedir()}function ni(e,t){let n=Le.relative(t,e);return!n.startsWith("..")&&!Le.isAbsolute(n)?`~/${n}`:e}function db(e){return Le.join(oi(e),".visa-cli","hud-self-heal.json")}function fb(e,t,n,r){try{if(!ve.existsSync(e))return!1;let s=JSON.parse(ve.readFileSync(e,"utf-8"));return s.version===t&&typeof s.checkedAt=="number"&&n-s.checkedAt<r}catch{return!1}}function pc(e,t,n){try{ri(e,{version:t,checkedAt:n})}catch{}}function pb(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function gc(e,t={}){let n=t.now??Date.now(),r=t.version??ub(),s=t.stampPath??db(e),o=t.minIntervalMs??cb,i=[],a=!1,c=!1;if(!t.force&&fb(s,r,n,o))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:i,skippedReason:"recently checked"};try{if(!ve.existsSync(e))return pc(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let l=JSON.parse(ve.readFileSync(e,"utf-8")),u=l.statusLine,d=u&&typeof u=="object"&&!Array.isArray(u)?u.command:"";if(!gn(d))return pc(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let p=(t.getCommand??si)();if(d!==p&&(l.statusLine=pb(u,p),ri(e,l),a=!0,i.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!ii()){let f=oi(e);if(Yn(f).length>0){let h=Ut(null,f);if(h.removed&&h.rcPaths&&h.rcPaths.length>0){let w=h.rcPaths.map(C=>ni(C,f)).join(", ");c=!0,i.push(`Cleaned legacy shell-prompt HUD block from ${w}.`)}}}return pc(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i}}catch(l){if(t.force){let u=l instanceof Error?l.message:"unknown error";try{process.stderr.write(`visa-cli: HUD self-heal skipped \u2014 ${u}. Run: visa-cli config hud doctor
113
- `)}catch{}}return{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i}}}function mb(e,t){let n=oi(t),r=Yn(n);if(r.length===0)return e;let s=r.map(o=>ni(o,n)).join(", ");return`${e}
114
- Note: a shell-prompt HUD block was detected in ${s}. If it is unintended, remove it with: visa-cli config hud disable shell`}function ii(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 Kd(e,t){let n=oi(t),r=Yn(n);if(r.length===0)return e;let s=r.map(i=>ni(i,n)).join(", ");if(ii())return`${e}
115
- Note: a legacy shell-prompt HUD block was detected in ${s}. VISA_HUD_KEEP_SHELL set \u2014 leaving it in place. Remove it any time with: visa-cli config hud disable shell`;let o=Ut(null,n);if(o.removed&&o.rcPaths&&o.rcPaths.length>0){let i=o.rcPaths.map(a=>ni(a,n)).join(", ");return`${e}
104
+ `);return`${e}${i}`}function ab(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 yc(e,t){try{let n=Q.dirname(gn());Y.mkdirSync(n,{recursive:!0});let r=e.split(`
105
+ `).map(o=>ub(o)).filter(o=>o.length>0).join(`
106
+ `),s={hudVersion:V_,renderedAt:Date.now(),line:r,cwd:process.cwd(),status:t};Vr(gn(),JSON.stringify(s)+`
107
+ `),Vr(Fs(),r+`
108
+ `)}catch{}}function Yd(e){try{let t=qs();if(!t)return;let n=Math.max(Date.now(),t.renderedAt+1),r={...t,refreshFailedAt:n,refreshErrorReason:hn(e).slice(0,200)};Vr(gn(),JSON.stringify(r)+`
109
+ `)}catch{}}function zd(){try{let e=qs();if(!e)return;let t={...e,renderedAt:0};Vr(gn(),JSON.stringify(t)+`
110
+ `)}catch{}}function Yn(){try{Y.unlinkSync(Vd())}catch{}}function qs(){let e=gn();if(!Y.existsSync(e))return null;try{let t=JSON.parse(Y.readFileSync(e,"utf-8"));return typeof t?.line=="string"&&si(t.line)?null:t}catch{return null}}function si(e){for(let t of e.split(`
111
+ `)){let n=t.trim();if(n.length===0)continue;let r=n.replace(/\[[0-?]*[ -/]*[@-~]/g,"").trim();if(/^VISA\s*\|\s*loading\b/i.test(r)||/^VISA\s*\|\s*HUD\s+not\s+(ready|initialized)\b/i.test(r))return!0}return!1}function Jd(){return qs()?.status??null}function cb(){if(process.env.JEST_WORKER_ID)return;let e=Vd();try{if(Y.mkdirSync(Q.dirname(e),{recursive:!0}),!hb(e))return;let t=process.argv[1]?Q.resolve(process.argv[1]):"";if(!t){Yn();return}let n=Xo(),r=(process.env.VISA_CLI_HUD_THEME??"").toLowerCase().trim(),s=n==="no-color"||r==="light"||r==="dark"?{}:{VISA_CLI_HUD_THEME:n},o=(0,Fd.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,...s,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});o.once("error",Yn),o.unref()}catch{Yn()}}function hn(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 lb=/^\u001B\[(?:0|38;2;\d{1,3};\d{1,3};\d{1,3}|38;5;\d{1,3})m$/;function ub(e){let t=[],n=`__VISA_CLI_HUD_SGR_${(0,pc.randomBytes)(8).toString("hex")}_`,r=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,o=>{if(!lb.test(o))return"";let i=`${n}${t.length}__`;return t.push(o),i}),s=new RegExp(`${n}(\\d+)__`,"g");return hn(r).replace(s,(o,i)=>t[Number(i)]??"")}function db(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 Hr(e){return`$${e.toFixed(2)}`}function fb(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 mb(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=hn(n.toUpperCase()),o=hn(r);return`${t.isDefault?"default":"active"} ${s} ****${o}`}var ee={get reset(){return Re().reset},get visaBlue(){return Re().visaBlue},get visaBlueSoft(){return Re().visaBlueSoft},get visaGold(){return Re().visaGold},get green(){return Re().green},get muted(){return Re().muted},get chrome(){return Re().chrome}};function te(e,t){return e.length===0||process.env.NO_COLOR||Zo()?e:`${t}${e}${ee.reset}`}function Bd(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _c(){let e=zn.homedir();if(!e||!Q.isAbsolute(e))throw new Error("unable to determine a valid home directory");return Q.resolve(e)}function pb(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function gb(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function hb(e){for(let t=0;t<2;t+=1){let n;try{return n=Y.openSync(e,"wx"),Y.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=Y.statSync(e);if(Date.now()-s.mtimeMs<=z_)return!1;Y.unlinkSync(e)}catch{}}finally{n!==void 0&&Y.closeSync(n)}}return!1}function mc(e){return e instanceof Error?e.message:"unknown file system error"}function Vr(e,t){Y.mkdirSync(Q.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${(0,pc.randomBytes)(8).toString("hex")}.tmp`;try{Y.writeFileSync(n,t),Y.renameSync(n,e)}catch(r){try{Y.unlinkSync(n)}catch{}throw r}}var yb=1440*60*1e3;function ii(e,t){ve.mkdirSync(Le.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Qd.randomBytes(8).toString("hex")}.tmp`;try{ve.writeFileSync(n,JSON.stringify(t,null,2)+`
112
+ `),ve.renameSync(n,e)}catch(r){try{ve.unlinkSync(n)}catch{}throw r}}function Xd(e){return`'${e.replace(/'/g,"'\\''")}'`}var vc="# visa-cli-hud-v1";function ai(e,t){if(!e&&!t&&_b())return`visa-cli config statusline ${vc}`;let n=e??process.execPath,r=t??process.argv[1]??"",s=r?Le.resolve(r):"";return`${s?`${Xd(n)} ${Xd(s)} config statusline`:"visa-cli config statusline"} ${vc}`}function _b(){try{return(0,ef.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function yn(e){return typeof e!="string"?!1:e.includes(vc)?!0:e.includes("visa-cli")&&e.includes("statusline")}function bb(){return"3.4.0-rc.5"}function ci(e){let t=Le.dirname(Le.resolve(e));return Le.basename(t)===".claude"?Le.dirname(t):tf.homedir()}function oi(e,t){let n=Le.relative(t,e);return!n.startsWith("..")&&!Le.isAbsolute(n)?`~/${n}`:e}function vb(e){return Le.join(ci(e),".visa-cli","hud-self-heal.json")}function wb(e,t,n,r){try{if(!ve.existsSync(e))return!1;let s=JSON.parse(ve.readFileSync(e,"utf-8"));return s.version===t&&typeof s.checkedAt=="number"&&n-s.checkedAt<r}catch{return!1}}function bc(e,t,n){try{ii(e,{version:t,checkedAt:n})}catch{}}function Sb(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function wc(e,t={}){let n=t.now??Date.now(),r=t.version??bb(),s=t.stampPath??vb(e),o=t.minIntervalMs??yb,i=[],a=!1,c=!1;if(!t.force&&wb(s,r,n,o))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:i,skippedReason:"recently checked"};try{if(!ve.existsSync(e))return bc(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let l=JSON.parse(ve.readFileSync(e,"utf-8")),u=l.statusLine,d=u&&typeof u=="object"&&!Array.isArray(u)?u.command:"";if(!yn(d))return bc(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let m=(t.getCommand??ai)();if(d!==m&&(l.statusLine=Sb(u,m),ii(e,l),a=!0,i.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!li()){let f=ci(e);if(Jn(f).length>0){let h=Dt(null,f);if(h.removed&&h.rcPaths&&h.rcPaths.length>0){let w=h.rcPaths.map(k=>oi(k,f)).join(", ");c=!0,i.push(`Cleaned legacy shell-prompt HUD block from ${w}.`)}}}return bc(s,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i}}catch(l){if(t.force){let u=l instanceof Error?l.message:"unknown error";try{process.stderr.write(`visa-cli: HUD self-heal skipped \u2014 ${u}. Run: visa-cli config hud doctor
113
+ `)}catch{}}return{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i}}}function xb(e,t){let n=ci(t),r=Jn(n);if(r.length===0)return e;let s=r.map(o=>oi(o,n)).join(", ");return`${e}
114
+ Note: a shell-prompt HUD block was detected in ${s}. If it is unintended, remove it with: visa-cli config hud disable shell`}function li(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 Zd(e,t){let n=ci(t),r=Jn(n);if(r.length===0)return e;let s=r.map(i=>oi(i,n)).join(", ");if(li())return`${e}
115
+ Note: a legacy shell-prompt HUD block was detected in ${s}. VISA_HUD_KEEP_SHELL set \u2014 leaving it in place. Remove it any time with: visa-cli config hud disable shell`;let o=Dt(null,n);if(o.removed&&o.rcPaths&&o.rcPaths.length>0){let i=o.rcPaths.map(a=>oi(a,n)).join(", ");return`${e}
116
116
  Cleaned legacy shell-prompt HUD block from ${i} (was leaking output above every shell prompt). Set VISA_HUD_KEEP_SHELL=true to keep both surfaces (also accepts 1, yes, on).`}return`${e}
117
- Note: a legacy shell-prompt HUD block was detected in ${s} but could not be auto-removed (${o.message}). Remove it manually with: visa-cli config hud disable shell`}function Hs(e,t=si){let n={},r=!1;if(ve.existsSync(e)){r=!0;try{n=JSON.parse(ve.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 gn(s)?{installed:"already-visa",message:Kd("Visa HUD already registered in ~/.claude/settings.json.",e)}:{installed:"other-hud-present",message:mb("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()},ri(e,n),{installed:"new",message:Kd(`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 hc(e){if(!ve.existsSync(e))return{removed:!1,status:"missing-settings",message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(ve.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(!gn(n))return{removed:!1,status:"foreign-statusline",message:"statusLine is owned by another tool \u2014 leaving it alone."};delete t.statusLine;try{ri(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 zd=R(require("os")),Jd=R(require("path"));function Dt(e=zd.homedir()){return Jd.join(e,".claude","settings.json")}var jt=R(require("fs")),gt=R(require("path"));var gb=1,zn={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},hb=["terminal","claude","claude-code","all"];function ci(e){let t=e.toLowerCase();return hb.includes(t)?t:null}var yb=50,_b=64*1024,Xd=10,yc=80,N={get reset(){return Re().reset},get visaBlue(){return Re().visaBlue},get visaBlueSoft(){return Re().visaBlueSoft},get visaGold(){return Re().visaGold},get green(){return Re().green},get muted(){return Re().muted},get chrome(){return Re().chrome}};function L(e,t){return e.length===0||process.env.NO_COLOR||zo()?e:`${t}${e}${N.reset}`}function Zd(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function nf(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)},yb);e.on("data",i),e.on("end",a),e.on("error",c)})}function Vs(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${L(r||"",N.visaBlueSoft)}${L(s||"",N.chrome)}`}function qs(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 bb(e){if(pf(e))return wb(e);let t=` ${L("\u2502",N.chrome)} `,n=ai(e)||"claude",r=e.cwd?me(gt.basename(e.cwd)):"",s=li(e.workspace),o=r||s,i=s&&s!==o?` ${L(`@${s}`,N.visaBlueSoft)}`:"",a=[L(`[${n}]`,N.visaBlueSoft)];o&&a.push(`${L(o,N.visaGold)}${i}`);let c=me(e.git_branch??e.branch??"");c&&a.push(`${L("git:(",N.muted)}${L(c,N.visaBlueSoft)}${L(")",N.muted)}`);let l=a.join(t),u=Number(e.context_window?.context_window_size??0),d=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,p=e.context_window?.current_usage,f=[p?.input_tokens,p?.output_tokens,p?.cache_creation_input_tokens,p?.cache_read_input_tokens].filter(I=>typeof I=="number"&&Number.isFinite(I)),m=f.length>0?f.reduce((I,y)=>I+y,0):null,h=Number(e.context_window?.total_input_tokens??m??p?.input_tokens??0),w=d!==null?Math.max(0,Math.min(1,d/100)):u>0?Math.max(0,Math.min(1,h/u)):0,C=d!==null&&u>0?Math.round(w*u):h,b;if(u>0||d!==null){let I=`${String(Math.round(w*100)).padStart(2," ")}%`,y=u>0?` ${L(`(${qs(C)}/${qs(u)})`,N.muted)}`:"";b=`${L("Context",N.muted)} ${Vs(w)} ${L(I,N.green)}${y}`}else b=`${L("Context",N.muted)} ${L("-",N.muted)}`;let v=rf(e.rate_limits),S=[b];v&&S.push(v);let A=S.join(t);return`${l}
118
- ${A}`}function vb(e){if(pf(e))return null;let t=` ${L("\u2502",N.chrome)} `,n=ai(e)||"claude",r=e.cwd?me(gt.basename(e.cwd)):"",s=li(e.workspace),o=r||s,i=s&&s!==o?` ${L(`@${s}`,N.visaBlueSoft)}`:"",a=[L(`[${n}]`,N.visaBlueSoft)];o&&a.push(`${L(o,N.visaGold)}${i}`);let c=me(e.git_branch??e.branch??"");c&&a.push(`${L("git:(",N.muted)}${L(c,N.visaBlueSoft)}${L(")",N.muted)}`);let l=Number(e.context_window?.context_window_size??0),u=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,d=e.context_window?.current_usage,p=[d?.input_tokens,d?.output_tokens,d?.cache_creation_input_tokens,d?.cache_read_input_tokens].filter(S=>typeof S=="number"&&Number.isFinite(S)),f=p.length>0?p.reduce((S,A)=>S+A,0):null,m=Number(e.context_window?.total_input_tokens??f??d?.input_tokens??0),h=u!==null?Math.max(0,Math.min(1,u/100)):l>0?Math.max(0,Math.min(1,m/l)):0,w=u!==null&&l>0?Math.round(h*l):m,C;if(l>0||u!==null){let S=`${String(Math.round(h*100)).padStart(2," ")}%`,A=l>0?` ${L(`(${qs(w)}/${qs(l)})`,N.muted)}`:"";C=`${L("Context",N.muted)} ${Vs(h)} ${L(S,N.green)}${A}`}else C=`${L("Context",N.muted)} ${L("-",N.muted)}`;let b=rf(e.rate_limits),v=[C];return b&&v.push(b),{identity:a.join(t),metrics:v.join(t)}}function wb(e){let t=` ${L("\u2502",N.chrome)} `,n=mf(e),r=n.model||"codex",s=[L(`[${r}]`,N.visaBlueSoft)];n.project&&s.push(L(n.project,N.visaGold)),n.gitBranch&&s.push(`${L("git",N.muted)} ${L(n.gitBranch,N.visaGold)}`);let o=s.join(t),i=[];if(typeof n.contextUsedPercent=="number"){let c=Math.max(0,Math.min(1,n.contextUsedPercent/100));i.push(`${L("Context",N.muted)} ${Vs(c)} ${L(`${Math.round(n.contextUsedPercent)}%`,N.green)}`)}else if(typeof n.contextRemainingPercent=="number"){let c=100-n.contextRemainingPercent,l=Math.max(0,Math.min(1,c/100));i.push(`${L("Context",N.muted)} ${Vs(l)} ${L(`${Math.round(c)}%`,N.green)}`)}typeof n.usedTokens=="number"&&i.push(`${L("Tokens",N.muted)} ${qs(n.usedTokens)}`),n.status&&i.push(`${L("Status",N.muted)} ${L(n.status,N.visaBlueSoft)}`),n.threadTitle&&i.push(`${L("Thread",N.muted)} ${L(n.threadTitle,N.visaBlueSoft)}`);let a=i.length>0?i.join(t):`${L("Context",N.muted)} ${L("-",N.muted)}`;return`${o}
119
- ${a}`}function Sb(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 Qd(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=Vs(r),o=n>=90?"\x1B[38;5;196m":n>=70?N.visaGold:N.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=Sb(e.resets_at),c=a?` ${L(`(${a} / ${t})`,N.muted)}`:` ${L(`(${t})`,N.muted)}`;return`${s} ${L(i,o)}${c}`}function rf(e){if(!e)return null;let t=Qd(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?Qd(e.seven_day,"7d"):null;if(!t&&!r)return null;let s=` ${L("\u2502",N.chrome)} `,o=[t,r].filter(Boolean);return`${L("Usage",N.muted)} ${o.join(s)}`}function sf(e){let t;try{let n=jt.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let s=Math.min(r,_b),o=r-s;t=jt.openSync(e,"r");let i=Buffer.alloc(s);jt.readSync(t,i,0,s,o);let a=i.toString("utf-8");if(o>0){let c=Buffer.alloc(1);if(jt.readSync(t,c,0,1,o-1),c[0]!==10){let l=a.indexOf(`
120
- `);l>=0&&(a=a.slice(l+1))}}return a}catch{return null}finally{if(t!==void 0)try{jt.closeSync(t)}catch{}}}function xb(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=gt.basename(gt.dirname(s)),i=gt.basename(s);return o&&o!=="."&&o!=="/"?`${o}/${i}`:i}return s}}}function Tb(e){let t=e.split(`
121
- `),n=[],r=new Set;for(let s=t.length-1;s>=0&&n.length<Xd*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 p=typeof d.id=="string"?d.id:"",f=p.length>0?!r.has(p):!1;n.push({name:d.name,target:xb(d.input),running:f})}}}return n.reverse(),n.slice(Math.max(0,n.length-Xd))}function Cb(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 kb(e){let t=e.running?L("\u25D0",N.visaGold):L("\u2713",N.green),n=e.running?N.visaGold:N.visaBlueSoft,r=L(me(e.name),n),s=e.target?me(e.target):"",o=s?`${L(":",N.chrome)} ${L(s,N.muted)}`:"",i=e.count>1?` ${L(`\xD7${e.count}`,N.muted)}`:"";return o?`${t} ${r}${o}${i}`:`${t} ${r}${i}`}function Eb(e){let t=` ${L("\u2502",N.chrome)} `,n=Zd(t),r=e.slice();for(;r.length>0;){let c=r.join(t);if(Zd(c)<=yc)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>yc-n-1?i.slice(0,yc-n-1)+s:i;return`${L(s,N.muted)}${t}${a}`}async function ef(e){if(!e||typeof e!="string")return null;let t=sf(e);if(!t)return null;let n;try{n=Tb(t)}catch{return null}if(n.length===0)return null;let s=Cb(n).map(kb);return Eb(s)||null}async function of(e,t,n){return(await cf(e,t,n)).join(`
122
- `)}function af(e,t,n){let r=!!t?.activeSession||e.includes("in session"),s=n?Rb(n):!1;return{isActive:r||s,hasSession:r,hasToolActivity:s}}async function cf(e,t,n){let{isActive:r}=af(e,n,t?.transcript_path),s=e.split(`
123
- `).filter(a=>a.length>0),i=t&&!r?s.map(a=>L(_c(a),N.muted)):[...s];if(t){let a=vb(t);if(a){if(i.push(a.identity),t.transcript_path){let c=await ef(t.transcript_path);c&&i.push(...c.split(`
124
- `))}i.push(a.metrics)}else{let c=bb(t);if(c&&i.push(...c.split(`
125
- `)),t.transcript_path){let l=await ef(t.transcript_path);l&&i.push(...l.split(`
126
- `))}}}return i}var Ab=["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 Rb(e){let t=sf(e);if(!t)return!1;let n=t.slice(-16384).toLowerCase();return Ab.some(r=>n.includes(`"${r}"`))}async function lf(e,t,n){let r=await cf(e,t,n),s=r.join(`
127
- `),{isActive:o}=af(e,n,t?.transcript_path);return{schemaVersion:gb,client:t?ff(t):zn.UNKNOWN,rendered:s,lines:r.map(_c),visa:{spendLine:_c(e),balanceCents:n?.balanceCents,balanceMicros:n?.balanceMicros,balanceUsd:n?.amountUsd,sessionMode:n?.sessionMode,activeSession:n?.activeSession,isVisaActive:o},context:t?mf(t):{}}}function me(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 li(e){if(typeof e=="string")return me(gt.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 me(t?gt.basename(t):e.name)}function uf(e){return me(e.app_name??e.appName??e.app??e.client)}function ai(e){return me(e.model?.display_name??e.model?.id??e.model_name??e.modelName)}function df(e){return me(e.cwd??e.current_dir??e.project_root)}function tf(e){let t=me(e.project);if(t)return t;let n=df(e);if(n)return me(gt.basename(n));let r=li(e.workspace);return r||""}function tt(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function ff(e){let t=uf(e).toLowerCase();return t.includes("codex")?zn.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?zn.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||tt(e.context_used)!==void 0?zn.CODEX:zn.UNKNOWN}function pf(e){return ff(e)===zn.CODEX}function mf(e){let t=uf(e),n=df(e),r=li(e.workspace),s=tt(e.context_used)??tt(e.context_window?.used_percentage??void 0),o=tt(e.context_remaining)??tt(e.context_window?.remaining_percentage??void 0);return{...t?{app:t}:{},...ai(e)?{model:ai(e)}:{},...tf(e)?{project:tf(e)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...me(e.git_branch??e.branch)?{gitBranch:me(e.git_branch??e.branch)}:{},...me(e.status??e.run_state??e.runState)?{status:me(e.status??e.run_state??e.runState)}:{},...me(e.thread_title??e.threadTitle)?{threadTitle:me(e.thread_title??e.threadTitle)}:{},...s!==void 0?{contextUsedPercent:s}:{},...o!==void 0?{contextRemainingPercent:o}:{},...tt(e.used_tokens)!==void 0?{usedTokens:tt(e.used_tokens)}:{},...tt(e.total_input_tokens)!==void 0?{totalInputTokens:tt(e.total_input_tokens)}:{},...tt(e.total_output_tokens)!==void 0?{totalOutputTokens:tt(e.total_output_tokens)}:{}}}function _c(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}var hf=R(require("path"));function gf(e){return e instanceof Error?e.message:String(e)}function bc(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: ${gf(a)}`]}}if(!o)return{ok:!1,messages:n,errors:[`Unknown HUD surface: ${s}`,"Supported: claude (default), shell, all"]};let i=!0;if(o==="claude"||o==="claude-code"||o==="all"){let a=hf.join(t.homeDir,".claude","settings.json");try{let c=t.installVisaStatusLine(a);n.push(c.message),(c.installed==="error"||c.installed==="malformed-json")&&(i=!1)}catch(c){i=!1,r.push(`Failed to install Claude HUD: ${gf(c)}`)}}return{ok:i,messages:n,errors:r}}function yf(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 _f=R(require("os")),bf=require("node:readline/promises"),Ks={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,bf.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 Ib(e,t){return e.replace(/[\x00-\x1F\x7F\u202A-\u202E\u2066-\u2069]/g,"").trim()||t}function vf(e=_f.hostname()){let t=Is().version,n=Ib(e,"this-machine");return[" Preview if installed (sample):",` VISA CLI v${t} | ${n} | ${Ks.card}`,` ${Ks.balance} | ${Ks.spentToday} | ${Ks.lastActivity}`,` [${Ks.model}] | you`," Activity live"].join(`
128
- `)}function wf(e="CLI"){return[" \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557"," \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551"," \u255A\u2588\u2588\u2557 \u2588\u2588\u2554\u255D\u2588\u2588\u2551\u255A\u2550\u2550\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551"," \u255A\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551",e?` \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u2588 ${e}`:" \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D"]}function wc(e){return`$${(e/100).toFixed(2)}`}function Sf(e){return typeof e=="number"?wc(e):"no cap"}function xf(e){return e.length>0?e.join(", "):"all tools"}var $b=[" \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 Pb(){return[...wf(null),...$b].join(`
129
- `)}var Tf="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 Ob(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 Cf(e,t={}){let n=t.authUrl??"https://auth.visacli.sh",r=[...Pb().split(`
130
- `),"","Visa Key active","Scoped agent spend credential ready for apps and agents","",...Ob([["Key",e.key],["Label",e.label],["Owner",e.owner],["Daily cap",`${wc(e.daily_cap_cents)}/day`],["Total cap",Sf(e.total_cap_cents)],["Allowed tools",xf(e.allowed_tools)]]),"","Guardrails",`- Spend: ${wc(e.daily_cap_cents)}/day, ${Sf(e.total_cap_cents)} total`,`- Tools: ${xf(e.allowed_tools)}`,"- Auth: X-Api-Key header; no OAuth handoff or per-call Touch ID","","Use it","Save this key now - it won't be shown again.","",`export VISAKEY_API_KEY=${e.key}`,"",`POST ${n}/v1/api/tools/{tool_name}/execute`,"Headers: X-Api-Key, Idempotency-Key, Content-Type: application/json"];return e.biometric_warning?r.push("",Tf,`Server warning: ${e.biometric_warning}`):e.biometric_enabled&&r.push("",Tf),`${r.join(`
117
+ Note: a legacy shell-prompt HUD block was detected in ${s} but could not be auto-removed (${o.message}). Remove it manually with: visa-cli config hud disable shell`}function Ks(e,t=ai){let n={},r=!1;if(ve.existsSync(e)){r=!0;try{n=JSON.parse(ve.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 yn(s)?{installed:"already-visa",message:Zd("Visa HUD already registered in ~/.claude/settings.json.",e)}:{installed:"other-hud-present",message:xb("Another HUD is already configured (keeping it). To switch to Visa HUD, edit ~/.claude/settings.json \u2192 statusLine.command",e)}}try{return n.statusLine={type:"command",command:t()},ii(e,n),{installed:"new",message:Zd(`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 Sc(e){if(!ve.existsSync(e))return{removed:!1,status:"missing-settings",message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(ve.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(!yn(n))return{removed:!1,status:"foreign-statusline",message:"statusLine is owned by another tool \u2014 leaving it alone."};delete t.statusLine;try{ii(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 nf=R(require("os")),rf=R(require("path"));function jt(e=nf.homedir()){return rf.join(e,".claude","settings.json")}var Bt=R(require("fs")),ht=R(require("path"));var Tb=1,Xn={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},kb=["terminal","claude","claude-code","all"];function di(e){let t=e.toLowerCase();return kb.includes(t)?t:null}var Cb=50,Ab=64*1024,sf=10,xc=80,N={get reset(){return Re().reset},get visaBlue(){return Re().visaBlue},get visaBlueSoft(){return Re().visaBlueSoft},get visaGold(){return Re().visaGold},get green(){return Re().green},get muted(){return Re().muted},get chrome(){return Re().chrome}};function L(e,t){return e.length===0||process.env.NO_COLOR||Zo()?e:`${t}${e}${N.reset}`}function of(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function uf(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)},Cb);e.on("data",i),e.on("end",a),e.on("error",c)})}function Gs(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${L(r||"",N.visaBlueSoft)}${L(s||"",N.chrome)}`}function Ws(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 Eb(e){if(vf(e))return Ib(e);let t=` ${L("\u2502",N.chrome)} `,n=ui(e)||"claude",r=e.cwd?ge(ht.basename(e.cwd)):"",s=fi(e.workspace),o=r||s,i=s&&s!==o?` ${L(`@${s}`,N.visaBlueSoft)}`:"",a=[L(`[${n}]`,N.visaBlueSoft)];o&&a.push(`${L(o,N.visaGold)}${i}`);let c=ge(e.git_branch??e.branch??"");c&&a.push(`${L("git:(",N.muted)}${L(c,N.visaBlueSoft)}${L(")",N.muted)}`);let l=a.join(t),u=Number(e.context_window?.context_window_size??0),d=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,m=e.context_window?.current_usage,f=[m?.input_tokens,m?.output_tokens,m?.cache_creation_input_tokens,m?.cache_read_input_tokens].filter(I=>typeof I=="number"&&Number.isFinite(I)),p=f.length>0?f.reduce((I,y)=>I+y,0):null,h=Number(e.context_window?.total_input_tokens??p??m?.input_tokens??0),w=d!==null?Math.max(0,Math.min(1,d/100)):u>0?Math.max(0,Math.min(1,h/u)):0,k=d!==null&&u>0?Math.round(w*u):h,b;if(u>0||d!==null){let I=`${String(Math.round(w*100)).padStart(2," ")}%`,y=u>0?` ${L(`(${Ws(k)}/${Ws(u)})`,N.muted)}`:"";b=`${L("Context",N.muted)} ${Gs(w)} ${L(I,N.green)}${y}`}else b=`${L("Context",N.muted)} ${L("-",N.muted)}`;let v=df(e.rate_limits),S=[b];v&&S.push(v);let E=S.join(t);return`${l}
118
+ ${E}`}function Rb(e){if(vf(e))return null;let t=` ${L("\u2502",N.chrome)} `,n=ui(e)||"claude",r=e.cwd?ge(ht.basename(e.cwd)):"",s=fi(e.workspace),o=r||s,i=s&&s!==o?` ${L(`@${s}`,N.visaBlueSoft)}`:"",a=[L(`[${n}]`,N.visaBlueSoft)];o&&a.push(`${L(o,N.visaGold)}${i}`);let c=ge(e.git_branch??e.branch??"");c&&a.push(`${L("git:(",N.muted)}${L(c,N.visaBlueSoft)}${L(")",N.muted)}`);let l=Number(e.context_window?.context_window_size??0),u=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,d=e.context_window?.current_usage,m=[d?.input_tokens,d?.output_tokens,d?.cache_creation_input_tokens,d?.cache_read_input_tokens].filter(S=>typeof S=="number"&&Number.isFinite(S)),f=m.length>0?m.reduce((S,E)=>S+E,0):null,p=Number(e.context_window?.total_input_tokens??f??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,w=u!==null&&l>0?Math.round(h*l):p,k;if(l>0||u!==null){let S=`${String(Math.round(h*100)).padStart(2," ")}%`,E=l>0?` ${L(`(${Ws(w)}/${Ws(l)})`,N.muted)}`:"";k=`${L("Context",N.muted)} ${Gs(h)} ${L(S,N.green)}${E}`}else k=`${L("Context",N.muted)} ${L("-",N.muted)}`;let b=df(e.rate_limits),v=[k];return b&&v.push(b),{identity:a.join(t),metrics:v.join(t)}}function Ib(e){let t=` ${L("\u2502",N.chrome)} `,n=wf(e),r=n.model||"codex",s=[L(`[${r}]`,N.visaBlueSoft)];n.project&&s.push(L(n.project,N.visaGold)),n.gitBranch&&s.push(`${L("git",N.muted)} ${L(n.gitBranch,N.visaGold)}`);let o=s.join(t),i=[];if(typeof n.contextUsedPercent=="number"){let c=Math.max(0,Math.min(1,n.contextUsedPercent/100));i.push(`${L("Context",N.muted)} ${Gs(c)} ${L(`${Math.round(n.contextUsedPercent)}%`,N.green)}`)}else if(typeof n.contextRemainingPercent=="number"){let c=100-n.contextRemainingPercent,l=Math.max(0,Math.min(1,c/100));i.push(`${L("Context",N.muted)} ${Gs(l)} ${L(`${Math.round(c)}%`,N.green)}`)}typeof n.usedTokens=="number"&&i.push(`${L("Tokens",N.muted)} ${Ws(n.usedTokens)}`),n.status&&i.push(`${L("Status",N.muted)} ${L(n.status,N.visaBlueSoft)}`),n.threadTitle&&i.push(`${L("Thread",N.muted)} ${L(n.threadTitle,N.visaBlueSoft)}`);let a=i.length>0?i.join(t):`${L("Context",N.muted)} ${L("-",N.muted)}`;return`${o}
119
+ ${a}`}function $b(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 af(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=Gs(r),o=n>=90?"\x1B[38;5;196m":n>=70?N.visaGold:N.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=$b(e.resets_at),c=a?` ${L(`(${a} / ${t})`,N.muted)}`:` ${L(`(${t})`,N.muted)}`;return`${s} ${L(i,o)}${c}`}function df(e){if(!e)return null;let t=af(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?af(e.seven_day,"7d"):null;if(!t&&!r)return null;let s=` ${L("\u2502",N.chrome)} `,o=[t,r].filter(Boolean);return`${L("Usage",N.muted)} ${o.join(s)}`}function ff(e){let t;try{let n=Bt.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let s=Math.min(r,Ab),o=r-s;t=Bt.openSync(e,"r");let i=Buffer.alloc(s);Bt.readSync(t,i,0,s,o);let a=i.toString("utf-8");if(o>0){let c=Buffer.alloc(1);if(Bt.readSync(t,c,0,1,o-1),c[0]!==10){let l=a.indexOf(`
120
+ `);l>=0&&(a=a.slice(l+1))}}return a}catch{return null}finally{if(t!==void 0)try{Bt.closeSync(t)}catch{}}}function Pb(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=ht.basename(ht.dirname(s)),i=ht.basename(s);return o&&o!=="."&&o!=="/"?`${o}/${i}`:i}return s}}}function Ob(e){let t=e.split(`
121
+ `),n=[],r=new Set;for(let s=t.length-1;s>=0&&n.length<sf*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 m=typeof d.id=="string"?d.id:"",f=m.length>0?!r.has(m):!1;n.push({name:d.name,target:Pb(d.input),running:f})}}}return n.reverse(),n.slice(Math.max(0,n.length-sf))}function Mb(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 Nb(e){let t=e.running?L("\u25D0",N.visaGold):L("\u2713",N.green),n=e.running?N.visaGold:N.visaBlueSoft,r=L(ge(e.name),n),s=e.target?ge(e.target):"",o=s?`${L(":",N.chrome)} ${L(s,N.muted)}`:"",i=e.count>1?` ${L(`\xD7${e.count}`,N.muted)}`:"";return o?`${t} ${r}${o}${i}`:`${t} ${r}${i}`}function Lb(e){let t=` ${L("\u2502",N.chrome)} `,n=of(t),r=e.slice();for(;r.length>0;){let c=r.join(t);if(of(c)<=xc)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>xc-n-1?i.slice(0,xc-n-1)+s:i;return`${L(s,N.muted)}${t}${a}`}async function cf(e){if(!e||typeof e!="string")return null;let t=ff(e);if(!t)return null;let n;try{n=Ob(t)}catch{return null}if(n.length===0)return null;let s=Mb(n).map(Nb);return Lb(s)||null}async function mf(e,t,n){return(await gf(e,t,n)).join(`
122
+ `)}function pf(e,t,n){let r=!!t?.activeSession||e.includes("in session"),s=n?Db(n):!1;return{isActive:r||s,hasSession:r,hasToolActivity:s}}async function gf(e,t,n){let{isActive:r}=pf(e,n,t?.transcript_path),s=e.split(`
123
+ `).filter(a=>a.length>0),i=t&&!r?s.map(a=>L(Tc(a),N.muted)):[...s];if(t){let a=Rb(t);if(a){if(i.push(a.identity),t.transcript_path){let c=await cf(t.transcript_path);c&&i.push(...c.split(`
124
+ `))}i.push(a.metrics)}else{let c=Eb(t);if(c&&i.push(...c.split(`
125
+ `)),t.transcript_path){let l=await cf(t.transcript_path);l&&i.push(...l.split(`
126
+ `))}}}return i}var Ub=["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 Db(e){let t=ff(e);if(!t)return!1;let n=t.slice(-16384).toLowerCase();return Ub.some(r=>n.includes(`"${r}"`))}async function hf(e,t,n){let r=await gf(e,t,n),s=r.join(`
127
+ `),{isActive:o}=pf(e,n,t?.transcript_path);return{schemaVersion:Tb,client:t?bf(t):Xn.UNKNOWN,rendered:s,lines:r.map(Tc),visa:{spendLine:Tc(e),balanceCents:n?.balanceCents,balanceMicros:n?.balanceMicros,balanceUsd:n?.amountUsd,sessionMode:n?.sessionMode,activeSession:n?.activeSession,isVisaActive:o},context:t?wf(t):{}}}function ge(e){return e?e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim():""}function fi(e){if(typeof e=="string")return ge(ht.basename(e));if(!e||typeof e!="object")return"";let t=typeof e.current_dir=="string"?e.current_dir:typeof e.path=="string"?e.path:"";return ge(t?ht.basename(t):e.name)}function yf(e){return ge(e.app_name??e.appName??e.app??e.client)}function ui(e){return ge(e.model?.display_name??e.model?.id??e.model_name??e.modelName)}function _f(e){return ge(e.cwd??e.current_dir??e.project_root)}function lf(e){let t=ge(e.project);if(t)return t;let n=_f(e);if(n)return ge(ht.basename(n));let r=fi(e.workspace);return r||""}function tt(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function bf(e){let t=yf(e).toLowerCase();return t.includes("codex")?Xn.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?Xn.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||tt(e.context_used)!==void 0?Xn.CODEX:Xn.UNKNOWN}function vf(e){return bf(e)===Xn.CODEX}function wf(e){let t=yf(e),n=_f(e),r=fi(e.workspace),s=tt(e.context_used)??tt(e.context_window?.used_percentage??void 0),o=tt(e.context_remaining)??tt(e.context_window?.remaining_percentage??void 0);return{...t?{app:t}:{},...ui(e)?{model:ui(e)}:{},...lf(e)?{project:lf(e)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...ge(e.git_branch??e.branch)?{gitBranch:ge(e.git_branch??e.branch)}:{},...ge(e.status??e.run_state??e.runState)?{status:ge(e.status??e.run_state??e.runState)}:{},...ge(e.thread_title??e.threadTitle)?{threadTitle:ge(e.thread_title??e.threadTitle)}:{},...s!==void 0?{contextUsedPercent:s}:{},...o!==void 0?{contextRemainingPercent:o}:{},...tt(e.used_tokens)!==void 0?{usedTokens:tt(e.used_tokens)}:{},...tt(e.total_input_tokens)!==void 0?{totalInputTokens:tt(e.total_input_tokens)}:{},...tt(e.total_output_tokens)!==void 0?{totalOutputTokens:tt(e.total_output_tokens)}:{}}}function Tc(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}var xf=R(require("path"));function Sf(e){return e instanceof Error?e.message:String(e)}function kc(e,t){let n=[],r=[],s=e??"claude",o=di(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: ${Sf(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=xf.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: ${Sf(c)}`)}}return{ok:i,messages:n,errors:r}}function Tf(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 kf=R(require("os")),Cf=require("node:readline/promises"),Ys={card:"default VISA ****7242",balance:"balance $6.38",spentToday:"spent today $0.62",lastActivity:"last Visa tool 38m",model:"Opus 4.6"};async function Cc(e,t=!1){if(!process.stdin.isTTY)return t;let n=t?"[Y/n]":"[y/N]",r,s;try{r=(0,Cf.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 jb(e,t){return e.replace(/[\x00-\x1F\x7F\u202A-\u202E\u2066-\u2069]/g,"").trim()||t}function Af(e=kf.hostname()){let t=Os().version,n=jb(e,"this-machine");return[" Preview if installed (sample):",` VISA CLI v${t} | ${n} | ${Ys.card}`,` ${Ys.balance} | ${Ys.spentToday} | ${Ys.lastActivity}`,` [${Ys.model}] | you`," Activity live"].join(`
128
+ `)}function Ef(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 Ac(e){return`$${(e/100).toFixed(2)}`}function Rf(e){return typeof e=="number"?Ac(e):"no cap"}function If(e){return e.length>0?e.join(", "):"all tools"}var Bb=[" \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 Fb(){return[...Ef(null),...Bb].join(`
129
+ `)}var $f="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 Hb(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 Pf(e,t={}){let n=t.authUrl??"https://auth.visacli.sh",r=[...Fb().split(`
130
+ `),"","Visa Key active","Scoped agent spend credential ready for apps and agents","",...Hb([["Key",e.key],["Label",e.label],["Owner",e.owner],["Daily cap",`${Ac(e.daily_cap_cents)}/day`],["Total cap",Rf(e.total_cap_cents)],["Allowed tools",If(e.allowed_tools)]]),"","Guardrails",`- Spend: ${Ac(e.daily_cap_cents)}/day, ${Rf(e.total_cap_cents)} total`,`- Tools: ${If(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("",$f,`Server warning: ${e.biometric_warning}`):e.biometric_enabled&&r.push("",$f),`${r.join(`
131
131
  `)}
132
- `}function kf(e){return e.json===!0||e.isTTY!==!0}function Sc(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 xc(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 Ef(e,t){let n=Sc(e);if(n!==void 0)return n;if(kf(t))return 500}function Af(e,t){let n=xc(e);if(n!==void 0)return n;if(kf(t)||t.recommendedCapsAccepted===!0)return 2500}async function ht(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,s=setTimeout(()=>r.abort(),n);try{let{timeoutMs:o,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(s)}}var Jn=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},Vr=class extends Error{code;budgetId;status;constructor(t,n,r={}){super(t),this.name="SessionInvalidError",this.code=n,this.budgetId=r.budgetId,this.status=r.status}},Bt=class extends Error{code="SESSION_LOCK_CONTENDED";retryAfterSecs;status;constructor(t,n=1,r){super(t),this.name="SessionLockContendedError",this.retryAfterSecs=n,this.status=r}},yt=class extends Error{code="PARENTLESS_NOT_ENABLED";status;serverErrorCode;constructor(t,n={}){super(t),this.name="ParentlessNotEnabledError",this.status=n.status,this.serverErrorCode=n.serverErrorCode}},ge=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(t,n,r,s,o,i,a,c){super(t),this.name="CardDeclinedError",this.retryable=n,this.code=r,this.reason=s,this.paymentErrorClass=o,this.correlationId=i,this.transactionId=a,this.retryAfter=c}},nt=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 Rf={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 qr(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&&Rf[n]?Rf[n]:`Network error contacting the Visa CLI server (${n?`${n}: ${typeof t.message=="string"?t.message:"unknown"}`:typeof t.message=="string"&&t.message.length>0?t.message:"unknown error"}). Check https://visacli.sh for status.`}_t();var Db=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Pf(e,t){let n=$f(e),r=$f(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:jb(n.pre,r.pre)>0}function $f(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(Db);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function jb(e,t){let n=e.split("."),r=t.split("."),s=Math.max(n.length,r.length);for(let o=0;o<s;o++){if(o>=n.length)return-1;if(o>=r.length)return 1;let i=n[o],a=r[o],c=/^\d+$/.test(i),l=/^\d+$/.test(a);if(c&&l){let u=Number(i)-Number(a);if(u!==0)return u}else{if(c)return-1;if(l)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function bt(){return!!(Of(process.env.VISA_CLI_NO_UPDATE_CHECK)||Of(process.env.CI)||process.env.NODE_ENV==="test")}function Of(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}Ht();var zb="CARD_REENROLLMENT_REQUIRED",Jb="https://auth.visacli.sh/enroll-card";function Xb(){try{return new URL("/enroll-card",Ue()).toString()}catch{return Jb}}function Zb(e){let t=Xb();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 _n="3.3.1-rc.3",Qb=/^(?:VisaKey_[A-Za-z0-9_-]{16,128}|visakey_[A-Za-z0-9_-]{16,128}|vk_[A-Za-z0-9_-]{32,128})$/;function e0(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 Mc(e){return e==="TOPUP_CHARGE_AMBIGUOUS"||e==="TOPUP_RECONCILIATION_REQUIRED"?e:null}var t0="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function Kr(e){return typeof e=="string"?e.trim():""}function zs(e){let t=e&&typeof e=="object"?e:{},n=Kr(t.error)||Kr(t.message);if(!n)return t0;let r=Kr(t.error_code),s=[["surface",Kr(t.disabled_surface)],["flag",Kr(t.flag)],["correlation_id",Kr(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 Js(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?Qb.test(r)?(n.push("VISA_CLI_API_KEY is set, but MCP bearer tools currently require a local session from visa-cli setup."),n.push("For headless API-key use, call the /v1/api/* HTTP routes with X-Api-Key instead of MCP bearer tools.")):(n.push("VISA_CLI_API_KEY is set but has invalid format (expected VisaKey_<...> or legacy vk_<...>)."),n.push("Create a new Visa Key with: visa-cli keys create <app-name>")):n.push("Run `visa-cli setup` in an interactive terminal to authenticate."),t===!1&&n.push("This process appears to be running without a TTY; complete setup in a normal terminal, then restart the MCP client."),n.join(`
133
- `)}var Ve=class{constructor(t){this.getSessionToken=t;this.baseUrl=Ue()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!bt()){let r=t.headers.get("X-Latest-Version");r&&Pf(r,_n)&&(this.lastSignals.updateAvailable={currentVersion:_n,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return _n}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new Jn(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(zs(n))}async request(t,n,r,s,o,i){let a=await this.getSessionToken();if(!a)throw new Error(Js());let c={Authorization:`Bearer ${a}`};o&&(t==="GET"?c["X-User-Context"]=encodeURIComponent(o.replace(/[\r\n\0]/g," ").slice(0,1e3)):r={...r||{},user_context:o}),i&&(c["X-Visa-Meta-Tool"]=i),r&&(c["Content-Type"]="application/json");let l;try{l=await ht(`${this.baseUrl}${n}`,{method:t,headers:{...c,"X-Visa-CLI-Version":_n,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:s})}catch(d){throw new Error(qr(d))}if(this.parseServerSignals(l),l.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(l.status===429){let d=l.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${d}s. Tip: use the batch tool to combine multiple requests into one.`)}l.status===503&&await this.throwServerUnavailable(l);let u;try{u=await l.json()}catch{throw l.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${n}. Try again.`)}if(!l.ok){if(l.status===500)throw new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(u),typeof u?.error_code=="string"&&u.error_code===zb){let p=typeof u?.last4=="string"?u.last4:"",f=typeof u?.brand=="string"?u.brand:"card",m=Zb(u?.reenroll_url),h=p?`${f} ending in ${p}`:"your card";throw new Error(`Please re-add ${h} to keep payments running. Open: ${m}`)}let d=Mc(u?.error_code);if(d)throw new nt(u?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",d,{transactionId:typeof u?.transactionId=="string"?u.transactionId:void 0,retryable:!!u?.retryable,reconciliationRequired:u?.reconciliation_required!==!1});if(u?.declined){let p=Number(u.retryAfter??l.headers.get("Retry-After"));throw new ge(u.error||"Your card was declined.",!!u.retryable,u.code,u.reason,u.payment_error_class,u.correlation_id,u.transactionId,Number.isFinite(p)&&p>0?p:void 0)}if(l.status===402){let p=u?.error||"Gateway returned 402",f=typeof u?.error_code=="string"?u.error_code:"";throw f==="SPENDING_LIMIT_EXCEEDED"||f==="DAILY_LIMIT_EXCEEDED"||f==="PER_TXN_LIMIT_EXCEEDED"?new Error(`${p}. Check your limits with get_status or run: visa-cli update-spending-controls`):new Error(p)}throw new Error(u?.error||`Request failed (${l.status}). Try again.`)}return u}async shortcut(t,n,r,s,o){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,s,o)}async shortcutWithSession(t,n,r,s,o,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error(Js());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":_n,"X-Source":"cli","Content-Type":"application/json"};i&&(l["X-Visa-Meta-Tool"]=i);let u={...n,...r};o&&(u.user_context=o.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await ht(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(m){throw new Error(qr(m))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let m=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${m}s. Tip: use the batch tool to combine multiple requests into one.`)}let p=d.headers.get("X-Voucher-Receipt"),f;try{f=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(f),d.status===503){if(f?.error_code==="SESSION_LOCK_CONTENDED"){let w=Number(d.headers.get("Retry-After"))||1;throw new Bt(f?.message||f?.error||"Session budget is being modified by another request. Retry shortly.",w,d.status)}throw new Error(zs(f))}let m=e0(f?.error_code);if(m||d.status===410){let w=m??"BUDGET_CLOSED";throw new Vr(f?.message||f?.error||"Your session was invalidated by the server.",w,{budgetId:n.session_budget_id,status:d.status})}if(f?.declined){let w=Number(f.retryAfter??d.headers.get("Retry-After"));throw new ge(f.error||"Your card was declined.",!!f.retryable,f.code,f.reason,f.payment_error_class,f.correlation_id,f.transactionId,Number.isFinite(w)&&w>0?w:void 0)}let h=Mc(f?.error_code);throw h?new nt(f?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",h,{transactionId:typeof f?.transactionId=="string"?f.transactionId:void 0,retryable:!!f?.retryable,reconciliationRequired:f?.reconciliation_required!==!1}):new Error(f?.error||`Request failed (${d.status}). Try again.`)}return{data:f,voucherReceiptHeader:p}}async shortcutParentless(t,n,r,s,o,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error(Js());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":_n,"X-Source":"cli","Content-Type":"application/json"};i&&(l["X-Visa-Meta-Tool"]=i);let u={...r,...n.attestation?{attestation:n.attestation}:{},nonce:n.nonce,approved_max_cents:n.approved_max_cents,idempotency_key:n.idempotency_key,...n.stream===!0?{stream:!0}:{}};o&&(u.user_context=o.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await ht(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(m){throw new Error(qr(m))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let m=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${m}s. Tip: use the batch tool to combine multiple requests into one.`)}let p=d.headers.get("X-Voucher-Receipt"),f;try{f=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):d.status===404?new yt("Parentless single-call is not available on this server.",{status:404}):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);this.throwIfAttestationDrift(f);let m=typeof f?.error_code=="string"?f.error_code:void 0;if(d.status===410&&m==="DIRECT_SHORTCUT_CARD_SURFACE_RETIRED")throw new yt(f?.error||"Parentless single-call is not enabled on this server.",{status:d.status,serverErrorCode:m});if(d.status===503){if(f?.error_code==="SESSION_LOCK_CONTENDED"){let w=Number(d.headers.get("Retry-After"))||1;throw new Bt(f?.message||f?.error||"Session budget is being modified by another request. Retry shortly.",w,d.status)}throw new Error(zs(f))}if(f?.declined){let w=Number(f.retryAfter??d.headers.get("Retry-After"));throw new ge(f.error||"Your card was declined.",!!f.retryable,f.code,f.reason,f.payment_error_class,f.correlation_id,f.transactionId,Number.isFinite(w)&&w>0?w:void 0)}let h=Mc(f?.error_code);throw h?new nt(f?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",h,{transactionId:typeof f?.transactionId=="string"?f.transactionId:void 0,retryable:!!f?.retryable,reconciliationRequired:f?.reconciliation_required!==!1}):new Error(f?.error||`Request failed (${d.status}). Try again.`)}return{data:f,voucherReceiptHeader:p}}async batchOpen(t){let n="/v1/batch/open",r=await this.getSessionToken();if(!r)throw new Error(Js());let s={Authorization:`Bearer ${r}`,"X-Visa-CLI-Version":_n,"X-Source":"cli","Content-Type":"application/json"},o={...t.attestation?{attestation:t.attestation}:{},nonce:t.nonce,approved_total_cents:t.approved_total_cents,batch_id:t.batch_id},i;try{i=await ht(`${this.baseUrl}${n}`,{method:"POST",headers:s,body:JSON.stringify(o),timeoutMs:void 0})}catch(u){throw new Error(qr(u))}if(this.parseServerSignals(i),i.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(i.status===429){let u=i.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${u}s before opening another batch.`)}let a;try{a=await i.json()}catch{throw i.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):i.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):i.status===404?new yt("Parentless batch is not available on this server.",{status:404}):new Error(`Unexpected response from ${n}. Try again.`)}if(!i.ok){if(i.status===500)throw new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`);this.throwIfAttestationDrift(a);let u=typeof a?.error_code=="string"?a.error_code:void 0;if(i.status===410&&u==="DIRECT_SHORTCUT_CARD_SURFACE_RETIRED")throw new yt(a?.error||"Parentless batch is not enabled on this server.",{status:i.status,serverErrorCode:u});if(i.status===503)throw new Error(zs(a));if(a?.declined){let d=Number(a.retryAfter??i.headers.get("Retry-After"));throw new ge(a.error||"Your card was declined.",!!a.retryable,a.code,a.reason,a.payment_error_class,a.correlation_id,a.transactionId,Number.isFinite(d)&&d>0?d:void 0)}throw new Error(a?.error||`Request failed (${i.status}). Try again.`)}let c=a?.parent_spend_execution_id??a?.batch_parent_id??a?.parent_id??a?.spend_execution_id,l=a?.idempotency_scope??a?.idempotency_key_scope??t.batch_id;if(typeof c!="string"||c.length===0)throw new Error(`Batch open returned no parent id from ${n}. Try again.`);return{batch_parent_id:c,idempotency_scope:String(l)}}async shortcutParentlessBatchItem(t,n,r,s,o,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error(Js());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":_n,"X-Source":"cli","Content-Type":"application/json"};i&&(l["X-Visa-Meta-Tool"]=i);let u={...r,batch_parent_id:n.batch_parent_id,batch_id:n.batch_id,batch_index:n.batch_index,batch_request_hash:n.batch_request_hash,item_ceiling_cents:n.item_ceiling_cents,idempotency_key:n.idempotency_key,...n.stream===!0?{stream:!0}:{}};o&&(u.user_context=o.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await ht(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(m){throw new Error(qr(m))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let m=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${m}s. Tip: use the batch tool to combine multiple requests into one.`)}let p=d.headers.get("X-Voucher-Receipt"),f;try{f=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(f),d.status===503){if(f?.error_code==="SESSION_LOCK_CONTENDED"){let m=Number(d.headers.get("Retry-After"))||1;throw new Bt(f?.message||f?.error||"Batch parent is being modified by another request. Retry shortly.",m,d.status)}throw new Error(zs(f))}if(f?.declined){let m=Number(f.retryAfter??d.headers.get("Retry-After"));throw new ge(f.error||"Your card was declined.",!!f.retryable,f.code,f.reason,f.payment_error_class,f.correlation_id,f.transactionId,Number.isFinite(m)&&m>0?m:void 0)}throw new Error(f?.error||`Request failed (${d.status}). Try again.`)}return{data:f,voucherReceiptHeader:p}}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async catalogSearch(t,n,r,s){let o=r??"discover_tools",i=new URLSearchParams;t&&i.set("q",t),n&&i.set("category",n),s?.limit!=null&&i.set("limit",String(s.limit)),s?.offset!=null&&i.set("offset",String(s.offset));let a=i.toString();return this.request("GET",`/v1/catalog${a?`?${a}`:""}`,void 0,void 0,void 0,o)}async catalogTool(t,n){let r=n??"discover_tools";try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(t)}`,void 0,void 0,void 0,r)}catch{return null}}async discoverMerchantRoutes(t){try{return await this.request("GET",`/v1/platform/discover/${encodeURIComponent(t)}`)}catch{return null}}async listPublicMerchants(){try{let t=await ht(`${this.baseUrl}/v1/platform/merchants/public`,{method:"GET",timeoutMs:8e3});if(!t.ok)return[];let n=await t.json();return Array.isArray(n.merchants)?n.merchants:[]}catch{return[]}}async getPublicMerchantDiscover(t){try{let n=await ht(`${this.baseUrl}/v1/platform/discover/${encodeURIComponent(t)}`,{method:"GET",timeoutMs:8e3});return n.ok?await n.json():null}catch{return null}}async paymentPreview(t,n){return this.request("POST","/v1/payment-preview",t,void 0,n)}async getBalance(){return this.request("GET","/v1/balance")}async topupBalance(t){return this.request("POST","/v1/balance/topup",t)}async createEnrollCode(){return this.request("POST","/v1/enroll-code")}async getAutoTopup(){let t=await this.getBalance();return{success:t.success,targetCents:t.autoTopupCents??null,thresholdCents:t.autoTopupThresholdCents??0}}async disableAutoTopup(){return this.request("PATCH","/v1/balance/auto-topup",{auto_topup_cents:null})}async createSessionBudget(t){return this.request("POST","/v1/session-budget/create",{...t,mode:"prepaid"})}async closeSession(t){return this.request("POST","/v1/session/close",{session_budget_id:t})}async getSessionBudget(t){return this.request("GET",`/v1/session-budget/${encodeURIComponent(t)}`)}async getSessionLedger(t){return this.request("GET",`/v1/session/${encodeURIComponent(t)}/ledger`)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getVisaSmi(t,n){return this.request("POST","/v1/visa/smi",t,6e4,n)}async getTransactions(t,n){let r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.offset!=null&&r.set("offset",String(t.offset));let s=r.toString(),o=s?`/v1/transactions?${s}`:"/v1/transactions";return this.request("GET",o,void 0,void 0,n)}async updateSpendingControls(t,n){return this.request("POST","/v1/spending-controls",t,void 0,n)}async removeCard(t,n,r){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(t))}`,n,void 0,r)}async setDefaultCard(t,n,r){return this.request("POST",`/v1/cards/${encodeURIComponent(String(t))}/default`,n,void 0,r)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t,n){return this.request("POST","/v1/attestation-key",{publicKey:t,...n?{attestation:n}:{}})}async startAttestationRecovery(t,n){return this.request("POST","/v1/attestation-key/recovery/start",{state:t},void 0,n)}async setBiometricPreference(t,n){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,n)}async getPendingWebAuthenticators(t){return this.request("GET","/v1/webauthn/pending",void 0,void 0,t)}async authorizeWebAuthenticator(t,n){return this.request("POST","/v1/webauthn/authorize",t,void 0,n)}async logout(t,n){return this.request("POST","/v1/logout",t,void 0,n)}async feedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async createAppApiKey(t){return this.request("POST","/v1/api/keys",t)}async listAppApiKeys(t){let n=new URLSearchParams;t?.limit!=null&&n.set("limit",String(t.limit)),t?.startingAfter!=null&&n.set("starting_after",String(t.startingAfter)),t?.endingBefore!=null&&n.set("ending_before",String(t.endingBefore));let r=n.toString();return this.request("GET",r?`/v1/api/keys?${r}`:"/v1/api/keys")}async listAllAppApiKeys(){let t=[],n=new Set,r,s=null,o=0;for(;;){let i=await this.listAppApiKeys({limit:100,...r!==void 0?{startingAfter:r}:{}});if(o+=1,s=i,t.push(...i.keys??[]),!i.has_more)break;if(i.next_cursor==null)throw new Error("API key pagination response did not include next_cursor.");if(n.has(i.next_cursor))throw new Error("API key pagination cursor did not advance.");n.add(i.next_cursor),r=i.next_cursor}return{...s??{success:!0,keys:[]},keys:t,limit:100,has_more:!1,next_cursor:null,previous_cursor:null,pages:o}}async revokeAppApiKey(t){return this.request("DELETE",`/v1/api/keys/${encodeURIComponent(String(t))}`)}async feedSubmit(t){return this.request("POST","/v1/feed",t)}async feedList(t){let n=new URLSearchParams;t?.tab&&n.set("tab",t.tab),t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset));let r=n.toString();return this.request("GET",`/v1/feed${r?"?"+r:""}`)}async feedVote(t,n){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/vote`,{direction:n})}async feedApprove(t){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/approve`)}async feedDelete(t){return this.request("DELETE",`/v1/feed/${encodeURIComponent(t)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async getFeedback(t,n){let r=new URLSearchParams;t&&r.set("limit",String(t));let s=r.toString();return this.request("GET",`/v1/feedback${s?"?"+s:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}};function Xs(e,t){return t||(typeof e!="number"||!Number.isFinite(e)?"price unknown":`$${(e/100).toFixed(2)}`)}function Wf(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 Gf(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function n0(e){let t=new Map;for(let n of e){let r=n.category||"other",s=t.get(r)??[];s.push(n),t.set(r,s)}return new Map([...t.entries()].sort(([n],[r])=>n.localeCompare(r)))}function r0(e){return Math.max(4,e.reduce((t,n)=>Math.max(t,n.id.length),0))}function s0(e){return Math.max(8,Math.min(14,e.reduce((t,n)=>Math.max(t,(n.category||"").length),0)))}function o0(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 Yf(e){let t=r0(e),n=7,r=s0(e),s=o0(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)} ${Xs(o.priceCents,o.priceDisplay).padEnd(n)} ${Gf(o.category||"other",r).padEnd(r)} ${Gf(Wf(o),s)}`)}function zf(e){console.log(`
132
+ `}function Of(e){return e.json===!0||e.isTTY!==!0}function Ec(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 Rc(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 Mf(e,t){let n=Ec(e);if(n!==void 0)return n;if(Of(t))return 500}function Nf(e,t){let n=Rc(e);if(n!==void 0)return n;if(Of(t)||t.recommendedCapsAccepted===!0)return 2500}async function yt(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,s=setTimeout(()=>r.abort(),n);try{let{timeoutMs:o,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(s)}}var Zn=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},Kr=class extends Error{code;budgetId;status;constructor(t,n,r={}){super(t),this.name="SessionInvalidError",this.code=n,this.budgetId=r.budgetId,this.status=r.status}},Ft=class extends Error{code="SESSION_LOCK_CONTENDED";retryAfterSecs;status;constructor(t,n=1,r){super(t),this.name="SessionLockContendedError",this.retryAfterSecs=n,this.status=r}},_t=class extends Error{code="PARENTLESS_NOT_ENABLED";status;serverErrorCode;constructor(t,n={}){super(t),this.name="ParentlessNotEnabledError",this.status=n.status,this.serverErrorCode=n.serverErrorCode}},he=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(t,n,r,s,o,i,a,c){super(t),this.name="CardDeclinedError",this.retryable=n,this.code=r,this.reason=s,this.paymentErrorClass=o,this.correlationId=i,this.transactionId=a,this.retryAfter=c}},nt=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 Lf={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 Gr(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&&Lf[n]?Lf[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.`}bt();var Wb=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function jf(e,t){let n=Df(e),r=Df(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:Yb(n.pre,r.pre)>0}function Df(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(Wb);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function Yb(e,t){let n=e.split("."),r=t.split("."),s=Math.max(n.length,r.length);for(let o=0;o<s;o++){if(o>=n.length)return-1;if(o>=r.length)return 1;let i=n[o],a=r[o],c=/^\d+$/.test(i),l=/^\d+$/.test(a);if(c&&l){let u=Number(i)-Number(a);if(u!==0)return u}else{if(c)return-1;if(l)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function vt(){return!!(Bf(process.env.VISA_CLI_NO_UPDATE_CHECK)||Bf(process.env.CI)||process.env.NODE_ENV==="test")}function Bf(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}Vt();var s0="CARD_REENROLLMENT_REQUIRED",o0="https://auth.visacli.sh/enroll-card";function i0(){try{return new URL("/enroll-card",Ue()).toString()}catch{return o0}}function a0(e){let t=i0();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 vn="3.4.0-rc.5",c0=/^(?:VisaKey_[A-Za-z0-9_-]{16,128}|visakey_[A-Za-z0-9_-]{16,128}|vk_[A-Za-z0-9_-]{32,128})$/;function l0(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 Bc(e){return e==="TOPUP_CHARGE_AMBIGUOUS"||e==="TOPUP_RECONCILIATION_REQUIRED"?e:null}var u0="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function Wr(e){return typeof e=="string"?e.trim():""}function Zs(e){let t=e&&typeof e=="object"?e:{},n=Wr(t.error)||Wr(t.message);if(!n)return u0;let r=Wr(t.error_code),s=[["surface",Wr(t.disabled_surface)],["flag",Wr(t.flag)],["correlation_id",Wr(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 Qs(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?c0.test(r)?(n.push("VISA_CLI_API_KEY is set, but MCP bearer tools currently require a local session from visa-cli setup."),n.push("For headless API-key use, call the /v1/api/* HTTP routes with X-Api-Key instead of MCP bearer tools.")):(n.push("VISA_CLI_API_KEY is set but has invalid format (expected VisaKey_<...> or legacy vk_<...>)."),n.push("Create a new Visa Key with: visa-cli keys create <app-name>")):n.push("Run `visa-cli setup` in an interactive terminal to authenticate."),t===!1&&n.push("This process appears to be running without a TTY; complete setup in a normal terminal, then restart the MCP client."),n.join(`
133
+ `)}var Ve=class{constructor(t){this.getSessionToken=t;this.baseUrl=Ue()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!vt()){let r=t.headers.get("X-Latest-Version");r&&jf(r,vn)&&(this.lastSignals.updateAvailable={currentVersion:vn,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return vn}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new Zn(t.error||"Your biometric key is out of sync with the server.",typeof t.hint=="string"?t.hint:void 0)}async throwServerUnavailable(t){let n=null;try{n=await t.json()}catch{}throw new Error(Zs(n))}async request(t,n,r,s,o,i){let a=await this.getSessionToken();if(!a)throw new Error(Qs());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 yt(`${this.baseUrl}${n}`,{method:t,headers:{...c,"X-Visa-CLI-Version":vn,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:s})}catch(d){throw new Error(Gr(d))}if(this.parseServerSignals(l),l.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(l.status===429){let d=l.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${d}s. Tip: use the batch tool to combine multiple requests into one.`)}l.status===503&&await this.throwServerUnavailable(l);let u;try{u=await l.json()}catch{throw l.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${n}. Try again.`)}if(!l.ok){if(l.status===500)throw new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(u),typeof u?.error_code=="string"&&u.error_code===s0){let m=typeof u?.last4=="string"?u.last4:"",f=typeof u?.brand=="string"?u.brand:"card",p=a0(u?.reenroll_url),h=m?`${f} ending in ${m}`:"your card";throw new Error(`Please re-add ${h} to keep payments running. Open: ${p}`)}let d=Bc(u?.error_code);if(d)throw new nt(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 m=Number(u.retryAfter??l.headers.get("Retry-After"));throw new he(u.error||"Your card was declined.",!!u.retryable,u.code,u.reason,u.payment_error_class,u.correlation_id,u.transactionId,Number.isFinite(m)&&m>0?m:void 0)}if(l.status===402){let m=u?.error||"Gateway returned 402",f=typeof u?.error_code=="string"?u.error_code:"";throw f==="SPENDING_LIMIT_EXCEEDED"||f==="DAILY_LIMIT_EXCEEDED"||f==="PER_TXN_LIMIT_EXCEEDED"?new Error(`${m}. Check your limits with get_status or run: visa-cli update-spending-controls`):new Error(m)}throw new Error(u?.error||`Request failed (${l.status}). Try again.`)}return u}async shortcut(t,n,r,s,o){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,s,o)}async shortcutWithSession(t,n,r,s,o,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error(Qs());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":vn,"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 yt(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(p){throw new Error(Gr(p))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let p=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${p}s. Tip: use the batch tool to combine multiple requests into one.`)}let m=d.headers.get("X-Voucher-Receipt"),f;try{f=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(f),d.status===503){if(f?.error_code==="SESSION_LOCK_CONTENDED"){let w=Number(d.headers.get("Retry-After"))||1;throw new Ft(f?.message||f?.error||"Session budget is being modified by another request. Retry shortly.",w,d.status)}throw new Error(Zs(f))}let p=l0(f?.error_code);if(p||d.status===410){let w=p??"BUDGET_CLOSED";throw new Kr(f?.message||f?.error||"Your session was invalidated by the server.",w,{budgetId:n.session_budget_id,status:d.status})}if(f?.declined){let w=Number(f.retryAfter??d.headers.get("Retry-After"));throw new he(f.error||"Your card was declined.",!!f.retryable,f.code,f.reason,f.payment_error_class,f.correlation_id,f.transactionId,Number.isFinite(w)&&w>0?w:void 0)}let h=Bc(f?.error_code);throw h?new nt(f?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",h,{transactionId:typeof f?.transactionId=="string"?f.transactionId:void 0,retryable:!!f?.retryable,reconciliationRequired:f?.reconciliation_required!==!1}):new Error(f?.error||`Request failed (${d.status}). Try again.`)}return{data:f,voucherReceiptHeader:m}}async shortcutParentless(t,n,r,s,o,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error(Qs());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":vn,"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 yt(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(p){throw new Error(Gr(p))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let p=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${p}s. Tip: use the batch tool to combine multiple requests into one.`)}let m=d.headers.get("X-Voucher-Receipt"),f;try{f=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):d.status===404?new _t("Parentless single-call is not available on this server.",{status:404}):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);this.throwIfAttestationDrift(f);let p=typeof f?.error_code=="string"?f.error_code:void 0;if(d.status===410&&p==="DIRECT_SHORTCUT_CARD_SURFACE_RETIRED")throw new _t(f?.error||"Parentless single-call is not enabled on this server.",{status:d.status,serverErrorCode:p});if(d.status===503){if(f?.error_code==="SESSION_LOCK_CONTENDED"){let w=Number(d.headers.get("Retry-After"))||1;throw new Ft(f?.message||f?.error||"Session budget is being modified by another request. Retry shortly.",w,d.status)}throw new Error(Zs(f))}if(f?.declined){let w=Number(f.retryAfter??d.headers.get("Retry-After"));throw new he(f.error||"Your card was declined.",!!f.retryable,f.code,f.reason,f.payment_error_class,f.correlation_id,f.transactionId,Number.isFinite(w)&&w>0?w:void 0)}let h=Bc(f?.error_code);throw h?new nt(f?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",h,{transactionId:typeof f?.transactionId=="string"?f.transactionId:void 0,retryable:!!f?.retryable,reconciliationRequired:f?.reconciliation_required!==!1}):new Error(f?.error||`Request failed (${d.status}). Try again.`)}return{data:f,voucherReceiptHeader:m}}async batchOpen(t){let n="/v1/batch/open",r=await this.getSessionToken();if(!r)throw new Error(Qs());let s={Authorization:`Bearer ${r}`,"X-Visa-CLI-Version":vn,"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 yt(`${this.baseUrl}${n}`,{method:"POST",headers:s,body:JSON.stringify(o),timeoutMs:void 0})}catch(u){throw new Error(Gr(u))}if(this.parseServerSignals(i),i.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(i.status===429){let u=i.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${u}s before opening another batch.`)}let a;try{a=await i.json()}catch{throw i.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):i.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):i.status===404?new _t("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 _t(a?.error||"Parentless batch is not enabled on this server.",{status:i.status,serverErrorCode:u});if(i.status===503)throw new Error(Zs(a));if(a?.declined){let d=Number(a.retryAfter??i.headers.get("Retry-After"));throw new he(a.error||"Your card was declined.",!!a.retryable,a.code,a.reason,a.payment_error_class,a.correlation_id,a.transactionId,Number.isFinite(d)&&d>0?d:void 0)}throw new Error(a?.error||`Request failed (${i.status}). Try again.`)}let c=a?.parent_spend_execution_id??a?.batch_parent_id??a?.parent_id??a?.spend_execution_id,l=a?.idempotency_scope??a?.idempotency_key_scope??t.batch_id;if(typeof c!="string"||c.length===0)throw new Error(`Batch open returned no parent id from ${n}. Try again.`);return{batch_parent_id:c,idempotency_scope:String(l)}}async shortcutParentlessBatchItem(t,n,r,s,o,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error(Qs());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":vn,"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 yt(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:s})}catch(p){throw new Error(Gr(p))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let p=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${p}s. Tip: use the batch tool to combine multiple requests into one.`)}let m=d.headers.get("X-Voucher-Receipt"),f;try{f=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(f),d.status===503){if(f?.error_code==="SESSION_LOCK_CONTENDED"){let p=Number(d.headers.get("Retry-After"))||1;throw new Ft(f?.message||f?.error||"Batch parent is being modified by another request. Retry shortly.",p,d.status)}throw new Error(Zs(f))}if(f?.declined){let p=Number(f.retryAfter??d.headers.get("Retry-After"));throw new he(f.error||"Your card was declined.",!!f.retryable,f.code,f.reason,f.payment_error_class,f.correlation_id,f.transactionId,Number.isFinite(p)&&p>0?p:void 0)}throw new Error(f?.error||`Request failed (${d.status}). Try again.`)}return{data:f,voucherReceiptHeader:m}}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async catalogSearch(t,n,r,s){let o=r??"discover_tools",i=new URLSearchParams;t&&i.set("q",t),n&&i.set("category",n),s?.limit!=null&&i.set("limit",String(s.limit)),s?.offset!=null&&i.set("offset",String(s.offset));let a=i.toString();return this.request("GET",`/v1/catalog${a?`?${a}`:""}`,void 0,void 0,void 0,o)}async catalogTool(t,n){let r=n??"discover_tools";try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(t)}`,void 0,void 0,void 0,r)}catch{return null}}async discoverMerchantRoutes(t){try{return await this.request("GET",`/v1/platform/discover/${encodeURIComponent(t)}`)}catch{return null}}async listPublicMerchants(){try{let t=await yt(`${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 yt(`${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 eo(e,t){return t||(typeof e!="number"||!Number.isFinite(e)?"price unknown":`$${(e/100).toFixed(2)}`)}function em(e){let t=e.inputSchema?.properties;return t&&typeof t=="object"&&!Array.isArray(t)?Object.keys(t).join(", ")||"none":Object.keys(e.inputSchema||{}).join(", ")||"none"}function Qf(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function d0(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 f0(e){return Math.max(4,e.reduce((t,n)=>Math.max(t,n.id.length),0))}function m0(e){return Math.max(8,Math.min(14,e.reduce((t,n)=>Math.max(t,(n.category||"").length),0)))}function p0(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 tm(e){let t=f0(e),n=7,r=m0(e),s=p0(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)} ${eo(o.priceCents,o.priceDisplay).padEnd(n)} ${Qf(o.category||"other",r).padEnd(r)} ${Qf(em(o),s)}`)}function nm(e){console.log(`
134
134
  Merchant tools
135
- `),Yf(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 Nc(e){console.log(`
135
+ `),tm(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 Fc(e){console.log(`
136
136
  Merchant tools
137
- `);for(let[t,n]of n0(e)){console.log(t[0]?.toUpperCase()+t.slice(1));for(let r of n)console.log(` ${r.id.padEnd(28)} ${Xs(r.priceCents,r.priceDisplay).padEnd(8)} ${r.description}`),console.log(` Params: ${Wf(r)}`);console.log()}console.log(`Run one with: visa-cli merchants run <tool> --json '{"prompt":"a lobster"}'`),console.log("Details: visa-cli describe <tool>"),console.log(`Shortcut: visa-cli generate image "a lobster"
138
- `)}function Jf(e,t){console.log(`
137
+ `);for(let[t,n]of d0(e)){console.log(t[0]?.toUpperCase()+t.slice(1));for(let r of n)console.log(` ${r.id.padEnd(28)} ${eo(r.priceCents,r.priceDisplay).padEnd(8)} ${r.description}`),console.log(` Params: ${em(r)}`);console.log()}console.log(`Run one with: visa-cli merchants run <tool> --json '{"prompt":"a lobster"}'`),console.log("Details: visa-cli describe <tool>"),console.log(`Shortcut: visa-cli generate image "a lobster"
138
+ `)}function rm(e,t){console.log(`
139
139
  ${e} tools
140
- `),Yf(t),console.log("\nUse `visa-cli describe <tool>` for full details (incl. parameter types)."),console.log(`Or scope it: \`visa-cli merchants ${e} describe <tool>\`
141
- `)}var _={};Lo(_,{BRAND:()=>$0,DIRTY:()=>Qn,EMPTY_PATH:()=>l0,INVALID:()=>D,NEVER:()=>gv,OK:()=>Ie,ParseStatus:()=>Te,Schema:()=>V,ZodAny:()=>wn,ZodArray:()=>Gt,ZodBigInt:()=>tr,ZodBoolean:()=>nr,ZodBranded:()=>Qs,ZodCatch:()=>pr,ZodDate:()=>rr,ZodDefault:()=>fr,ZodDiscriminatedUnion:()=>_i,ZodEffects:()=>Je,ZodEnum:()=>ur,ZodError:()=>Be,ZodFirstPartyTypeKind:()=>j,ZodFunction:()=>vi,ZodIntersection:()=>ar,ZodIssueCode:()=>x,ZodLazy:()=>cr,ZodLiteral:()=>lr,ZodMap:()=>Xr,ZodNaN:()=>Qr,ZodNativeEnum:()=>dr,ZodNever:()=>st,ZodNull:()=>or,ZodNullable:()=>St,ZodNumber:()=>er,ZodObject:()=>Fe,ZodOptional:()=>Ye,ZodParsedType:()=>E,ZodPipeline:()=>eo,ZodPromise:()=>Sn,ZodReadonly:()=>mr,ZodRecord:()=>bi,ZodSchema:()=>V,ZodSet:()=>Zr,ZodString:()=>vn,ZodSymbol:()=>zr,ZodTransformer:()=>Je,ZodTuple:()=>wt,ZodType:()=>V,ZodUndefined:()=>sr,ZodUnion:()=>ir,ZodUnknown:()=>Kt,ZodVoid:()=>Jr,addIssueToContext:()=>k,any:()=>B0,array:()=>q0,bigint:()=>N0,boolean:()=>ap,coerce:()=>mv,custom:()=>sp,date:()=>L0,datetimeRegex:()=>np,defaultErrorMap:()=>Vt,discriminatedUnion:()=>Y0,effect:()=>iv,enum:()=>rv,function:()=>ev,getErrorMap:()=>Gr,getParsedType:()=>vt,instanceof:()=>O0,intersection:()=>z0,isAborted:()=>hi,isAsync:()=>Wr,isDirty:()=>yi,isValid:()=>bn,late:()=>P0,lazy:()=>tv,literal:()=>nv,makeIssue:()=>Zs,map:()=>Z0,nan:()=>M0,nativeEnum:()=>sv,never:()=>H0,null:()=>j0,nullable:()=>cv,number:()=>ip,object:()=>K0,objectUtil:()=>Lc,oboolean:()=>pv,onumber:()=>fv,optional:()=>av,ostring:()=>dv,pipeline:()=>uv,preprocess:()=>lv,promise:()=>ov,quotelessJson:()=>i0,record:()=>X0,set:()=>Q0,setErrorMap:()=>c0,strictObject:()=>G0,string:()=>op,symbol:()=>U0,transformer:()=>iv,tuple:()=>J0,undefined:()=>D0,union:()=>W0,unknown:()=>F0,util:()=>q,void:()=>V0});var q;(function(e){e.assertEqual=s=>{};function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{let o={};for(let i of s)o[i]=i;return o},e.getValidEnumValues=s=>{let o=e.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(let a of o)i[a]=s[a];return e.objectValues(i)},e.objectValues=s=>e.objectKeys(s).map(function(o){return s[o]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},e.find=(s,o)=>{for(let i of s)if(o(i))return i},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}e.joinValues=r,e.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(q||(q={}));var Lc;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Lc||(Lc={}));var E=q.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),vt=e=>{switch(typeof e){case"undefined":return E.undefined;case"string":return E.string;case"number":return Number.isNaN(e)?E.nan:E.number;case"boolean":return E.boolean;case"function":return E.function;case"bigint":return E.bigint;case"symbol":return E.symbol;case"object":return Array.isArray(e)?E.array:e===null?E.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?E.promise:typeof Map<"u"&&e instanceof Map?E.map:typeof Set<"u"&&e instanceof Set?E.set:typeof Date<"u"&&e instanceof Date?E.date:E.object;default:return E.unknown}};var x=q.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),i0=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),Be=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(o){return o.message},r={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(n(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return s(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,q.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];n[o]=n[o]||[],n[o].push(t(s))}else r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Be.create=e=>new Be(e);var a0=(e,t)=>{let n;switch(e.code){case x.invalid_type:e.received===E.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case x.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,q.jsonStringifyReplacer)}`;break;case x.unrecognized_keys:n=`Unrecognized key(s) in object: ${q.joinValues(e.keys,", ")}`;break;case x.invalid_union:n="Invalid input";break;case x.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${q.joinValues(e.options)}`;break;case x.invalid_enum_value:n=`Invalid enum value. Expected ${q.joinValues(e.options)}, received '${e.received}'`;break;case x.invalid_arguments:n="Invalid function arguments";break;case x.invalid_return_type:n="Invalid function return type";break;case x.invalid_date:n="Invalid date";break;case x.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:q.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case x.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case x.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case x.custom:n="Invalid input";break;case x.invalid_intersection_types:n="Intersection results could not be merged";break;case x.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case x.not_finite:n="Number must be finite";break;default:n=t.defaultError,q.assertNever(e)}return{message:n}},Vt=a0;var Xf=Vt;function c0(e){Xf=e}function Gr(){return Xf}var Zs=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}},l0=[];function k(e,t){let n=Gr(),r=Zs({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Vt?void 0:Vt].filter(s=>!!s)});e.common.issues.push(r)}var Te=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let s of n){if(s.status==="aborted")return D;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let s of n){let o=await s.key,i=await s.value;r.push({key:o,value:i})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let s of n){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return D;o.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(r[o.value]=i.value)}return{status:t.value,value:r}}},D=Object.freeze({status:"aborted"}),Qn=e=>({status:"dirty",value:e}),Ie=e=>({status:"valid",value:e}),hi=e=>e.status==="aborted",yi=e=>e.status==="dirty",bn=e=>e.status==="valid",Wr=e=>typeof Promise<"u"&&e instanceof Promise;var M;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(M||(M={}));var ze=class{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Zf=(e,t)=>{if(bn(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new Be(e.common.issues);return this._error=n,this._error}}};function B(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(i,a)=>{let{message:c}=e;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??n??a.defaultError}},description:s}}var V=class{get description(){return this._def.description}_getType(t){return vt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:vt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Te,ctx:{common:t.parent.common,data:t.data,parsedType:vt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Wr(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:vt(t)},s=this._parseSync({data:t,path:r.path,parent:r});return Zf(r,s)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:vt(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return bn(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=>bn(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(t,n){let r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:vt(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(Wr(s)?s:Promise.resolve(s));return Zf(r,o)}refine(t,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{let i=t(s),a=()=>o.addIssue({code:x.custom,...r(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new Je({schema:this,typeName:j.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Ye.create(this,this._def)}nullable(){return St.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Gt.create(this)}promise(){return Sn.create(this,this._def)}or(t){return ir.create([this,t],this._def)}and(t){return ar.create(this,t,this._def)}transform(t){return new Je({...B(this._def),schema:this,typeName:j.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new fr({...B(this._def),innerType:this,defaultValue:n,typeName:j.ZodDefault})}brand(){return new Qs({typeName:j.ZodBranded,type:this,...B(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new pr({...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 eo.create(this,t)}readonly(){return mr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},u0=/^c[^\s-]{8,}$/i,d0=/^[0-9a-z]+$/,f0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,p0=/^[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,m0=/^[a-z0-9_-]{21}$/i,g0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,h0=/^[-+]?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)?)??$/,y0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Uc,b0=/^(?:(?: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])$/,v0=/^(?:(?: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])$/,w0=/^(([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]))$/,S0=/^(([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])$/,x0=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,T0=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ep="((\\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])))",C0=new RegExp(`^${ep}$`);function tp(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 k0(e){return new RegExp(`^${tp(e)}$`)}function np(e){let t=`${ep}T${tp(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 E0(e,t){return!!((t==="v4"||!t)&&b0.test(e)||(t==="v6"||!t)&&w0.test(e))}function A0(e,t){if(!g0.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 R0(e,t){return!!((t==="v4"||!t)&&v0.test(e)||(t==="v6"||!t)&&S0.test(e))}var vn=class e extends V{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==E.string){let o=this._getOrReturnCtx(t);return k(o,{code:x.invalid_type,expected:E.string,received:o.parsedType}),D}let r=new Te,s;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(s=this._getOrReturnCtx(t,s),k(s,{code:x.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")t.data.length>o.value&&(s=this._getOrReturnCtx(t,s),k(s,{code:x.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){let i=t.data.length>o.value,a=t.data.length<o.value;(i||a)&&(s=this._getOrReturnCtx(t,s),i?k(s,{code:x.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&k(s,{code:x.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")y0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"email",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")Uc||(Uc=new RegExp(_0,"u")),Uc.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"emoji",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")p0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"uuid",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")m0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"nanoid",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")u0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"cuid",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")d0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"cuid2",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")f0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"ulid",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),k(s,{validation:"url",code:x.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"regex",code:x.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(t,s),k(s,{code:x.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(s=this._getOrReturnCtx(t,s),k(s,{code:x.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(s=this._getOrReturnCtx(t,s),k(s,{code:x.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?np(o).test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{code:x.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?C0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{code:x.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?k0(o).test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{code:x.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?h0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"duration",code:x.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?E0(t.data,o.version)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"ip",code:x.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?A0(t.data,o.alg)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"jwt",code:x.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?R0(t.data,o.version)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"cidr",code:x.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?x0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"base64",code:x.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?T0.test(t.data)||(s=this._getOrReturnCtx(t,s),k(s,{validation:"base64url",code:x.invalid_string,message:o.message}),r.dirty()):q.assertNever(o);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:x.invalid_string,...M.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...M.errToObj(t)})}url(t){return this._addCheck({kind:"url",...M.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...M.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...M.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...M.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...M.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...M.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...M.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...M.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...M.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...M.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...M.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...M.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...M.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...M.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...M.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...M.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...M.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...M.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...M.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...M.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...M.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...M.errToObj(n)})}nonempty(t){return this.min(1,M.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};vn.create=e=>new vn({checks:[],typeName:j.ZodString,coerce:e?.coerce??!1,...B(e)});function I0(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 er=class e extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==E.number){let o=this._getOrReturnCtx(t);return k(o,{code:x.invalid_type,expected:E.number,received:o.parsedType}),D}let r,s=new Te;for(let o of this._def.checks)o.kind==="int"?q.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),k(r,{code:x.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),k(r,{code:x.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),k(r,{code:x.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?I0(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),k(r,{code:x.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),k(r,{code:x.not_finite,message:o.message}),s.dirty()):q.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,M.toString(n))}gt(t,n){return this.setLimit("min",t,!1,M.toString(n))}lte(t,n){return this.setLimit("max",t,!0,M.toString(n))}lt(t,n){return this.setLimit("max",t,!1,M.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:M.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:M.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:M.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:M.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:M.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:M.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:M.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:M.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:M.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:M.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&q.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};er.create=e=>new er({checks:[],typeName:j.ZodNumber,coerce:e?.coerce||!1,...B(e)});var tr=class e extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==E.bigint)return this._getInvalidInput(t);let r,s=new Te;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),k(r,{code:x.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),k(r,{code:x.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),k(r,{code:x.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):q.assertNever(o);return{status:s.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return k(n,{code:x.invalid_type,expected:E.bigint,received:n.parsedType}),D}gte(t,n){return this.setLimit("min",t,!0,M.toString(n))}gt(t,n){return this.setLimit("min",t,!1,M.toString(n))}lte(t,n){return this.setLimit("max",t,!0,M.toString(n))}lt(t,n){return this.setLimit("max",t,!1,M.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:M.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:M.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:M.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:M.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:M.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:M.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};tr.create=e=>new tr({checks:[],typeName:j.ZodBigInt,coerce:e?.coerce??!1,...B(e)});var nr=class extends V{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==E.boolean){let r=this._getOrReturnCtx(t);return k(r,{code:x.invalid_type,expected:E.boolean,received:r.parsedType}),D}return Ie(t.data)}};nr.create=e=>new nr({typeName:j.ZodBoolean,coerce:e?.coerce||!1,...B(e)});var rr=class e extends V{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==E.date){let o=this._getOrReturnCtx(t);return k(o,{code:x.invalid_type,expected:E.date,received:o.parsedType}),D}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return k(o,{code:x.invalid_date}),D}let r=new Te,s;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(s=this._getOrReturnCtx(t,s),k(s,{code:x.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(s=this._getOrReturnCtx(t,s),k(s,{code:x.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):q.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:M.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:M.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};rr.create=e=>new rr({checks:[],coerce:e?.coerce||!1,typeName:j.ZodDate,...B(e)});var zr=class extends V{_parse(t){if(this._getType(t)!==E.symbol){let r=this._getOrReturnCtx(t);return k(r,{code:x.invalid_type,expected:E.symbol,received:r.parsedType}),D}return Ie(t.data)}};zr.create=e=>new zr({typeName:j.ZodSymbol,...B(e)});var sr=class extends V{_parse(t){if(this._getType(t)!==E.undefined){let r=this._getOrReturnCtx(t);return k(r,{code:x.invalid_type,expected:E.undefined,received:r.parsedType}),D}return Ie(t.data)}};sr.create=e=>new sr({typeName:j.ZodUndefined,...B(e)});var or=class extends V{_parse(t){if(this._getType(t)!==E.null){let r=this._getOrReturnCtx(t);return k(r,{code:x.invalid_type,expected:E.null,received:r.parsedType}),D}return Ie(t.data)}};or.create=e=>new or({typeName:j.ZodNull,...B(e)});var wn=class extends V{constructor(){super(...arguments),this._any=!0}_parse(t){return Ie(t.data)}};wn.create=e=>new wn({typeName:j.ZodAny,...B(e)});var Kt=class extends V{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Ie(t.data)}};Kt.create=e=>new Kt({typeName:j.ZodUnknown,...B(e)});var st=class extends V{_parse(t){let n=this._getOrReturnCtx(t);return k(n,{code:x.invalid_type,expected:E.never,received:n.parsedType}),D}};st.create=e=>new st({typeName:j.ZodNever,...B(e)});var Jr=class extends V{_parse(t){if(this._getType(t)!==E.undefined){let r=this._getOrReturnCtx(t);return k(r,{code:x.invalid_type,expected:E.void,received:r.parsedType}),D}return Ie(t.data)}};Jr.create=e=>new Jr({typeName:j.ZodVoid,...B(e)});var Gt=class e extends V{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==E.array)return k(n,{code:x.invalid_type,expected:E.array,received:n.parsedType}),D;if(s.exactLength!==null){let i=n.data.length>s.exactLength.value,a=n.data.length<s.exactLength.value;(i||a)&&(k(n,{code:i?x.too_big:x.too_small,minimum:a?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(k(n,{code:x.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(k(n,{code:x.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>s.type._parseAsync(new ze(n,i,n.path,a)))).then(i=>Te.mergeArray(r,i));let o=[...n.data].map((i,a)=>s.type._parseSync(new ze(n,i,n.path,a)));return Te.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:M.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:M.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:M.toString(n)}})}nonempty(t){return this.min(1,t)}};Gt.create=(e,t)=>new Gt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:j.ZodArray,...B(t)});function Yr(e){if(e instanceof Fe){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Ye.create(Yr(r))}return new Fe({...e._def,shape:()=>t})}else return e instanceof Gt?new Gt({...e._def,type:Yr(e.element)}):e instanceof Ye?Ye.create(Yr(e.unwrap())):e instanceof St?St.create(Yr(e.unwrap())):e instanceof wt?wt.create(e.items.map(t=>Yr(t))):e}var Fe=class e extends V{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=q.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==E.object){let l=this._getOrReturnCtx(t);return k(l,{code:x.invalid_type,expected:E.object,received:l.parsedType}),D}let{status:r,ctx:s}=this._processInputParams(t),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof st&&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 st){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(l==="strict")a.length>0&&(k(s,{code:x.unrecognized_keys,keys:a}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let d=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new ze(s,d,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,p=await u.value;l.push({key:d,value:p,alwaysSet:u.alwaysSet})}return l}).then(l=>Te.mergeObjectSync(r,l)):Te.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(t){return M.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:M.errToObj(t).message??s}:{message:s}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:j.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of q.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let r of q.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return Yr(this)}partial(t){let n={};for(let r of q.objectKeys(this.shape)){let s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let r of q.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof Ye;)o=o._def.innerType;n[r]=o}return new e({...this._def,shape:()=>n})}keyof(){return rp(q.objectKeys(this.shape))}};Fe.create=(e,t)=>new Fe({shape:()=>e,unknownKeys:"strip",catchall:st.create(),typeName:j.ZodObject,...B(t)});Fe.strictCreate=(e,t)=>new Fe({shape:()=>e,unknownKeys:"strict",catchall:st.create(),typeName:j.ZodObject,...B(t)});Fe.lazycreate=(e,t)=>new Fe({shape:e,unknownKeys:"strip",catchall:st.create(),typeName:j.ZodObject,...B(t)});var ir=class extends V{_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new Be(a.ctx.common.issues));return k(n,{code:x.invalid_union,unionErrors:i}),D}if(n.common.async)return Promise.all(r.map(async o=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let c of r){let l={...n,common:{...n.common,issues:[]},parent:null},u=c._parseSync({data:n.data,path:n.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(c=>new Be(c));return k(n,{code:x.invalid_union,unionErrors:a}),D}}get options(){return this._def.options}};ir.create=(e,t)=>new ir({options:e,typeName:j.ZodUnion,...B(t)});var qt=e=>e instanceof cr?qt(e.schema):e instanceof Je?qt(e.innerType()):e instanceof lr?[e.value]:e instanceof ur?e.options:e instanceof dr?q.objectValues(e.enum):e instanceof fr?qt(e._def.innerType):e instanceof sr?[void 0]:e instanceof or?[null]:e instanceof Ye?[void 0,...qt(e.unwrap())]:e instanceof St?[null,...qt(e.unwrap())]:e instanceof Qs||e instanceof mr?qt(e.unwrap()):e instanceof pr?qt(e._def.innerType):[],_i=class e extends V{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==E.object)return k(n,{code:x.invalid_type,expected:E.object,received:n.parsedType}),D;let r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(k(n,{code:x.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),D)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let s=new Map;for(let o of n){let i=qt(o.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of i){if(s.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);s.set(a,o)}}return new e({typeName:j.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...B(r)})}};function Dc(e,t){let n=vt(e),r=vt(t);if(e===t)return{valid:!0,data:e};if(n===E.object&&r===E.object){let s=q.objectKeys(t),o=q.objectKeys(e).filter(a=>s.indexOf(a)!==-1),i={...e,...t};for(let a of o){let c=Dc(e[a],t[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===E.array&&r===E.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let o=0;o<e.length;o++){let i=e[o],a=t[o],c=Dc(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===E.date&&r===E.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var ar=class extends V{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=(o,i)=>{if(hi(o)||hi(i))return D;let a=Dc(o.value,i.value);return a.valid?((yi(o)||yi(i))&&n.dirty(),{status:n.value,value:a.data}):(k(r,{code:x.invalid_intersection_types}),D)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};ar.create=(e,t,n)=>new ar({left:e,right:t,typeName:j.ZodIntersection,...B(n)});var wt=class e extends V{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==E.array)return k(r,{code:x.invalid_type,expected:E.array,received:r.parsedType}),D;if(r.data.length<this._def.items.length)return k(r,{code:x.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),D;!this._def.rest&&r.data.length>this._def.items.length&&(k(r,{code:x.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...r.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new ze(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>Te.mergeArray(n,i)):Te.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};wt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new wt({items:e,typeName:j.ZodTuple,rest:null,...B(t)})};var bi=class e extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==E.object)return k(r,{code:x.invalid_type,expected:E.object,received:r.parsedType}),D;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in r.data)s.push({key:o._parse(new ze(r,a,r.path,a)),value:i._parse(new ze(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?Te.mergeObjectAsync(n,s):Te.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof V?new e({keyType:t,valueType:n,typeName:j.ZodRecord,...B(r)}):new e({keyType:vn.create(),valueType:t,typeName:j.ZodRecord,...B(n)})}},Xr=class extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==E.map)return k(r,{code:x.invalid_type,expected:E.map,received:r.parsedType}),D;let s=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([a,c],l)=>({key:s._parse(new ze(r,a,r.path,[l,"key"])),value:o._parse(new ze(r,c,r.path,[l,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return D;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let c of i){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return D;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}}}};Xr.create=(e,t,n)=>new Xr({valueType:t,keyType:e,typeName:j.ZodMap,...B(n)});var Zr=class e extends V{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==E.set)return k(r,{code:x.invalid_type,expected:E.set,received:r.parsedType}),D;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(k(r,{code:x.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(k(r,{code:x.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let o=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return D;u.status==="dirty"&&n.dirty(),l.add(u.value)}return{status:n.value,value:l}}let a=[...r.data.values()].map((c,l)=>o._parse(new ze(r,c,r.path,l)));return r.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(t,n){return new e({...this._def,minSize:{value:t,message:M.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:M.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};Zr.create=(e,t)=>new Zr({valueType:e,minSize:null,maxSize:null,typeName:j.ZodSet,...B(t)});var vi=class e extends V{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==E.function)return k(n,{code:x.invalid_type,expected:E.function,received:n.parsedType}),D;function r(a,c){return Zs({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Gr(),Vt].filter(l=>!!l),issueData:{code:x.invalid_arguments,argumentsError:c}})}function s(a,c){return Zs({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Gr(),Vt].filter(l=>!!l),issueData:{code:x.invalid_return_type,returnTypeError:c}})}let o={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof Sn){let a=this;return Ie(async function(...c){let l=new Be([]),u=await a._def.args.parseAsync(c,o).catch(f=>{throw l.addIssue(r(c,f)),l}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,o).catch(f=>{throw l.addIssue(s(d,f)),l})})}else{let a=this;return Ie(function(...c){let l=a._def.args.safeParse(c,o);if(!l.success)throw new Be([r(c,l.error)]);let u=Reflect.apply(i,this,l.data),d=a._def.returns.safeParse(u,o);if(!d.success)throw new Be([s(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:wt.create(t).rest(Kt.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new e({args:t||wt.create([]).rest(Kt.create()),returns:n||Kt.create(),typeName:j.ZodFunction,...B(r)})}},cr=class extends V{get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};cr.create=(e,t)=>new cr({getter:e,typeName:j.ZodLazy,...B(t)});var lr=class extends V{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return k(n,{received:n.data,code:x.invalid_literal,expected:this._def.value}),D}return{status:"valid",value:t.data}}get value(){return this._def.value}};lr.create=(e,t)=>new lr({value:e,typeName:j.ZodLiteral,...B(t)});function rp(e,t){return new ur({values:e,typeName:j.ZodEnum,...B(t)})}var ur=class e extends V{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return k(n,{expected:q.joinValues(r),received:n.parsedType,code:x.invalid_type}),D}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return k(n,{received:n.data,code:x.invalid_enum_value,options:r}),D}return Ie(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};ur.create=rp;var dr=class extends V{_parse(t){let n=q.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==E.string&&r.parsedType!==E.number){let s=q.objectValues(n);return k(r,{expected:q.joinValues(s),received:r.parsedType,code:x.invalid_type}),D}if(this._cache||(this._cache=new Set(q.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let s=q.objectValues(n);return k(r,{received:r.data,code:x.invalid_enum_value,options:s}),D}return Ie(t.data)}get enum(){return this._def.values}};dr.create=(e,t)=>new dr({values:e,typeName:j.ZodNativeEnum,...B(t)});var Sn=class extends V{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==E.promise&&n.common.async===!1)return k(n,{code:x.invalid_type,expected:E.promise,received:n.parsedType}),D;let r=n.parsedType===E.promise?n.data:Promise.resolve(n.data);return Ie(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Sn.create=(e,t)=>new Sn({type:e,typeName:j.ZodPromise,...B(t)});var Je=class extends V{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===j.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,o={addIssue:i=>{k(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(r.data,o);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return D;let c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?D:c.status==="dirty"?Qn(c.value):n.value==="dirty"?Qn(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"?Qn(a.value):n.value==="dirty"?Qn(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(!bn(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=>bn(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:n.value,value:a})):D);q.assertNever(s)}};Je.create=(e,t,n)=>new Je({schema:e,typeName:j.ZodEffects,effect:t,...B(n)});Je.createWithPreprocess=(e,t,n)=>new Je({schema:t,effect:{type:"preprocess",transform:e},typeName:j.ZodEffects,...B(n)});var Ye=class extends V{_parse(t){return this._getType(t)===E.undefined?Ie(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ye.create=(e,t)=>new Ye({innerType:e,typeName:j.ZodOptional,...B(t)});var St=class extends V{_parse(t){return this._getType(t)===E.null?Ie(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};St.create=(e,t)=>new St({innerType:e,typeName:j.ZodNullable,...B(t)});var fr=class extends V{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===E.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};fr.create=(e,t)=>new fr({innerType:e,typeName:j.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...B(t)});var pr=class extends V{_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Wr(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}};pr.create=(e,t)=>new pr({innerType:e,typeName:j.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...B(t)});var Qr=class extends V{_parse(t){if(this._getType(t)!==E.nan){let r=this._getOrReturnCtx(t);return k(r,{code:x.invalid_type,expected:E.nan,received:r.parsedType}),D}return{status:"valid",value:t.data}}};Qr.create=e=>new Qr({typeName:j.ZodNaN,...B(e)});var $0=Symbol("zod_brand"),Qs=class extends V{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},eo=class e extends V{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?D:o.status==="dirty"?(n.dirty(),Qn(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})}},mr=class extends V{_parse(t){let n=this._def.innerType._parse(t),r=s=>(bn(s)&&(s.value=Object.freeze(s.value)),s);return Wr(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};mr.create=(e,t)=>new mr({innerType:e,typeName:j.ZodReadonly,...B(t)});function Qf(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function sp(e,t={},n){return e?wn.create().superRefine((r,s)=>{let o=e(r);if(o instanceof Promise)return o.then(i=>{if(!i){let a=Qf(t,r),c=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=Qf(t,r),a=i.fatal??n??!0;s.addIssue({code:"custom",...i,fatal:a})}}):wn.create()}var P0={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 O0=(e,t={message:`Input not instance of ${e.name}`})=>sp(n=>n instanceof e,t),op=vn.create,ip=er.create,M0=Qr.create,N0=tr.create,ap=nr.create,L0=rr.create,U0=zr.create,D0=sr.create,j0=or.create,B0=wn.create,F0=Kt.create,H0=st.create,V0=Jr.create,q0=Gt.create,K0=Fe.create,G0=Fe.strictCreate,W0=ir.create,Y0=_i.create,z0=ar.create,J0=wt.create,X0=bi.create,Z0=Xr.create,Q0=Zr.create,ev=vi.create,tv=cr.create,nv=lr.create,rv=ur.create,sv=dr.create,ov=Sn.create,iv=Je.create,av=Ye.create,cv=St.create,lv=Je.createWithPreprocess,uv=eo.create,dv=()=>op().optional(),fv=()=>ip().optional(),pv=()=>ap().optional(),mv={string:(e=>vn.create({...e,coerce:!0})),number:(e=>er.create({...e,coerce:!0})),boolean:(e=>nr.create({...e,coerce:!0})),bigint:(e=>tr.create({...e,coerce:!0})),date:(e=>rr.create({...e,coerce:!0}))};var gv=D;var hv=/^[A-Za-z0-9._-]+$/,yv=/^[A-Za-z0-9._-]+(\|[A-Za-z0-9._-]+)*$/,cp=new Set([".",".."]),De=class extends Error{pattern;constructor(t,n){super(`Invalid freeReadPathPattern ${JSON.stringify(n)}: ${t}`),this.pattern=n,this.name="FreePathPatternError"}};function _v(e,t){if(e==="*")return{raw:e,kind:"single"};if(e==="**")return{raw:e,kind:"multi"};if(e.startsWith("(")){let n=e.endsWith(")?"),r=e.endsWith(")");if(!n&&!r)throw new De(`malformed alternation segment ${JSON.stringify(e)}`,t);let s=n?e.slice(1,-2):e.slice(1,-1);if(!yv.test(s))throw new De(`malformed alternation segment ${JSON.stringify(e)}`,t);let o=s.split("|");if(o.some(i=>cp.has(i)))throw new De(`alternation segment ${JSON.stringify(e)} may not contain '.' or '..'`,t);return{raw:e,kind:n?"alt-optional":"alt",alternatives:o}}if(hv.test(e)){if(cp.has(e))throw new De(`literal segment ${JSON.stringify(e)} is not permitted`,t);return{raw:e,kind:"literal"}}throw new De(`segment ${JSON.stringify(e)} must be '*', '**', a [A-Za-z0-9._-]+ literal, or (a|b) alternation`,t)}function bv(e){if(typeof e!="string"||e.length===0)throw new De("must be a non-empty string",String(e));if(!e.startsWith("/"))throw new De("must start with '/'",e);if(e.slice(1).includes("//"))throw new De("empty segments ('//') are not permitted",e);if(e.length>1&&e.endsWith("/"))throw new De("must not end with '/'",e);let n=e.slice(1).split("/").map(o=>_v(o,e));if(n.filter(o=>o.kind==="multi").length>1)throw new De("at most one '**' is permitted per pattern",e);if(n[0]?.kind==="multi")throw new De("'**' may not be the first segment (a literal prefix anchor is required)",e);let s=n.findIndex(o=>o.kind==="alt-optional");if(s!==-1&&s!==n.length-1)throw new De("optional alternation '(...)?' is only allowed as the final segment",e);return n}function jc(e){bv(e)}var lp=["tempo","mpp_self","merchant_self"],up=["catalog_static","fal_direct","fal_queue","openrouter_chat","openrouter_image","platform_proxy","tempo_gateway","x402_gateway"],dp=["image","audio","queued_audio","video","queued_video","model_3d","llm","transcription","utility"],fp=["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 Fc=_.object({inputPerMillion:_.number().positive(),outputPerMillion:_.number().positive(),contextWindow:_.number().int().positive().optional(),maxOutput:_.number().int().positive().optional(),perRequestFeeCents:_.number().nonnegative().optional()}),vv=_.object({strategy:_.enum(["flat","token","band"]).optional(),pricingModel:_.enum(["per-call","per-token","band"]).optional(),priceCents:_.number().nonnegative().optional(),currency:_.string().optional(),display:_.string().optional(),estimate:_.boolean().optional(),source:_.string().optional(),priceBand:_.record(_.unknown()).optional(),tokenPricing:Fc.optional()}).passthrough(),Hc=_.discriminatedUnion("type",[_.object({type:_.literal("shortcut"),routedPath:_.string().min(1).startsWith("/")}),_.object({type:_.literal("custom"),merchantSlug:_.string().min(1),subPath:_.string().optional()}),_.object({type:_.literal("local"),fn:_.string().min(1)}),_.object({type:_.literal("read")})]),Vc=_.object({amount:_.number().nonnegative(),currency:_.string().length(3).optional(),display:_.string().optional(),free:_.boolean().optional(),batchDiscount:_.number().min(0).max(100).optional()}),pp=_.object({attestation:_.boolean().optional(),rateLimitMs:_.number().positive().optional()}),mp=_.object({displayName:_.string().optional(),feedbackEligible:_.boolean().optional(),suggestionEligible:_.boolean().optional(),batchable:_.boolean().optional()}),gp=_.object({enabled:_.boolean().optional(),gatewayPath:_.string().min(1).startsWith("/").optional(),method:_.enum(["GET","POST","PUT","PATCH","DELETE"]).optional(),timeoutMs:_.number().int().positive().max(12e4).optional()}).strict(),wv=_.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),Sv=120,xv=120,Tv=1200,Cv=/^[^\u0000-\u001F\u007F]+$/;function Bc(e,t){return _.string().min(1).max(e).regex(Cv,`${t} must not contain control characters`)}var qc={id:_.string().min(1),name:Bc(Sv,"name"),description:Bc(Tv,"description"),provider:_.string().min(1),model:_.string().min(1),category:wv,priceCents:_.number().nonnegative(),inputSchema:_.record(_.unknown()),gatewayUrl:_.string().min(1),merchantName:Bc(xv,"merchantName"),isAsync:_.boolean().optional(),pollUrl:_.string().optional(),pollInterval:_.number().positive().optional(),pollTimeout:_.number().positive().optional(),tags:_.array(_.string()).optional(),tokenPricing:Fc.optional(),priceDisplay:_.string().optional(),pricingModel:_.enum(["per-call","per-token","band"]).optional(),pricingInfo:vv.optional(),status:_.enum(["available","unavailable"]).optional(),handler:Hc.optional(),pricing:Vc.optional(),security:pp.optional(),engagement:mp.optional(),gatewayConfig:gp.optional(),freeReadPathPattern:_.string().optional().superRefine((e,t)=>{if(e!==void 0)try{jc(e)}catch(n){t.addIssue({code:_.ZodIssueCode.custom,message:n instanceof Error?n.message:String(n)})}}),enabled:_.boolean().optional(),beta:_.boolean().optional(),deprecated:_.boolean().optional(),internal:_.boolean().optional(),employeeOnly:_.boolean().optional(),employeeOnlyRolloutFlag:_.string().min(1).max(100).optional(),replacementTool:_.string().optional(),minCliVersion:_.string().optional(),sunsetAt:_.string().optional(),rail:_.enum(lp).optional(),executionKind:_.enum(up).optional(),resultKind:_.enum(dp).optional(),extractionMode:_.enum(fp).optional(),pricingStrategy:_.enum(["flat","token","band"]).optional()},hp=_.object({...qc,dispatch:_.literal("routed"),routedPath:_.string().min(1).startsWith("/")}).strict(),yp=_.object({...qc,dispatch:_.literal("enveloped")}).strict(),_p=_.object({...qc,handler:Hc,pricing:Vc}).strict(),bp=_.union([_.discriminatedUnion("dispatch",[hp,yp]),_p]);var Kc=/^[a-z0-9][a-z0-9_-]*$/;var Av="https://fal.run",xp="https://openrouter.mpp.tempo.xyz",Wc=1024,Si=8192,Rv=4096,Iv=10;function $v(e){return e>=Iv?Rv:Si}function Tp(e,t){let n=typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):Wc;return Math.min(n,t)}var Pv=["num_images","num_outputs","num_samples","num_videos","batch_size","n"];function Cp(e){for(let t of Pv)delete e[t];return e}function Ov(e){let{attestation:t,tool_id:n,...r}=e;return Cp(r)}var vp={"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 wi(e){let{attestation:t,tool_id:n,aspect_ratio:r,image_size:s,...o}=e,i=Cp({...o});return typeof s=="string"&&s.length>0?(i.image_size=s,i):(typeof r=="string"&&vp[r]&&(i.image_size=vp[r]),i)}function Mv(e){let{attestation:t,tool_id:n,...r}=e;return r}function wp(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 Nv(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 Lv(e,t,n,r,s,o,i,a){return Nv(e,t,n,"suno-ai",r,s,o,i,{merchantName:"Suno AI",...a})}function he(e,t,n,r,s,o,i,a){return{dispatch:"routed",id:e,name:t,description:n,provider:"fal",model:r,category:s,priceCents:o,inputSchema:i,routedPath:`/api/v1/fal/${r}`,gatewayUrl:`${Av}/${r}`,merchantName:"fal.ai",buildBody:Ov,tags:[],...a}}function kp(e,t=Si){return n=>{let{attestation:r,tool_id:s,model:o,prompt:i,system_prompt:a,max_tokens:c,max_completion_tokens:l,n:u,messages:d,temperature:p,...f}=n;return typeof o=="string"&&o.length>0&&o!==e&&console.warn("[catalog] openrouterBuildBody: caller model override ignored",{catalogModel:e,callerModel:o}),{messages:Array.isArray(d)?d:[...a?[{role:"system",content:a}]:[],{role:"user",content:i}],temperature:p??.7,...f,model:e,max_tokens:Tp(c??l,t)}}}function Ep(e,t=Si){return n=>{let{attestation:r,tool_id:s,prompt:o,image_url:i,aspect_ratio:a,max_tokens:c,max_completion_tokens:l,n:u,model:d,messages:p,image_config:f,temperature:m,...h}=n,w=[{type:"text",text:o}];return typeof i=="string"&&i.length>0&&w.push({type:"image_url",image_url:{url:i}}),{messages:Array.isArray(p)?p:[{role:"user",content:w}],temperature:m??.7,...h,model:e,...typeof a=="string"&&a.length>0?{image_config:{aspect_ratio:a}}:{},max_tokens:Tp(c??l,t)}}}function le(e,t,n,r,s,o,i){let a=i?.maxOutputTokens??$v(o),c=i?.perRequestFeeCents??0,l=500/1e6*s*100,u=500/1e6*o*100,d=Math.max(1,Math.ceil(l+u+c)),{perRequestFeeCents:p,maxOutputTokens:f,...m}=i??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"llm",priceCents:d,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The prompt or question to send to the model"},system_prompt:{type:"string",description:"Optional system prompt to set model behavior"},max_tokens:{type:"integer",description:`Maximum tokens in response (default: ${Wc}); 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:`${xp}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:kp(r,a),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:s,outputPerMillion:o,...c>0?{perRequestFeeCents:c}:{}},...m}}function Gc(e,t,n,r,s,o){let i=o?.maxOutputTokens??Si,{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: ${Wc}); 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:`${xp}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:Ep(r,i),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...c}}var Yc=[he("fal-flux-pro-ultra","FLUX Pro Ultra","Highest quality image generation. Best for detailed, photorealistic images.","fal-ai/flux-pro/v1.1-ultra","image",6,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},{tags:["image","flux","photorealistic","high-quality"]}),he("fal-flux-pro","FLUX Pro","Fast, high-quality image generation. Good balance of speed and quality.","fal-ai/flux-pro/v1.1","image",4,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},{tags:["image","flux","fast"],buildBody:wi}),he("fal-flux-dev","FLUX Dev","Open-source image generation. Cheaper, good for experimentation.","fal-ai/flux/dev","image",3,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["image","flux","open-source","cheap"],buildBody:wi}),he("fal-flux-schnell","FLUX Schnell","Fastest image generation. Ultra-cheap, great for drafts and iteration.","fal-ai/flux/schnell","image",1,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["image","flux","fast","cheap","draft"],buildBody:wi}),he("fal-recraft-v3","Recraft V3","Design-focused image generation. Great for illustrations, icons, and graphic design.","fal-ai/recraft/v3/text-to-image","image",5,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},style:{type:"string",description:"Style preset: realistic_image, digital_illustration, vector_illustration, icon"}},required:["prompt"]},{tags:["image","design","illustration","icon","vector"]}),Gc("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),Gc("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}}),Gc("or-gemini-nano-banana-pro","Nano Banana Pro","Google Gemini 3 Pro Image Preview via OpenRouter for professional image generation, edits, and text rendering.","google/gemini-3-pro-image-preview",8,{tags:["image","gemini","google","nano-banana","pro","text-rendering"],tokenPricing:{inputPerMillion:2,outputPerMillion:12}}),he("fal-ideogram-v2","Ideogram V2","Excellent text rendering in images. Best for logos, posters, and text-heavy visuals.","fal-ai/ideogram/v2","image",8,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"1:1"}},required:["prompt"]},{tags:["image","text-rendering","logo","poster","typography"]}),he("fal-ideogram-v2-turbo","Ideogram V2 Turbo","Fast text rendering in images. Good balance of speed and text accuracy.","fal-ai/ideogram/v2/turbo","image",5,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"1:1"}},required:["prompt"]},{tags:["image","text-rendering","fast"]}),he("fal-fast-sdxl","Fast SDXL","Ultra-fast Stable Diffusion. 4-step inference, cheapest option.","fal-ai/fast-sdxl","image",1,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"}},required:["prompt"]},{tags:["image","stable-diffusion","fast","cheap"]}),he("fal-wan-video","Wan Video","Text-to-video generation. Create short video clips from text descriptions.","fal-ai/wan/v2.1/1.3b/text-to-video","video",10,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"},num_frames:{type:"number",description:"Number of frames (default: 81)"}},required:["prompt"]},{tags:["video","text-to-video","wan"]}),he("fal-minimax-video","MiniMax Video","High-quality video generation with excellent motion and coherence.","fal-ai/minimax-video/video-01-live","video",15,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"}},required:["prompt"]},{tags:["video","text-to-video","high-quality"]}),he("fal-kling-video","Kling Video","Professional video generation with cinematic quality.","fal-ai/kling-video/v2/master/text-to-video","video",20,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"},duration:{type:"string",description:"Duration: 5 or 10 seconds",default:"5"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["video","text-to-video","cinematic","professional"]}),he("fal-kling-i2v","Kling Image-to-Video","Animate a still image into a 5\u201310s video clip. Cinematic motion quality.","fal-ai/kling-video/v1.6/standard/image-to-video","video",35,{type:"object",properties:{image_url:{type:"string",description:"URL of the source image (jpg, png, webp, gif, avif)"},prompt:{type:"string",description:"Text description of the motion to animate"},duration:{type:"string",description:"Duration: 5 or 10 seconds",default:"5"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 9:16, 1:1)",default:"16:9"},negative_prompt:{type:"string",description:"Elements to avoid in the generated motion"},cfg_scale:{type:"number",description:"Classifier-free guidance (default 0.5)",default:.5}},required:["image_url","prompt"]},{tags:["video","image-to-video","kling","cinematic"]}),he("fal-stable-audio","Stable Audio","Generate sound effects and ambient audio from text descriptions.","fal-ai/stable-audio","audio",4,{type:"object",properties:{prompt:{type:"string",description:"Description of the audio to generate"},seconds_total:{type:"number",description:"Duration in seconds (max 47)",default:30}},required:["prompt"]},{tags:["audio","sound-effects","ambient"]}),he("fal-ace-step-music","ACE-Step Music","Generate full music tracks from a prompt, with optional vocals or instrumentals.","fal-ai/ace-step/prompt-to-audio","audio",2,{type:"object",properties:{prompt:{type:"string",description:"Description of the song, genre, mood, instruments, and lyrics direction"},instrumental:{type:"boolean",description:"Generate instrumental music without vocals",default:!1},duration:{type:"number",description:"Duration in seconds",default:60}},required:["prompt"]},{tags:["music","song","vocals","instrumental","ace-step"]}),Lv("suno-music","Suno Music","AI music generation. Create full songs with vocals or instrumentals.","/suno/generate-music","audio",10,{type:"object",properties:{prompt:{type:"string",description:"Description of the song (genre, mood, instruments)"},instrumental:{type:"boolean",description:"Instrumental only, no vocals",default:!1}},required:["prompt"]},{isAsync:!0,pollUrl:"https://api.sunoapi.org/suno/get-music-status",deprecated:!0,tags:["music","song","vocals","instrumental"],buildBody:e=>{let{attestation:t,tool_id:n,prompt:r,instrumental:s,...o}=e;return{prompt:r,customMode:!1,instrumental:typeof s=="boolean"?s:!1,model:"V4",...o}}}),he("fal-trellis-3d","Trellis 3D","Generate 3D models from images. Upload a photo, get a 3D asset.","fal-ai/trellis","3d",8,{type:"object",properties:{image_url:{type:"string",description:"URL of the image to convert to 3D"}},required:["image_url"]},{tags:["3d","model","image-to-3d"]}),he("fal-aura-sr","Aura SR","Upscale images to higher resolution. 4x upscaling with detail enhancement.","fal-ai/aura-sr","upscale",3,{type:"object",properties:{image_url:{type:"string",description:"URL of the image to upscale"}},required:["image_url"]},{tags:["upscale","super-resolution","enhance"]}),he("fal-metavoice","MetaVoice Voice Cloning","Voice cloning TTS \u2014 clone any voice from an audio sample. Provide text and a voice sample URL.","fal-ai/metavoice-v1","tts",3,{type:"object",properties:{text:{type:"string",description:"Text to convert to speech"},audio_url:{type:"string",description:"URL of the voice sample to clone"}},required:["text","audio_url"]},{tags:["tts","voice","voice-cloning","speech"]}),he("fal-whisper","Whisper Transcription","Transcribe audio to text. Supports multiple languages.","fal-ai/whisper","transcription",2,{type:"object",properties:{audio_url:{type:"string",description:"URL of the audio to transcribe"},language:{type:"string",description:"Language code (e.g. en, es, fr)"}},required:["audio_url"]},{tags:["transcription","speech-to-text","whisper"]}),le("or-gpt-4o","GPT-4o","OpenAI's flagship multimodal model. Best for complex reasoning and analysis.","openai/gpt-4o",2.5,10,{tags:["llm","gpt","openai","multimodal","reasoning"]}),le("or-gpt-55","GPT-5.5","OpenAI frontier model for complex professional reasoning, coding, and long-context analysis.","openai/gpt-5.5",5,30,{tags:["llm","gpt","openai","frontier","reasoning","coding","long-context"]}),le("or-gpt-55-pro","GPT-5.5 Pro","OpenAI high-capability frontier model optimized for deep reasoning and high-stakes workloads.","openai/gpt-5.5-pro",30,180,{tags:["llm","gpt","openai","frontier","pro","deep-reasoning","coding","long-context"]}),le("or-gpt-4o-mini","GPT-4o Mini","Fast, affordable GPT-4o. Great for everyday tasks, chat, and simple analysis.","openai/gpt-4o-mini",.15,.6,{tags:["llm","gpt","openai","fast","cheap"]}),le("or-claude-opus","Claude Opus 4.7","Anthropic's most capable model. 1M context, reasoning, best for complex tasks.","anthropic/claude-opus-4.7",15,75,{tags:["llm","claude","anthropic","reasoning","coding"]}),le("or-claude-sonnet","Claude Sonnet 4.6","Anthropic's best balance of intelligence and speed. Excellent for coding and analysis.","anthropic/claude-sonnet-4.6",3,15,{tags:["llm","claude","anthropic","coding","analysis"]}),le("or-claude-opus-fast","Claude Opus 4.6 Fast","Fast Opus variant with lower latency.","anthropic/claude-opus-4.6-fast",15,75,{tags:["llm","claude","anthropic","fast"]}),le("or-claude-haiku","Claude 3.5 Haiku","Anthropic's fastest model. Great for quick tasks, chat, and simple reasoning.","anthropic/claude-3.5-haiku",.8,4,{tags:["llm","claude","anthropic","fast"]}),le("or-gemini-pro","Gemini 2.0 Flash","Google's fast multimodal model. Good for general tasks with long context.","google/gemini-2.0-flash-001",.1,.4,{tags:["llm","gemini","google","multimodal","fast","cheap"]}),le("or-gemini-3-flash","Gemini 3 Flash","Google's high-speed thinking model for agentic workflows, coding, and multimodal tasks.","google/gemini-3-flash-preview",.5,3,{tags:["llm","gemini","google","agentic","coding","fast"]}),le("or-gemini-3-pro","Gemini 3 Pro","Google's flagship frontier model for deep reasoning, multimodal analysis, and agentic coding.","google/gemini-3-pro-preview",2,12,{tags:["llm","gemini","google","reasoning","coding","multimodal"]}),le("or-gemini-35-flash","Gemini 3.5 Flash","Google frontier Flash model for multimodal reasoning, coding, and parallel agentic workflows.","google/gemini-3.5-flash",1.5,9,{tags:["llm","gemini","google","frontier","multimodal","reasoning","coding","fast"]}),le("or-gemini-3-lite","Gemini 3.1 Flash Lite","Google's efficient multimodal model optimized for low-latency, high-volume agent workloads.","google/gemini-3.1-flash-lite",.25,1.5,{tags:["llm","gemini","google","fast","cheap","multimodal"]}),le("or-llama-70b","Llama 3.3 70B","Meta's best open model. Strong reasoning, fully open-source.","meta-llama/llama-3.3-70b-instruct",.3,.4,{tags:["llm","llama","meta","open-source","reasoning"]}),le("or-llama-8b","Llama 3.1 8B","Fast, lightweight open model. Great for simple tasks at minimal cost.","meta-llama/llama-3.1-8b-instruct",.05,.08,{tags:["llm","llama","meta","open-source","fast","cheap"]}),le("or-mistral-large","Mistral Large","Mistral's flagship model. Strong at multilingual and European languages.","mistralai/mistral-large-2411",2,6,{tags:["llm","mistral","multilingual","european"]}),le("or-mistral-small","Mistral Small","Fast, efficient Mistral model. Good for everyday tasks.","mistralai/mistral-small-3.1-24b-instruct",.1,.3,{tags:["llm","mistral","fast","cheap"]}),le("or-deepseek-chat","DeepSeek Chat V3","Strong reasoning model at very low cost. Excellent for coding and math.","deepseek/deepseek-chat-v3-0324",.3,.88,{tags:["llm","deepseek","coding","math","cheap","reasoning"]}),le("or-deepseek-r1","DeepSeek R1","Advanced reasoning model with chain-of-thought. Best for complex problems.","deepseek/deepseek-r1",.55,2.19,{tags:["llm","deepseek","reasoning","chain-of-thought","math"]}),le("or-qwen-72b","Qwen 2.5 72B","Alibaba's large model. Strong at coding, math, and multilingual tasks.","qwen/qwen-2.5-72b-instruct",.3,.4,{tags:["llm","qwen","alibaba","coding","multilingual"]}),le("or-phi-4","Phi-4","Microsoft's compact reasoning model. Punches above its weight for size.","microsoft/phi-4",.07,.14,{tags:["llm","phi","microsoft","compact","cheap","reasoning"]}),le("or-perplexity-sonar","Perplexity Sonar","Search-augmented LLM. Answers with real-time web sources and citations.","perplexity/sonar",1,1,{perRequestFeeCents:.5,tags:["llm","perplexity","search","web","citations","real-time"]}),{dispatch:"enveloped",id:"query_onchain_prices",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly and daily granularity.",provider:"allium",model:"allium-prices",category:"onchain",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly) or '1d' (daily). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",internal:!0,executionKind:"x402_gateway",resultKind:"utility",gatewayConfig:{enabled:!1,gatewayPath:"/gateway",method:"POST",timeoutMs:3e4},buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:wp,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:Mv,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=>wi({prompt:e.prompt,aspect_ratio:e.aspect_ratio}),tags:["image","flux","legacy"]},{dispatch:"enveloped",id:"generate_image_schnell_card",name:"Generate Image (Cheap)",description:"Cheap, fast FLUX image generation (~$0.01).",provider:"fal",model:"fal-ai/flux/schnell",category:"image",priceCents:1,inputSchema:{type:"object",properties:{prompt:{type:"string"},image_size:{type:"string"},num_inference_steps:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux/schnell",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-schnell",buildBody:e=>{let t={prompt:e.prompt};return e.image_size&&(t.image_size=e.image_size),e.num_inference_steps!==void 0&&(t.num_inference_steps=e.num_inference_steps),e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","flux","schnell","legacy"]},{dispatch:"enveloped",id:"generate_image_recraft_card",name:"Generate Image (Recraft)",description:"Recraft V3 image generation with style control.",provider:"fal",model:"fal-ai/recraft-v3",category:"image",priceCents:5,inputSchema:{type:"object",properties:{prompt:{type:"string"},style:{type:"string"},image_size:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/recraft-v3",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-recraft-v3",buildBody:e=>{let t={prompt:e.prompt};return e.style&&(t.style=e.style),e.image_size&&(t.image_size=e.image_size),t},tags:["image","recraft","legacy"]},{dispatch:"enveloped",id:"generate_image_ideogram_card",name:"Generate Image (Ideogram)",description:"Ideogram V2 image generation, strong with text rendering.",provider:"fal",model:"fal-ai/ideogram/v2",category:"image",priceCents:8,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},style_type:{type:"string"},negative_prompt:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/ideogram/v2",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-ideogram-v2",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.style_type&&(t.style_type=e.style_type),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),t},tags:["image","ideogram","text","legacy"]},he("upscale_image_card","Upscale Image","Upscale an image using ESRGAN.","fal-ai/esrgan","upscale",2,{type:"object",properties:{image_url:{type:"string"},scale:{type:"number"}},required:["image_url"]},{buildBody:e=>{let t={image_url:e.image_url};return e.scale!==void 0&&(t.scale=e.scale),t},tags:["upscale","esrgan"],deprecated:!0,replacementTool:"fal-aura-sr"}),he("edit_image_seed_card","Edit Image (SeedEdit)","Inpaint/edit an image with a prompt using SeedEdit.","fal-ai/bytedance/seededit","image",5,{type:"object",properties:{image_url:{type:"string"},prompt:{type:"string"},seed:{type:"number"}},required:["image_url","prompt"]},{buildBody:e=>{let t={image_url:e.image_url,prompt:e.prompt};return e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","edit","inpaint","seededit"],deprecated:!0,replacementTool:"or-gemini-nano-banana"}),{dispatch:"enveloped",id:"generate_video_tempo_card",name:"Generate Video (Grok)",description:"Generate a video from a text prompt using Grok Imagine Video.",provider:"fal",model:"xai/grok-imagine-video/text-to-video",category:"video",priceCents:30,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/xai/grok-imagine-video/text-to-video",merchantName:"Grok Video via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),t},tags:["video","grok","legacy"]},{dispatch:"enveloped",id:"generate_video_kling_card",name:"Generate Video (Kling)",description:"Generate a video using Kling v1.6 (async, ~$0.40).",provider:"fal",model:"fal-ai/kling-video/v1.6/standard/text-to-video",category:"video",priceCents:40,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/kling-video/v1.6/standard/text-to-video",merchantName:"Kling via fal.ai",deprecated:!0,replacementTool:"fal-kling-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","kling","legacy"]},{dispatch:"enveloped",id:"generate_video_wan_card",name:"Generate Video (Wan)",description:"Generate a video using Wan T2V (async, ~$0.25).",provider:"fal",model:"fal-ai/wan/t2v-1.3b",category:"video",priceCents:25,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/wan/t2v-1.3b",merchantName:"Wan T2V via fal.ai",deprecated:!0,replacementTool:"fal-wan-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","wan","legacy"]},{dispatch:"enveloped",id:"generate_video_minimax_card",name:"Generate Video (MiniMax)",description:"Generate a video using MiniMax (async, ~$0.35).",provider:"fal",model:"fal-ai/minimax/video-01",category:"video",priceCents:35,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/minimax/video-01",merchantName:"MiniMax via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","minimax","legacy"]},{id:"check_fal_status",name:"Check fal Async Job Status",description:"Poll an async fal.ai queue job for completion. Free.",provider:"fal",model:"queue-status",category:"image",priceCents:0,inputSchema:{type:"object",properties:{model_path:{type:"string",description:"Model path (e.g. fal-ai/kling-video/v1.6/standard/text-to-video)"},request_id:{type:"string"}},required:["model_path","request_id"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue",merchantName:"fal.ai",handler:{type:"local",fn:"check_fal_status"},pricing:{amount:0,currency:"USD",display:"$0.00",free:!0},freeReadPathPattern:"/api/v1/fal/**/requests/*/(status)?",tags:["status","fal","async"]},{dispatch:"enveloped",id:"generate_3d_card",name:"Generate 3D Model",description:"Generate a 3D mesh from a text prompt using Meshy (async, ~$0.50).",provider:"fal",model:"fal-ai/meshy-ai/text-to-3d",category:"3d",priceCents:50,inputSchema:{type:"object",properties:{object_prompt:{type:"string"},style_prompt:{type:"string"},negative_prompt:{type:"string"},art_style:{type:"string"},seed:{type:"number"}},required:["object_prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/meshy-ai/text-to-3d",merchantName:"Meshy via fal.ai",deprecated:!0,replacementTool:"fal-trellis-3d",buildBody:e=>{let t={object_prompt:e.object_prompt};return e.style_prompt&&(t.style_prompt=e.style_prompt),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.art_style&&(t.art_style=e.art_style),e.seed!==void 0&&(t.seed=e.seed),t},tags:["3d","mesh","meshy","legacy"]},{dispatch:"enveloped",id:"generate_speech_card",name:"Generate Speech",description:"Text-to-speech using F5-TTS with optional voice cloning.",provider:"fal",model:"fal-ai/f5-tts",category:"tts",priceCents:3,inputSchema:{type:"object",properties:{gen_text:{type:"string",description:"Text to synthesize"},ref_audio_url:{type:"string",description:"Reference audio URL (for voice cloning)"},ref_text:{type:"string",description:"Transcription of ref audio"},remove_silence:{type:"boolean"}},required:["gen_text"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/f5-tts",merchantName:"fal.ai",buildBody:e=>{let t={gen_text:e.gen_text};return e.ref_audio_url&&(t.ref_audio_url=e.ref_audio_url),e.ref_text&&(t.ref_text=e.ref_text),e.remove_silence!==void 0&&(t.remove_silence=e.remove_silence),t},deprecated:!0,replacementTool:"fal-metavoice",tags:["tts","speech","f5-tts","legacy"]},{dispatch:"enveloped",id:"generate_music_tempo_card",name:"Generate Music (Suno) \u2014 retired",description:"[Retired] Suno music generation. Use `generate_music` (ACE-Step) instead.",enabled:!1,sunsetAt:"2026-06-25",provider:"suno",model:"suno-v4",category:"audio",priceCents:50,inputSchema:{type:"object",properties:{prompt:{type:"string"},instrumental:{type:"boolean"},model:{type:"string",default:"V4"}},required:["prompt"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/generate-music",merchantName:"Suno via Tempo",buildBody:e=>({prompt:e.prompt,customMode:!1,instrumental:e.instrumental??!1,model:e.model||"V4"}),isAsync:!0,pollUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",pollInterval:15e3,pollTimeout:3e5,deprecated:!0,replacementTool:"fal-ace-step-music",tags:["music","audio","suno","async","legacy"]},{dispatch:"enveloped",id:"check_music_status_tempo_card",name:"Check Music Status (Suno) \u2014 retired",description:"[Retired] Suno status poll. No replacement; ACE-Step jobs poll via `check_fal_status`.",enabled:!1,sunsetAt:"2026-06-25",provider:"suno",model:"suno-status",category:"audio",priceCents:0,inputSchema:{type:"object",properties:{taskId:{type:"string"}},required:["taskId"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",merchantName:"Suno Status",buildBody:e=>({taskId:e.taskId}),deprecated:!0,tags:["music","status","suno","legacy"]},{dispatch:"enveloped",id:"query_onchain_prices_card",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly, daily, and weekly granularity.",provider:"allium",model:"allium-prices",category:"llm",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly), '1d' (daily), or '1w' (weekly). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",deprecated:!0,replacementTool:"query_onchain_prices",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:wp,tags:["onchain","prices","allium","crypto","legacy"]}];function es(e){return Yc.find(t=>t.id===e)}var Ap=1,Rp=["pick_one","fan_out"],Ip=["concat","dedupe_by_url","top_k_by_score"],jv=8,Bv=_.object({type:_.string().min(1),description:_.string().min(1),enum:_.array(_.string()).optional(),default:_.unknown().optional(),minimum:_.number().optional(),maximum:_.number().optional()}),Fv=_.object({toolId:_.string().min(1),notes:_.string().min(1)}),Hv=_.string().regex(/^[a-z0-9_-]{1,32}$/,"tier key must be 1-32 chars [a-z0-9_-]"),Vv=_.object({providers:_.array(_.string().min(1)).min(1).max(jv),merge:_.enum(Ip),maxResults:_.number().int().positive().optional()}),$p=_.object({mode:_.enum(Rp).default("pick_one"),intro:_.string().min(1),defaultTier:_.string().min(1),tiers:_.record(Hv,Fv).refine(e=>Object.keys(e).length>0,{message:"must have at least one tier"}),fanOut:Vv.optional(),guidance:_.string().min(1),inputProperties:_.record(_.string(),Bv),required:_.array(_.string())}).refine(e=>e.tiers[e.defaultTier]!==void 0,{message:"defaultTier must exist in tiers",path:["defaultTier"]}).refine(e=>e.mode!=="fan_out"||e.fanOut!==void 0,{message:"fan_out mode requires fanOut config",path:["fanOut"]}).refine(e=>e.required.every(t=>t in e.inputProperties),{message:"required entries must exist in inputProperties",path:["required"]}),qv=_.object({version:_.literal(Ap),generatedAt:_.string().datetime(),tools:_.record(_.string().regex(Kc,"tool name must match MCP naming rules"),$p).refine(e=>Object.keys(e).length>0,{message:"manifest must have at least one tool"})});var xa=R(ts());var ki=require("child_process"),Hp=require("util"),Vp=R(require("crypto")),te=R(require("fs")),qp=R(require("os")),$e=R(require("path"));_t();var ot=(0,Hp.promisify)(ki.execFile),uw=6e4,dw=()=>process.platform==="darwin",xn=()=>process.platform==="win32",Tn=$e.join(qp.homedir(),".visa-mcp","bin"),gr=$e.join(Tn,"Visa CLI"),Yt=$e.join(Tn,"visa-keychain-win.exe"),Kp=$e.join(__dirname,"..","native"),Op="6",Mp=$e.join(Tn,"visa-keychain.version"),Np=$e.join(Tn,"visa-keychain.sha256"),Lp="1",Up=$e.join(Tn,"visa-keychain-win.version"),Dp=$e.join(Tn,"visa-keychain-win.sha256"),Gp=[$e.join(Kp,"bin","win32-x64","visa-keychain-win.exe"),$e.resolve(__dirname,"..","..","native","bin","win32-x64","visa-keychain-win.exe"),$e.resolve(__dirname,"..","native","bin","win32-x64","visa-keychain-win.exe")];function xi(e){let t=te.readFileSync(e);return Vp.createHash("sha256").update(t).digest("hex")}function fw(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 jp(e){let t=typeof e?.message=="string"?e.message:"";return e?.code==="ETIMEDOUT"||e?.killed===!0||/timed out|timeout/i.test(t)}function Bp(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 zc(){try{if(te.readFileSync(Mp,"utf-8").trim()===Op&&te.existsSync(gr)){let r=te.readFileSync(Np,"utf-8").trim();if(xi(gr)!==r)g.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),te.unlinkSync(gr);else return gr}}catch{}let e=$e.join(Kp,"visa-keychain.m");if(te.existsSync(e)||(e=$e.resolve(__dirname,"..","..","native","visa-keychain.m")),te.existsSync(e)||(e=$e.resolve(__dirname,"..","native","visa-keychain.m")),!te.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");te.mkdirSync(Tn,{recursive:!0,mode:448});try{await ot("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",gr,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=xi(gr);return te.writeFileSync(Np,t,{mode:384}),te.writeFileSync(Mp,Op,{mode:384}),gr}function Wp(){for(let e of Gp)if(te.existsSync(e))return e;return null}async function ns(){try{if(te.readFileSync(Up,"utf-8").trim()===Lp&&te.existsSync(Yt)){let r=te.readFileSync(Dp,"utf-8").trim();if(xi(Yt)!==r)g.warn("binary:hash-mismatch:win32",{message:"Windows binary hash mismatch. Redeploying."}),te.unlinkSync(Yt);else return Yt}}catch{}let e=Wp();if(!e)throw new Error(`visa-keychain-win.exe not found in package. Reinstall @visa/cli.
142
- If building from source, run native/build-win.bat first.`);te.mkdirSync(Tn,{recursive:!0}),te.copyFileSync(e,Yt);let t=xi(Yt);return te.writeFileSync(Dp,t,{mode:384}),te.writeFileSync(Up,Lp,{mode:384}),Yt}async function pw(){return xn()?ns():zc()}var Ti="visa-cli",Ci="attestation-key";async function mw(e){try{await ot("security",["delete-generic-password","-s",Ti,"-a",Ci],{timeout:5e3})}catch{}await ot("security",["add-generic-password","-s",Ti,"-a",Ci,"-w",e],{timeout:5e3})}function gw(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 hw(){try{let{stdout:e}=await ot("security",["find-generic-password","-s",Ti,"-a",Ci,"-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:gw(e)}}}async function Jc(){let e=await hw();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 Yp(e){let t=await pw(),n;try{n=(await ot(t,e,{timeout:6e4})).stdout}catch(r){n=r.stdout||"";let s=n.trim();throw s.startsWith("ERROR:")?new Error(s.slice(6)):new Error(r.stderr?.trim()||r.message||"Unknown error")}return fw(n)}var Fp=!1;function yw(){if(!xn())return!1;try{return te.existsSync(Yt)||Wp()!==null?!0:(Fp||(Fp=!0,g.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:Yt,searchedPrebuiltPaths:Gp})),!1)}catch{return!1}}function ue(){return Lr()||dw()?!0:xn()?yw():!1}async function Ei(){if(xn()){let s=await ns(),{stdout:o}=await ot(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 Yp(["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 mw(n),r}async function Ai(){if(xn())try{let e=await ns(),{stdout:t}=await ot(e,["public-key"],{timeout:1e4});return t.trim().startsWith("OK:")}catch{return!1}return await Jc()!==null}async function zp(){if(Lr())return"mock-public-key-spki";if(xn()){let n=await ns(),{stdout:r}=await ot(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 Jc();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await zc();return new Promise((n,r)=>{let s=(0,ki.execFile)(t,["public-key"],{timeout:6e4},(o,i)=>{let a=(i||"").trim();if(o){a.startsWith("ERROR:")?r(new Error(a.slice(6))):r(new Error(o.stderr?.trim()||o.message||"Unknown error"));return}a.startsWith("OK:")?n(a.slice(3)):r(new Error(a.startsWith("ERROR:")?a.slice(6):"Unknown error"))});s.stdin.write(e),s.stdin.end()})}async function Cn(e,t,n={}){if(Lr())return Promise.resolve(cd());let r=n.timeoutMs??uw;if(xn()){let a=await ns(),c=["sign",e];t&&c.push(t);let l;try{l=(await ot(a,c,{timeout:r})).stdout}catch(d){throw jp(d)?Bp(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 Jc();if(!s)throw new Error("Attestation key not found. Run setup to generate a new key.");let o=await zc(),i=["sign",e];return t&&i.push(t),new Promise((a,c)=>{let l=(0,ki.execFile)(o,i,{timeout:r},(u,d)=>{let p=(d||"").trim();if(u){p.startsWith("ERROR:")?c(new Error(p.slice(6))):jp(u)?c(Bp(r)):c(new Error(u.stderr?.trim()||u.message||"Unknown error"));return}p.startsWith("OK:")?a(p.slice(3)):c(new Error(p.startsWith("ERROR:")?p.slice(6):"Unknown error"))});l.stdin.write(s),l.stdin.end()})}async function Ri(){if(xn()){try{let e=await ns();await ot(e,["delete-key"],{timeout:1e4})}catch{}return}try{await ot("security",["delete-generic-password","-s",Ti,"-a",Ci],{timeout:5e3})}catch{}try{await Yp(["delete-key"])}catch{}}_t();var _w=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],bw=[..._w.map(e=>({id:`legacy.${e}`,match:{kind:"exact_tool",toolId:e},targetToolId:e,rail:"tempo",reason:"Preserve legacy Tempo _card target while the top-level MCP surface is opt-in."}))];function Zc(e,t=bw){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=Xc(e.intentText);for(let r of t)if(r.match.kind==="intent"&&r.match.metaTool===e.metaTool&&!(r.match.tier&&r.match.tier!==e.tier)&&!(r.match.provider&&!n.includes(Xc(r.match.provider)))&&r.match.keywords.every(s=>n.includes(Xc(s))))return r.targetToolId;return null}function Xc(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}_t();Ht();var no={generate_image:{intro:'Generate an AI image from a text prompt \u2014 useful for hero shots, marketing assets, social posts, blog covers, app mockups, or any time the user asks for art, a logo, an icon, a thumbnail, or "a picture of \u2026". From $0.01 (fast) to $0.06 (pro), returns a hosted PNG/JPG URL. Default tier: balanced ($0.04, 1K, ~10s).',tiers:{balanced:{toolId:"fal-flux-pro",notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",notes:"Recraft V3 \u2014 vector/flat/illustration styles"}},guidance:"If the user didn't specify a tier, pick 'balanced' unless the prompt clearly signals otherwise (text \u2192 text_heavy, logo/icon \u2192 vector, quick test \u2192 fast, hero/print \u2192 pro).",inputProperties:{prompt:{type:"string",description:"Text description of the image to generate."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9", "1:1", "9:16".',default:"16:9"}},required:["prompt"]},generate_video:{intro:'Generate a short AI video from a text prompt \u2014 useful for product demos, social clips, mood reels, ad concepts, or any "make me a video of \u2026" request. $0.10\u2013$0.40 per ~6s clip depending on tier. Async: returns a request_id; use execute_tool with tool_id "check_fal_status" to resolve it (60\u2013180s).',tiers:{balanced:{toolId:"fal-minimax-video",notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",notes:"Kling \u2014 highest quality, cinematic"}},guidance:'Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate and are processed asynchronously. The response includes a request_id and model_path. Poll with execute_tool using tool_id "check_fal_status" and the exact request_id/model_path returned by the async response. Do not substitute the catalog model path manually. Do not poll more than once per 30 seconds.',inputProperties:{prompt:{type:"string",description:"Text description of the video scene."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9" or "9:16".',default:"16:9"}},required:["prompt"]},generate_music:{intro:'Generate an original music track from a prompt via ACE-Step. ~$0.02 for the default 60s track. Use for songs, backing tracks, jingles, vocal music, instrumental music, or any "make a song/music/track" request. Takes ~60-90s and may return a request_id to poll with check_fal_status. For SFX, chimes, ambient beds, or TTS, use generate_audio instead.',tiers:{ace_step:{toolId:"fal-ace-step-music",notes:"ACE-Step \u2014 prompt-to-music with vocals or instrumentals"}},guidance:"Use for songs and music tracks. Takes ~60-90s and may return a request_id to poll with check_fal_status. For sound effects, chimes, ambient beds, or TTS, use generate_audio instead.",inputProperties:{prompt:{type:"string",description:"Musical style, mood, instruments, subject, and lyrics direction."},instrumental:{type:"boolean",description:"True for instrumental music with no vocals; false for vocal tracks.",default:!1},duration:{type:"number",description:"Duration in seconds.",default:60}},required:["prompt"]},generate_audio:{intro:'Generate sound effects from a text prompt (sfx tier \u2014 default), or voice-cloned speech from text + a reference audio URL (tts tier). $0.03\u2013$0.04. Use for SFX, chimes, UI sounds, ambient audio (default sfx), or voice cloning when a reference audio URL is available (pass tier:"tts"). Default tier is sfx; pass tier:"tts" for voice cloning.',tiers:{sfx:{toolId:"fal-stable-audio",notes:"Stable Audio \u2014 sound effects and ambient from a prompt"},tts:{toolId:"fal-metavoice",notes:"MetaVoice \u2014 voice cloning TTS (requires a voice sample URL)"}},guidance:'Default tier is sfx: pass prompt describing the sound. For tts (voice cloning): pass tier:"tts" + text + audio_url.',inputProperties:{prompt:{type:"string",description:"Description of sound to generate (sfx tier, default)."},text:{type:"string",description:"Text to speak aloud (tts tier)."},audio_url:{type:"string",description:"URL of a voice sample to clone (tts tier, required for voice cloning)."}},required:[]},generate_3d:{intro:"Generate a 3D mesh (GLB) from an image URL via Trellis. ~$0.08, ~30\u201360s. Use when the user shares an image and asks for a 3D model, asset, AR-ready mesh, or game-ready GLB.",tiers:{trellis:{toolId:"fal-trellis-3d",notes:"Trellis \u2014 image-to-3D, returns a GLB mesh URL"}},guidance:"Pass an image URL. Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{image_url:{type:"string",description:"URL of the image to convert to a 3D model."}},required:["image_url"]},upscale_image:{intro:'Upscale an image to 4\xD7 resolution via Aura SR (preserves detail without hallucination). ~$0.03. Use whenever the user shares a low-res image and asks to "upscale", "make this higher resolution", "4x this", "enhance", or to print/export at larger size.',tiers:{aura:{toolId:"fal-aura-sr",notes:"Aura SR \u2014 default; preserves detail without hallucination"}},guidance:"Pass the existing image URL. Returns an upscaled version.",inputProperties:{image_url:{type:"string",description:"URL of the image to upscale."}},required:["image_url"]},transcribe_audio:{intro:'Transcribe speech in an audio or video file (URL) to text via OpenAI Whisper. ~$0.02 per file, multilingual, handles long files. Use whenever the user asks to "transcribe this", "what does this audio say", "make subtitles", "convert this to text", or shares an audio/video URL with no other clear intent.',tiers:{whisper:{toolId:"fal-whisper",notes:"OpenAI Whisper \u2014 fast, multilingual"}},guidance:"Pass the URL. Returns the transcript text.",inputProperties:{audio_url:{type:"string",description:"URL of the audio or video file to transcribe."}},required:["audio_url"]},run_llm:{intro:"Run a text prompt through a different LLM (GPT-4o-mini, Claude Sonnet, DeepSeek R1/V3, Perplexity Sonar with web search, or Llama 70B). Token-metered, typically ~$0.01\u2013$0.10 per call. Use for: web-grounded answers (search tier), second-opinion reasoning (reasoning tier), code generation in a different family (coding tier), deep math/logic (deep_reasoning tier), or fast cheap text cleanup (fast tier). Pair with batch for multi-model councils.",tiers:{fast:{toolId:"or-gpt-4o-mini",notes:"GPT-4o Mini. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",notes:"Claude Sonnet. Strong reasoning, long-context. Warn user it is materially pricier than `fast`."},frontier_openai:{toolId:"or-gpt-55",notes:"GPT-5.5. OpenAI frontier model for complex professional reasoning."},frontier_openai_pro:{toolId:"or-gpt-55-pro",notes:"GPT-5.5 Pro. Highest-capability OpenAI frontier tier; materially more expensive."},frontier_anthropic:{toolId:"or-claude-opus",notes:"Claude Opus 4.7. Anthropic frontier model for complex tasks."},frontier_google:{toolId:"or-gemini-35-flash",notes:"Gemini 3.5 Flash. Google frontier Flash model for multimodal reasoning and coding."},deep_reasoning:{toolId:"or-deepseek-r1",notes:"DeepSeek R1. Deep chain-of-thought reasoning, mid-range pricing."},search:{toolId:"or-perplexity-sonar",notes:"Perplexity Sonar. Search-augmented, web-grounded with citations."},open_source:{toolId:"or-llama-70b",notes:"Llama 3.3 70B. Open-source large model."},coding:{toolId:"or-deepseek-chat",notes:"DeepSeek Chat V3. Strong at code generation."}},guidance:"Pick based on the user's need: fast (most questions, cheapest), reasoning (complex analysis; warn user it is materially pricier than fast), frontier_* (top-model council / highest quality; warn user these are materially pricier), search (questions about current events), coding (code generation), deep_reasoning (hard math/logic problems).",inputProperties:{prompt:{type:"string",description:"The user query."},system_prompt:{type:"string",description:"Optional system prompt to set model behavior."},max_tokens:{type:"number",description:"Maximum output tokens.",default:1024,minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature \u2014 0 is deterministic, higher is more creative.",default:.7,minimum:0,maximum:2}},required:["prompt"]}};function kn(e,t,n){if(!Xp(e))return xw(e,n);let r=Jp[e];if(!r)return e;let s=Object.keys(r.tiers),o=t||s[0],i=Tw(e,o,n);return i||Cw(e,r,o,s)}function xw(e,t){return Zc({requestedTool:e,intentText:t})??e}function Tw(e,t,n){return Zc({requestedTool:e,metaTool:e,tier:t,intentText:n})}function Cw(e,t,n,r){let s=t.tiers[n];if(!s)throw new Error(`Unknown tier '${n}' for ${e}. Valid tiers: ${r.join(", ")}`);return s.toolId}var Jp=no;function Xp(e){return e in Jp}var ro=Object.keys(no);function Qc(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function Zp(e=process.env){return Qc(e)!==null}var kw=new Set(["false","0","no","off","disable","disabled"]),Ew=new Set(["true","1","yes","on","enable","enabled"]);function Qp(e){let t=(e??"").trim().toLowerCase();return t?kw.has(t)?!1:!!Ew.has(t):!0}function em(e=process.env){return Qp(e.VISA_CLI_PARENTLESS_SINGLE_CALL)}function tm(e=process.env){return Qp(e.VISA_CLI_PARENTLESS_BATCH)}var Lh=require("child_process"),Se=R(require("crypto")),lt=R(require("fs")),So=R(require("os")),Ta=R(require("path"));function xt(e,t={}){if(!e||typeof e!="object")return e;let n=e,r=t.tag??(typeof n.merchantName=="string"?n.merchantName:"media"),s=n.content?.[0]?.text,o=typeof s=="string"?Ur(s):null,i=Array.isArray(n.urls)?n.urls[0]:void 0,c=typeof i=="string"&&i.startsWith("data:")?Ur(i):null;if(!o&&!c)return e;let l=o??c,u=o?"content":"urls",d;try{d=$s(l,{tag:Aw(r,n)})}catch(f){return{...n,_inline_media_warning:`Failed to persist inline media to disk: ${f instanceof Error?f.message:String(f)}`}}let p={...n,filePath:d.filePath,mime:d.mime,bytes:d.bytes};return u==="urls"?p.urls=void 0:(p.content=Array.isArray(n.content)?[...n.content]:[{}],p.content[0]={...p.content[0]??{},text:`[inline media saved to ${d.filePath}]`}),p}function Aw(e,t){let n=typeof t.transactionId=="string"?t.transactionId:typeof t.transaction_id=="string"?t.transaction_id:null;return n?`${e}-${n}`:e}_t();var nm=!1;async function hr(e,t,n){try{return await t()}catch(r){if(!(r.message==="Invalid signature"||r.code==="ATTESTATION_KEY_DRIFT"||r.error_code==="ATTESTATION_KEY_DRIFT"||r.name==="AttestationDriftError")||!ue())throw r;if(g.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(nm)throw g.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;nm=!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 Ei();return await e.registerAttestationKey(i),await e.setBiometricPreference({required:!0}),g.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),g.info("attestation:key-reregistered-after-recovery"),await t()}catch(o){throw g.error("attestation:recovery-failure",{error:o.message}),r}}throw r}}function Tt(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}async function Ii(e,t){if(!ue())return{ok:!1,code:"TOUCH_ID_UNAVAILABLE",message:"Touch ID is not available in this process. Run `visa-cli setup` from an interactive macOS terminal before enabling Touch ID."};if(!await Ai())return{ok:!1,code:"LOCAL_ATTESTATION_KEY_MISSING",message:"No local attestation key found on this device. Run `visa-cli setup` before enabling Touch ID; otherwise payments and biometric off can require a key this device cannot produce."};let n=await e.getStatus(t);return Tt(n)?{ok:!0,status:n}:{ok:!1,code:"SERVER_ATTESTATION_KEY_MISSING",message:"No server attestation key is registered for this account. Run `visa-cli setup` before enabling Touch ID."}}Ht();var rm="3.3.1-rc.3";function el(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function $i(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=pi(t);return s!==void 0?{value:s,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function qe(e){return e==null?"\u2014":e?"yes":"no"}function Pi(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function Rw(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function Iw(){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=Oc("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:$c,source:{kind:"default"}}}async function so(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(y){n=y?.message||"unknown error"}let r=[],s=process.env.VISA_AUTH_URL,o=Pc("auth.serverUrl"),i=Ue(),a=s!==void 0&&s!==""?{kind:"env",var:"VISA_AUTH_URL"}:o!==void 0?{kind:"settings"}:{kind:"default"};r.push({key:"auth.serverUrl",value:i,formatted:i,source:a,hint:a.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),r.push({key:"account.enrolled",value:t?.enrolled??null,formatted:qe(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),t?.githubUser&&r.push({key:"account.githubUser",value:t.githubUser,formatted:t.githubUser,source:{kind:"server"}}),t?.userId&&r.push({key:"account.userId",value:t.userId,formatted:t.userId,source:{kind:"server"},hint:"Opaque stable account id used for account-scoped local credentials."});let c=t?t.attestationRequired!==!1:void 0;r.push({key:"biometric.required",value:c,formatted:qe(c),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"},hint:c===!1?"Touch ID prompts are suppressed. Re-enable with `visa-cli config biometric on`.":void 0}),r.push({key:"biometric.keyRegistered",value:t?.hasAttestationKey??null,formatted:qe(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:ue(),formatted:qe(ue()),source:{kind:"device"}});let l=t?.spendingControls,u=l?l.max_transaction_amount??l.maxTransactionAmount??null:null,d=l?l.daily_limit??l.dailyLimit??null:null;r.push({key:"spending.maxPerTxn",value:u,formatted:Pi(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:Pi(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:Pi(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:Pi(t?.dailyRemaining),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"cards.count",value:t?.cardCount??null,formatted:t?.cardCount!=null?String(t.cardCount):"\u2014",source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}});let p=t?.cards?.find(y=>y.isDefault)??t?.cards?.[0];p&&r.push({key:"cards.default",value:{brand:p.brand??null,last4:p.last4},formatted:`${p.brand||"card"} \u2022\u2022\u2022\u2022 ${p.last4}`,source:{kind:"server"}});let f=Iw();r.push({key:"credit.sessionCapCents",value:f.value,formatted:Rw(f.value),source:f.source});let m=Hf();m.length>0&&r.push({key:"settings.retired",value:m.map(y=>y.key),formatted:m.map(y=>y.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${m.map(y=>`visa-cli config unset ${y.key}`).join(" && ")}`});let h=$i("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:h.value,formatted:qe(h.value),source:h.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let w=$i("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:w.value,formatted:qe(w.value),source:w.source});let C=bt(),b;process.env.VISA_CLI_NO_UPDATE_CHECK?b={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?b={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?b={kind:"env",var:"NODE_ENV"}:b={kind:"default"},r.push({key:"ui.updateCheck",value:!C,formatted:qe(!C),source:b});let v=$i("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:v.value,formatted:qe(v.value),source:v.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let S=$i("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:S.value,formatted:qe(S.value),source:S.source});let A=process.env.VISA_DRY_RUN,I=Zp();if(r.push({key:"tools.dryRun",value:I,formatted:qe(I),source:A===void 0?{kind:"default"}:{kind:"env",var:"VISA_DRY_RUN"},hint:"VISA_DRY_RUN=true|1|mock returns deterministic paid-tool fixtures (no card, no upstream). VISA_DRY_RUN=preflight makes a real zero-cost OpenRouter call for LLM tools (image/video still mocked)."}),r.push({key:"client.version",value:rm,formatted:rm,source:{kind:"default"}}),e.includeDev){let y=process.env.VISA_MOCK_KEYCHAIN,T=an();r.push({key:"dev.mockKeychain",value:T,formatted:qe(T),source:el("VISA_MOCK_KEYCHAIN",!!y),hint:Ka()});let Y=process.env.VISA_MOCK_TOUCHID,X=Lr();r.push({key:"dev.mockTouchid",value:X,formatted:qe(X),source:el("VISA_MOCK_TOUCHID",!!Y),hint:Ka()});let H=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!H,formatted:qe(!!H),source:el("VISA_CLI_DEBUG",!!H)})}return{entries:r,statusError:n}}function $w(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 sm(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}(${$w(o.source)})`),t.verbose&&o.hint&&s.push(` ${"\u21B3".padStart(n)} ${o.hint}`)}return s.join(`
143
- `)}function om(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 im(e){if(e<=0)return null;let t=(e/100).toFixed(2);return{_credits_prompt:{message:`You've got $${t} in free credits \u2014 enough for about ${Math.floor(e/6)} images. Try something now, or save them for later.`,balanceUsd:t,examples:[{tool:"generate_image",cost:"$0.06",what:"an AI image"},{tool:"run_llm",cost:"token-priced",what:"a quick model call"},{tool:"generate_music",cost:"$0.02",what:"a music track"}]}}}Ht();_t();var En=require("fs"),cm=require("os"),tl=require("path"),Pw=(0,tl.join)((0,cm.homedir)(),".visa-mcp"),am=(0,tl.join)(Pw,"mcp-session-budget.json");function Oi(){try{(0,En.existsSync)(am)&&(0,En.unlinkSync)(am)}catch{}}var rl=require("crypto"),at=R(ts()),_r=null,Ke=0,Rn=0,He=0,An=null,sl=null,ol=null,yr=Promise.resolve();function Ow(e){return Number((0,at.fromCents)(e))}function um(e){return(0,at.toCents)((0,at.micros)(BigInt(e)))}function lm(e){return(0,at.toWire)((0,at.fromCents)(e))}function nl(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Mi(e){return typeof e=="string"&&/^\d+$/.test(e)}var Mw=43,Nw=new RegExp(`^[A-Za-z0-9_-]{${Mw}}$`);function Lw(e){return typeof e=="string"&&Nw.test(e)}function Uw(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||_r&&e.session_id!==_r||typeof e.nonce!="string"||e.nonce.length===0||!Lw(e.server_signature)||!nl(e.cumulative)||!nl(e.remaining)||!nl(e.delta)||e.cumulative<Ke||He>0&&e.cumulative>He||He>0&&e.remaining>He||e.cumulative_micros!==void 0&&!Mi(e.cumulative_micros)||e.remaining_micros!==void 0&&!Mi(e.remaining_micros)||e.delta_micros!==void 0&&!Mi(e.delta_micros)||e.reserved_micros!==void 0&&!Mi(e.reserved_micros))}function zt(e){_r=e,Ke=0,Rn=0,He=0,An=null,sl=null,ol=null,yr=Promise.resolve()}function oo(e){He=Math.max(0,Math.floor(e))}function il(){return _r}function al(e){if(!_r)return null;let t=Ke+Rn;return He>0&&t>He&&(t=He),{session_budget_id:_r,cumulative_micros:Ow(t),nonce:(0,rl.randomUUID)(),idempotency_key:e||(0,rl.randomUUID)()}}function io(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 Uw(r)?(Ke=Math.max(Ke,r.cumulative),Rn=0,An=r,r):null}function dm(){return An}function cl(e){let t=um(e.cumulative_micros);Ke=Math.max(Ke,t),Rn=0;let n={status:"accepted",session_id:e.session_budget_id,cumulative:Ke,remaining:Math.max(0,He-Ke),delta:0,cumulative_micros:lm(Ke),remaining_micros:lm(Math.max(0,He-Ke)),delta_micros:"0",nonce:e.nonce};return An=n,n}function ao(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,at.toCents)((0,at.micros)(n));if(!Number.isFinite(r)||r<0)return;sl=t;let s=e,o=typeof s.session_id=="string"?s.session_id:_r??"";An?(typeof s.remaining_micros=="string"&&/^\d+$/.test(s.remaining_micros)&&(An.remaining_micros=s.remaining_micros),typeof s.charged_micros=="string"&&/^\d+$/.test(s.charged_micros)&&(An.delta_micros=s.charged_micros)):An={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 fm(e){let t=e.receipt??null;ol={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:um(e.voucher.cumulative_micros),estimatedCumulativeCents:Ni(),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 pm(){return ol}function mm(){return Ke}function gm(){return sl}function Ni(){let e=Ke+Rn;return He>0&&e>He&&(e=He),e}function ll(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return yr=yr.then(()=>{Rn+=t}),yr}function co(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return yr=yr.then(()=>{Rn=Math.max(0,Rn-t)}),yr}var Dw=10,jw=1,de=null,hm=Promise.resolve();function ul(e){let t=hm.catch(()=>{}).then(e);return hm=t.then(()=>{},()=>{}),t}var we=class extends Error{balanceCents;minRequiredCents;constructor(t,n){super(`Prepaid balance is $${(t/100).toFixed(2)}; at least $${(n/100).toFixed(2)} required to open a credit session. Top up via the buy_credits tool first.`),this.name="InsufficientBalanceError"}};async function dl(e,t,n){return ul(()=>ym(e,t,n))}async function ym(e,t,n){if(Oi(),de&&new Date(de.expiresAt).getTime()>Date.now())return il()!==de.budgetId&&(zt(de.budgetId),oo(de.totalCents)),g.info("mcp-session:active-hit",{budgetId:de.budgetId,tool:n.toolName,remainingEstimatedCents:de.totalCents-Ni()}),{budgetId:de.budgetId,isFresh:!1,totalCents:de.totalCents,requestedCapCents:de.totalCents,appliedCapCents:de.totalCents,clampedReason:null};de&&(de=null,zt(null));let r=await e.getBalance();if(!r.success)throw new Error(`Could not read balance: ${r.error||"unknown error"}`);let s=n.sessionKind??"explicit",o=s==="one_shot"?jw:Dw,i=Math.max(o,Math.ceil(n.minRequiredCents??o));if(r.balanceCents<i)throw new we(r.balanceCents,i);let a=n.capCentsOverride??Kf(),c=Math.min(a,r.balanceCents),l=c<a?"balance":null,u=await t("session_create",c,"Visa CLI Session",`open credit-model session with $${(c/100).toFixed(2)} cap`,n.userContext),d=await e.createSessionBudget({total_cents:c,session_kind:s,...u?{attestation:u}:{}});if(!d.success||!d.budget){let f=d.error||"unknown error";throw new Error(`Failed to open credit session: ${f}`)}let p={budgetId:d.budget.id,expiresAt:d.budget.expiresAt,totalCents:d.budget.totalCents,createdAt:d.budget.createdAt};return de=p,zt(p.budgetId),oo(p.totalCents),g.info("mcp-session:opened",{budgetId:p.budgetId,capCents:p.totalCents,requestedCapCents:a,clampedReason:l,sessionKind:s,expiresAt:p.expiresAt,tool:n.toolName}),{budgetId:p.budgetId,isFresh:!0,totalCents:p.totalCents,requestedCapCents:a,appliedCapCents:p.totalCents,clampedReason:l}}async function _m(e,t,n){return ul(async()=>{let s=In()?await bm(e):null,o=await ym(e,t,n);return{budgetId:o.budgetId,totalCents:o.totalCents,closedPrevious:s,requestedCapCents:o.requestedCapCents,appliedCapCents:o.appliedCapCents,clampedReason:o.clampedReason}})}async function bm(e){let n=In()?.budgetId??il(),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 Oi(),de=null,zt(null),{closedServerSide:r,budgetId:n,finalCumulativeCents:s,finalCumulativeMicros:o}}async function Li(e){return ul(()=>bm(e))}function In(){return Oi(),de?new Date(de.expiresAt).getTime()<=Date.now()?(de=null,zt(null),null):{budgetId:de.budgetId,totalCents:de.totalCents,lastReceiptCumulative:mm(),lastReceiptCumulativeMicros:dm()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:gm(),estimatedCumulative:Ni(),lastToolSpend:pm(),expiresAt:de.expiresAt}:null}var wm=R(ts()),vm=10000n;function Bw(e){return e<=0n?0:Number((e+vm-1n)/vm)}function Sm(e){return Bw((0,wm.fromUsd)(e))}var Ui=R(ts()),Fw=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;function Di(e){if(typeof e!="string"||!Fw.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,Ui.toDisplay)((0,Ui.fromCents)(s),{symbol:""})}}var ji="Buying credits requires local biometric attestation from a Touch ID-capable Mac or a Windows Hello-capable PC running the Visa CLI. This device cannot create the required attestation, so no card charge was attempted. Credits are account-level, so you can top up this account from any interactive biometric-capable CLI, then use the balance from this remote server.",xm="Tell the user that buying credits requires a local CLI/MCP process with Touch ID (Mac) or Windows Hello (PC) today. Credits are account-level: suggest topping up the same account from any interactive biometric-capable CLI, then continuing on this remote server. Do not retry buy_credits from this process; it cannot produce the required card-charge attestation.";Ht();var xh=Promise.resolve();function PT(e,t){if(e)try{let n=(0,xa.fromWire)(e),r=n%10000n===0n?2:6;return(0,xa.toDisplay)(n,{decimals:r})}catch{}return`$${(t/100).toFixed(2)}`}var Th=!1,Ch=!1,kh=!1;function Ca(e){let t=xh.catch(()=>{}).then(e);return xh=t.then(()=>{},()=>{}),t}async function Uh(e){let t=await xe(()=>dl(U,Qe,{toolName:e.toolId,userContext:e.userContext}));await ll(e.estimatedAmountCents);let n=al(e.idempotencyKey);if(!n)throw await co(e.estimatedAmountCents),new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await BT(),s,o,i=async()=>U.shortcutWithSession(e.toolId,n,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);try{try{({data:s,voucherReceiptHeader:o}=await i())}catch(u){if(u instanceof Bt){let d=Math.min(Math.max(u.retryAfterSecs,0),5)*1e3;g.warn("mcp-session:lock-contended-retrying",{tool:e.toolId,retryAfterSecs:u.retryAfterSecs}),await new Promise(p=>setTimeout(p,d)),{data:s,voucherReceiptHeader:o}=await i()}else throw u}}catch(u){if(await co(e.estimatedAmountCents),u instanceof Vr){if(g.warn("mcp-session:server-invalidated-budget",{code:u.code,budgetId:u.budgetId??t.budgetId,tool:e.toolId}),await Li(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 kh||(kh=!0,console.error(`[visa-cli] Your session was closed by another process; reopened automatically as pay-as-you-go.
144
- To require an explicit session approval instead, set VISA_REQUIRE_EXPLICIT_SESSION=true.`)),g.info("mcp-session:falling-back-to-payg",{code:u.code,tool:e.toolId}),Dh(e)}throw u instanceof Bt?(g.warn("mcp-session:lock-contended-give-up",{tool:e.toolId}),new Error("Another paid call is currently in progress on this session. Wait a moment and try again.")):u}let a=io(o)??(n?cl(n):null);if(ao(s?.receipt_v2),fm({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),du(s))return xt(s);let c=await uu();if(e.idempotencyKey&&fu(s,c,e.idempotencyKey))return xt(s);let l=c?vo(c):null;return xt(pu(s,r,l))}function Ze(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function va(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(va).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${va(r)}`).join(",")}}`}function lu(e,t,n,r){let s=Se.createHash("sha256").update(`${n}:${va(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${s}`}function OT(e,t){return`${e}:${t}`}function MT(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 wa(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,s=ct(r),o=s!==null?s.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=MT(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),c=i!=null?String(i):a;return{batch_id:e,item_id:OT(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 Dh(e){return xe(()=>LT(e))}async function jh(e,t,n){if(du(e))return xt(e);let r=await uu();if(n&&fu(e,r,n))return xt(e);let s=r?vo(r):null;return xt(pu(e,t,s))}async function NT(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 Qe("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 io(i),ao(o?.receipt_v2),g.info("parentless-single-call:completed",{tool:e.toolId}),jh(o,e.beforeBalanceMicros,e.idempotencyKey)}async function LT(e){let t=Math.max(1,Math.ceil(e.estimatedAmountCents)),n=await U.getBalance();if(!n.success)throw new Error(`Could not read balance: ${n.error||"unknown error"}`);if(n.balanceCents<t)throw new we(n.balanceCents,t);let r=t,s=vo(n);if(em()&&!Th){let u=e.idempotencyKey??Se.randomUUID();try{return await NT({toolId:e.toolId,toolParams:e.toolParams,estimatedAmountCents:e.estimatedAmountCents,cap:r,beforeBalanceMicros:s,userContext:e.userContext,metaTool:e.metaTool,timeoutMs:e.timeoutMs,idempotencyKey:u})}catch(d){if(d instanceof yt)Th=!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 Qe("session_create",r,"Visa CLI Session",o,e.userContext),a=await U.createSessionBudget({total_cents:r,session_kind:"one_shot",...i?{attestation:i}:{}});if(!a.success||!a.budget)throw new Error(`Failed to open on-demand session: ${a.error||"unknown error"}`);let c=a.budget.id;zt(c),oo(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=al(e.idempotencyKey);if(!u)throw await co(e.estimatedAmountCents),new Error(`Internal: mintVoucher returned null after on-demand session-open ${c}`);let{data:d,voucherReceiptHeader:p}=await U.shortcutWithSession(e.toolId,u,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(io(p)||cl(u),l=!0,ao(d?.receipt_v2),du(d))return xt(d);let f=await uu();if(e.idempotencyKey&&fu(d,f,e.idempotencyKey))return xt(d);let m=f?vo(f):null;return xt(pu(d,s,m))}catch(u){throw l||await co(e.estimatedAmountCents),u}finally{try{await U.closeSession(c)}catch(u){g.warn("on-demand-session:close-failed",{budgetId:c,error:u?.message||String(u)})}zt(null),g.info("on-demand-session:closed",{budgetId:c,tool:e.toolId})}}async function Hn(e){return Ca(async()=>In()?Uh(e):Dh(e))}function ka(){return Ue()}var U=new Ve(()=>K.getSessionToken());function ct(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function vo(e){return ct(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function UT(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 DT(e){let t=ct(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=ct(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=ct(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function _a(e,t="INVALID_TOOL_PARAMS",n){return{success:!1,error_code:t,code:t,error:e,message:e,...n??{}}}function jT(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 BT(){try{let e=await U.getBalance();return e.success?vo(e):null}catch{return null}}async function uu(){try{let e=await U.getBalance();return e.success?e:null}catch{return null}}function du(e){if(!e||e.success===!1)return!1;let t=ct(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=ct(e.amountMicros??e.amount_micros??e.charged_micros),r=t??n;if(r===null||r<=0n)return!1;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,e.charged_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),!0}function fu(e,t,n){if(!e||e.success===!1||!t||!Array.isArray(t.ledger))return!1;let r=t.ledger.find(a=>a.idempotencyKey===n);if(!r)return!1;let s=ct(r.deltaMicros)??BigInt(r.deltaCents)*10000n,o=s<0n?-s:s;if(o<=0n)return!1;let i=o.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(o)/1e6),!0}function pu(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 FT="3.3.1-rc.3",S2=["","","You're ready to go! Try:","","Core:",'\u2022 "Show my account status" \u2192 get_status','\u2022 "List my enrolled cards" \u2192 get_cards','\u2022 "Show my paid tool use history" \u2192 transaction_history','\u2022 "Set my daily top-up limit to $50" \u2192 update_spending_controls','\u2022 "Generate 3 variations in parallel" \u2192 batch',"","Category tools:",'\u2022 "Generate an image of a sunset over Tokyo" \u2192 generate_image','\u2022 "Make a 4-second video of a penguin juggling" \u2192 generate_video','\u2022 "Make a song about coding late at night" \u2192 generate_music','\u2022 "Create a sound effect for a checkout chime" \u2192 generate_audio','\u2022 "Create a 3D asset from this product sketch" \u2192 generate_3d','\u2022 "Upscale this product image" \u2192 upscale_image','\u2022 "Transcribe this meeting recording" \u2192 transcribe_audio','\u2022 "Run a reasoning model on this prompt" \u2192 run_llm',"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
145
- `);function ut(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=Ls(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(Vf())return{opened:!1,url:t,blockedReason:"suppressed"};let n=sc();if(n.headless)return g.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let r=xd(t,ka());if(!r)return g.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let s=Cd(r);return s?((0,Lh.execFile)(s.cmd,s.args,o=>{o&&g.warn(`Browser open failed: ${o.message}. URL: ${r}`)}),{opened:!0,url:r}):(g.info(`No browser command for platform "${So.platform()}". URL: ${r}`),{opened:!1,url:r,blockedReason:"unsupported_platform"})}async function xe(e){return hr(U,e,Yh)}var Bh="get_cards",Fh="set_default_card";function HT(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 '${Bh}' to see enrolled cards and '${Fh}' to switch, then retry the original request.`}function VT(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 '${Bh}' to see enrolled cards and '${Fh}' to switch. Do not retry automatically.`}function dt(e,t){let n=e.retryable?HT(e.code,e.retryAfter):VT(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 qT(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 vs=null,KT=3e4;function Hh(){vs=null}var Fn=class extends Error{constructor(n){super(`${Sa()} attestation is required for this action, but it is not available in this MCP process. `+mu());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function Ea(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. `+mu()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function GT(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:ji,agent_guidance:xm}}function Sa(){return process.platform==="darwin"?"Touch ID":"local biometric"}function mu(){return process.platform==="darwin"?"Run the action from an interactive terminal with Touch ID access, or use reset with confirm:true to clear stale server biometric state through GitHub re-authentication.":"This platform cannot create Visa CLI Touch ID attestations. Use reset with confirm:true to clear stale server biometric state through GitHub re-authentication."}async function WT(e){let t=Date.now();if(vs&&vs.expiresAt>t)return{required:vs.required,hasRegisteredKey:vs.hasRegisteredKey};try{let n=await U.getStatus(e),r=n.attestationRequired!==!1,s=Tt(n);return vs={required:r,hasRegisteredKey:s,expiresAt:t+KT},{required:r,hasRegisteredKey:s}}catch{return{required:!0,hasRegisteredKey:!0}}}async function Qe(e,t,n,r,s,o){if(!o?.forceRequired){let i=await WT(s);if(!i.required){g.info("attestation:skipped-by-server-policy",{context:e});return}if(!i.hasRegisteredKey){g.info("attestation:skipped-no-registered-key",{context:e});return}}if(!ue())throw g.warn("attestation:unavailable",{context:e}),new Fn(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 Cn(a,r);return g.info("attestation:success",{context:e,amount:t,merchant:n}),{signature:c,nonce:i,amount:t,merchant:n}}catch(i){throw g.error("attestation:failure",{context:e,amount:t,merchant:n,error:i.message}),i}}var Eh="[dry-run] https://placeholder.visa-cli.dev/image.png",YT=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"]),zT=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 JT(e,t){return t==="run_llm"||e.startsWith("or-")?"llm":t==="generate_image"||YT.has(e)?"image":t==="generate_video"||zT.has(e)?"video":XT(e)?"media":null}function XT(e){let t=es(e);return t?!yu(t):!1}function ZT(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function QT(e){return e==="llm"?"OpenRouter":"fal.ai"}function ws(e,t,n,r){let s={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:QT(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${ZT(n)}`;return{...s,content:i,data:{content:i,model:t,dry_run:!0}}}return{...s,urls:[Eh],data:{[e==="video"?"videoUrl":e==="image"?"imageUrl":"url"]:Eh,metadata:{dry_run:!0}}}}async function iu(e){let t=e.mode??"mock",n=t==="preflight"?"/v1/telemetry/preflight":"/v1/telemetry/dry-run",r=t==="preflight"?"preflight":null;try{await U.emitTelemetry([{id:Se.randomUUID(),timestamp:new Date().toISOString(),tool_name:e.toolName,user_prompt:e.userContext??"",tool_params:JSON.stringify(e.toolParams),result_success:!0,result_error:null,result_json:JSON.stringify(e.result),payment_rail:r,payment_amount:0,payment_currency:"USD",merchant_name:e.result.merchantName,transaction_id:e.result.transactionId,tx_hash:null,protocol:null,http_status:200,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",event_kind:"mcp_tool",endpoint:n,resolved_model:e.resolvedModel,session_budget_id:null}])}catch(s){g.warn("dry_run:telemetry_failed",{tool:e.toolName,error:s?.message||String(s),mode:t})}}var eC="https://openrouter.ai/api/v1/chat/completions",tC="openrouter/free",nC=50,rC=15e3;function sC(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 oC(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:ws("llm",e,t,n),degraded:!0,resolvedModel:null};let s=sC(t),o;try{o=await ht(eC,{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:tC,messages:[{role:"user",content:s}],max_tokens:nC}),timeoutMs:rC})}catch(u){return g.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:ws("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:ws("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:ws("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 xo(e,t,n,r){let s=Qc();if(!s)return null;let o=JT(e,r);if(!o)return null;let i=Date.now();if(s==="mock"){let l=ws(o,e,t,r);return await iu({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=ws(o,e,t,r);return await iu({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 oC(e,t,r);return await iu({toolName:r??e,resolvedModel:c??(r&&r!==e?e:null),toolParams:t,result:a,userContext:n,startedAt:i,mode:"preflight"}),g.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:o,mode:s}),a}async function rn(e,t,n){let r=await U.paymentPreview({tool:e,url:t},n);if(!r||!r.merchantName||r.amount===void 0||r.amount===null||r.amount<0)throw new Error("Could not determine payment amount and merchant. Try again.");if(!Number.isFinite(r.amount)||r.amount<0||r.amount>999999)throw new Error(`Invalid payment amount: ${r.amount}. Payment rejected for safety.`);return r}function sn(e){return Sm(e.amount)}function iC(e,t,n){return n.has(e.resolvedTool)?0:Math.max(1,sn(t[e.resolvedTool]))}function aC(){return Ta.join(So.homedir(),".visa-mcp","allium-results")}var x2=16*1024,T2=50*1024*1024;function cC(){let e=aC();try{if(!lt.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=lt.readdirSync(e),n=0,r=0;for(let s of t)try{let o=lt.statSync(Ta.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 Ah=3600*1e3,au=0;function lC(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function To(e){if(!qf()&&!(Date.now()<au))try{if(!await K.getSessionToken())return;await U.feedSubmit({prompt:e.prompt,tool:e.tool,media_url:e.mediaUrl,media_type:e.mediaType,cost:e.cost,transaction_id:e.transactionId,auto:!0,...e.userContext&&{user_context:e.userContext}}),g.info("feed:submitted",{tool:e.tool,mediaType:e.mediaType,transactionId:e.transactionId})}catch(t){if(lC(t)){let n=au===0;au=Date.now()+Ah,n&&g.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:Ah});return}g.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function uC(e,t){let n=(e.state||"").trim().toUpperCase(),r=(e.county||"").trim(),s=(e.start_date||"").trim(),o=(e.end_date||s).trim();if(!/^[A-Z]{2}$/.test(n))throw new Error('state must be a 2-letter US state code (e.g. "VA").');if(!r)throw new Error("county is required.");if(!/^\d{4}-\d{2}$/.test(s))throw new Error('start_date must be YYYY-MM (e.g. "2025-08").');if(o&&!/^\d{4}-\d{2}$/.test(o))throw new Error("end_date must be YYYY-MM.");let i="Visa SMI",a=.1,c=`Pay $0.10 to ${i} for SMI data (${n} / ${r})`;g.info("payment:attempt",{tool:"get_visa_smi",amount:a,merchant:i});try{return await xe(async()=>{let l=await Qe("get_visa_smi",a,i,c),u=await U.getVisaSmi({state:n,county:r,start_date:s,end_date:o,attestation:l,idempotencyKey:Se.randomUUID()},t);return u.success?g.info("payment:success",{tool:"get_visa_smi",merchant:i,charged_cents:u.charged_cents}):g.warn("payment:declined",{tool:"get_visa_smi",merchant:i,message:u.error}),u})}catch(l){if(l instanceof ge)return g.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:l.code,retryable:l.retryable}),dt(l,{amount:a,merchantName:i,description:"Visa SMI data"});throw g.error("payment:failure",{tool:"get_visa_smi",merchant:i,error:l.message}),l}}async function dC(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await xo("generate_image_card",e,t);if(n)return n;let r=await rn("generate_image_card",void 0,t),s=Se.randomUUID();g.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await xe(async()=>{let o;try{o=await Hn({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:sn(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof we)return Ze(i);throw i}return g.info("payment:success",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>ut(i)),To({prompt:e.prompt,tool:"generate_image_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):g.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof ge)return g.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),dt(o,r);throw on(o,{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName}),o}}async function fC(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 xo("generate_image_fast_card",e,t);if(n)return n;let r=await rn("generate_image_fast_card",void 0,t),s=Se.randomUUID();g.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await xe(async()=>{let o;try{o=await Hn({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:sn(r),userContext:t,timeoutMs:6e4,idempotencyKey:s})}catch(i){if(i instanceof we)return Ze(i);throw i}return g.info("payment:success",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>ut(i)),To({prompt:e.prompt,tool:"generate_image_fast_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):g.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof ge)return g.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),dt(o,r);throw on(o,{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName}),o}}async function pC(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 xo("generate_video_tempo_card",e,t);if(n)return n;let r=await rn("generate_video_tempo_card",void 0,t),s=Se.randomUUID();g.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await xe(async()=>{let o;try{o=await Hn({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:sn(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof we)return Ze(i);throw i}return g.info("payment:success",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>ut(i)),To({prompt:e.prompt,tool:"generate_video_tempo_card",mediaUrl:o.urls[0],mediaType:"video",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):g.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof ge)return g.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),dt(o,r);throw on(o,{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName}),o}}async function mC(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await rn("generate_music_tempo_card",void 0,t),r=Se.randomUUID();g.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await xe(async()=>{let s;try{s=await Hn({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:sn(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(o){if(o instanceof we)return Ze(o);throw o}return g.info("payment:success",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),s.urls?.length&&s.status!=="processing"?(s.urls.forEach(o=>ut(o)),To({prompt:e.prompt,tool:"generate_music_tempo_card",mediaUrl:s.urls[0],mediaType:"audio",cost:s.amount??n.amount,transactionId:s.transactionId,userContext:t})):s.urls?.length&&s.status==="processing"?(s._preliminary_urls=s.urls,delete s.urls,g.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):g.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof ge)return g.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),dt(s,n);throw on(s,{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName}),s}}async function gC(e,t){let n=await rn("check_music_status_tempo_card",void 0,t),r=Se.randomUUID();g.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await xe(async()=>{let s;try{s=await Hn({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:sn(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof we)return Ze(o);throw o}return g.info("payment:success",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),s.urls?.length&&s.urls.forEach(o=>ut(o)),s})}catch(s){if(s instanceof ge)return g.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),dt(s,n);throw on(s,{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName}),s}}async function hC(e,t){if(!e.chain||!e.chain.trim())throw new Error('A chain is required (e.g., "ethereum", "solana").');if(!e.token_address||!e.token_address.trim())throw new Error("A token address is required. Provide the contract address for the token.");let n=await rn("query_onchain_prices",void 0,t),r=Se.randomUUID();g.info("payment:attempt",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName});try{return await xe(async()=>{let s;try{s=await Hn({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:sn(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof we)return Ze(o);throw o}if(g.info("payment:success",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,mode:"session"}),Array.isArray(s?.data))s.data=s.data.map(o=>{if("mint"in o&&!("address"in o)){let{mint:i,...a}=o;return{address:i,...a}}return o});else if(s&&"mint"in s&&!("address"in s)){let{mint:o,...i}=s;return{address:o,...i}}return s})}catch(s){if(s instanceof ge)return g.warn("payment:declined",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),dt(s,n);throw on(s,{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName}),s}}var yC=["generate_music_tempo_card"],bs=10,Rh=5,Ih=new Map;function $h(e){let t=Ih.get(e);if(t!==void 0)return t;let r=es(e)?.isAsync===!0||yC.includes(e);return Ih.set(e,r),r}var _C=36e4,bC=18e4,vC=15e3,wC=12e4,SC=2e3;function cu(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}function xC(e,t){return Se.createHash("sha256").update(`${e}:${va(t)}`).digest("hex")}function TC(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,...wa(n,r,o)});let l=0,u=0n;if(o?.success!==!1){let d=ct(o?.amountMicros??o?.amount_micros),p=typeof o?.amount=="number"?o.amount:i?.amount??0;d!==null&&d>0n?u+=d:u+=BigInt(Math.round(p*1e6)),l+=p}return o?.urls&&o.urls.forEach(d=>ut(d)),{deltaCharged:l,deltaMicros:u}}function CC(e){let{results:t,resolvedItems:n,uniqueTools:r,isHomogeneous:s,primaryTool:o,merchantNames:i,totalAmount:a,totalCharged:c,totalChargedMicros:l,batchId:u,mode:d}=e,p=t.filter(C=>C?.success===!1).length,f=t.length-p,m=t.flatMap(C=>Array.isArray(C?.urls)?C.urls:[]),h=l>0n?Number(l)/1e6:Math.round((c+Number.EPSILON)*100)/100,w=f===0?"failure":p===0?"success":"partial";return g.info("payment:success",{tool:"batch",batchTool:o,count:n.length,totalAmount:a,totalCharged:h,merchant:i,successCount:f,failedCount:p,outcome:w,mode:d,batchId:u}),{success:f>0,outcome:w,batch_id:u,tool:s?r[0]:o,count:n.length,successCount:f,failedCount:p,totalCharged:h,...l>0n?{totalChargedMicros:l.toString(),amountMicros:l.toString(),amount_micros:l.toString()}:{},merchantName:i,results:t,...m.length?{urls:m}:{}}}async function kC(e){let{resolvedItems:t,previews:n,freeTools:r,catalogEntries:s,itemCeilingCents:o,batchCeilingCents:i,uniqueTools:a,isHomogeneous:c,primaryTool:l,merchantNames:u,totalAmount:d,timeoutMs:p,batchId:f,userContext:m}=e,h=i,w=await U.getBalance();if(!w.success)throw new Error(`Could not read balance: ${w.error||"unknown error"}`);if(w.balanceCents<h)throw new we(w.balanceCents,h);let C=`batch-${f}`,b=`spend up to $${(h/100).toFixed(2)} across a batch of ${t.length}`,{batchParentId:v}=await xe(async()=>{let y=await Qe("batch_open",h,C,b,m,{forceRequired:!0}),T=y?.nonce??(await U.getAttestationChallenge()).nonce;g.info("parentless-batch:open-attempt",{batchTool:l,count:t.length,approvedTotalCents:h,attested:!!y});let{batch_parent_id:Y}=await U.batchOpen({...y?{attestation:y}:{},nonce:T,approved_total_cents:h,batch_id:f});return{batchParentId:Y}});g.info("parentless-batch:opened",{batchTool:l,count:t.length,batchParentId:v});let S=[],A=0,I=0n;try{for(let y=0;y<t.length;y+=1){let T=t[y],Y=n[T.resolvedTool],X=r.has(T.resolvedTool);try{let H;if(X)H=await U.shortcut(T.resolvedTool,T.params,p,m,"batch");else{let{data:J,voucherReceiptHeader:Es}=await U.shortcutParentlessBatchItem(T.resolvedTool,{batch_parent_id:v,batch_id:f,batch_index:y,batch_request_hash:xC(T.resolvedTool,T.params),item_ceiling_cents:o[y],idempotency_key:lu(f,y,T.resolvedTool,T.params)},T.params,p,m,"batch");io(Es),ao(J?.receipt_v2),H=await jh(J,null,lu(f,y,T.resolvedTool,T.params))}let{deltaCharged:_e,deltaMicros:re}=TC({results:S,batchId:f,index:y,item:T,itemResult:H,preview:Y,isFree:X,catalogName:s[T.resolvedTool]?.name});A+=_e,I+=re}catch(H){if(H instanceof we&&S.length===0)return Ze(H);g.warn("payment:batch-item-failed",{tool:T.resolvedTool,index:y,error:H?.message||String(H)}),S.push({success:!1,tool:T.resolvedTool,...wa(f,y),error:H?.message||String(H)})}}return CC({results:S,resolvedItems:t,uniqueTools:a,isHomogeneous:c,primaryTool:l,merchantNames:u,totalAmount:d,totalCharged:A,totalChargedMicros:I,batchId:f,mode:"parentless"})}catch(y){if(y instanceof ge)return g.warn("payment:declined",{tool:"batch",batchTool:l,count:t.length,totalAmount:d,merchant:u,code:y.code,retryable:y.retryable}),dt(y,{amount:d,merchantName:u});throw on(y,{tool:"batch",batchTool:l,count:t.length,totalAmount:d,merchant:u}),y}}async function EC(e,t){let n;if(Array.isArray(e.requests)&&e.requests.length>bs)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${bs} items. Please split into smaller batches.`};if(e.requests?.some(y=>y.tool||y.tool_id)&&e.requests)n=e.requests.map(y=>{let T=y.tool||y.tool_id||e.tool;if(!T)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let Y=kn(T,y.tier||e.tier,y.prompt??t),{tool:X,tool_id:H,tier:_e,params:re,...J}=y,Es=re&&typeof re=="object"?{...re,...J}:J;return{resolvedTool:Y,params:Es}});else if(e.tool){let y=kn(e.tool,e.tier,e.params?.prompt??t);if(e.count!==void 0){if(!Number.isSafeInteger(e.count)||e.count<1)return cu("BATCH_INVALID_COUNT","Batch count must be a positive integer.");if(e.count>bs)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${bs} 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 cu("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return cu("BATCH_EMPTY","Batch requires at least one item.");if(n.length>bs)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${bs} items. Please split into smaller batches.`};if([...new Set(n.map(y=>y.resolvedTool))].some($h)&&n.length>Rh)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${Rh} 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 zh(y);let l=new Set(i.filter(y=>c[y]&&yu(c[y]))),u={};for(let y of i)l.has(y)||(u[y]=await rn(y,void 0,t));let d=0;for(let y of n)d+=u[y.resolvedTool]?.amount??0;let p=n.map(y=>iC(y,u,l)),f=p.reduce((y,T)=>y+T,0),m=[...new Set([...Object.values(u).map(y=>y.merchantName),...i.filter(y=>l.has(y)).map(y=>c[y]?.name??y)])].join(", "),h=a?i[0]:"mixed";g.info("payment:attempt",{tool:"batch",batchTool:h,count:n.length,totalAmount:d,merchant:m,heterogeneous:!a});let w=n.some(y=>$h(y.resolvedTool)),C=n.some(y=>y.resolvedTool.startsWith("or-")||y.resolvedTool==="run_llm"||y.resolvedTool==="execute_tool"),b=w?_C:C?bC+n.length*vC:wC+n.length*SC,v=Se.randomUUID(),S=[],A=0,I=0n;return Ca(async()=>{let y=!In();if(tm()&&!Ch&&y&&f>0)try{return await kC({resolvedItems:n,previews:u,freeTools:l,catalogEntries:c,itemCeilingCents:p,batchCeilingCents:f,uniqueTools:i,isHomogeneous:a,primaryTool:h,merchantNames:m,totalAmount:d,timeoutMs:b,batchId:v,userContext:t})}catch(T){if(T instanceof yt)Ch=!0,g.info("parentless-batch:falling-back-to-session",{batchTool:h,count:n.length,status:T.status,serverErrorCode:T.serverErrorCode});else{if(T instanceof we)return Ze(T);throw T}}if(y&&f>0)try{let T=f;await xe(()=>dl(U,Qe,{toolName:"batch",userContext:t,sessionKind:"one_shot",minRequiredCents:T,capCentsOverride:T}))}catch(T){return T instanceof we?Ze(T):(g.warn("payment:batch-prewarm-failed",{batchTool:h,count:n.length,error:T?.message||String(T)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:T?.message||"Failed to authenticate batch session",tool:h,count:n.length,failedCount:n.length,results:[]})}try{for(let re=0;re<n.length;re+=1){let J=n[re],Es=u[J.resolvedTool];try{let ce=l.has(J.resolvedTool)?await U.shortcut(J.resolvedTool,J.params,b,t,"batch"):await Uh({toolId:J.resolvedTool,toolParams:J.params,estimatedAmountCents:p[re],userContext:t,metaTool:"batch",timeoutMs:b,idempotencyKey:lu(v,re,J.resolvedTool,J.params)});if(l.has(J.resolvedTool)&&ce&&typeof ce=="object"&&!Array.isArray(ce)&&ce.merchantName==null&&(ce.merchantName=c[J.resolvedTool]?.name??J.resolvedTool),S.push({success:ce?.success!==!1,tool:J.resolvedTool,...ce,...wa(v,re,ce)}),ce?.success!==!1){let As=ct(ce?.amountMicros??ce?.amount_micros),Xu=typeof ce?.amount=="number"?ce.amount:Es?.amount??0;As!==null&&As>0n?I+=As:I+=BigInt(Math.round(Xu*1e6)),A+=Xu}ce?.urls&&ce.urls.forEach(As=>ut(As))}catch(ce){if(ce instanceof we&&S.length===0)return Ze(ce);g.warn("payment:batch-item-failed",{tool:J.resolvedTool,index:re,error:ce?.message||String(ce)}),S.push({success:!1,tool:J.resolvedTool,...wa(v,re),error:ce?.message||String(ce)})}}let T=S.filter(re=>re?.success===!1).length,Y=S.length-T,X=S.flatMap(re=>Array.isArray(re?.urls)?re.urls:[]),H=I>0n?Number(I)/1e6:Math.round((A+Number.EPSILON)*100)/100,_e=Y===0?"failure":T===0?"success":"partial";return g.info("payment:success",{tool:"batch",batchTool:h,count:n.length,totalAmount:d,totalCharged:H,merchant:m,successCount:Y,failedCount:T,outcome:_e,mode:"session",batchId:v}),{success:Y>0,outcome:_e,batch_id:v,tool:a?i[0]:h,count:n.length,successCount:Y,failedCount:T,totalCharged:H,...I>0n?{totalChargedMicros:I.toString(),amountMicros:I.toString(),amount_micros:I.toString()}:{},merchantName:m,results:S,...X.length?{urls:X}:{}}}catch(T){if(T instanceof ge)return g.warn("payment:declined",{tool:"batch",batchTool:h,count:n.length,totalAmount:d,merchant:m,code:T.code,retryable:T.retryable}),dt(T,{amount:d,merchantName:m});throw on(T,{tool:"batch",batchTool:h,count:n.length,totalAmount:d,merchant:m}),T}finally{if(y){let T=await Li(U);g.info("batch-session:closed",{budgetId:T.budgetId,closedServerSide:T.closedServerSide})}}})}function AC(){let e=!1,t;try{let r=Ta.join(So.homedir(),".claude","settings.json");if(lt.existsSync(r)){let s=JSON.parse(lt.readFileSync(r,"utf-8")),o=typeof s.statusLine=="object"?s.statusLine.command:"";e=gn(o)}}catch{}let n=Zo();return n||(t="visa-cli config hud enable"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function RC(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=cC();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=AC(),!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=FT,Array.isArray(t.cards)&&(t.cards=t.cards.map(o=>({...o,displayName:gu(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=In();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 gu(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 Vh(e,t){try{let r=((await U.getStatus(t)).cards||[]).find(s=>s?.id===e);if(r)return gu(r)}catch(n){g.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function IC(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:gu(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 $C(e,t){return await U.getTransactions({limit:e.limit,offset:e.offset},t)}async function PC(e,t){return await U.feedback(e.message,e.transaction_id,t)}async function OC(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return $r("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=Di(String(e.amount));if(n.ok===!1)return{success:!1,error:n.error};let r=n.cents,s=r/100,o=Se.randomUUID();g.info("buy_credits:attempt",{amountCents:r});try{return await xe(async()=>{let i=await Qe("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=PT(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 Fn)return GT();if(i instanceof nt)return g.warn("buy_credits:ambiguous",{amountCents:r,code:i.code,transactionId:i.transactionId}),qT(i);throw g.error("buy_credits:failure",{amountCents:r,error:i.message}),i}}function $r(e,t){return{success:!1,error:t,code:e,message:t}}async function MC(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return $r("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 $r("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 $r("INVALID_VALUE","dailyLimit must be at least $1");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return $r("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");g.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await xe(async()=>{let n=await Qe("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 Fn)return Ea(n,"update_spending_controls");if(String(n?.message||n).includes("Attestation required"))return $r("ATTESTATION_REQUIRED","Changing spending controls requires local attestation, even when payment biometric prompts are disabled.");throw n}}async function NC(e){let t=await so({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 hu=new Set(["auth.serverUrl"]);function wo(){return Object.keys(Zn).filter(e=>!hu.has(e)).sort()}function qh(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:wo()}}async function LC(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(hu.has(e.key))return g.warn("config:set:rejected:mcp-forbidden",{key:e.key}),qh(e.key,"set");g.info("config:set",{key:e.key});try{let t=mi(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 rt?"UNKNOWN_KEY":t instanceof Ft?"SERVER_CONTROLLED":t instanceof hn?"RETIRED_KEY":"INVALID_VALUE",r=t instanceof rt?`Unknown setting "${e.key}". MCP-settable keys: ${wo().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:wo()}}}async function UC(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(hu.has(e.key))return g.warn("config:unset:rejected:mcp-forbidden",{key:e.key}),qh(e.key,"unset");g.info("config:unset",{key:e.key});try{let t=gi(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 rt?"UNKNOWN_KEY":t instanceof Ft?"SERVER_CONTROLLED":t instanceof hn?"RETIRED_KEY":"INVALID_VALUE",r=t instanceof rt?`Unknown setting "${e.key}". MCP-settable keys: ${wo().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:wo()}}}async function DC(e){let t=await U.getStatus(e),n=t.attestationRequired!==!1,r=Tt(t),s=ue(),o=n?r?s?`${Sa()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${Sa()} is not available in this process. ${mu()}`:"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 jC(e){g.info("biometric:on");let t=await Ii(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?(Hh(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:n.error||"unknown error"}}async function BC(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return $r("MISSING_CONFIRMATION","Please confirm by setting confirm: true. Disabling Touch ID is a security downgrade \u2014 the user will be prompted for one final Touch ID confirmation before the change takes effect.");g.info("biometric:off");try{return await xe(async()=>{let n=await U.getStatus(t),r;if(Tt(n)&&(r=await Qe("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${Sa()} 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 Hh(),{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 Fn)return Ea(n,"biometric_off");throw n}}var Ph=3e4,FC=3e5;async function Kh(e,t,n="login"){let r=Se.randomUUID(),s=`${e}${e.includes("?")?"&":"?"}state=${r}`,o=ut(s);return!o.opened&&o.blockedReason!=="non_internal_host"&&o.blockedReason!=="invalid_url"?Gh(s,o,n):o.opened?{...await Wh(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 Gh(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 Wh(e,t,n="login"){let r=Date.now()+FC;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:Ph,...t&&{user_context:t}}),signal:AbortSignal.timeout(Ph+5e3)});if(!o.ok){await fn(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=im(a);if(n!=="enrollment"&&i.sessionToken){await K.saveSessionToken(i.sessionToken);let u=i.user||"",d=i.last4||"****";return g.info("auth:login_complete",{user:u,last4:d,bonusCents:a}),{success:!0,message:`Signed in as ${u}. Card ending in ${d} enrolled and ready for payments.`,...c||{}}}let l=i.last4||"****";return g.info("auth:card_added",{last4:l,bonusCents:a}),{success:!0,message:`Card ending in ${l} enrolled and ready for payments.`,...c||{}}}}catch{await fn(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 Yh(e){let t=Se.randomUUID(),n;try{n=await U.startAttestationRecovery(t,e)}catch(o){return{success:!1,message:`Could not start biometric reset: ${o?.message||"unknown error"}`}}if(!n.success||!n.recoveryUrl)return{success:!1,message:n.error||"Could not start biometric reset. Please try again."};let r=ut(n.recoveryUrl);return!r.opened&&r.blockedReason!=="non_internal_host"&&r.blockedReason!=="invalid_url"?Gh(n.recoveryUrl,r,"attestation-recovery"):r.opened?{...await Wh(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 HC(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 Vh(n,t)}`;try{return await xe(async()=>{let o=await Qe(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 Fn)return Ea(o,"remove_card");throw o}}async function VC(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 Vh(n,t)} as default`;try{return await xe(async()=>{let o=await Qe(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 Fn)return Ea(o,"set_default_card");throw o}}async function qC(e){return g.info("auth:login_attempt"),Kh(`${ka()}/login`,e)}function KC(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 GC(e={},t){let n;try{n=KC(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return Ca(async()=>{let r=await xe(()=>_m(U,Qe,{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 WC(){let e=In();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 YC(){return Ca(async()=>{let e=In();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 Li(U);g.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=DT(e),r=ct(t.finalCumulativeMicros),s=r??(typeof t.finalCumulativeCents=="number"?BigInt(Math.max(0,t.finalCumulativeCents))*10000n:n.micros),o=Number(s/10000n);return g.info("session:closed:final-spend",{budgetId:t.budgetId,closedServerSide:t.closedServerSide,finalSpendMicros:s.toString(),finalSpendCents:o,finalSpendSource:r!==null?"server.finalCumulativeMicros":typeof t.finalCumulativeCents=="number"?"server.finalCumulativeCents":n.source,totalCents:e.totalCents}),{success:!0,closed:!0,closedServerSide:t.closedServerSide,budgetId:t.budgetId,finalEstimatedCumulativeCents:o,finalEstimatedCumulativeMicros:s.toString(),totalCents:e.totalCents,message:t.closedServerSide?`Explicit approval window closed. Spent ${UT(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 zC(e){if(g.info("auth:add_card_attempt"),!await K.getSessionToken())return{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."};let{code:n}=await U.createEnrollCode();return Kh(`${ka()}/enroll-card?code=${encodeURIComponent(n)}`,e,"enrollment")}async function Oh(){if(await K.clearAll(),ue())try{await Ri()}catch{}}async function JC(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 Oh(),g.info("reset:success",{localOnly:!0}),{success:!0,message:"Device reset locally. Local credentials and keys have been removed; server-side session and biometric state were not changed. Use the login tool or visa-cli setup to sign in with the GitHub account you want to use."};let n=!1;try{let r=await U.getStatus(t);if(r&&Tt(r)){let s=await Yh(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 Oh(),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 XC(e){let t=e.query?.trim()||void 0,n=e.category?.trim()||void 0,r=!t&&!n;g.info("catalog:discover",{query:t,category:n,browseAll:r});try{let o=(await U.catalogSearch(t,n)).tools||[];if(o.length===0)return{content:[{type:"text",text:r?"The tool catalog is currently empty.":`No tools found for "${t||n}". Try a different search term.`}]};if(r){let a={};for(let l of o){let u=l.category||"other";(a[u]??=[]).push(l)}let c=Object.keys(a).sort().map(l=>{let u=a[l].map((p,f)=>`${f+1}. **${p.name}** (${p.id})
146
- ${p.description}
147
- Provider: ${p.provider} | Price: ${Mh(p)}${Nh(p)}
148
- Params: ${Object.keys(p.inputSchema?.properties||p.inputSchema||{}).join(", ")||"none"}`).join(`
140
+ `),tm(t),console.log("\nUse `visa-cli describe <tool>` for full details (incl. parameter types)."),console.log(`Or scope it: \`visa-cli merchants ${e} describe <tool>\`
141
+ `)}var _={};jo(_,{BRAND:()=>B0,DIRTY:()=>tr,EMPTY_PATH:()=>_0,INVALID:()=>D,NEVER:()=>Tv,OK:()=>Ie,ParseStatus:()=>Te,Schema:()=>V,ZodAny:()=>xn,ZodArray:()=>Wt,ZodBigInt:()=>rr,ZodBoolean:()=>sr,ZodBranded:()=>no,ZodCatch:()=>gr,ZodDate:()=>or,ZodDefault:()=>pr,ZodDiscriminatedUnion:()=>wi,ZodEffects:()=>Je,ZodEnum:()=>fr,ZodError:()=>Be,ZodFirstPartyTypeKind:()=>j,ZodFunction:()=>xi,ZodIntersection:()=>lr,ZodIssueCode:()=>x,ZodLazy:()=>ur,ZodLiteral:()=>dr,ZodMap:()=>Qr,ZodNaN:()=>ts,ZodNativeEnum:()=>mr,ZodNever:()=>st,ZodNull:()=>ar,ZodNullable:()=>xt,ZodNumber:()=>nr,ZodObject:()=>Fe,ZodOptional:()=>Ye,ZodParsedType:()=>A,ZodPipeline:()=>ro,ZodPromise:()=>Tn,ZodReadonly:()=>hr,ZodRecord:()=>Si,ZodSchema:()=>V,ZodSet:()=>es,ZodString:()=>Sn,ZodSymbol:()=>Xr,ZodTransformer:()=>Je,ZodTuple:()=>St,ZodType:()=>V,ZodUndefined:()=>ir,ZodUnion:()=>cr,ZodUnknown:()=>Gt,ZodVoid:()=>Zr,addIssueToContext:()=>C,any:()=>z0,array:()=>Q0,bigint:()=>q0,boolean:()=>pm,coerce:()=>xv,custom:()=>dm,date:()=>K0,datetimeRegex:()=>lm,defaultErrorMap:()=>qt,discriminatedUnion:()=>rv,effect:()=>gv,enum:()=>fv,function:()=>lv,getErrorMap:()=>Yr,getParsedType:()=>wt,instanceof:()=>H0,intersection:()=>sv,isAborted:()=>bi,isAsync:()=>zr,isDirty:()=>vi,isValid:()=>wn,late:()=>F0,lazy:()=>uv,literal:()=>dv,makeIssue:()=>to,map:()=>av,nan:()=>V0,nativeEnum:()=>mv,never:()=>X0,null:()=>Y0,nullable:()=>yv,number:()=>mm,object:()=>ev,objectUtil:()=>Hc,oboolean:()=>Sv,onumber:()=>wv,optional:()=>hv,ostring:()=>vv,pipeline:()=>bv,preprocess:()=>_v,promise:()=>pv,quotelessJson:()=>g0,record:()=>iv,set:()=>cv,setErrorMap:()=>y0,strictObject:()=>tv,string:()=>fm,symbol:()=>G0,transformer:()=>gv,tuple:()=>ov,undefined:()=>W0,union:()=>nv,unknown:()=>J0,util:()=>q,void:()=>Z0});var q;(function(e){e.assertEqual=s=>{};function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{let o={};for(let i of s)o[i]=i;return o},e.getValidEnumValues=s=>{let o=e.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(let a of o)i[a]=s[a];return e.objectValues(i)},e.objectValues=s=>e.objectKeys(s).map(function(o){return s[o]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},e.find=(s,o)=>{for(let i of s)if(o(i))return i},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}e.joinValues=r,e.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(q||(q={}));var Hc;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Hc||(Hc={}));var A=q.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),wt=e=>{switch(typeof e){case"undefined":return A.undefined;case"string":return A.string;case"number":return Number.isNaN(e)?A.nan:A.number;case"boolean":return A.boolean;case"function":return A.function;case"bigint":return A.bigint;case"symbol":return A.symbol;case"object":return Array.isArray(e)?A.array:e===null?A.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?A.promise:typeof Map<"u"&&e instanceof Map?A.map:typeof Set<"u"&&e instanceof Set?A.set:typeof Date<"u"&&e instanceof Date?A.date:A.object;default:return A.unknown}};var x=q.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),g0=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),Be=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(o){return o.message},r={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(n(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return s(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,q.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];n[o]=n[o]||[],n[o].push(t(s))}else r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Be.create=e=>new Be(e);var h0=(e,t)=>{let n;switch(e.code){case x.invalid_type:e.received===A.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case x.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,q.jsonStringifyReplacer)}`;break;case x.unrecognized_keys:n=`Unrecognized key(s) in object: ${q.joinValues(e.keys,", ")}`;break;case x.invalid_union:n="Invalid input";break;case x.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${q.joinValues(e.options)}`;break;case x.invalid_enum_value:n=`Invalid enum value. Expected ${q.joinValues(e.options)}, received '${e.received}'`;break;case x.invalid_arguments:n="Invalid function arguments";break;case x.invalid_return_type:n="Invalid function return type";break;case x.invalid_date:n="Invalid date";break;case x.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:q.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case x.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case x.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case x.custom:n="Invalid input";break;case x.invalid_intersection_types:n="Intersection results could not be merged";break;case x.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case x.not_finite:n="Number must be finite";break;default:n=t.defaultError,q.assertNever(e)}return{message:n}},qt=h0;var sm=qt;function y0(e){sm=e}function Yr(){return sm}var to=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}},_0=[];function C(e,t){let n=Yr(),r=to({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===qt?void 0:qt].filter(s=>!!s)});e.common.issues.push(r)}var Te=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let s of n){if(s.status==="aborted")return D;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let s of n){let o=await s.key,i=await s.value;r.push({key:o,value:i})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let s of n){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return D;o.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(r[o.value]=i.value)}return{status:t.value,value:r}}},D=Object.freeze({status:"aborted"}),tr=e=>({status:"dirty",value:e}),Ie=e=>({status:"valid",value:e}),bi=e=>e.status==="aborted",vi=e=>e.status==="dirty",wn=e=>e.status==="valid",zr=e=>typeof Promise<"u"&&e instanceof Promise;var M;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(M||(M={}));var 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}},om=(e,t)=>{if(wn(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new Be(e.common.issues);return this._error=n,this._error}}};function B(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(i,a)=>{let{message:c}=e;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??n??a.defaultError}},description:s}}var V=class{get description(){return this._def.description}_getType(t){return wt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:wt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Te,ctx:{common:t.parent.common,data:t.data,parsedType:wt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(zr(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:wt(t)},s=this._parseSync({data:t,path:r.path,parent:r});return om(r,s)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:wt(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return wn(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=>wn(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(t,n){let r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:wt(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(zr(s)?s:Promise.resolve(s));return om(r,o)}refine(t,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{let i=t(s),a=()=>o.addIssue({code:x.custom,...r(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new Je({schema:this,typeName:j.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Ye.create(this,this._def)}nullable(){return xt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Wt.create(this)}promise(){return Tn.create(this,this._def)}or(t){return cr.create([this,t],this._def)}and(t){return lr.create(this,t,this._def)}transform(t){return new Je({...B(this._def),schema:this,typeName:j.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new pr({...B(this._def),innerType:this,defaultValue:n,typeName:j.ZodDefault})}brand(){return new no({typeName:j.ZodBranded,type:this,...B(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new gr({...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 ro.create(this,t)}readonly(){return hr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},b0=/^c[^\s-]{8,}$/i,v0=/^[0-9a-z]+$/,w0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,S0=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,x0=/^[a-z0-9_-]{21}$/i,T0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,k0=/^[-+]?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)?)??$/,C0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,A0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Vc,E0=/^(?:(?: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])$/,R0=/^(?:(?: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])$/,I0=/^(([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]))$/,$0=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,P0=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,O0=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,am="((\\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])))",M0=new RegExp(`^${am}$`);function cm(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 N0(e){return new RegExp(`^${cm(e)}$`)}function lm(e){let t=`${am}T${cm(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 L0(e,t){return!!((t==="v4"||!t)&&E0.test(e)||(t==="v6"||!t)&&I0.test(e))}function U0(e,t){if(!T0.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 D0(e,t){return!!((t==="v4"||!t)&&R0.test(e)||(t==="v6"||!t)&&$0.test(e))}var Sn=class e extends V{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==A.string){let o=this._getOrReturnCtx(t);return C(o,{code:x.invalid_type,expected:A.string,received:o.parsedType}),D}let r=new Te,s;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(s=this._getOrReturnCtx(t,s),C(s,{code:x.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")t.data.length>o.value&&(s=this._getOrReturnCtx(t,s),C(s,{code:x.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){let i=t.data.length>o.value,a=t.data.length<o.value;(i||a)&&(s=this._getOrReturnCtx(t,s),i?C(s,{code:x.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&C(s,{code:x.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")C0.test(t.data)||(s=this._getOrReturnCtx(t,s),C(s,{validation:"email",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")Vc||(Vc=new RegExp(A0,"u")),Vc.test(t.data)||(s=this._getOrReturnCtx(t,s),C(s,{validation:"emoji",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")S0.test(t.data)||(s=this._getOrReturnCtx(t,s),C(s,{validation:"uuid",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")x0.test(t.data)||(s=this._getOrReturnCtx(t,s),C(s,{validation:"nanoid",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")b0.test(t.data)||(s=this._getOrReturnCtx(t,s),C(s,{validation:"cuid",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")v0.test(t.data)||(s=this._getOrReturnCtx(t,s),C(s,{validation:"cuid2",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")w0.test(t.data)||(s=this._getOrReturnCtx(t,s),C(s,{validation:"ulid",code:x.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),C(s,{validation:"url",code:x.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),C(s,{validation:"regex",code:x.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(t,s),C(s,{code:x.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(s=this._getOrReturnCtx(t,s),C(s,{code:x.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(s=this._getOrReturnCtx(t,s),C(s,{code:x.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?lm(o).test(t.data)||(s=this._getOrReturnCtx(t,s),C(s,{code:x.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?M0.test(t.data)||(s=this._getOrReturnCtx(t,s),C(s,{code:x.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?N0(o).test(t.data)||(s=this._getOrReturnCtx(t,s),C(s,{code:x.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?k0.test(t.data)||(s=this._getOrReturnCtx(t,s),C(s,{validation:"duration",code:x.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?L0(t.data,o.version)||(s=this._getOrReturnCtx(t,s),C(s,{validation:"ip",code:x.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?U0(t.data,o.alg)||(s=this._getOrReturnCtx(t,s),C(s,{validation:"jwt",code:x.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?D0(t.data,o.version)||(s=this._getOrReturnCtx(t,s),C(s,{validation:"cidr",code:x.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?P0.test(t.data)||(s=this._getOrReturnCtx(t,s),C(s,{validation:"base64",code:x.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?O0.test(t.data)||(s=this._getOrReturnCtx(t,s),C(s,{validation:"base64url",code:x.invalid_string,message:o.message}),r.dirty()):q.assertNever(o);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:x.invalid_string,...M.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...M.errToObj(t)})}url(t){return this._addCheck({kind:"url",...M.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...M.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...M.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...M.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...M.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...M.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...M.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...M.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...M.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...M.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...M.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...M.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...M.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...M.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...M.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...M.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...M.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...M.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...M.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...M.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...M.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...M.errToObj(n)})}nonempty(t){return this.min(1,M.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};Sn.create=e=>new Sn({checks:[],typeName:j.ZodString,coerce:e?.coerce??!1,...B(e)});function j0(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 nr=class e extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==A.number){let o=this._getOrReturnCtx(t);return C(o,{code:x.invalid_type,expected:A.number,received:o.parsedType}),D}let r,s=new Te;for(let o of this._def.checks)o.kind==="int"?q.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),C(r,{code:x.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),C(r,{code:x.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),C(r,{code:x.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?j0(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),C(r,{code:x.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),C(r,{code:x.not_finite,message:o.message}),s.dirty()):q.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,M.toString(n))}gt(t,n){return this.setLimit("min",t,!1,M.toString(n))}lte(t,n){return this.setLimit("max",t,!0,M.toString(n))}lt(t,n){return this.setLimit("max",t,!1,M.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:M.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:M.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:M.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:M.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:M.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:M.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:M.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:M.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:M.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:M.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&q.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};nr.create=e=>new nr({checks:[],typeName:j.ZodNumber,coerce:e?.coerce||!1,...B(e)});var rr=class e extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==A.bigint)return this._getInvalidInput(t);let r,s=new Te;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),C(r,{code:x.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),C(r,{code:x.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),C(r,{code:x.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):q.assertNever(o);return{status:s.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return C(n,{code:x.invalid_type,expected:A.bigint,received:n.parsedType}),D}gte(t,n){return this.setLimit("min",t,!0,M.toString(n))}gt(t,n){return this.setLimit("min",t,!1,M.toString(n))}lte(t,n){return this.setLimit("max",t,!0,M.toString(n))}lt(t,n){return this.setLimit("max",t,!1,M.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:M.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:M.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:M.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:M.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:M.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:M.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};rr.create=e=>new rr({checks:[],typeName:j.ZodBigInt,coerce:e?.coerce??!1,...B(e)});var sr=class extends V{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==A.boolean){let r=this._getOrReturnCtx(t);return C(r,{code:x.invalid_type,expected:A.boolean,received:r.parsedType}),D}return Ie(t.data)}};sr.create=e=>new sr({typeName:j.ZodBoolean,coerce:e?.coerce||!1,...B(e)});var or=class e extends V{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==A.date){let o=this._getOrReturnCtx(t);return C(o,{code:x.invalid_type,expected:A.date,received:o.parsedType}),D}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return C(o,{code:x.invalid_date}),D}let r=new Te,s;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(s=this._getOrReturnCtx(t,s),C(s,{code:x.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(s=this._getOrReturnCtx(t,s),C(s,{code:x.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):q.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:M.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:M.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};or.create=e=>new or({checks:[],coerce:e?.coerce||!1,typeName:j.ZodDate,...B(e)});var Xr=class extends V{_parse(t){if(this._getType(t)!==A.symbol){let r=this._getOrReturnCtx(t);return C(r,{code:x.invalid_type,expected:A.symbol,received:r.parsedType}),D}return Ie(t.data)}};Xr.create=e=>new Xr({typeName:j.ZodSymbol,...B(e)});var ir=class extends V{_parse(t){if(this._getType(t)!==A.undefined){let r=this._getOrReturnCtx(t);return C(r,{code:x.invalid_type,expected:A.undefined,received:r.parsedType}),D}return Ie(t.data)}};ir.create=e=>new ir({typeName:j.ZodUndefined,...B(e)});var ar=class extends V{_parse(t){if(this._getType(t)!==A.null){let r=this._getOrReturnCtx(t);return C(r,{code:x.invalid_type,expected:A.null,received:r.parsedType}),D}return Ie(t.data)}};ar.create=e=>new ar({typeName:j.ZodNull,...B(e)});var xn=class extends V{constructor(){super(...arguments),this._any=!0}_parse(t){return Ie(t.data)}};xn.create=e=>new xn({typeName:j.ZodAny,...B(e)});var Gt=class extends V{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Ie(t.data)}};Gt.create=e=>new Gt({typeName:j.ZodUnknown,...B(e)});var st=class extends V{_parse(t){let n=this._getOrReturnCtx(t);return C(n,{code:x.invalid_type,expected:A.never,received:n.parsedType}),D}};st.create=e=>new st({typeName:j.ZodNever,...B(e)});var Zr=class extends V{_parse(t){if(this._getType(t)!==A.undefined){let r=this._getOrReturnCtx(t);return C(r,{code:x.invalid_type,expected:A.void,received:r.parsedType}),D}return Ie(t.data)}};Zr.create=e=>new Zr({typeName:j.ZodVoid,...B(e)});var Wt=class e extends V{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==A.array)return C(n,{code:x.invalid_type,expected:A.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)&&(C(n,{code:i?x.too_big:x.too_small,minimum:a?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(C(n,{code:x.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(C(n,{code:x.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>s.type._parseAsync(new ze(n,i,n.path,a)))).then(i=>Te.mergeArray(r,i));let o=[...n.data].map((i,a)=>s.type._parseSync(new ze(n,i,n.path,a)));return Te.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:M.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:M.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:M.toString(n)}})}nonempty(t){return this.min(1,t)}};Wt.create=(e,t)=>new Wt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:j.ZodArray,...B(t)});function Jr(e){if(e instanceof Fe){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Ye.create(Jr(r))}return new Fe({...e._def,shape:()=>t})}else return e instanceof Wt?new Wt({...e._def,type:Jr(e.element)}):e instanceof Ye?Ye.create(Jr(e.unwrap())):e instanceof xt?xt.create(Jr(e.unwrap())):e instanceof St?St.create(e.items.map(t=>Jr(t))):e}var Fe=class e extends V{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=q.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==A.object){let l=this._getOrReturnCtx(t);return C(l,{code:x.invalid_type,expected:A.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 st&&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 st){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&&(C(s,{code:x.unrecognized_keys,keys:a}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let d=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new ze(s,d,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,m=await u.value;l.push({key:d,value:m,alwaysSet:u.alwaysSet})}return l}).then(l=>Te.mergeObjectSync(r,l)):Te.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(t){return M.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:M.errToObj(t).message??s}:{message:s}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:j.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of q.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let r of q.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return Jr(this)}partial(t){let n={};for(let r of q.objectKeys(this.shape)){let s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let r of q.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof Ye;)o=o._def.innerType;n[r]=o}return new e({...this._def,shape:()=>n})}keyof(){return um(q.objectKeys(this.shape))}};Fe.create=(e,t)=>new Fe({shape:()=>e,unknownKeys:"strip",catchall:st.create(),typeName:j.ZodObject,...B(t)});Fe.strictCreate=(e,t)=>new Fe({shape:()=>e,unknownKeys:"strict",catchall:st.create(),typeName:j.ZodObject,...B(t)});Fe.lazycreate=(e,t)=>new Fe({shape:e,unknownKeys:"strip",catchall:st.create(),typeName:j.ZodObject,...B(t)});var cr=class extends V{_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new Be(a.ctx.common.issues));return C(n,{code:x.invalid_union,unionErrors:i}),D}if(n.common.async)return Promise.all(r.map(async o=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let c of r){let l={...n,common:{...n.common,issues:[]},parent:null},u=c._parseSync({data:n.data,path:n.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(c=>new Be(c));return C(n,{code:x.invalid_union,unionErrors:a}),D}}get options(){return this._def.options}};cr.create=(e,t)=>new cr({options:e,typeName:j.ZodUnion,...B(t)});var Kt=e=>e instanceof ur?Kt(e.schema):e instanceof Je?Kt(e.innerType()):e instanceof dr?[e.value]:e instanceof fr?e.options:e instanceof mr?q.objectValues(e.enum):e instanceof pr?Kt(e._def.innerType):e instanceof ir?[void 0]:e instanceof ar?[null]:e instanceof Ye?[void 0,...Kt(e.unwrap())]:e instanceof xt?[null,...Kt(e.unwrap())]:e instanceof no||e instanceof hr?Kt(e.unwrap()):e instanceof gr?Kt(e._def.innerType):[],wi=class e extends V{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==A.object)return C(n,{code:x.invalid_type,expected:A.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}):(C(n,{code:x.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),D)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let s=new Map;for(let o of n){let i=Kt(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 qc(e,t){let n=wt(e),r=wt(t);if(e===t)return{valid:!0,data:e};if(n===A.object&&r===A.object){let s=q.objectKeys(t),o=q.objectKeys(e).filter(a=>s.indexOf(a)!==-1),i={...e,...t};for(let a of o){let c=qc(e[a],t[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===A.array&&r===A.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=qc(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===A.date&&r===A.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var lr=class extends V{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=(o,i)=>{if(bi(o)||bi(i))return D;let a=qc(o.value,i.value);return a.valid?((vi(o)||vi(i))&&n.dirty(),{status:n.value,value:a.data}):(C(r,{code:x.invalid_intersection_types}),D)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};lr.create=(e,t,n)=>new lr({left:e,right:t,typeName:j.ZodIntersection,...B(n)});var St=class e extends V{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.array)return C(r,{code:x.invalid_type,expected:A.array,received:r.parsedType}),D;if(r.data.length<this._def.items.length)return C(r,{code:x.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),D;!this._def.rest&&r.data.length>this._def.items.length&&(C(r,{code:x.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...r.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new ze(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>Te.mergeArray(n,i)):Te.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};St.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new St({items:e,typeName:j.ZodTuple,rest:null,...B(t)})};var Si=class e extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.object)return C(r,{code:x.invalid_type,expected:A.object,received:r.parsedType}),D;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in r.data)s.push({key:o._parse(new ze(r,a,r.path,a)),value:i._parse(new ze(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?Te.mergeObjectAsync(n,s):Te.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof V?new e({keyType:t,valueType:n,typeName:j.ZodRecord,...B(r)}):new e({keyType:Sn.create(),valueType:t,typeName:j.ZodRecord,...B(n)})}},Qr=class extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.map)return C(r,{code:x.invalid_type,expected:A.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}}}};Qr.create=(e,t,n)=>new Qr({valueType:t,keyType:e,typeName:j.ZodMap,...B(n)});var es=class e extends V{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==A.set)return C(r,{code:x.invalid_type,expected:A.set,received:r.parsedType}),D;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(C(r,{code:x.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(C(r,{code:x.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let o=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return D;u.status==="dirty"&&n.dirty(),l.add(u.value)}return{status:n.value,value:l}}let a=[...r.data.values()].map((c,l)=>o._parse(new ze(r,c,r.path,l)));return r.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(t,n){return new e({...this._def,minSize:{value:t,message:M.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:M.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};es.create=(e,t)=>new es({valueType:e,minSize:null,maxSize:null,typeName:j.ZodSet,...B(t)});var xi=class e extends V{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==A.function)return C(n,{code:x.invalid_type,expected:A.function,received:n.parsedType}),D;function r(a,c){return to({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Yr(),qt].filter(l=>!!l),issueData:{code:x.invalid_arguments,argumentsError:c}})}function s(a,c){return to({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Yr(),qt].filter(l=>!!l),issueData:{code:x.invalid_return_type,returnTypeError:c}})}let o={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof Tn){let a=this;return Ie(async function(...c){let l=new Be([]),u=await a._def.args.parseAsync(c,o).catch(f=>{throw l.addIssue(r(c,f)),l}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,o).catch(f=>{throw l.addIssue(s(d,f)),l})})}else{let a=this;return Ie(function(...c){let l=a._def.args.safeParse(c,o);if(!l.success)throw new Be([r(c,l.error)]);let u=Reflect.apply(i,this,l.data),d=a._def.returns.safeParse(u,o);if(!d.success)throw new Be([s(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:St.create(t).rest(Gt.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new e({args:t||St.create([]).rest(Gt.create()),returns:n||Gt.create(),typeName:j.ZodFunction,...B(r)})}},ur=class extends V{get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};ur.create=(e,t)=>new ur({getter:e,typeName:j.ZodLazy,...B(t)});var dr=class extends V{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return C(n,{received:n.data,code:x.invalid_literal,expected:this._def.value}),D}return{status:"valid",value:t.data}}get value(){return this._def.value}};dr.create=(e,t)=>new dr({value:e,typeName:j.ZodLiteral,...B(t)});function um(e,t){return new fr({values:e,typeName:j.ZodEnum,...B(t)})}var fr=class e extends V{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return C(n,{expected:q.joinValues(r),received:n.parsedType,code:x.invalid_type}),D}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return C(n,{received:n.data,code:x.invalid_enum_value,options:r}),D}return Ie(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};fr.create=um;var mr=class extends V{_parse(t){let n=q.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==A.string&&r.parsedType!==A.number){let s=q.objectValues(n);return C(r,{expected:q.joinValues(s),received:r.parsedType,code:x.invalid_type}),D}if(this._cache||(this._cache=new Set(q.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let s=q.objectValues(n);return C(r,{received:r.data,code:x.invalid_enum_value,options:s}),D}return Ie(t.data)}get enum(){return this._def.values}};mr.create=(e,t)=>new mr({values:e,typeName:j.ZodNativeEnum,...B(t)});var Tn=class extends V{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==A.promise&&n.common.async===!1)return C(n,{code:x.invalid_type,expected:A.promise,received:n.parsedType}),D;let r=n.parsedType===A.promise?n.data:Promise.resolve(n.data);return Ie(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Tn.create=(e,t)=>new Tn({type:e,typeName:j.ZodPromise,...B(t)});var Je=class extends V{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===j.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,o={addIssue:i=>{C(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"?tr(c.value):n.value==="dirty"?tr(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"?tr(a.value):n.value==="dirty"?tr(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(!wn(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=>wn(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:n.value,value:a})):D);q.assertNever(s)}};Je.create=(e,t,n)=>new Je({schema:e,typeName:j.ZodEffects,effect:t,...B(n)});Je.createWithPreprocess=(e,t,n)=>new Je({schema:t,effect:{type:"preprocess",transform:e},typeName:j.ZodEffects,...B(n)});var Ye=class extends V{_parse(t){return this._getType(t)===A.undefined?Ie(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ye.create=(e,t)=>new Ye({innerType:e,typeName:j.ZodOptional,...B(t)});var xt=class extends V{_parse(t){return this._getType(t)===A.null?Ie(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};xt.create=(e,t)=>new xt({innerType:e,typeName:j.ZodNullable,...B(t)});var pr=class extends V{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===A.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};pr.create=(e,t)=>new pr({innerType:e,typeName:j.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...B(t)});var gr=class extends V{_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return zr(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new 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}};gr.create=(e,t)=>new gr({innerType:e,typeName:j.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...B(t)});var ts=class extends V{_parse(t){if(this._getType(t)!==A.nan){let r=this._getOrReturnCtx(t);return C(r,{code:x.invalid_type,expected:A.nan,received:r.parsedType}),D}return{status:"valid",value:t.data}}};ts.create=e=>new ts({typeName:j.ZodNaN,...B(e)});var B0=Symbol("zod_brand"),no=class extends V{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},ro=class e extends V{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?D:o.status==="dirty"?(n.dirty(),tr(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})}},hr=class extends V{_parse(t){let n=this._def.innerType._parse(t),r=s=>(wn(s)&&(s.value=Object.freeze(s.value)),s);return zr(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};hr.create=(e,t)=>new hr({innerType:e,typeName:j.ZodReadonly,...B(t)});function im(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function dm(e,t={},n){return e?xn.create().superRefine((r,s)=>{let o=e(r);if(o instanceof Promise)return o.then(i=>{if(!i){let a=im(t,r),c=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=im(t,r),a=i.fatal??n??!0;s.addIssue({code:"custom",...i,fatal:a})}}):xn.create()}var F0={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 H0=(e,t={message:`Input not instance of ${e.name}`})=>dm(n=>n instanceof e,t),fm=Sn.create,mm=nr.create,V0=ts.create,q0=rr.create,pm=sr.create,K0=or.create,G0=Xr.create,W0=ir.create,Y0=ar.create,z0=xn.create,J0=Gt.create,X0=st.create,Z0=Zr.create,Q0=Wt.create,ev=Fe.create,tv=Fe.strictCreate,nv=cr.create,rv=wi.create,sv=lr.create,ov=St.create,iv=Si.create,av=Qr.create,cv=es.create,lv=xi.create,uv=ur.create,dv=dr.create,fv=fr.create,mv=mr.create,pv=Tn.create,gv=Je.create,hv=Ye.create,yv=xt.create,_v=Je.createWithPreprocess,bv=ro.create,vv=()=>fm().optional(),wv=()=>mm().optional(),Sv=()=>pm().optional(),xv={string:(e=>Sn.create({...e,coerce:!0})),number:(e=>nr.create({...e,coerce:!0})),boolean:(e=>sr.create({...e,coerce:!0})),bigint:(e=>rr.create({...e,coerce:!0})),date:(e=>or.create({...e,coerce:!0}))};var Tv=D;var kv=/^[A-Za-z0-9._-]+$/,Cv=/^[A-Za-z0-9._-]+(\|[A-Za-z0-9._-]+)*$/,gm=new Set([".",".."]),De=class extends Error{pattern;constructor(t,n){super(`Invalid freeReadPathPattern ${JSON.stringify(n)}: ${t}`),this.pattern=n,this.name="FreePathPatternError"}};function Av(e,t){if(e==="*")return{raw:e,kind:"single"};if(e==="**")return{raw:e,kind:"multi"};if(e.startsWith("(")){let n=e.endsWith(")?"),r=e.endsWith(")");if(!n&&!r)throw new De(`malformed alternation segment ${JSON.stringify(e)}`,t);let s=n?e.slice(1,-2):e.slice(1,-1);if(!Cv.test(s))throw new De(`malformed alternation segment ${JSON.stringify(e)}`,t);let o=s.split("|");if(o.some(i=>gm.has(i)))throw new De(`alternation segment ${JSON.stringify(e)} may not contain '.' or '..'`,t);return{raw:e,kind:n?"alt-optional":"alt",alternatives:o}}if(kv.test(e)){if(gm.has(e))throw new De(`literal segment ${JSON.stringify(e)} is not permitted`,t);return{raw:e,kind:"literal"}}throw new De(`segment ${JSON.stringify(e)} must be '*', '**', a [A-Za-z0-9._-]+ literal, or (a|b) alternation`,t)}function Ev(e){if(typeof e!="string"||e.length===0)throw new De("must be a non-empty string",String(e));if(!e.startsWith("/"))throw new De("must start with '/'",e);if(e.slice(1).includes("//"))throw new De("empty segments ('//') are not permitted",e);if(e.length>1&&e.endsWith("/"))throw new De("must not end with '/'",e);let n=e.slice(1).split("/").map(o=>Av(o,e));if(n.filter(o=>o.kind==="multi").length>1)throw new De("at most one '**' is permitted per pattern",e);if(n[0]?.kind==="multi")throw new De("'**' may not be the first segment (a literal prefix anchor is required)",e);let s=n.findIndex(o=>o.kind==="alt-optional");if(s!==-1&&s!==n.length-1)throw new De("optional alternation '(...)?' is only allowed as the final segment",e);return n}function Kc(e){Ev(e)}var hm=["tempo","mpp_self","merchant_self"],ym=["catalog_static","fal_direct","fal_queue","openrouter_chat","openrouter_image","platform_proxy","tempo_gateway","x402_gateway"],_m=["image","audio","queued_audio","video","queued_video","model_3d","llm","transcription","utility"],bm=["images[0].url","image.url","audio.url","audio_file.url","audio_url","video.url","model_mesh.url","text","choices[0].message.content","choices[0].message.images[0].image_url.url","request_id"];var Wc=_.object({inputPerMillion:_.number().positive(),outputPerMillion:_.number().positive(),contextWindow:_.number().int().positive().optional(),maxOutput:_.number().int().positive().optional(),perRequestFeeCents:_.number().nonnegative().optional()}),Rv=_.object({strategy:_.enum(["flat","token","band"]).optional(),pricingModel:_.enum(["per-call","per-token","band"]).optional(),priceCents:_.number().nonnegative().optional(),currency:_.string().optional(),display:_.string().optional(),estimate:_.boolean().optional(),source:_.string().optional(),priceBand:_.record(_.unknown()).optional(),tokenPricing:Wc.optional()}).passthrough(),Yc=_.discriminatedUnion("type",[_.object({type:_.literal("shortcut"),routedPath:_.string().min(1).startsWith("/")}),_.object({type:_.literal("custom"),merchantSlug:_.string().min(1),subPath:_.string().optional()}),_.object({type:_.literal("local"),fn:_.string().min(1)}),_.object({type:_.literal("read")})]),zc=_.object({amount:_.number().nonnegative(),currency:_.string().length(3).optional(),display:_.string().optional(),free:_.boolean().optional(),batchDiscount:_.number().min(0).max(100).optional()}),vm=_.object({attestation:_.boolean().optional(),rateLimitMs:_.number().positive().optional()}),wm=_.object({displayName:_.string().optional(),feedbackEligible:_.boolean().optional(),suggestionEligible:_.boolean().optional(),batchable:_.boolean().optional()}),Sm=_.object({enabled:_.boolean().optional(),gatewayPath:_.string().min(1).startsWith("/").optional(),method:_.enum(["GET","POST","PUT","PATCH","DELETE"]).optional(),timeoutMs:_.number().int().positive().max(12e4).optional()}).strict(),Iv=_.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),$v=120,Pv=120,Ov=1200,Mv=/^[^\u0000-\u001F\u007F]+$/;function Gc(e,t){return _.string().min(1).max(e).regex(Mv,`${t} must not contain control characters`)}var Jc={id:_.string().min(1),name:Gc($v,"name"),description:Gc(Ov,"description"),provider:_.string().min(1),model:_.string().min(1),category:Iv,priceCents:_.number().nonnegative(),inputSchema:_.record(_.unknown()),gatewayUrl:_.string().min(1),merchantName:Gc(Pv,"merchantName"),isAsync:_.boolean().optional(),pollUrl:_.string().optional(),pollInterval:_.number().positive().optional(),pollTimeout:_.number().positive().optional(),tags:_.array(_.string()).optional(),tokenPricing:Wc.optional(),priceDisplay:_.string().optional(),pricingModel:_.enum(["per-call","per-token","band"]).optional(),pricingInfo:Rv.optional(),status:_.enum(["available","unavailable"]).optional(),handler:Yc.optional(),pricing:zc.optional(),security:vm.optional(),engagement:wm.optional(),gatewayConfig:Sm.optional(),freeReadPathPattern:_.string().optional().superRefine((e,t)=>{if(e!==void 0)try{Kc(e)}catch(n){t.addIssue({code:_.ZodIssueCode.custom,message:n instanceof Error?n.message:String(n)})}}),enabled:_.boolean().optional(),beta:_.boolean().optional(),deprecated:_.boolean().optional(),internal:_.boolean().optional(),employeeOnly:_.boolean().optional(),employeeOnlyRolloutFlag:_.string().min(1).max(100).optional(),replacementTool:_.string().optional(),minCliVersion:_.string().optional(),sunsetAt:_.string().optional(),rail:_.enum(hm).optional(),executionKind:_.enum(ym).optional(),resultKind:_.enum(_m).optional(),extractionMode:_.enum(bm).optional(),pricingStrategy:_.enum(["flat","token","band"]).optional()},xm=_.object({...Jc,dispatch:_.literal("routed"),routedPath:_.string().min(1).startsWith("/")}).strict(),Tm=_.object({...Jc,dispatch:_.literal("enveloped")}).strict(),km=_.object({...Jc,handler:Yc,pricing:zc}).strict(),Cm=_.union([_.discriminatedUnion("dispatch",[xm,Tm]),km]);var Xc=/^[a-z0-9][a-z0-9_-]*$/;var Uv="https://fal.run",Im="https://openrouter.mpp.tempo.xyz",Qc=1024,ki=8192,Dv=4096,jv=10;function Bv(e){return e>=jv?Dv:ki}function $m(e,t){let n=typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):Qc;return Math.min(n,t)}var Fv=["num_images","num_outputs","num_samples","num_videos","batch_size","n"];function Pm(e){for(let t of Fv)delete e[t];return e}function Hv(e){let{attestation:t,tool_id:n,...r}=e;return Pm(r)}var Am={"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 Ti(e){let{attestation:t,tool_id:n,aspect_ratio:r,image_size:s,...o}=e,i=Pm({...o});return typeof s=="string"&&s.length>0?(i.image_size=s,i):(typeof r=="string"&&Am[r]&&(i.image_size=Am[r]),i)}function Vv(e){let{attestation:t,tool_id:n,...r}=e;return r}function Em(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 qv(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 Kv(e,t,n,r,s,o,i,a){return qv(e,t,n,"suno-ai",r,s,o,i,{merchantName:"Suno AI",...a})}function ye(e,t,n,r,s,o,i,a){return{dispatch:"routed",id:e,name:t,description:n,provider:"fal",model:r,category:s,priceCents:o,inputSchema:i,routedPath:`/api/v1/fal/${r}`,gatewayUrl:`${Uv}/${r}`,merchantName:"fal.ai",buildBody:Hv,tags:[],...a}}function Om(e,t=ki){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:m,...f}=n;return typeof o=="string"&&o.length>0&&o!==e&&console.warn("[catalog] openrouterBuildBody: caller model override ignored",{catalogModel:e,callerModel:o}),{messages:Array.isArray(d)?d:[...a?[{role:"system",content:a}]:[],{role:"user",content:i}],temperature:m??.7,...f,model:e,max_tokens:$m(c??l,t)}}}function Mm(e,t=ki){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:m,image_config:f,temperature:p,...h}=n,w=[{type:"text",text:o}];return typeof i=="string"&&i.length>0&&w.push({type:"image_url",image_url:{url:i}}),{messages:Array.isArray(m)?m:[{role:"user",content:w}],temperature:p??.7,...h,model:e,...typeof a=="string"&&a.length>0?{image_config:{aspect_ratio:a}}:{},max_tokens:$m(c??l,t)}}}function ue(e,t,n,r,s,o,i){let a=i?.maxOutputTokens??Bv(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:m,maxOutputTokens:f,...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: ${Qc}); 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:`${Im}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:Om(r,a),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:s,outputPerMillion:o,...c>0?{perRequestFeeCents:c}:{}},...p}}function Zc(e,t,n,r,s,o){let i=o?.maxOutputTokens??ki,{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: ${Qc}); 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:`${Im}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:Mm(r,i),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...c}}var el=[ye("fal-flux-pro-ultra","FLUX Pro Ultra","Highest quality image generation. Best for detailed, photorealistic images.","fal-ai/flux-pro/v1.1-ultra","image",6,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},{tags:["image","flux","photorealistic","high-quality"]}),ye("fal-flux-pro","FLUX Pro","Fast, high-quality image generation. Good balance of speed and quality.","fal-ai/flux-pro/v1.1","image",4,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},{tags:["image","flux","fast"],buildBody:Ti}),ye("fal-flux-dev","FLUX Dev","Open-source image generation. Cheaper, good for experimentation.","fal-ai/flux/dev","image",3,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["image","flux","open-source","cheap"],buildBody:Ti}),ye("fal-flux-schnell","FLUX Schnell","Fastest image generation. Ultra-cheap, great for drafts and iteration.","fal-ai/flux/schnell","image",1,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["image","flux","fast","cheap","draft"],buildBody:Ti}),ye("fal-recraft-v3","Recraft V3","Design-focused image generation. Great for illustrations, icons, and graphic design.","fal-ai/recraft/v3/text-to-image","image",5,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},style:{type:"string",description:"Style preset: realistic_image, digital_illustration, vector_illustration, icon"}},required:["prompt"]},{tags:["image","design","illustration","icon","vector"]}),Zc("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),Zc("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}}),Zc("or-gemini-nano-banana-pro","Nano Banana Pro","Google Gemini 3 Pro Image Preview via OpenRouter for professional image generation, edits, and text rendering.","google/gemini-3-pro-image-preview",8,{tags:["image","gemini","google","nano-banana","pro","text-rendering"],tokenPricing:{inputPerMillion:2,outputPerMillion:12}}),ye("fal-ideogram-v2","Ideogram V2","Excellent text rendering in images. Best for logos, posters, and text-heavy visuals.","fal-ai/ideogram/v2","image",8,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"1:1"}},required:["prompt"]},{tags:["image","text-rendering","logo","poster","typography"]}),ye("fal-ideogram-v2-turbo","Ideogram V2 Turbo","Fast text rendering in images. Good balance of speed and text accuracy.","fal-ai/ideogram/v2/turbo","image",5,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"1:1"}},required:["prompt"]},{tags:["image","text-rendering","fast"]}),ye("fal-fast-sdxl","Fast SDXL","Ultra-fast Stable Diffusion. 4-step inference, cheapest option.","fal-ai/fast-sdxl","image",1,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"}},required:["prompt"]},{tags:["image","stable-diffusion","fast","cheap"]}),ye("fal-wan-video","Wan Video","Text-to-video generation. Create short video clips from text descriptions.","fal-ai/wan/v2.1/1.3b/text-to-video","video",10,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"},num_frames:{type:"number",description:"Number of frames (default: 81)"}},required:["prompt"]},{tags:["video","text-to-video","wan"]}),ye("fal-minimax-video","MiniMax Video","High-quality video generation with excellent motion and coherence.","fal-ai/minimax-video/video-01-live","video",15,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"}},required:["prompt"]},{tags:["video","text-to-video","high-quality"]}),ye("fal-kling-video","Kling Video","Professional video generation with cinematic quality.","fal-ai/kling-video/v2/master/text-to-video","video",20,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"},duration:{type:"string",description:"Duration: 5 or 10 seconds",default:"5"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["video","text-to-video","cinematic","professional"]}),ye("fal-kling-i2v","Kling Image-to-Video","Animate a still image into a 5\u201310s video clip. Cinematic motion quality.","fal-ai/kling-video/v1.6/standard/image-to-video","video",35,{type:"object",properties:{image_url:{type:"string",description:"URL of the source image (jpg, png, webp, gif, avif)"},prompt:{type:"string",description:"Text description of the motion to animate"},duration:{type:"string",description:"Duration: 5 or 10 seconds",default:"5"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 9:16, 1:1)",default:"16:9"},negative_prompt:{type:"string",description:"Elements to avoid in the generated motion"},cfg_scale:{type:"number",description:"Classifier-free guidance (default 0.5)",default:.5}},required:["image_url","prompt"]},{tags:["video","image-to-video","kling","cinematic"]}),ye("fal-stable-audio","Stable Audio","Generate sound effects and ambient audio from text descriptions.","fal-ai/stable-audio","audio",4,{type:"object",properties:{prompt:{type:"string",description:"Description of the audio to generate"},seconds_total:{type:"number",description:"Duration in seconds (max 47)",default:30}},required:["prompt"]},{tags:["audio","sound-effects","ambient"]}),ye("fal-ace-step-music","ACE-Step Music","Generate full music tracks from a prompt, with optional vocals or instrumentals.","fal-ai/ace-step/prompt-to-audio","audio",2,{type:"object",properties:{prompt:{type:"string",description:"Description of the song, genre, mood, instruments, and lyrics direction"},instrumental:{type:"boolean",description:"Generate instrumental music without vocals",default:!1},duration:{type:"number",description:"Duration in seconds",default:60}},required:["prompt"]},{tags:["music","song","vocals","instrumental","ace-step"]}),Kv("suno-music","Suno Music","AI music generation. Create full songs with vocals or instrumentals.","/suno/generate-music","audio",10,{type:"object",properties:{prompt:{type:"string",description:"Description of the song (genre, mood, instruments)"},instrumental:{type:"boolean",description:"Instrumental only, no vocals",default:!1}},required:["prompt"]},{isAsync:!0,pollUrl:"https://api.sunoapi.org/suno/get-music-status",deprecated:!0,tags:["music","song","vocals","instrumental"],buildBody:e=>{let{attestation:t,tool_id:n,prompt:r,instrumental:s,...o}=e;return{prompt:r,customMode:!1,instrumental:typeof s=="boolean"?s:!1,model:"V4",...o}}}),ye("fal-trellis-3d","Trellis 3D","Generate 3D models from images. Upload a photo, get a 3D asset.","fal-ai/trellis","3d",8,{type:"object",properties:{image_url:{type:"string",description:"URL of the image to convert to 3D"}},required:["image_url"]},{tags:["3d","model","image-to-3d"]}),ye("fal-aura-sr","Aura SR","Upscale images to higher resolution. 4x upscaling with detail enhancement.","fal-ai/aura-sr","upscale",3,{type:"object",properties:{image_url:{type:"string",description:"URL of the image to upscale"}},required:["image_url"]},{tags:["upscale","super-resolution","enhance"]}),ye("fal-metavoice","MetaVoice Voice Cloning","Voice cloning TTS \u2014 clone any voice from an audio sample. Provide text and a voice sample URL.","fal-ai/metavoice-v1","tts",3,{type:"object",properties:{text:{type:"string",description:"Text to convert to speech"},audio_url:{type:"string",description:"URL of the voice sample to clone"}},required:["text","audio_url"]},{tags:["tts","voice","voice-cloning","speech"]}),ye("fal-whisper","Whisper Transcription","Transcribe audio to text. Supports multiple languages.","fal-ai/whisper","transcription",2,{type:"object",properties:{audio_url:{type:"string",description:"URL of the audio to transcribe"},language:{type:"string",description:"Language code (e.g. en, es, fr)"}},required:["audio_url"]},{tags:["transcription","speech-to-text","whisper"]}),ue("or-gpt-4o","GPT-4o","OpenAI's flagship multimodal model. Best for complex reasoning and analysis.","openai/gpt-4o",2.5,10,{tags:["llm","gpt","openai","multimodal","reasoning"]}),ue("or-gpt-55","GPT-5.5","OpenAI frontier model for complex professional reasoning, coding, and long-context analysis.","openai/gpt-5.5",5,30,{tags:["llm","gpt","openai","frontier","reasoning","coding","long-context"]}),ue("or-gpt-55-pro","GPT-5.5 Pro","OpenAI high-capability frontier model optimized for deep reasoning and high-stakes workloads.","openai/gpt-5.5-pro",30,180,{tags:["llm","gpt","openai","frontier","pro","deep-reasoning","coding","long-context"]}),ue("or-gpt-4o-mini","GPT-4o Mini","Fast, affordable GPT-4o. Great for everyday tasks, chat, and simple analysis.","openai/gpt-4o-mini",.15,.6,{tags:["llm","gpt","openai","fast","cheap"]}),ue("or-claude-opus","Claude Opus 4.7","Anthropic's most capable model. 1M context, reasoning, best for complex tasks.","anthropic/claude-opus-4.7",15,75,{tags:["llm","claude","anthropic","reasoning","coding"]}),ue("or-claude-sonnet","Claude Sonnet 4.6","Anthropic's best balance of intelligence and speed. Excellent for coding and analysis.","anthropic/claude-sonnet-4.6",3,15,{tags:["llm","claude","anthropic","coding","analysis"]}),ue("or-claude-opus-fast","Claude Opus 4.6 Fast","Fast Opus variant with lower latency.","anthropic/claude-opus-4.6-fast",15,75,{tags:["llm","claude","anthropic","fast"]}),ue("or-claude-haiku","Claude 3.5 Haiku","Anthropic's fastest model. Great for quick tasks, chat, and simple reasoning.","anthropic/claude-3.5-haiku",.8,4,{tags:["llm","claude","anthropic","fast"]}),ue("or-gemini-pro","Gemini 2.0 Flash","Google's fast multimodal model. Good for general tasks with long context.","google/gemini-2.0-flash-001",.1,.4,{tags:["llm","gemini","google","multimodal","fast","cheap"]}),ue("or-gemini-3-flash","Gemini 3 Flash","Google's high-speed thinking model for agentic workflows, coding, and multimodal tasks.","google/gemini-3-flash-preview",.5,3,{tags:["llm","gemini","google","agentic","coding","fast"]}),ue("or-gemini-3-pro","Gemini 3 Pro","Google's flagship frontier model for deep reasoning, multimodal analysis, and agentic coding.","google/gemini-3-pro-preview",2,12,{tags:["llm","gemini","google","reasoning","coding","multimodal"]}),ue("or-gemini-35-flash","Gemini 3.5 Flash","Google frontier Flash model for multimodal reasoning, coding, and parallel agentic workflows.","google/gemini-3.5-flash",1.5,9,{tags:["llm","gemini","google","frontier","multimodal","reasoning","coding","fast"]}),ue("or-gemini-3-lite","Gemini 3.1 Flash Lite","Google's efficient multimodal model optimized for low-latency, high-volume agent workloads.","google/gemini-3.1-flash-lite",.25,1.5,{tags:["llm","gemini","google","fast","cheap","multimodal"]}),ue("or-llama-70b","Llama 3.3 70B","Meta's best open model. Strong reasoning, fully open-source.","meta-llama/llama-3.3-70b-instruct",.3,.4,{tags:["llm","llama","meta","open-source","reasoning"]}),ue("or-llama-8b","Llama 3.1 8B","Fast, lightweight open model. Great for simple tasks at minimal cost.","meta-llama/llama-3.1-8b-instruct",.05,.08,{tags:["llm","llama","meta","open-source","fast","cheap"]}),ue("or-mistral-large","Mistral Large","Mistral's flagship model. Strong at multilingual and European languages.","mistralai/mistral-large-2411",2,6,{tags:["llm","mistral","multilingual","european"]}),ue("or-mistral-small","Mistral Small","Fast, efficient Mistral model. Good for everyday tasks.","mistralai/mistral-small-3.1-24b-instruct",.1,.3,{tags:["llm","mistral","fast","cheap"]}),ue("or-deepseek-chat","DeepSeek Chat V3","Strong reasoning model at very low cost. Excellent for coding and math.","deepseek/deepseek-chat-v3-0324",.3,.88,{tags:["llm","deepseek","coding","math","cheap","reasoning"]}),ue("or-deepseek-r1","DeepSeek R1","Advanced reasoning model with chain-of-thought. Best for complex problems.","deepseek/deepseek-r1",.55,2.19,{tags:["llm","deepseek","reasoning","chain-of-thought","math"]}),ue("or-qwen-72b","Qwen 2.5 72B","Alibaba's large model. Strong at coding, math, and multilingual tasks.","qwen/qwen-2.5-72b-instruct",.3,.4,{tags:["llm","qwen","alibaba","coding","multilingual"]}),ue("or-phi-4","Phi-4","Microsoft's compact reasoning model. Punches above its weight for size.","microsoft/phi-4",.07,.14,{tags:["llm","phi","microsoft","compact","cheap","reasoning"]}),ue("or-perplexity-sonar","Perplexity Sonar","Search-augmented LLM. Answers with real-time web sources and citations.","perplexity/sonar",1,1,{perRequestFeeCents:.5,tags:["llm","perplexity","search","web","citations","real-time"]}),{dispatch:"enveloped",id:"query_onchain_prices",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly and daily granularity.",provider:"allium",model:"allium-prices",category:"onchain",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly) or '1d' (daily). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",internal:!0,executionKind:"x402_gateway",resultKind:"utility",gatewayConfig:{enabled:!1,gatewayPath:"/gateway",method:"POST",timeoutMs:3e4},buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:Em,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:Vv,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=>Ti({prompt:e.prompt,aspect_ratio:e.aspect_ratio}),tags:["image","flux","legacy"]},{dispatch:"enveloped",id:"generate_image_schnell_card",name:"Generate Image (Cheap)",description:"Cheap, fast FLUX image generation (~$0.01).",provider:"fal",model:"fal-ai/flux/schnell",category:"image",priceCents:1,inputSchema:{type:"object",properties:{prompt:{type:"string"},image_size:{type:"string"},num_inference_steps:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux/schnell",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-schnell",buildBody:e=>{let t={prompt:e.prompt};return e.image_size&&(t.image_size=e.image_size),e.num_inference_steps!==void 0&&(t.num_inference_steps=e.num_inference_steps),e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","flux","schnell","legacy"]},{dispatch:"enveloped",id:"generate_image_recraft_card",name:"Generate Image (Recraft)",description:"Recraft V3 image generation with style control.",provider:"fal",model:"fal-ai/recraft-v3",category:"image",priceCents:5,inputSchema:{type:"object",properties:{prompt:{type:"string"},style:{type:"string"},image_size:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/recraft-v3",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-recraft-v3",buildBody:e=>{let t={prompt:e.prompt};return e.style&&(t.style=e.style),e.image_size&&(t.image_size=e.image_size),t},tags:["image","recraft","legacy"]},{dispatch:"enveloped",id:"generate_image_ideogram_card",name:"Generate Image (Ideogram)",description:"Ideogram V2 image generation, strong with text rendering.",provider:"fal",model:"fal-ai/ideogram/v2",category:"image",priceCents:8,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},style_type:{type:"string"},negative_prompt:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/ideogram/v2",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-ideogram-v2",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.style_type&&(t.style_type=e.style_type),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),t},tags:["image","ideogram","text","legacy"]},ye("upscale_image_card","Upscale Image","Upscale an image using ESRGAN.","fal-ai/esrgan","upscale",2,{type:"object",properties:{image_url:{type:"string"},scale:{type:"number"}},required:["image_url"]},{buildBody:e=>{let t={image_url:e.image_url};return e.scale!==void 0&&(t.scale=e.scale),t},tags:["upscale","esrgan"],deprecated:!0,replacementTool:"fal-aura-sr"}),ye("edit_image_seed_card","Edit Image (SeedEdit)","Inpaint/edit an image with a prompt using SeedEdit.","fal-ai/bytedance/seededit","image",5,{type:"object",properties:{image_url:{type:"string"},prompt:{type:"string"},seed:{type:"number"}},required:["image_url","prompt"]},{buildBody:e=>{let t={image_url:e.image_url,prompt:e.prompt};return e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","edit","inpaint","seededit"],deprecated:!0,replacementTool:"or-gemini-nano-banana"}),{dispatch:"enveloped",id:"generate_video_tempo_card",name:"Generate Video (Grok)",description:"Generate a video from a text prompt using Grok Imagine Video.",provider:"fal",model:"xai/grok-imagine-video/text-to-video",category:"video",priceCents:30,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/xai/grok-imagine-video/text-to-video",merchantName:"Grok Video via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),t},tags:["video","grok","legacy"]},{dispatch:"enveloped",id:"generate_video_kling_card",name:"Generate Video (Kling)",description:"Generate a video using Kling v1.6 (async, ~$0.40).",provider:"fal",model:"fal-ai/kling-video/v1.6/standard/text-to-video",category:"video",priceCents:40,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/kling-video/v1.6/standard/text-to-video",merchantName:"Kling via fal.ai",deprecated:!0,replacementTool:"fal-kling-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","kling","legacy"]},{dispatch:"enveloped",id:"generate_video_wan_card",name:"Generate Video (Wan)",description:"Generate a video using Wan T2V (async, ~$0.25).",provider:"fal",model:"fal-ai/wan/t2v-1.3b",category:"video",priceCents:25,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/wan/t2v-1.3b",merchantName:"Wan T2V via fal.ai",deprecated:!0,replacementTool:"fal-wan-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","wan","legacy"]},{dispatch:"enveloped",id:"generate_video_minimax_card",name:"Generate Video (MiniMax)",description:"Generate a video using MiniMax (async, ~$0.35).",provider:"fal",model:"fal-ai/minimax/video-01",category:"video",priceCents:35,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/minimax/video-01",merchantName:"MiniMax via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","minimax","legacy"]},{id:"check_fal_status",name:"Check fal Async Job Status",description:"Poll an async fal.ai queue job for completion. Free.",provider:"fal",model:"queue-status",category:"image",priceCents:0,inputSchema:{type:"object",properties:{model_path:{type:"string",description:"Model path (e.g. fal-ai/kling-video/v1.6/standard/text-to-video)"},request_id:{type:"string"}},required:["model_path","request_id"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue",merchantName:"fal.ai",handler:{type:"local",fn:"check_fal_status"},pricing:{amount:0,currency:"USD",display:"$0.00",free:!0},freeReadPathPattern:"/api/v1/fal/**/requests/*/(status)?",tags:["status","fal","async"]},{dispatch:"enveloped",id:"generate_3d_card",name:"Generate 3D Model",description:"Generate a 3D mesh from a text prompt using Meshy (async, ~$0.50).",provider:"fal",model:"fal-ai/meshy-ai/text-to-3d",category:"3d",priceCents:50,inputSchema:{type:"object",properties:{object_prompt:{type:"string"},style_prompt:{type:"string"},negative_prompt:{type:"string"},art_style:{type:"string"},seed:{type:"number"}},required:["object_prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/meshy-ai/text-to-3d",merchantName:"Meshy via fal.ai",deprecated:!0,replacementTool:"fal-trellis-3d",buildBody:e=>{let t={object_prompt:e.object_prompt};return e.style_prompt&&(t.style_prompt=e.style_prompt),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.art_style&&(t.art_style=e.art_style),e.seed!==void 0&&(t.seed=e.seed),t},tags:["3d","mesh","meshy","legacy"]},{dispatch:"enveloped",id:"generate_speech_card",name:"Generate Speech",description:"Text-to-speech using F5-TTS with optional voice cloning.",provider:"fal",model:"fal-ai/f5-tts",category:"tts",priceCents:3,inputSchema:{type:"object",properties:{gen_text:{type:"string",description:"Text to synthesize"},ref_audio_url:{type:"string",description:"Reference audio URL (for voice cloning)"},ref_text:{type:"string",description:"Transcription of ref audio"},remove_silence:{type:"boolean"}},required:["gen_text"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/f5-tts",merchantName:"fal.ai",buildBody:e=>{let t={gen_text:e.gen_text};return e.ref_audio_url&&(t.ref_audio_url=e.ref_audio_url),e.ref_text&&(t.ref_text=e.ref_text),e.remove_silence!==void 0&&(t.remove_silence=e.remove_silence),t},deprecated:!0,replacementTool:"fal-metavoice",tags:["tts","speech","f5-tts","legacy"]},{dispatch:"enveloped",id:"generate_music_tempo_card",name:"Generate Music (Suno) \u2014 retired",description:"[Retired] Suno music generation. Use `generate_music` (ACE-Step) instead.",enabled:!1,sunsetAt:"2026-06-25",provider:"suno",model:"suno-v4",category:"audio",priceCents:50,inputSchema:{type:"object",properties:{prompt:{type:"string"},instrumental:{type:"boolean"},model:{type:"string",default:"V4"}},required:["prompt"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/generate-music",merchantName:"Suno via Tempo",buildBody:e=>({prompt:e.prompt,customMode:!1,instrumental:e.instrumental??!1,model:e.model||"V4"}),isAsync:!0,pollUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",pollInterval:15e3,pollTimeout:3e5,deprecated:!0,replacementTool:"fal-ace-step-music",tags:["music","audio","suno","async","legacy"]},{dispatch:"enveloped",id:"check_music_status_tempo_card",name:"Check Music Status (Suno) \u2014 retired",description:"[Retired] Suno status poll. No replacement; ACE-Step jobs poll via `check_fal_status`.",enabled:!1,sunsetAt:"2026-06-25",provider:"suno",model:"suno-status",category:"audio",priceCents:0,inputSchema:{type:"object",properties:{taskId:{type:"string"}},required:["taskId"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",merchantName:"Suno Status",buildBody:e=>({taskId:e.taskId}),deprecated:!0,tags:["music","status","suno","legacy"]},{dispatch:"enveloped",id:"query_onchain_prices_card",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly, daily, and weekly granularity.",provider:"allium",model:"allium-prices",category:"llm",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly), '1d' (daily), or '1w' (weekly). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",deprecated:!0,replacementTool:"query_onchain_prices",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:Em,tags:["onchain","prices","allium","crypto","legacy"]}];function ns(e){return el.find(t=>t.id===e)}var Nm=1,Lm=["pick_one","fan_out"],Um=["concat","dedupe_by_url","top_k_by_score"],Yv=8,zv=_.object({type:_.string().min(1),description:_.string().min(1),enum:_.array(_.string()).optional(),default:_.unknown().optional(),minimum:_.number().optional(),maximum:_.number().optional()}),Jv=_.object({toolId:_.string().min(1),notes:_.string().min(1)}),Xv=_.string().regex(/^[a-z0-9_-]{1,32}$/,"tier key must be 1-32 chars [a-z0-9_-]"),Zv=_.object({providers:_.array(_.string().min(1)).min(1).max(Yv),merge:_.enum(Um),maxResults:_.number().int().positive().optional()}),Dm=_.object({mode:_.enum(Lm).default("pick_one"),intro:_.string().min(1),defaultTier:_.string().min(1),tiers:_.record(Xv,Jv).refine(e=>Object.keys(e).length>0,{message:"must have at least one tier"}),fanOut:Zv.optional(),guidance:_.string().min(1),inputProperties:_.record(_.string(),zv),required:_.array(_.string())}).refine(e=>e.tiers[e.defaultTier]!==void 0,{message:"defaultTier must exist in tiers",path:["defaultTier"]}).refine(e=>e.mode!=="fan_out"||e.fanOut!==void 0,{message:"fan_out mode requires fanOut config",path:["fanOut"]}).refine(e=>e.required.every(t=>t in e.inputProperties),{message:"required entries must exist in inputProperties",path:["required"]}),Qv=_.object({version:_.literal(Nm),generatedAt:_.string().datetime(),tools:_.record(_.string().regex(Xc,"tool name must match MCP naming rules"),Dm).refine(e=>Object.keys(e).length>0,{message:"manifest must have at least one tool"})});var Aa=R(ss());var Ii=require("child_process"),Zm=require("util"),Qm=R(require("crypto")),ne=R(require("fs")),ep=R(require("os")),$e=R(require("path"));bt();var it=(0,Zm.promisify)(Ii.execFile),Aw=6e4,Ew=()=>process.platform==="darwin",kn=()=>process.platform==="win32",Cn=$e.join(ep.homedir(),".visa-mcp","bin"),yr=$e.join(Cn,"Visa CLI"),Jt=$e.join(Cn,"visa-keychain-win.exe"),tp=$e.join(__dirname,"..","native"),Vm="6",qm=$e.join(Cn,"visa-keychain.version"),Km=$e.join(Cn,"visa-keychain.sha256"),Gm="1",Wm=$e.join(Cn,"visa-keychain-win.version"),Ym=$e.join(Cn,"visa-keychain-win.sha256"),np=[$e.join(tp,"bin","win32-x64","visa-keychain-win.exe"),$e.resolve(__dirname,"..","..","native","bin","win32-x64","visa-keychain-win.exe"),$e.resolve(__dirname,"..","native","bin","win32-x64","visa-keychain-win.exe")];function Ai(e){let t=ne.readFileSync(e);return Qm.createHash("sha256").update(t).digest("hex")}function Rw(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 zm(e){let t=typeof e?.message=="string"?e.message:"";return e?.code==="ETIMEDOUT"||e?.killed===!0||/timed out|timeout/i.test(t)}function Jm(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 tl(){try{if(ne.readFileSync(qm,"utf-8").trim()===Vm&&ne.existsSync(yr)){let r=ne.readFileSync(Km,"utf-8").trim();if(Ai(yr)!==r)g.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),ne.unlinkSync(yr);else return yr}}catch{}let e=$e.join(tp,"visa-keychain.m");if(ne.existsSync(e)||(e=$e.resolve(__dirname,"..","..","native","visa-keychain.m")),ne.existsSync(e)||(e=$e.resolve(__dirname,"..","native","visa-keychain.m")),!ne.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");ne.mkdirSync(Cn,{recursive:!0,mode:448});try{await it("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",yr,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=Ai(yr);return ne.writeFileSync(Km,t,{mode:384}),ne.writeFileSync(qm,Vm,{mode:384}),yr}function rp(){for(let e of np)if(ne.existsSync(e))return e;return null}async function os(){try{if(ne.readFileSync(Wm,"utf-8").trim()===Gm&&ne.existsSync(Jt)){let r=ne.readFileSync(Ym,"utf-8").trim();if(Ai(Jt)!==r)g.warn("binary:hash-mismatch:win32",{message:"Windows binary hash mismatch. Redeploying."}),ne.unlinkSync(Jt);else return Jt}}catch{}let e=rp();if(!e)throw new Error(`visa-keychain-win.exe not found in package. Reinstall @visa/cli.
142
+ If building from source, run native/build-win.bat first.`);ne.mkdirSync(Cn,{recursive:!0}),ne.copyFileSync(e,Jt);let t=Ai(Jt);return ne.writeFileSync(Ym,t,{mode:384}),ne.writeFileSync(Wm,Gm,{mode:384}),Jt}async function Iw(){return kn()?os():tl()}var Ei="visa-cli",Ri="attestation-key";async function $w(e){try{await it("security",["delete-generic-password","-s",Ei,"-a",Ri],{timeout:5e3})}catch{}await it("security",["add-generic-password","-s",Ei,"-a",Ri,"-w",e],{timeout:5e3})}function Pw(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 Ow(){try{let{stdout:e}=await it("security",["find-generic-password","-s",Ei,"-a",Ri,"-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:Pw(e)}}}async function nl(){let e=await Ow();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 sp(e){let t=await Iw(),n;try{n=(await it(t,e,{timeout:6e4})).stdout}catch(r){n=r.stdout||"";let s=n.trim();throw s.startsWith("ERROR:")?new Error(s.slice(6)):new Error(r.stderr?.trim()||r.message||"Unknown error")}return Rw(n)}var Xm=!1;function Mw(){if(!kn())return!1;try{return ne.existsSync(Jt)||rp()!==null?!0:(Xm||(Xm=!0,g.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:Jt,searchedPrebuiltPaths:np})),!1)}catch{return!1}}function de(){return Dr()||Ew()?!0:kn()?Mw():!1}async function $i(){if(kn()){let s=await os(),{stdout:o}=await it(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 sp(["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 $w(n),r}async function Pi(){if(kn())try{let e=await os(),{stdout:t}=await it(e,["public-key"],{timeout:1e4});return t.trim().startsWith("OK:")}catch{return!1}return await nl()!==null}async function op(){if(Dr())return"mock-public-key-spki";if(kn()){let n=await os(),{stdout:r}=await it(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 nl();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await tl();return new Promise((n,r)=>{let s=(0,Ii.execFile)(t,["public-key"],{timeout:6e4},(o,i)=>{let a=(i||"").trim();if(o){a.startsWith("ERROR:")?r(new Error(a.slice(6))):r(new Error(o.stderr?.trim()||o.message||"Unknown error"));return}a.startsWith("OK:")?n(a.slice(3)):r(new Error(a.startsWith("ERROR:")?a.slice(6):"Unknown error"))});s.stdin.write(e),s.stdin.end()})}async function An(e,t,n={}){if(Dr())return Promise.resolve(pd());let r=n.timeoutMs??Aw;if(kn()){let a=await os(),c=["sign",e];t&&c.push(t);let l;try{l=(await it(a,c,{timeout:r})).stdout}catch(d){throw zm(d)?Jm(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 nl();if(!s)throw new Error("Attestation key not found. Run setup to generate a new key.");let o=await tl(),i=["sign",e];return t&&i.push(t),new Promise((a,c)=>{let l=(0,Ii.execFile)(o,i,{timeout:r},(u,d)=>{let m=(d||"").trim();if(u){m.startsWith("ERROR:")?c(new Error(m.slice(6))):zm(u)?c(Jm(r)):c(new Error(u.stderr?.trim()||u.message||"Unknown error"));return}m.startsWith("OK:")?a(m.slice(3)):c(new Error(m.startsWith("ERROR:")?m.slice(6):"Unknown error"))});l.stdin.write(s),l.stdin.end()})}async function Oi(){if(kn()){try{let e=await os();await it(e,["delete-key"],{timeout:1e4})}catch{}return}try{await it("security",["delete-generic-password","-s",Ei,"-a",Ri],{timeout:5e3})}catch{}try{await sp(["delete-key"])}catch{}}bt();var Nw=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],Lw=[...Nw.map(e=>({id:`legacy.${e}`,match:{kind:"exact_tool",toolId:e},targetToolId:e,rail:"tempo",reason:"Preserve legacy Tempo _card target while the top-level MCP surface is opt-in."}))];function sl(e,t=Lw){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=rl(e.intentText);for(let r of t)if(r.match.kind==="intent"&&r.match.metaTool===e.metaTool&&!(r.match.tier&&r.match.tier!==e.tier)&&!(r.match.provider&&!n.includes(rl(r.match.provider)))&&r.match.keywords.every(s=>n.includes(rl(s))))return r.targetToolId;return null}function rl(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}bt();Vt();var oo={generate_image:{intro:'Generate an AI image from a text prompt \u2014 useful for hero shots, marketing assets, social posts, blog covers, app mockups, or any time the user asks for art, a logo, an icon, a thumbnail, or "a picture of \u2026". From $0.01 (fast) to $0.06 (pro), returns a hosted PNG/JPG URL. Default tier: balanced ($0.04, 1K, ~10s).',tiers:{balanced:{toolId:"fal-flux-pro",notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",notes:"Recraft V3 \u2014 vector/flat/illustration styles"}},guidance:"If the user didn't specify a tier, pick 'balanced' unless the prompt clearly signals otherwise (text \u2192 text_heavy, logo/icon \u2192 vector, quick test \u2192 fast, hero/print \u2192 pro).",inputProperties:{prompt:{type:"string",description:"Text description of the image to generate."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9", "1:1", "9:16".',default:"16:9"}},required:["prompt"]},generate_video:{intro:'Generate a short AI video from a text prompt \u2014 useful for product demos, social clips, mood reels, ad concepts, or any "make me a video of \u2026" request. $0.10\u2013$0.40 per ~6s clip depending on tier. Async: returns a request_id; use execute_tool with tool_id "check_fal_status" to resolve it (60\u2013180s).',tiers:{balanced:{toolId:"fal-minimax-video",notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",notes:"Kling \u2014 highest quality, cinematic"}},guidance:'Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate and are processed asynchronously. The response includes a request_id and model_path. Poll with execute_tool using tool_id "check_fal_status" and the exact request_id/model_path returned by the async response. Do not substitute the catalog model path manually. Do not poll more than once per 30 seconds.',inputProperties:{prompt:{type:"string",description:"Text description of the video scene."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9" or "9:16".',default:"16:9"}},required:["prompt"]},generate_music:{intro:'Generate an original music track from a prompt via ACE-Step. ~$0.02 for the default 60s track. Use for songs, backing tracks, jingles, vocal music, instrumental music, or any "make a song/music/track" request. Takes ~60-90s and may return a request_id to poll with check_fal_status. For SFX, chimes, ambient beds, or TTS, use generate_audio instead.',tiers:{ace_step:{toolId:"fal-ace-step-music",notes:"ACE-Step \u2014 prompt-to-music with vocals or instrumentals"}},guidance:"Use for songs and music tracks. Takes ~60-90s and may return a request_id to poll with check_fal_status. For sound effects, chimes, ambient beds, or TTS, use generate_audio instead.",inputProperties:{prompt:{type:"string",description:"Musical style, mood, instruments, subject, and lyrics direction."},instrumental:{type:"boolean",description:"True for instrumental music with no vocals; false for vocal tracks.",default:!1},duration:{type:"number",description:"Duration in seconds.",default:60}},required:["prompt"]},generate_audio:{intro:'Generate sound effects from a text prompt (sfx tier \u2014 default), or voice-cloned speech from text + a reference audio URL (tts tier). $0.03\u2013$0.04. Use for SFX, chimes, UI sounds, ambient audio (default sfx), or voice cloning when a reference audio URL is available (pass tier:"tts"). Default tier is sfx; pass tier:"tts" for voice cloning.',tiers:{sfx:{toolId:"fal-stable-audio",notes:"Stable Audio \u2014 sound effects and ambient from a prompt"},tts:{toolId:"fal-metavoice",notes:"MetaVoice \u2014 voice cloning TTS (requires a voice sample URL)"}},guidance:'Default tier is sfx: pass prompt describing the sound. For tts (voice cloning): pass tier:"tts" + text + audio_url.',inputProperties:{prompt:{type:"string",description:"Description of sound to generate (sfx tier, default)."},text:{type:"string",description:"Text to speak aloud (tts tier)."},audio_url:{type:"string",description:"URL of a voice sample to clone (tts tier, required for voice cloning)."}},required:[]},generate_3d:{intro:"Generate a 3D mesh (GLB) from an image URL via Trellis. ~$0.08, ~30\u201360s. Use when the user shares an image and asks for a 3D model, asset, AR-ready mesh, or game-ready GLB.",tiers:{trellis:{toolId:"fal-trellis-3d",notes:"Trellis \u2014 image-to-3D, returns a GLB mesh URL"}},guidance:"Pass an image URL. Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{image_url:{type:"string",description:"URL of the image to convert to a 3D model."}},required:["image_url"]},upscale_image:{intro:'Upscale an image to 4\xD7 resolution via Aura SR (preserves detail without hallucination). ~$0.03. Use whenever the user shares a low-res image and asks to "upscale", "make this higher resolution", "4x this", "enhance", or to print/export at larger size.',tiers:{aura:{toolId:"fal-aura-sr",notes:"Aura SR \u2014 default; preserves detail without hallucination"}},guidance:"Pass the existing image URL. Returns an upscaled version.",inputProperties:{image_url:{type:"string",description:"URL of the image to upscale."}},required:["image_url"]},transcribe_audio:{intro:'Transcribe speech in an audio or video file (URL) to text via OpenAI Whisper. ~$0.02 per file, multilingual, handles long files. Use whenever the user asks to "transcribe this", "what does this audio say", "make subtitles", "convert this to text", or shares an audio/video URL with no other clear intent.',tiers:{whisper:{toolId:"fal-whisper",notes:"OpenAI Whisper \u2014 fast, multilingual"}},guidance:"Pass the URL. Returns the transcript text.",inputProperties:{audio_url:{type:"string",description:"URL of the audio or video file to transcribe."}},required:["audio_url"]},run_llm:{intro:"Run a text prompt through a different LLM (GPT-4o-mini, Claude Sonnet, DeepSeek R1/V3, Perplexity Sonar with web search, or Llama 70B). Token-metered, typically ~$0.01\u2013$0.10 per call. Use for: web-grounded answers (search tier), second-opinion reasoning (reasoning tier), code generation in a different family (coding tier), deep math/logic (deep_reasoning tier), or fast cheap text cleanup (fast tier). Pair with batch for multi-model councils.",tiers:{fast:{toolId:"or-gpt-4o-mini",notes:"GPT-4o Mini. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",notes:"Claude Sonnet. Strong reasoning, long-context. Warn user it is materially pricier than `fast`."},frontier_openai:{toolId:"or-gpt-55",notes:"GPT-5.5. OpenAI frontier model for complex professional reasoning."},frontier_openai_pro:{toolId:"or-gpt-55-pro",notes:"GPT-5.5 Pro. Highest-capability OpenAI frontier tier; materially more expensive."},frontier_anthropic:{toolId:"or-claude-opus",notes:"Claude Opus 4.7. Anthropic frontier model for complex tasks."},frontier_google:{toolId:"or-gemini-35-flash",notes:"Gemini 3.5 Flash. Google frontier Flash model for multimodal reasoning and coding."},deep_reasoning:{toolId:"or-deepseek-r1",notes:"DeepSeek R1. Deep chain-of-thought reasoning, mid-range pricing."},search:{toolId:"or-perplexity-sonar",notes:"Perplexity Sonar. Search-augmented, web-grounded with citations."},open_source:{toolId:"or-llama-70b",notes:"Llama 3.3 70B. Open-source large model."},coding:{toolId:"or-deepseek-chat",notes:"DeepSeek Chat V3. Strong at code generation."}},guidance:"Pick based on the user's need: fast (most questions, cheapest), reasoning (complex analysis; warn user it is materially pricier than fast), frontier_* (top-model council / highest quality; warn user these are materially pricier), search (questions about current events), coding (code generation), deep_reasoning (hard math/logic problems).",inputProperties:{prompt:{type:"string",description:"The user query."},system_prompt:{type:"string",description:"Optional system prompt to set model behavior."},max_tokens:{type:"number",description:"Maximum output tokens.",default:1024,minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature \u2014 0 is deterministic, higher is more creative.",default:.7,minimum:0,maximum:2}},required:["prompt"]}};function En(e,t,n){if(!ap(e))return Bw(e,n);let r=ip[e];if(!r)return e;let s=Object.keys(r.tiers),o=t||s[0],i=Fw(e,o,n);return i||Hw(e,r,o,s)}function Bw(e,t){return sl({requestedTool:e,intentText:t})??e}function Fw(e,t,n){return sl({requestedTool:e,metaTool:e,tier:t,intentText:n})}function Hw(e,t,n,r){let s=t.tiers[n];if(!s)throw new Error(`Unknown tier '${n}' for ${e}. Valid tiers: ${r.join(", ")}`);return s.toolId}var ip=oo;function ap(e){return e in ip}var io=Object.keys(oo);function ol(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function cp(e=process.env){return ol(e)!==null}var Vw=new Set(["false","0","no","off","disable","disabled"]),qw=new Set(["true","1","yes","on","enable","enabled"]);function lp(e){let t=(e??"").trim().toLowerCase();return t?Vw.has(t)?!1:!!qw.has(t):!0}function up(e=process.env){return lp(e.VISA_CLI_PARENTLESS_SINGLE_CALL)}function dp(e=process.env){return lp(e.VISA_CLI_PARENTLESS_BATCH)}var Kh=require("child_process"),Se=R(require("crypto")),ut=R(require("fs")),ko=R(require("os")),Ea=R(require("path"));function Tt(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"?jr(s):null,i=Array.isArray(n.urls)?n.urls[0]:void 0,c=typeof i=="string"&&i.startsWith("data:")?jr(i):null;if(!o&&!c)return e;let l=o??c,u=o?"content":"urls",d;try{d=Ms(l,{tag:Kw(r,n)})}catch(f){return{...n,_inline_media_warning:`Failed to persist inline media to disk: ${f instanceof Error?f.message:String(f)}`}}let m={...n,filePath:d.filePath,mime:d.mime,bytes:d.bytes};return u==="urls"?m.urls=void 0:(m.content=Array.isArray(n.content)?[...n.content]:[{}],m.content[0]={...m.content[0]??{},text:`[inline media saved to ${d.filePath}]`}),m}function Kw(e,t){let n=typeof t.transactionId=="string"?t.transactionId:typeof t.transaction_id=="string"?t.transaction_id:null;return n?`${e}-${n}`:e}bt();var il=!1;async function _r(e,t,n){try{return await t()}catch(r){if(!(r.message==="Invalid signature"||r.code==="ATTESTATION_KEY_DRIFT"||r.error_code==="ATTESTATION_KEY_DRIFT"||r.name==="AttestationDriftError")||!de())throw r;if(g.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(il)throw g.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;il=!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 $i();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 il=!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 Mi(e,t){if(!de())return{ok:!1,code:"TOUCH_ID_UNAVAILABLE",message:"Touch ID is not available in this process. Run `visa-cli setup` from an interactive macOS terminal before enabling Touch ID."};if(!await Pi())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."}}Vt();var fp="3.4.0-rc.5";function al(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function Ni(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=hi(t);return s!==void 0?{value:s,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function qe(e){return e==null?"\u2014":e?"yes":"no"}function Li(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function Gw(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function Ww(){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=jc("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:Uc,source:{kind:"default"}}}async function ao(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(y){n=y?.message||"unknown error"}let r=[],s=process.env.VISA_AUTH_URL,o=Dc("auth.serverUrl"),i=Ue(),a=s!==void 0&&s!==""?{kind:"env",var:"VISA_AUTH_URL"}:o!==void 0?{kind:"settings"}:{kind:"default"};r.push({key:"auth.serverUrl",value:i,formatted:i,source:a,hint:a.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),r.push({key:"account.enrolled",value:t?.enrolled??null,formatted:qe(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),t?.githubUser&&r.push({key:"account.githubUser",value:t.githubUser,formatted:t.githubUser,source:{kind:"server"}}),t?.userId&&r.push({key:"account.userId",value:t.userId,formatted:t.userId,source:{kind:"server"},hint:"Opaque stable account id used for account-scoped local credentials."});let c=t?t.attestationRequired!==!1:void 0;r.push({key:"biometric.required",value:c,formatted:qe(c),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"},hint:c===!1?"Touch ID prompts are suppressed. Re-enable with `visa-cli config biometric on`.":void 0}),r.push({key:"biometric.keyRegistered",value:t?.hasAttestationKey??null,formatted:qe(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:de(),formatted:qe(de()),source:{kind:"device"}});let l=t?.spendingControls,u=l?l.max_transaction_amount??l.maxTransactionAmount??null:null,d=l?l.daily_limit??l.dailyLimit??null:null;r.push({key:"spending.maxPerTxn",value:u,formatted:Li(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:Li(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:Li(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:Li(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 m=t?.cards?.find(y=>y.isDefault)??t?.cards?.[0];m&&r.push({key:"cards.default",value:{brand:m.brand??null,last4:m.last4},formatted:`${m.brand||"card"} \u2022\u2022\u2022\u2022 ${m.last4}`,source:{kind:"server"}});let f=Ww();r.push({key:"credit.sessionCapCents",value:f.value,formatted:Gw(f.value),source:f.source});let p=zf();p.length>0&&r.push({key:"settings.retired",value:p.map(y=>y.key),formatted:p.map(y=>y.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${p.map(y=>`visa-cli config unset ${y.key}`).join(" && ")}`});let h=Ni("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:h.value,formatted:qe(h.value),source:h.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let w=Ni("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:w.value,formatted:qe(w.value),source:w.source});let k=vt(),b;process.env.VISA_CLI_NO_UPDATE_CHECK?b={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?b={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?b={kind:"env",var:"NODE_ENV"}:b={kind:"default"},r.push({key:"ui.updateCheck",value:!k,formatted:qe(!k),source:b});let v=Ni("VISA_META_TOOLS","tools.meta","opt-in");r.push({key:"tools.meta",value:v.value,formatted:qe(v.value),source:v.source,hint:"Meta-tools are deprecated and off by default. Re-enable with `visa-cli config set tools.meta true`. Restart Claude Code for changes to take effect."});let S=Ni("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:S.value,formatted:qe(S.value),source:S.source});let E=process.env.VISA_DRY_RUN,I=cp();if(r.push({key:"tools.dryRun",value:I,formatted:qe(I),source:E===void 0?{kind:"default"}:{kind:"env",var:"VISA_DRY_RUN"},hint:"VISA_DRY_RUN=true|1|mock returns deterministic paid-tool fixtures (no card, no upstream). VISA_DRY_RUN=preflight makes a real zero-cost OpenRouter call for LLM tools (image/video still mocked)."}),r.push({key:"client.version",value:fp,formatted:fp,source:{kind:"default"}}),e.includeDev){let y=process.env.VISA_MOCK_KEYCHAIN,T=ln();r.push({key:"dev.mockKeychain",value:T,formatted:qe(T),source:al("VISA_MOCK_KEYCHAIN",!!y),hint:Ja()});let z=process.env.VISA_MOCK_TOUCHID,Z=Dr();r.push({key:"dev.mockTouchid",value:Z,formatted:qe(Z),source:al("VISA_MOCK_TOUCHID",!!z),hint:Ja()});let H=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!H,formatted:qe(!!H),source:al("VISA_CLI_DEBUG",!!H)})}return{entries:r,statusError:n}}function Yw(e){switch(e.kind){case"default":return"default";case"env":return`env ${e.var}`;case"settings":return"settings.json";case"server":return"server";case"device":return"device";case"unset":return"unset";case"unknown":return`unknown (${e.reason})`}}function mp(e,t={}){if(e.length===0)return"";let n=Math.max(...e.map(o=>o.key.length)),r=Math.max(...e.map(o=>o.formatted.length)),s=[];for(let o of e){let i=o.key.padEnd(n+2),a=o.formatted.padEnd(r+2);s.push(`${i}${a}(${Yw(o.source)})`),t.verbose&&o.hint&&s.push(` ${"\u21B3".padStart(n)} ${o.hint}`)}return s.join(`
143
+ `)}function pp(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 gp(e){if(e<=0)return null;let t=(e/100).toFixed(2);return{_credits_prompt:{message:`You've got $${t} in free credits \u2014 enough for about ${Math.floor(e/6)} images. Try something now, or save them for later.`,balanceUsd:t,examples:[{tool:"generate_image",cost:"$0.06",what:"an AI image"},{tool:"run_llm",cost:"token-priced",what:"a quick model call"},{tool:"generate_music",cost:"$0.02",what:"a music track"}]}}}Vt();bt();var Rn=require("fs"),yp=require("os"),cl=require("path"),zw=(0,cl.join)((0,yp.homedir)(),".visa-mcp"),hp=(0,cl.join)(zw,"mcp-session-budget.json");function Ui(){try{(0,Rn.existsSync)(hp)&&(0,Rn.unlinkSync)(hp)}catch{}}var ul=require("crypto"),ct=R(ss()),vr=null,Ke=0,$n=0,He=0,In=null,dl=null,fl=null,br=Promise.resolve();function Jw(e){return Number((0,ct.fromCents)(e))}function bp(e){return(0,ct.toCents)((0,ct.micros)(BigInt(e)))}function _p(e){return(0,ct.toWire)((0,ct.fromCents)(e))}function ll(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Di(e){return typeof e=="string"&&/^\d+$/.test(e)}var Xw=43,Zw=new RegExp(`^[A-Za-z0-9_-]{${Xw}}$`);function Qw(e){return typeof e=="string"&&Zw.test(e)}function eS(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||vr&&e.session_id!==vr||typeof e.nonce!="string"||e.nonce.length===0||!Qw(e.server_signature)||!ll(e.cumulative)||!ll(e.remaining)||!ll(e.delta)||e.cumulative<Ke||He>0&&e.cumulative>He||He>0&&e.remaining>He||e.cumulative_micros!==void 0&&!Di(e.cumulative_micros)||e.remaining_micros!==void 0&&!Di(e.remaining_micros)||e.delta_micros!==void 0&&!Di(e.delta_micros)||e.reserved_micros!==void 0&&!Di(e.reserved_micros))}function Xt(e){vr=e,Ke=0,$n=0,He=0,In=null,dl=null,fl=null,br=Promise.resolve()}function co(e){He=Math.max(0,Math.floor(e))}function ml(){return vr}function pl(e){if(!vr)return null;let t=Ke+$n;return He>0&&t>He&&(t=He),{session_budget_id:vr,cumulative_micros:Jw(t),nonce:(0,ul.randomUUID)(),idempotency_key:e||(0,ul.randomUUID)()}}function lo(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 eS(r)?(Ke=Math.max(Ke,r.cumulative),$n=0,In=r,r):null}function vp(){return In}function gl(e){let t=bp(e.cumulative_micros);Ke=Math.max(Ke,t),$n=0;let n={status:"accepted",session_id:e.session_budget_id,cumulative:Ke,remaining:Math.max(0,He-Ke),delta:0,cumulative_micros:_p(Ke),remaining_micros:_p(Math.max(0,He-Ke)),delta_micros:"0",nonce:e.nonce};return In=n,n}function uo(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,ct.toCents)((0,ct.micros)(n));if(!Number.isFinite(r)||r<0)return;dl=t;let s=e,o=typeof s.session_id=="string"?s.session_id:vr??"";In?(typeof s.remaining_micros=="string"&&/^\d+$/.test(s.remaining_micros)&&(In.remaining_micros=s.remaining_micros),typeof s.charged_micros=="string"&&/^\d+$/.test(s.charged_micros)&&(In.delta_micros=s.charged_micros)):In={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 wp(e){let t=e.receipt??null;fl={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:bp(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 Sp(){return fl}function xp(){return Ke}function Tp(){return dl}function ji(){let e=Ke+$n;return He>0&&e>He&&(e=He),e}function hl(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return br=br.then(()=>{$n+=t}),br}function fo(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return br=br.then(()=>{$n=Math.max(0,$n-t)}),br}var tS=10,nS=1,fe=null,kp=Promise.resolve();function yl(e){let t=kp.catch(()=>{}).then(e);return kp=t.then(()=>{},()=>{}),t}var we=class extends Error{balanceCents;minRequiredCents;constructor(t,n){super(`Prepaid balance is $${(t/100).toFixed(2)}; at least $${(n/100).toFixed(2)} required to open a credit session. Top up via the buy_credits tool first.`),this.name="InsufficientBalanceError"}};async function _l(e,t,n){return yl(()=>Cp(e,t,n))}async function Cp(e,t,n){if(Ui(),fe&&new Date(fe.expiresAt).getTime()>Date.now())return ml()!==fe.budgetId&&(Xt(fe.budgetId),co(fe.totalCents)),g.info("mcp-session:active-hit",{budgetId:fe.budgetId,tool:n.toolName,remainingEstimatedCents:fe.totalCents-ji()}),{budgetId:fe.budgetId,isFresh:!1,totalCents:fe.totalCents,requestedCapCents:fe.totalCents,appliedCapCents:fe.totalCents,clampedReason:null};fe&&(fe=null,Xt(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"?nS:tS,i=Math.max(o,Math.ceil(n.minRequiredCents??o));if(r.balanceCents<i)throw new we(r.balanceCents,i);let a=n.capCentsOverride??Zf(),c=Math.min(a,r.balanceCents),l=c<a?"balance":null,u=await t("session_create",c,"Visa CLI Session",`open credit-model session with $${(c/100).toFixed(2)} cap`,n.userContext),d=await e.createSessionBudget({total_cents:c,session_kind:s,...u?{attestation:u}:{}});if(!d.success||!d.budget){let f=d.error||"unknown error";throw new Error(`Failed to open credit session: ${f}`)}let m={budgetId:d.budget.id,expiresAt:d.budget.expiresAt,totalCents:d.budget.totalCents,createdAt:d.budget.createdAt};return fe=m,Xt(m.budgetId),co(m.totalCents),g.info("mcp-session:opened",{budgetId:m.budgetId,capCents:m.totalCents,requestedCapCents:a,clampedReason:l,sessionKind:s,expiresAt:m.expiresAt,tool:n.toolName}),{budgetId:m.budgetId,isFresh:!0,totalCents:m.totalCents,requestedCapCents:a,appliedCapCents:m.totalCents,clampedReason:l}}async function Ap(e,t,n){return yl(async()=>{let s=Pn()?await Ep(e):null,o=await Cp(e,t,n);return{budgetId:o.budgetId,totalCents:o.totalCents,closedPrevious:s,requestedCapCents:o.requestedCapCents,appliedCapCents:o.appliedCapCents,clampedReason:o.clampedReason}})}async function Ep(e){let n=Pn()?.budgetId??ml(),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 Ui(),fe=null,Xt(null),{closedServerSide:r,budgetId:n,finalCumulativeCents:s,finalCumulativeMicros:o}}async function Bi(e){return yl(()=>Ep(e))}function Pn(){return Ui(),fe?new Date(fe.expiresAt).getTime()<=Date.now()?(fe=null,Xt(null),null):{budgetId:fe.budgetId,totalCents:fe.totalCents,lastReceiptCumulative:xp(),lastReceiptCumulativeMicros:vp()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:Tp(),estimatedCumulative:ji(),lastToolSpend:Sp(),expiresAt:fe.expiresAt}:null}var Ip=R(ss()),Rp=10000n;function rS(e){return e<=0n?0:Number((e+Rp-1n)/Rp)}function $p(e){return rS((0,Ip.fromUsd)(e))}var Fi=R(ss()),sS=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;function Hi(e){if(typeof e!="string"||!sS.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,Fi.toDisplay)((0,Fi.fromCents)(s),{symbol:""})}}var Vi="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.",Pp="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.";Vt();var Ph=Promise.resolve();function zT(e,t){if(e)try{let n=(0,Aa.fromWire)(e),r=n%10000n===0n?2:6;return(0,Aa.toDisplay)(n,{decimals:r})}catch{}return`$${(t/100).toFixed(2)}`}var Oh=!1,Mh=!1,Nh=!1;function Ra(e){let t=Ph.catch(()=>{}).then(e);return Ph=t.then(()=>{},()=>{}),t}async function Gh(e){let t=await xe(()=>_l(U,Qe,{toolName:e.toolId,userContext:e.userContext}));await hl(e.estimatedAmountCents);let n=pl(e.idempotencyKey);if(!n)throw await fo(e.estimatedAmountCents),new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await rk(),s,o,i=async()=>U.shortcutWithSession(e.toolId,n,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);try{try{({data:s,voucherReceiptHeader:o}=await i())}catch(u){if(u instanceof Ft){let d=Math.min(Math.max(u.retryAfterSecs,0),5)*1e3;g.warn("mcp-session:lock-contended-retrying",{tool:e.toolId,retryAfterSecs:u.retryAfterSecs}),await new Promise(m=>setTimeout(m,d)),{data:s,voucherReceiptHeader:o}=await i()}else throw u}}catch(u){if(await fo(e.estimatedAmountCents),u instanceof Kr){if(g.warn("mcp-session:server-invalidated-budget",{code:u.code,budgetId:u.budgetId??t.budgetId,tool:e.toolId}),await Bi(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 Nh||(Nh=!0,console.error(`[visa-cli] Your session was closed by another process; reopened automatically as pay-as-you-go.
144
+ To require an explicit session approval instead, set VISA_REQUIRE_EXPLICIT_SESSION=true.`)),g.info("mcp-session:falling-back-to-payg",{code:u.code,tool:e.toolId}),Wh(e)}throw u instanceof Ft?(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=lo(o)??(n?gl(n):null);if(uo(s?.receipt_v2),wp({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),_u(s))return Tt(s);let c=await yu();if(e.idempotencyKey&&bu(s,c,e.idempotencyKey))return Tt(s);let l=c?xo(c):null;return Tt(vu(s,r,l))}function Ze(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function Ta(e){if(e===null||typeof e!="object"){let n=JSON.stringify(e);return n===void 0?String(e):n}return Array.isArray(e)?`[${e.map(Ta).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${Ta(r)}`).join(",")}}`}function hu(e,t,n,r){let s=Se.createHash("sha256").update(`${n}:${Ta(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${s}`}function JT(e,t){return`${e}:${t}`}function XT(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 ka(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,s=lt(r),o=s!==null?s.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=XT(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),c=i!=null?String(i):a;return{batch_id:e,item_id:JT(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 Wh(e){return xe(()=>QT(e))}async function Yh(e,t,n){if(_u(e))return Tt(e);let r=await yu();if(n&&bu(e,r,n))return Tt(e);let s=r?xo(r):null;return Tt(vu(e,t,s))}async function ZT(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 Qe("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 lo(i),uo(o?.receipt_v2),g.info("parentless-single-call:completed",{tool:e.toolId}),Yh(o,e.beforeBalanceMicros,e.idempotencyKey)}async function QT(e){let t=Math.max(1,Math.ceil(e.estimatedAmountCents)),n=await U.getBalance();if(!n.success)throw new Error(`Could not read balance: ${n.error||"unknown error"}`);if(n.balanceCents<t)throw new we(n.balanceCents,t);let r=t,s=xo(n);if(up()&&!Oh){let u=e.idempotencyKey??Se.randomUUID();try{return await ZT({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 _t)Oh=!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 Qe("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;Xt(c),co(a.budget.totalCents),g.info("on-demand-session:opened",{budgetId:c,capCents:a.budget.totalCents,tool:e.toolId});let l=!1;try{await hl(e.estimatedAmountCents);let u=pl(e.idempotencyKey);if(!u)throw await fo(e.estimatedAmountCents),new Error(`Internal: mintVoucher returned null after on-demand session-open ${c}`);let{data:d,voucherReceiptHeader:m}=await U.shortcutWithSession(e.toolId,u,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(lo(m)||gl(u),l=!0,uo(d?.receipt_v2),_u(d))return Tt(d);let f=await yu();if(e.idempotencyKey&&bu(d,f,e.idempotencyKey))return Tt(d);let p=f?xo(f):null;return Tt(vu(d,s,p))}catch(u){throw l||await fo(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)})}Xt(null),g.info("on-demand-session:closed",{budgetId:c,tool:e.toolId})}}async function qn(e){return Ra(async()=>Pn()?Gh(e):Wh(e))}function Ia(){return Ue()}var U=new Ve(()=>G.getSessionToken());function lt(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function xo(e){return lt(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function ek(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 tk(e){let t=lt(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=lt(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=lt(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function Sa(e,t="INVALID_TOOL_PARAMS",n){return{success:!1,error_code:t,code:t,error:e,message:e,...n??{}}}function nk(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 rk(){try{let e=await U.getBalance();return e.success?xo(e):null}catch{return null}}async function yu(){try{let e=await U.getBalance();return e.success?e:null}catch{return null}}function _u(e){if(!e||e.success===!1)return!1;let t=lt(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=lt(e.amountMicros??e.amount_micros??e.charged_micros),r=t??n;if(r===null||r<=0n)return!1;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,e.charged_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),!0}function bu(e,t,n){if(!e||e.success===!1||!t||!Array.isArray(t.ledger))return!1;let r=t.ledger.find(a=>a.idempotencyKey===n);if(!r)return!1;let s=lt(r.deltaMicros)??BigInt(r.deltaCents)*10000n,o=s<0n?-s:s;if(o<=0n)return!1;let i=o.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(o)/1e6),!0}function vu(e,t,n){if(!e||e.success===!1||t===null||n===null)return e;let r=t-n;if(r<=0n)return e;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),e}var sk="3.4.0-rc.5",F2=["","","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(`
145
+ `);function dt(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=js(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(Jf())return{opened:!1,url:t,blockedReason:"suppressed"};let n=uc();if(n.headless)return g.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let r=Id(t,Ia());if(!r)return g.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let s=Pd(r);return s?((0,Kh.execFile)(s.cmd,s.args,o=>{o&&g.warn(`Browser open failed: ${o.message}. URL: ${r}`)}),{opened:!0,url:r}):(g.info(`No browser command for platform "${ko.platform()}". URL: ${r}`),{opened:!1,url:r,blockedReason:"unsupported_platform"})}async function xe(e){return _r(U,e,ry)}var zh="get_cards",Jh="set_default_card";function ok(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 '${zh}' to see enrolled cards and '${Jh}' to switch, then retry the original request.`}function ik(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 '${zh}' to see enrolled cards and '${Jh}' to switch. Do not retry automatically.`}function ft(e,t){let n=e.retryable?ok(e.code,e.retryAfter):ik(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 ak(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 xs=null,ck=3e4;function Xh(){xs=null}var Vn=class extends Error{constructor(n){super(`${Ca()} attestation is required for this action, but it is not available in this MCP process. `+wu());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function $a(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. `+wu()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function lk(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:Vi,agent_guidance:Pp}}function Ca(){return process.platform==="darwin"?"Touch ID":"local biometric"}function wu(){return process.platform==="darwin"?"Run the action from an interactive terminal with Touch ID access, or use reset with confirm:true to clear stale server biometric state through GitHub re-authentication.":"This platform cannot create Visa CLI Touch ID attestations. Use reset with confirm:true to clear stale server biometric state through GitHub re-authentication."}async function uk(e){let t=Date.now();if(xs&&xs.expiresAt>t)return{required:xs.required,hasRegisteredKey:xs.hasRegisteredKey};try{let n=await U.getStatus(e),r=n.attestationRequired!==!1,s=kt(n);return xs={required:r,hasRegisteredKey:s,expiresAt:t+ck},{required:r,hasRegisteredKey:s}}catch{return{required:!0,hasRegisteredKey:!0}}}async function Qe(e,t,n,r,s,o){if(!o?.forceRequired){let i=await uk(s);if(!i.required){g.info("attestation:skipped-by-server-policy",{context:e});return}if(!i.hasRegisteredKey){g.info("attestation:skipped-no-registered-key",{context:e});return}}if(!de())throw g.warn("attestation:unavailable",{context:e}),new Vn(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 An(a,r);return g.info("attestation:success",{context:e,amount:t,merchant:n}),{signature:c,nonce:i,amount:t,merchant:n}}catch(i){throw g.error("attestation:failure",{context:e,amount:t,merchant:n,error:i.message}),i}}var Lh="[dry-run] https://placeholder.visa-cli.dev/image.png",dk=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"]),fk=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 mk(e,t){return t==="run_llm"||e.startsWith("or-")?"llm":t==="generate_image"||dk.has(e)?"image":t==="generate_video"||fk.has(e)?"video":pk(e)?"media":null}function pk(e){let t=ns(e);return t?!Tu(t):!1}function gk(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function hk(e){return e==="llm"?"OpenRouter":"fal.ai"}function Ts(e,t,n,r){let s={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:hk(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${gk(n)}`;return{...s,content:i,data:{content:i,model:t,dry_run:!0}}}return{...s,urls:[Lh],data:{[e==="video"?"videoUrl":e==="image"?"imageUrl":"url"]:Lh,metadata:{dry_run:!0}}}}async function mu(e){let t=e.mode??"mock",n=t==="preflight"?"/v1/telemetry/preflight":"/v1/telemetry/dry-run",r=t==="preflight"?"preflight":null;try{await U.emitTelemetry([{id:Se.randomUUID(),timestamp:new Date().toISOString(),tool_name:e.toolName,user_prompt:e.userContext??"",tool_params:JSON.stringify(e.toolParams),result_success:!0,result_error:null,result_json:JSON.stringify(e.result),payment_rail:r,payment_amount:0,payment_currency:"USD",merchant_name:e.result.merchantName,transaction_id:e.result.transactionId,tx_hash:null,protocol:null,http_status:200,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",event_kind:"mcp_tool",endpoint:n,resolved_model:e.resolvedModel,session_budget_id:null}])}catch(s){g.warn("dry_run:telemetry_failed",{tool:e.toolName,error:s?.message||String(s),mode:t})}}var yk="https://openrouter.ai/api/v1/chat/completions",_k="openrouter/free",bk=50,vk=15e3;function wk(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 Sk(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:Ts("llm",e,t,n),degraded:!0,resolvedModel:null};let s=wk(t),o;try{o=await yt(yk,{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:_k,messages:[{role:"user",content:s}],max_tokens:bk}),timeoutMs:vk})}catch(u){return g.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:Ts("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:Ts("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:Ts("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 Co(e,t,n,r){let s=ol();if(!s)return null;let o=mk(e,r);if(!o)return null;let i=Date.now();if(s==="mock"){let l=Ts(o,e,t,r);return await mu({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=Ts(o,e,t,r);return await mu({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 Sk(e,t,r);return await mu({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 on(e,t,n){let r=await U.paymentPreview({tool:e,url:t},n);if(!r||!r.merchantName||r.amount===void 0||r.amount===null||r.amount<0)throw new Error("Could not determine payment amount and merchant. Try again.");if(!Number.isFinite(r.amount)||r.amount<0||r.amount>999999)throw new Error(`Invalid payment amount: ${r.amount}. Payment rejected for safety.`);return r}function an(e){return $p(e.amount)}function xk(e,t,n){return n.has(e.resolvedTool)?0:Math.max(1,an(t[e.resolvedTool]))}function Tk(){return Ea.join(ko.homedir(),".visa-mcp","allium-results")}var H2=16*1024,V2=50*1024*1024;function kk(){let e=Tk();try{if(!ut.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=ut.readdirSync(e),n=0,r=0;for(let s of t)try{let o=ut.statSync(Ea.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 Uh=3600*1e3,pu=0;function Ck(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function Ao(e){if(!Xf()&&!(Date.now()<pu))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(Ck(t)){let n=pu===0;pu=Date.now()+Uh,n&&g.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:Uh});return}g.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function Ak(e,t){let n=(e.state||"").trim().toUpperCase(),r=(e.county||"").trim(),s=(e.start_date||"").trim(),o=(e.end_date||s).trim();if(!/^[A-Z]{2}$/.test(n))throw new Error('state must be a 2-letter US state code (e.g. "VA").');if(!r)throw new Error("county is required.");if(!/^\d{4}-\d{2}$/.test(s))throw new Error('start_date must be YYYY-MM (e.g. "2025-08").');if(o&&!/^\d{4}-\d{2}$/.test(o))throw new Error("end_date must be YYYY-MM.");let i="Visa SMI",a=.1,c=`Pay $0.10 to ${i} for SMI data (${n} / ${r})`;g.info("payment:attempt",{tool:"get_visa_smi",amount:a,merchant:i});try{return await xe(async()=>{let l=await Qe("get_visa_smi",a,i,c),u=await U.getVisaSmi({state:n,county:r,start_date:s,end_date:o,attestation:l,idempotencyKey:Se.randomUUID()},t);return u.success?g.info("payment:success",{tool:"get_visa_smi",merchant:i,charged_cents:u.charged_cents}):g.warn("payment:declined",{tool:"get_visa_smi",merchant:i,message:u.error}),u})}catch(l){if(l instanceof he)return g.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:l.code,retryable:l.retryable}),ft(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 Ek(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 Co("generate_image_card",e,t);if(n)return n;let r=await on("generate_image_card",void 0,t),s=Se.randomUUID();g.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await xe(async()=>{let o;try{o=await qn({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:an(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof we)return Ze(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=>dt(i)),Ao({prompt:e.prompt,tool:"generate_image_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):g.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof he)return g.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),ft(o,r);throw cn(o,{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName}),o}}async function Rk(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 Co("generate_image_fast_card",e,t);if(n)return n;let r=await on("generate_image_fast_card",void 0,t),s=Se.randomUUID();g.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await xe(async()=>{let o;try{o=await qn({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:an(r),userContext:t,timeoutMs:6e4,idempotencyKey:s})}catch(i){if(i instanceof we)return Ze(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=>dt(i)),Ao({prompt:e.prompt,tool:"generate_image_fast_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):g.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof he)return g.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),ft(o,r);throw cn(o,{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName}),o}}async function Ik(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 Co("generate_video_tempo_card",e,t);if(n)return n;let r=await on("generate_video_tempo_card",void 0,t),s=Se.randomUUID();g.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await xe(async()=>{let o;try{o=await qn({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:an(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof we)return Ze(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=>dt(i)),Ao({prompt:e.prompt,tool:"generate_video_tempo_card",mediaUrl:o.urls[0],mediaType:"video",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):g.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof he)return g.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),ft(o,r);throw cn(o,{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName}),o}}async function $k(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 on("generate_music_tempo_card",void 0,t),r=Se.randomUUID();g.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await xe(async()=>{let s;try{s=await qn({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:an(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(o){if(o instanceof we)return Ze(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=>dt(o)),Ao({prompt:e.prompt,tool:"generate_music_tempo_card",mediaUrl:s.urls[0],mediaType:"audio",cost:s.amount??n.amount,transactionId:s.transactionId,userContext:t})):s.urls?.length&&s.status==="processing"?(s._preliminary_urls=s.urls,delete s.urls,g.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):g.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof he)return g.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),ft(s,n);throw cn(s,{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName}),s}}async function Pk(e,t){let n=await on("check_music_status_tempo_card",void 0,t),r=Se.randomUUID();g.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await xe(async()=>{let s;try{s=await qn({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:an(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof we)return Ze(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=>dt(o)),s})}catch(s){if(s instanceof he)return g.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),ft(s,n);throw cn(s,{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName}),s}}async function Ok(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 on("query_onchain_prices",void 0,t),r=Se.randomUUID();g.info("payment:attempt",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName});try{return await xe(async()=>{let s;try{s=await qn({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:an(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof we)return Ze(o);throw o}if(g.info("payment:success",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,mode:"session"}),Array.isArray(s?.data))s.data=s.data.map(o=>{if("mint"in o&&!("address"in o)){let{mint:i,...a}=o;return{address:i,...a}}return o});else if(s&&"mint"in s&&!("address"in s)){let{mint:o,...i}=s;return{address:o,...i}}return s})}catch(s){if(s instanceof he)return g.warn("payment:declined",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),ft(s,n);throw cn(s,{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName}),s}}var Mk=["generate_music_tempo_card"],Ss=10,Dh=5,jh=new Map;function Bh(e){let t=jh.get(e);if(t!==void 0)return t;let r=ns(e)?.isAsync===!0||Mk.includes(e);return jh.set(e,r),r}var Nk=36e4,Lk=18e4,Uk=15e3,Dk=12e4,jk=2e3;function gu(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}function Bk(e,t){return Se.createHash("sha256").update(`${e}:${Ta(t)}`).digest("hex")}function Fk(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,...ka(n,r,o)});let l=0,u=0n;if(o?.success!==!1){let d=lt(o?.amountMicros??o?.amount_micros),m=typeof o?.amount=="number"?o.amount:i?.amount??0;d!==null&&d>0n?u+=d:u+=BigInt(Math.round(m*1e6)),l+=m}return o?.urls&&o.urls.forEach(d=>dt(d)),{deltaCharged:l,deltaMicros:u}}function Hk(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,m=t.filter(k=>k?.success===!1).length,f=t.length-m,p=t.flatMap(k=>Array.isArray(k?.urls)?k.urls:[]),h=l>0n?Number(l)/1e6:Math.round((c+Number.EPSILON)*100)/100,w=f===0?"failure":m===0?"success":"partial";return g.info("payment:success",{tool:"batch",batchTool:o,count:n.length,totalAmount:a,totalCharged:h,merchant:i,successCount:f,failedCount:m,outcome:w,mode:d,batchId:u}),{success:f>0,outcome:w,batch_id:u,tool:s?r[0]:o,count:n.length,successCount:f,failedCount:m,totalCharged:h,...l>0n?{totalChargedMicros:l.toString(),amountMicros:l.toString(),amount_micros:l.toString()}:{},merchantName:i,results:t,...p.length?{urls:p}:{}}}async function Vk(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:m,batchId:f,userContext:p}=e,h=i,w=await U.getBalance();if(!w.success)throw new Error(`Could not read balance: ${w.error||"unknown error"}`);if(w.balanceCents<h)throw new we(w.balanceCents,h);let k=`batch-${f}`,b=`spend up to $${(h/100).toFixed(2)} across a batch of ${t.length}`,{batchParentId:v}=await xe(async()=>{let y=await Qe("batch_open",h,k,b,p,{forceRequired:!0}),T=y?.nonce??(await U.getAttestationChallenge()).nonce;g.info("parentless-batch:open-attempt",{batchTool:l,count:t.length,approvedTotalCents:h,attested:!!y});let{batch_parent_id:z}=await U.batchOpen({...y?{attestation:y}:{},nonce:T,approved_total_cents:h,batch_id:f});return{batchParentId:z}});g.info("parentless-batch:opened",{batchTool:l,count:t.length,batchParentId:v});let S=[],E=0,I=0n;try{for(let y=0;y<t.length;y+=1){let T=t[y],z=n[T.resolvedTool],Z=r.has(T.resolvedTool);try{let H;if(Z)H=await U.shortcut(T.resolvedTool,T.params,m,p,"batch");else{let{data:X,voucherReceiptHeader:Is}=await U.shortcutParentlessBatchItem(T.resolvedTool,{batch_parent_id:v,batch_id:f,batch_index:y,batch_request_hash:Bk(T.resolvedTool,T.params),item_ceiling_cents:o[y],idempotency_key:hu(f,y,T.resolvedTool,T.params)},T.params,m,p,"batch");lo(Is),uo(X?.receipt_v2),H=await Yh(X,null,hu(f,y,T.resolvedTool,T.params))}let{deltaCharged:be,deltaMicros:se}=Fk({results:S,batchId:f,index:y,item:T,itemResult:H,preview:z,isFree:Z,catalogName:s[T.resolvedTool]?.name});E+=be,I+=se}catch(H){if(H instanceof we&&S.length===0)return Ze(H);g.warn("payment:batch-item-failed",{tool:T.resolvedTool,index:y,error:H?.message||String(H)}),S.push({success:!1,tool:T.resolvedTool,...ka(f,y),error:H?.message||String(H)})}}return Hk({results:S,resolvedItems:t,uniqueTools:a,isHomogeneous:c,primaryTool:l,merchantNames:u,totalAmount:d,totalCharged:E,totalChargedMicros:I,batchId:f,mode:"parentless"})}catch(y){if(y instanceof he)return g.warn("payment:declined",{tool:"batch",batchTool:l,count:t.length,totalAmount:d,merchant:u,code:y.code,retryable:y.retryable}),ft(y,{amount:d,merchantName:u});throw cn(y,{tool:"batch",batchTool:l,count:t.length,totalAmount:d,merchant:u}),y}}async function qk(e,t){let n;if(Array.isArray(e.requests)&&e.requests.length>Ss)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${Ss} items. Please split into smaller batches.`};if(e.requests?.some(y=>y.tool||y.tool_id)&&e.requests)n=e.requests.map(y=>{let T=y.tool||y.tool_id||e.tool;if(!T)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let z=En(T,y.tier||e.tier,y.prompt??t),{tool:Z,tool_id:H,tier:be,params:se,...X}=y,Is=se&&typeof se=="object"?{...se,...X}:X;return{resolvedTool:z,params:Is}});else if(e.tool){let y=En(e.tool,e.tier,e.params?.prompt??t);if(e.count!==void 0){if(!Number.isSafeInteger(e.count)||e.count<1)return gu("BATCH_INVALID_COUNT","Batch count must be a positive integer.");if(e.count>Ss)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${Ss} items. Please split into smaller batches.`}}n=(e.requests||(e.count!==void 0&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(z=>({resolvedTool:y,params:z}))}else return gu("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return gu("BATCH_EMPTY","Batch requires at least one item.");if(n.length>Ss)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${Ss} items. Please split into smaller batches.`};if([...new Set(n.map(y=>y.resolvedTool))].some(Bh)&&n.length>Dh)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${Dh} 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 sy(y);let l=new Set(i.filter(y=>c[y]&&Tu(c[y]))),u={};for(let y of i)l.has(y)||(u[y]=await on(y,void 0,t));let d=0;for(let y of n)d+=u[y.resolvedTool]?.amount??0;let m=n.map(y=>xk(y,u,l)),f=m.reduce((y,T)=>y+T,0),p=[...new Set([...Object.values(u).map(y=>y.merchantName),...i.filter(y=>l.has(y)).map(y=>c[y]?.name??y)])].join(", "),h=a?i[0]:"mixed";g.info("payment:attempt",{tool:"batch",batchTool:h,count:n.length,totalAmount:d,merchant:p,heterogeneous:!a});let w=n.some(y=>Bh(y.resolvedTool)),k=n.some(y=>y.resolvedTool.startsWith("or-")||y.resolvedTool==="run_llm"||y.resolvedTool==="execute_tool"),b=w?Nk:k?Lk+n.length*Uk:Dk+n.length*jk,v=Se.randomUUID(),S=[],E=0,I=0n;return Ra(async()=>{let y=!Pn();if(dp()&&!Mh&&y&&f>0)try{return await Vk({resolvedItems:n,previews:u,freeTools:l,catalogEntries:c,itemCeilingCents:m,batchCeilingCents:f,uniqueTools:i,isHomogeneous:a,primaryTool:h,merchantNames:p,totalAmount:d,timeoutMs:b,batchId:v,userContext:t})}catch(T){if(T instanceof _t)Mh=!0,g.info("parentless-batch:falling-back-to-session",{batchTool:h,count:n.length,status:T.status,serverErrorCode:T.serverErrorCode});else{if(T instanceof we)return Ze(T);throw T}}if(y&&f>0)try{let T=f;await xe(()=>_l(U,Qe,{toolName:"batch",userContext:t,sessionKind:"one_shot",minRequiredCents:T,capCentsOverride:T}))}catch(T){return T instanceof we?Ze(T):(g.warn("payment:batch-prewarm-failed",{batchTool:h,count:n.length,error:T?.message||String(T)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:T?.message||"Failed to authenticate batch session",tool:h,count:n.length,failedCount:n.length,results:[]})}try{for(let se=0;se<n.length;se+=1){let X=n[se],Is=u[X.resolvedTool];try{let le=l.has(X.resolvedTool)?await U.shortcut(X.resolvedTool,X.params,b,t,"batch"):await Gh({toolId:X.resolvedTool,toolParams:X.params,estimatedAmountCents:m[se],userContext:t,metaTool:"batch",timeoutMs:b,idempotencyKey:hu(v,se,X.resolvedTool,X.params)});if(l.has(X.resolvedTool)&&le&&typeof le=="object"&&!Array.isArray(le)&&le.merchantName==null&&(le.merchantName=c[X.resolvedTool]?.name??X.resolvedTool),S.push({success:le?.success!==!1,tool:X.resolvedTool,...le,...ka(v,se,le)}),le?.success!==!1){let $s=lt(le?.amountMicros??le?.amount_micros),sd=typeof le?.amount=="number"?le.amount:Is?.amount??0;$s!==null&&$s>0n?I+=$s:I+=BigInt(Math.round(sd*1e6)),E+=sd}le?.urls&&le.urls.forEach($s=>dt($s))}catch(le){if(le instanceof we&&S.length===0)return Ze(le);g.warn("payment:batch-item-failed",{tool:X.resolvedTool,index:se,error:le?.message||String(le)}),S.push({success:!1,tool:X.resolvedTool,...ka(v,se),error:le?.message||String(le)})}}let T=S.filter(se=>se?.success===!1).length,z=S.length-T,Z=S.flatMap(se=>Array.isArray(se?.urls)?se.urls:[]),H=I>0n?Number(I)/1e6:Math.round((E+Number.EPSILON)*100)/100,be=z===0?"failure":T===0?"success":"partial";return g.info("payment:success",{tool:"batch",batchTool:h,count:n.length,totalAmount:d,totalCharged:H,merchant:p,successCount:z,failedCount:T,outcome:be,mode:"session",batchId:v}),{success:z>0,outcome:be,batch_id:v,tool:a?i[0]:h,count:n.length,successCount:z,failedCount:T,totalCharged:H,...I>0n?{totalChargedMicros:I.toString(),amountMicros:I.toString(),amount_micros:I.toString()}:{},merchantName:p,results:S,...Z.length?{urls:Z}:{}}}catch(T){if(T instanceof he)return g.warn("payment:declined",{tool:"batch",batchTool:h,count:n.length,totalAmount:d,merchant:p,code:T.code,retryable:T.retryable}),ft(T,{amount:d,merchantName:p});throw cn(T,{tool:"batch",batchTool:h,count:n.length,totalAmount:d,merchant:p}),T}finally{if(y){let T=await Bi(U);g.info("batch-session:closed",{budgetId:T.budgetId,closedServerSide:T.closedServerSide})}}})}function Kk(){let e=!1,t;try{let r=Ea.join(ko.homedir(),".claude","settings.json");if(ut.existsSync(r)){let s=JSON.parse(ut.readFileSync(r,"utf-8")),o=typeof s.statusLine=="object"?s.statusLine.command:"";e=yn(o)}}catch{}let n=ti();return n||(t="visa-cli config hud enable"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function Gk(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=kk();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=Kk(),!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=sk,Array.isArray(t.cards)&&(t.cards=t.cards.map(o=>({...o,displayName:Su(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=Pn();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 Su(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 Zh(e,t){try{let r=((await U.getStatus(t)).cards||[]).find(s=>s?.id===e);if(r)return Su(r)}catch(n){g.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function Wk(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:Su(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 Yk(e,t){return await U.getTransactions({limit:e.limit,offset:e.offset},t)}async function zk(e,t){return await U.feedback(e.message,e.transaction_id,t)}async function Jk(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Or("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=Hi(String(e.amount));if(n.ok===!1)return{success:!1,error:n.error};let r=n.cents,s=r/100,o=Se.randomUUID();g.info("buy_credits:attempt",{amountCents:r});try{return await xe(async()=>{let i=await Qe("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=zT(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 Vn)return lk();if(i instanceof nt)return g.warn("buy_credits:ambiguous",{amountCents:r,code:i.code,transactionId:i.transactionId}),ak(i);throw g.error("buy_credits:failure",{amountCents:r,error:i.message}),i}}function Or(e,t){return{success:!1,error:t,code:e,message:t}}async function Xk(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Or("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 Or("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 Or("INVALID_VALUE","dailyLimit must be at least $1");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return Or("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");g.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await xe(async()=>{let n=await Qe("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 Vn)return $a(n,"update_spending_controls");if(String(n?.message||n).includes("Attestation required"))return Or("ATTESTATION_REQUIRED","Changing spending controls requires local attestation, even when payment biometric prompts are disabled.");throw n}}async function Zk(e){let t=await ao({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 xu=new Set(["auth.serverUrl"]);function To(){return Object.keys(er).filter(e=>!xu.has(e)).sort()}function Qh(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:To()}}async function Qk(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(xu.has(e.key))return g.warn("config:set:rejected:mcp-forbidden",{key:e.key}),Qh(e.key,"set");g.info("config:set",{key:e.key});try{let t=yi(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 rt?"UNKNOWN_KEY":t instanceof Ht?"SERVER_CONTROLLED":t instanceof _n?"RETIRED_KEY":"INVALID_VALUE",r=t instanceof rt?`Unknown setting "${e.key}". MCP-settable keys: ${To().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:To()}}}async function eC(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(xu.has(e.key))return g.warn("config:unset:rejected:mcp-forbidden",{key:e.key}),Qh(e.key,"unset");g.info("config:unset",{key:e.key});try{let t=_i(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 rt?"UNKNOWN_KEY":t instanceof Ht?"SERVER_CONTROLLED":t instanceof _n?"RETIRED_KEY":"INVALID_VALUE",r=t instanceof rt?`Unknown setting "${e.key}". MCP-settable keys: ${To().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:To()}}}async function tC(e){let t=await U.getStatus(e),n=t.attestationRequired!==!1,r=kt(t),s=de(),o=n?r?s?`${Ca()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${Ca()} is not available in this process. ${wu()}`:"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 nC(e){g.info("biometric:on");let t=await Mi(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?(Xh(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:n.error||"unknown error"}}async function rC(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Or("MISSING_CONFIRMATION","Please confirm by setting confirm: true. Disabling Touch ID is a security downgrade \u2014 the user will be prompted for one final Touch ID confirmation before the change takes effect.");g.info("biometric:off");try{return await xe(async()=>{let n=await U.getStatus(t),r;if(kt(n)&&(r=await Qe("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${Ca()} 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 Xh(),{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 Vn)return $a(n,"biometric_off");throw n}}var Fh=3e4,sC=3e5;async function ey(e,t,n="login"){let r=Se.randomUUID(),s=`${e}${e.includes("?")?"&":"?"}state=${r}`,o=dt(s);return!o.opened&&o.blockedReason!=="non_internal_host"&&o.blockedReason!=="invalid_url"?ty(s,o,n):o.opened?{...await ny(r,t,n),browserUrl:s}:{success:!1,browserUrl:s,message:`Could not open the browser URL safely. Please check the configured auth server and try again. URL: ${s}`}}function ty(e,t,n){let r=n==="enrollment"?"card enrollment":n==="attestation-recovery"?"biometric reset":"login",s=t.blockedReason==="suppressed"?"browser auto-open is suppressed":t.blockedReason==="headless"?"this process appears to be headless":t.blockedReason==="unsupported_platform"?"this platform has no configured browser opener":"browser auto-open is unavailable";return{success:!1,requiresBrowser:!0,browserUrl:e,message:`Browser auto-open was skipped because ${s}. Open this URL to continue ${r}: ${e}`}}async function ny(e,t,n="login"){let r=Date.now()+sC;for(;Date.now()<r;)try{let o=await fetch(`${Ia()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:Fh,...t&&{user_context:t}}),signal:AbortSignal.timeout(Fh+5e3)});if(!o.ok){await pn(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=gp(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 pn(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 ry(e){let t=Se.randomUUID(),n;try{n=await U.startAttestationRecovery(t,e)}catch(o){return{success:!1,message:`Could not start biometric reset: ${o?.message||"unknown error"}`}}if(!n.success||!n.recoveryUrl)return{success:!1,message:n.error||"Could not start biometric reset. Please try again."};let r=dt(n.recoveryUrl);return!r.opened&&r.blockedReason!=="non_internal_host"&&r.blockedReason!=="invalid_url"?ty(n.recoveryUrl,r,"attestation-recovery"):r.opened?{...await ny(t,e,"attestation-recovery"),browserUrl:n.recoveryUrl}:{success:!1,browserUrl:n.recoveryUrl,message:`Could not open the browser URL safely. Please check the configured auth server and try again. URL: ${n.recoveryUrl}`}}async function oC(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 Zh(n,t)}`;try{return await xe(async()=>{let o=await Qe(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 Vn)return $a(o,"remove_card");throw o}}async function iC(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 Zh(n,t)} as default`;try{return await xe(async()=>{let o=await Qe(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 Vn)return $a(o,"set_default_card");throw o}}async function aC(e){return g.info("auth:login_attempt"),ey(`${Ia()}/login`,e)}function cC(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 lC(e={},t){let n;try{n=cC(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return Ra(async()=>{let r=await xe(()=>Ap(U,Qe,{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 uC(){let e=Pn();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 dC(){return Ra(async()=>{let e=Pn();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 Bi(U);g.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=tk(e),r=lt(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 ${ek(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 fC(e){if(g.info("auth:add_card_attempt"),!await G.getSessionToken())return{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."};let{code:n}=await U.createEnrollCode();return ey(`${Ia()}/enroll-card?code=${encodeURIComponent(n)}`,e,"enrollment")}async function Hh(){if(await G.clearAll(),de())try{await Oi()}catch{}}async function mC(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 Hh(),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 ry(t);if(!s.success)return s;n=!0}}catch(r){let s=r?.message||"unknown error";if(!/not logged in|session.*expired|no local credentials/i.test(s))return{success:!1,message:`Could not check server biometric state: ${s}`};g.warn("reset:server_attestation_status_unavailable",{error:s})}try{await U.logout(void 0,t)}catch{}return await Hh(),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 pC(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((m,f)=>`${f+1}. **${m.name}** (${m.id})
146
+ ${m.description}
147
+ Provider: ${m.provider} | Price: ${Vh(m)}${qh(m)}
148
+ Params: ${Object.keys(m.inputSchema?.properties||m.inputSchema||{}).join(", ")||"none"}`).join(`
149
149
 
150
150
  `);return`## ${l.length<=3?l.toUpperCase():l.charAt(0).toUpperCase()+l.slice(1)}
151
151
 
@@ -157,58 +157,61 @@ ${c}
157
157
 
158
158
  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})
159
159
  ${a.description}
160
- Provider: ${a.provider} | Category: ${a.category} | Price: ${Mh(a)}${Nh(a)}
160
+ Provider: ${a.provider} | Category: ${a.category} | Price: ${Vh(a)}${qh(a)}
161
161
  Params: ${Object.keys(a.inputSchema?.properties||a.inputSchema||{}).join(", ")||"none"}`).join(`
162
162
 
163
163
  `);return g.info("catalog:discovered",{count:o.length}),{content:[{type:"text",text:`Found ${o.length} tool(s):
164
164
 
165
165
  ${i}
166
166
 
167
- 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 Mh(e){return e.priceDisplay??`$${(e.priceCents/100).toFixed(2)}`}function Nh(e){let t=e.protocol;return t==="mpp"||t==="x402"?" | Paid from your prepaid balance":""}function ZC(e,t){return t==="image"||t==="video"||t==="audio"?t:e?.match(/\.(mp4|webm|mov)/)?"video":"image"}function ba(e,t){return Array.isArray(e.type)?e.type.includes(t):e.type===t}function QC(e,t,n){let r=e.inputSchema;if(!r||r.type!=="object")return null;let s=r.properties??{},o=n??e.id;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)){if(l.enum&&!l.enum.includes(c))return`${a} must be one of: ${l.enum.map(String).join(", ")}.`;if(ba(l,"integer")){if(typeof c!="number"||!Number.isInteger(c))return`${a} must be an integer.`}else if(ba(l,"number")){if(typeof c!="number"||!Number.isFinite(c))return`${a} must be a number.`}else if(ba(l,"string")){if(typeof c!="string")return`${a} must be a string.`;if(c.trim()==="")return`${a} cannot be empty.`;if(l.minLength!==void 0&&c.length<l.minLength)return`${a} is too short.`;if(l.maxLength!==void 0&&c.length>l.maxLength)return`${a} is too long.`}else if(ba(l,"boolean")&&typeof c!="boolean")return`${a} must be a boolean.`;if(typeof c=="number"){if(l.minimum!==void 0&&c<l.minimum)return`${a} must be at least ${l.minimum}.`;if(l.maximum!==void 0&&c>l.maximum)return`${a} must be at most ${l.maximum}.`}}}return null}async function zh(e){let t=es(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 yu(e){let t=e.priceCents,n=e.pricing;return e.executionMode==="free_authenticated"||e.accessMode==="free"||n?.free===!0||t===0||n?.amount===0}function ek(e){return e.split(/[-_]/).filter(t=>t.length>0&&!/^[0-9a-f]{8,}$/i.test(t)).join(" ").trim()}async function tk(e){let t=ek(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 nk(e,t,n="execute_tool"){let{tool_id:r,params:s,...o}=e,i=s||o;if(!r)return _a("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 zh(r);if(!a){let f=await tk(r),m=f.length?` Did you mean: ${f.map(h=>h.tool_id).join(", ")}?`:"";return _a(`Unknown tool: '${r}'.${m} Use discover_tools first to find available tools.`,"UNKNOWN_TOOL",f.length?{suggestions:f}:void 0)}if(a.deprecated){let f=a.replacementTool?` Use '${a.replacementTool}' instead.`:"";return _a(`Tool '${r}' is deprecated and is no longer available for new paid calls.${f}`,"DEPRECATED_TOOL")}let l=QC(a,i,n&&n!=="execute_tool"?n:void 0);if(l)return g.info("catalog:execute:validation_failed",{tool:r,metaTool:n,error:l}),_a(l);let u=await xo(r,i,t,n);if(u)return u;if(yu(a)){g.info("catalog:execute:free",{tool:r,metaTool:n});let f=await U.shortcut(r,i,6e4,t,n);return f&&typeof f=="object"&&!Array.isArray(f)&&f.merchantName==null&&(f.merchantName=a.name??r),f}let d=await rn(r,void 0,t),p=Se.randomUUID();g.info("payment:attempt",{tool:r,amount:d.amount,merchant:d.merchantName});try{return await xe(async()=>{let f;try{f=await Hn({toolId:r,toolParams:i,estimatedAmountCents:sn(d),userContext:t,metaTool:n,timeoutMs:12e4,idempotencyKey:p})}catch(m){if(m instanceof we)return Ze(m);throw m}if(g.info("payment:success",{tool:r,amount:d.amount,merchant:d.merchantName,mode:"session"}),f&&typeof f=="object"&&!Array.isArray(f)&&f.merchantName==null&&(f.merchantName=a?.name??r),f.urls?.length){f.urls.forEach(h=>ut(h));let m=ZC(f.urls[0],f.mediaType);To({prompt:i.prompt||`${r} execution`,tool:r,mediaUrl:f.urls[0],mediaType:m,cost:f.amount??d.amount,transactionId:f.transactionId,userContext:t})}return f})}catch(f){return f instanceof ge?(g.warn("payment:declined",{tool:r,amount:d.amount,merchant:d.merchantName,code:f.code,retryable:f.retryable}),dt(f,d)):(Jh(f?.message)?g.warn("payment:ambiguous",{tool:r,amount:d.amount,merchant:d.merchantName,error:f.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:d.amount,merchant:d.merchantName,error:f.message}),jT({toolId:r,surface:n,merchantName:d.merchantName,amount:d.amount,message:f?.message||"Tool execution failed."}))}}function Jh(e){return e?/\b(task_id|polling?|timeout|timed out|queue|IN_QUEUE|aborted)\b/i.test(e):!1}function on(e,t){let n={...t,error:e?.message};Jh(e?.message)?g.warn("payment:ambiguous",n):g.error("payment:failure",n)}async function rk(e){if(!e.name)return{success:!1,error:"name is required"};try{let{registerName:t,ensureMailbox:n}=await Promise.resolve().then(()=>(bo(),ya)),r=await t(e.name);return await n(e.name),{success:!0,...r}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async function sk(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(()=>(bo(),ya)),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 ok(e){try{let{readInbox:t,resolveActingName:n,meshName:r}=await Promise.resolve().then(()=>(bo(),ya)),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 it=class{static async subwayRegister(t){return rk(t||{})}static async subwaySend(t){return sk(t||{})}static async subwayInbox(t){return ok(t||{})}static async getStatus(t){return RC(t)}static async getVisaSmi(t,n){return uC(t,n)}static async getCards(t){return IC(t)}static async transactionHistory(t,n){return $C(t||{},n)}static async feedback(t,n){return PC(t,n)}static async updateSpendingControls(t,n){return MC(t,n)}static async configList(t){return NC(t||{})}static async configSet(t){return LC(t||{})}static async configUnset(t){return UC(t||{})}static async biometricStatus(t){return DC(t)}static async biometricOn(t){return jC(t)}static async biometricOff(t,n){return BC(t,n)}static async reset(t,n){return JC(t,n)}static async login(t){return qC(t)}static async closeSession(t){return YC()}static async startSession(t,n){return GC(t||{},n)}static async getSessionStatus(t){return WC()}static async addCard(t){return zC(t)}static async removeCard(t,n){return HC(t,n)}static async setDefaultCard(t,n){return VC(t,n)}static async buyCredits(t,n){return OC(t,n)}static async batch(t,n){return EC(t,n)}static async discoverTools(t){return XC(t)}static async executeTool(t,n,r="execute_tool"){return nk(t,n,r)}static async shortcut(t,n,r){switch(t){case"generate_image_card":return dC(n,r);case"generate_image_fast_card":return fC(n,r);case"generate_video_tempo_card":return pC(n,r);case"generate_music_tempo_card":return mC(n,r);case"check_music_status_tempo_card":return gC(n,r);case"query_onchain_prices_card":return hC(n,r);default:{let s=await xo(t,n,r);if(s)return s;let o=await rn(t,void 0,r);g.info("payment:attempt",{tool:t});try{let i=await Hn({toolId:t,toolParams:n,estimatedAmountCents:sn(o),userContext:r,timeoutMs:6e4});return g.info("payment:success",{tool:t,mode:"session"}),i.urls?.length&&i.urls.forEach(a=>ut(a)),i}catch(i){if(i instanceof we)return Ze(i);if(i instanceof ge)return g.warn("payment:declined",{tool:t,code:i.code,retryable:i.retryable}),dt(i,o);throw on(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}}};_t();function Xh(e,t=process.stderr){if(bt()||!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(`
167
+ 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 Vh(e){return e.priceDisplay??`$${(e.priceCents/100).toFixed(2)}`}function qh(e){let t=e.protocol;return t==="mpp"||t==="x402"?" | Paid from your prepaid balance":""}function gC(e,t){return t==="image"||t==="video"||t==="audio"?t:e?.match(/\.(mp4|webm|mov)/)?"video":"image"}function xa(e,t){return Array.isArray(e.type)?e.type.includes(t):e.type===t}function hC(e,t,n){let r=e.inputSchema;if(!r||r.type!=="object")return null;let s=r.properties??{},o=n??e.id;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)){if(l.enum&&!l.enum.includes(c))return`${a} must be one of: ${l.enum.map(String).join(", ")}.`;if(xa(l,"integer")){if(typeof c!="number"||!Number.isInteger(c))return`${a} must be an integer.`}else if(xa(l,"number")){if(typeof c!="number"||!Number.isFinite(c))return`${a} must be a number.`}else if(xa(l,"string")){if(typeof c!="string")return`${a} must be a string.`;if(c.trim()==="")return`${a} cannot be empty.`;if(l.minLength!==void 0&&c.length<l.minLength)return`${a} is too short.`;if(l.maxLength!==void 0&&c.length>l.maxLength)return`${a} is too long.`}else if(xa(l,"boolean")&&typeof c!="boolean")return`${a} must be a boolean.`;if(typeof c=="number"){if(l.minimum!==void 0&&c<l.minimum)return`${a} must be at least ${l.minimum}.`;if(l.maximum!==void 0&&c>l.maximum)return`${a} must be at most ${l.maximum}.`}}}return null}async function sy(e){let t=ns(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 Tu(e){let t=e.priceCents,n=e.pricing;return e.executionMode==="free_authenticated"||e.accessMode==="free"||n?.free===!0||t===0||n?.amount===0}function yC(e){return e.split(/[-_]/).filter(t=>t.length>0&&!/^[0-9a-f]{8,}$/i.test(t)).join(" ").trim()}async function _C(e){let t=yC(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 bC(e,t,n="execute_tool"){let{tool_id:r,params:s,...o}=e,i=s||o;if(!r)return Sa("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 sy(r);if(!a){let f=await _C(r),p=f.length?` Did you mean: ${f.map(h=>h.tool_id).join(", ")}?`:"";return Sa(`Unknown tool: '${r}'.${p} Use discover_tools first to find available tools.`,"UNKNOWN_TOOL",f.length?{suggestions:f}:void 0)}if(a.deprecated){let f=a.replacementTool?` Use '${a.replacementTool}' instead.`:"";return Sa(`Tool '${r}' is deprecated and is no longer available for new paid calls.${f}`,"DEPRECATED_TOOL")}let l=hC(a,i,n&&n!=="execute_tool"?n:void 0);if(l)return g.info("catalog:execute:validation_failed",{tool:r,metaTool:n,error:l}),Sa(l);let u=await Co(r,i,t,n);if(u)return u;if(Tu(a)){g.info("catalog:execute:free",{tool:r,metaTool:n});let f=await U.shortcut(r,i,6e4,t,n);return f&&typeof f=="object"&&!Array.isArray(f)&&f.merchantName==null&&(f.merchantName=a.name??r),f}let d=await on(r,void 0,t),m=Se.randomUUID();g.info("payment:attempt",{tool:r,amount:d.amount,merchant:d.merchantName});try{return await xe(async()=>{let f;try{f=await qn({toolId:r,toolParams:i,estimatedAmountCents:an(d),userContext:t,metaTool:n,timeoutMs:12e4,idempotencyKey:m})}catch(p){if(p instanceof we)return Ze(p);throw p}if(g.info("payment:success",{tool:r,amount:d.amount,merchant:d.merchantName,mode:"session"}),f&&typeof f=="object"&&!Array.isArray(f)&&f.merchantName==null&&(f.merchantName=a?.name??r),f.urls?.length){f.urls.forEach(h=>dt(h));let p=gC(f.urls[0],f.mediaType);Ao({prompt:i.prompt||`${r} execution`,tool:r,mediaUrl:f.urls[0],mediaType:p,cost:f.amount??d.amount,transactionId:f.transactionId,userContext:t})}return f})}catch(f){return f instanceof he?(g.warn("payment:declined",{tool:r,amount:d.amount,merchant:d.merchantName,code:f.code,retryable:f.retryable}),ft(f,d)):(oy(f?.message)?g.warn("payment:ambiguous",{tool:r,amount:d.amount,merchant:d.merchantName,error:f.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:d.amount,merchant:d.merchantName,error:f.message}),nk({toolId:r,surface:n,merchantName:d.merchantName,amount:d.amount,message:f?.message||"Tool execution failed."}))}}function oy(e){return e?/\b(task_id|polling?|timeout|timed out|queue|IN_QUEUE|aborted)\b/i.test(e):!1}function cn(e,t){let n={...t,error:e?.message};oy(e?.message)?g.warn("payment:ambiguous",n):g.error("payment:failure",n)}async function vC(e){if(!e.name)return{success:!1,error:"name is required"};try{let{registerName:t,ensureMailbox:n}=await Promise.resolve().then(()=>(So(),wa)),r=await t(e.name);return await n(e.name),{success:!0,...r}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async function wC(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(()=>(So(),wa)),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 SC(e){try{let{readInbox:t,resolveActingName:n,meshName:r}=await Promise.resolve().then(()=>(So(),wa)),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 at=class{static async subwayRegister(t){return vC(t||{})}static async subwaySend(t){return wC(t||{})}static async subwayInbox(t){return SC(t||{})}static async getStatus(t){return Gk(t)}static async getVisaSmi(t,n){return Ak(t,n)}static async getCards(t){return Wk(t)}static async transactionHistory(t,n){return Yk(t||{},n)}static async feedback(t,n){return zk(t,n)}static async updateSpendingControls(t,n){return Xk(t,n)}static async configList(t){return Zk(t||{})}static async configSet(t){return Qk(t||{})}static async configUnset(t){return eC(t||{})}static async biometricStatus(t){return tC(t)}static async biometricOn(t){return nC(t)}static async biometricOff(t,n){return rC(t,n)}static async reset(t,n){return mC(t,n)}static async login(t){return aC(t)}static async closeSession(t){return dC()}static async startSession(t,n){return lC(t||{},n)}static async getSessionStatus(t){return uC()}static async addCard(t){return fC(t)}static async removeCard(t,n){return oC(t,n)}static async setDefaultCard(t,n){return iC(t,n)}static async buyCredits(t,n){return Jk(t,n)}static async batch(t,n){return qk(t,n)}static async discoverTools(t){return pC(t)}static async executeTool(t,n,r="execute_tool"){return bC(t,n,r)}static async shortcut(t,n,r){switch(t){case"generate_image_card":return Ek(n,r);case"generate_image_fast_card":return Rk(n,r);case"generate_video_tempo_card":return Ik(n,r);case"generate_music_tempo_card":return $k(n,r);case"check_music_status_tempo_card":return Pk(n,r);case"query_onchain_prices_card":return Ok(n,r);default:{let s=await Co(t,n,r);if(s)return s;let o=await on(t,void 0,r);g.info("payment:attempt",{tool:t});try{let i=await qn({toolId:t,toolParams:n,estimatedAmountCents:an(o),userContext:r,timeoutMs:6e4});return g.info("payment:success",{tool:t,mode:"session"}),i.urls?.length&&i.urls.forEach(a=>dt(a)),i}catch(i){if(i instanceof we)return Ze(i);if(i instanceof he)return g.warn("payment:declined",{tool:t,code:i.code,retryable:i.retryable}),ft(i,o);throw cn(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}}};bt();function iy(e,t=process.stderr){if(vt()||!e?.updateAvailable)return!1;let{latestVersion:n}=e.updateAvailable;if(!n)return!1;let r=`Update available: v${n}. Run: visa-cli update`;return t.write(`
168
168
  \x1B[33m\u2191 ${r}\x1B[0m
169
- `),!0}function Zh(e){let t=Array.isArray(e.inputSchema?.required)?e.inputSchema.required.filter(s=>typeof s=="string"):[],n=e.inputSchema?.properties&&typeof e.inputSchema.properties=="object"?e.inputSchema.properties:{};if(t.length===0)return{prompt:"a lobster"};let r={};for(let s of t)r[s]=ik(s,n[s]?.description);return r}function ik(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 ak(e){let t=Pt(e.referralCode,"");if(!t)return[];let n=["Referrals",` Your code ${t}`],r=Pt(e.referralLink,"");if(r&&n.push(` Your link ${r}`),typeof e.referralCount=="number"&&Number.isFinite(e.referralCount)){let s=Math.max(0,Math.trunc(e.referralCount));n.push(` Joined ${s} ${s===1?"person":"people"} via your link`)}return n}var ck=20;function ey(e,t,n,r){let s=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=gk(e.spendingControls).dailyLimit,a=Math.max(0,Co(e.dailyCardFundedTopupSpent??e.dailySpent)),c=i>0?Math.min(i,Math.max(0,Co(e.dailyCardFundedTopupRemaining??e.dailyRemaining??i-a))):0,l=i>0?Math.min(1,a/i):0,d=(Array.isArray(t)?t:[]).filter(dk),p=d.slice(0,3),f=fk(d,3),m=(e.cards??[]).slice(0,3),h=r.latestVersion?Pr(r.latestVersion):"",w=r.updateCheckDisabled?"update checks disabled":h?`update ready: v${h}`:"up to date",C=Math.round(l*100),b=Pt(e.status,e.enrolled?"approved":"not enrolled"),S=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${b} | touch id: ${n?"ready":"unavailable"}`,`Version: v${s} | ${w}`,`Top-up meter: ${Qh(l)} ${String(C).padStart(3," ")}% | remaining ${Ss(c)}/day | daily top-up cap ${Ss(i)}`,"","Card top-ups",` Remaining ${Ss(c)} / ${Ss(i)}`,` Usage ${Qh(l)} ${C}%`,` Top-ups today ${Ss(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...m.length>0?m.map(I=>` ${mk(I)}`):[" No cards enrolled"],"","Last 3 services",...f.length>0?f.map((I,y)=>` ${y+1}. ${I}`):[" No paid services yet"],"","Recent receipts",...p.length>0?p.map(I=>` ${pk(I)}`):[" No receipts yet"]],A=ak(e);return A.length>0&&S.push("",...A),h&&!r.updateCheckDisabled?(S.push("",`Update: v${h} ready \u2014 run \`visa-cli update\``),r.updateMessage&&S.push(` ${Pr(r.updateMessage)}`)):r.updateMessage&&S.push("",`Update: ${Pr(r.updateMessage)}`),`${S.join(`
169
+ `),!0}function ay(e){let t=Array.isArray(e.inputSchema?.required)?e.inputSchema.required.filter(s=>typeof s=="string"):[],n=e.inputSchema?.properties&&typeof e.inputSchema.properties=="object"?e.inputSchema.properties:{};if(t.length===0)return{prompt:"a lobster"};let r={};for(let s of t)r[s]=xC(s,n[s]?.description);return r}function xC(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 TC(e){let t=Ot(e.referralCode,"");if(!t)return[];let n=["Referrals",` Your code ${t}`],r=Ot(e.referralLink,"");if(r&&n.push(` Your link ${r}`),typeof e.referralCount=="number"&&Number.isFinite(e.referralCount)){let s=Math.max(0,Math.trunc(e.referralCount));n.push(` Joined ${s} ${s===1?"person":"people"} via your link`)}return n}var kC=20;function ly(e,t,n,r){let s=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=PC(e.spendingControls).dailyLimit,a=Math.max(0,Eo(e.dailyCardFundedTopupSpent??e.dailySpent)),c=i>0?Math.min(i,Math.max(0,Eo(e.dailyCardFundedTopupRemaining??e.dailyRemaining??i-a))):0,l=i>0?Math.min(1,a/i):0,d=(Array.isArray(t)?t:[]).filter(EC),m=d.slice(0,3),f=RC(d,3),p=(e.cards??[]).slice(0,3),h=r.latestVersion?Mr(r.latestVersion):"",w=r.updateCheckDisabled?"update checks disabled":h?`update ready: v${h}`:"up to date",k=Math.round(l*100),b=Ot(e.status,e.enrolled?"approved":"not enrolled"),S=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${b} | touch id: ${n?"ready":"unavailable"}`,`Version: v${s} | ${w}`,`Top-up meter: ${cy(l)} ${String(k).padStart(3," ")}% | remaining ${ks(c)}/day | daily top-up cap ${ks(i)}`,"","Card top-ups",` Remaining ${ks(c)} / ${ks(i)}`,` Usage ${cy(l)} ${k}%`,` Top-ups today ${ks(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...p.length>0?p.map(I=>` ${$C(I)}`):[" No cards enrolled"],"","Last 3 services",...f.length>0?f.map((I,y)=>` ${y+1}. ${I}`):[" No paid services yet"],"","Recent receipts",...m.length>0?m.map(I=>` ${IC(I)}`):[" No receipts yet"]],E=TC(e);return E.length>0&&S.push("",...E),h&&!r.updateCheckDisabled?(S.push("",`Update: v${h} ready \u2014 run \`visa-cli update\``),r.updateMessage&&S.push(` ${Mr(r.updateMessage)}`)):r.updateMessage&&S.push("",`Update: ${Mr(r.updateMessage)}`),`${S.join(`
170
170
  `)}
171
- `}function lk(e){return e.tool_name!=null}function uk(e){return Co(e.amount)===0&&e.status==="failed"}function dk(e){return lk(e)&&!uk(e)}function fk(e,t=1/0){let n=new Set,r=[];for(let s of e){if(r.length>=t)break;let o=Pt(s.merchant_name,"Unknown merchant"),i=Pt(s.tool_name,"unknown_tool"),a=`${o} :: ${i}`;n.has(a)||(n.add(a),r.push(`${o} [${i}]`))}return r}function pk(e){let t=Pt(e.merchant_name,"Unknown merchant"),n=Pt(e.tool_name,"unknown_tool"),r=Ss(Co(e.amount)),s=Pt(e.status,"unknown"),o=hk(e.created_at);return`${r} ${s.padEnd(9)} ${t} [${n}] ${o}`}function mk(e){let t=Pt(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function gk(e){return{dailyLimit:Co(e?.daily_limit??e?.dailyLimit??0)}}function Co(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function Ss(e){return`$${e.toFixed(2)}`}function Qh(e,t=ck){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function Pt(e,t){let n=Pr(e??"").trim();return n.length>0?n:t}function hk(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?Pt(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function Pr(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 yk=/^[1-9]\d{0,9}$/;function _u(e){if(!yk.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 ty(e){let t=Pr(e.brand||"Visa"),n=Pr(e.last4||"unknown");return{id:Number.isInteger(e.id)?String(e.id):"-",brand:t.charAt(0).toUpperCase()+t.slice(1).toLowerCase(),card:`****${n}`,default:e.isDefault?"yes":""}}var Ot=R(require("fs")),ye=R(require("path")),_k=["npm","pnpm","yarn","bun"],bk=/\s+/,vk=process.platform==="win32"?"visa-cli.cmd":"visa-cli",bu=["node_modules","@visa","cli"];function wk(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(bk)[0]??"",r=n.indexOf("/"),s=r===-1?n:n.slice(0,r);return _k.includes(s)?s:void 0}function vu(e){if(!e)return;let t=e;try{t=Ot.realpathSync(e)}catch{}let n=t.replace(/\\/g,"/").toLowerCase();if(n.includes("/pnpm/")||n.includes("/.pnpm/"))return"pnpm";if(n.includes("/yarn/")||n.includes("/.yarn/"))return"yarn";if(n.includes("/bun/")||n.includes("/.bun/"))return"bun";if(n.includes("/npm/")||n.includes("/node_modules/@visa/cli/"))return"npm"}function Sk(e=process.argv[1]){return wk()??vu(process.env.npm_execpath)??vu(process.env.npm_node_execpath)??vu(e)}function xk(e=process.env.PATH??""){let t=[];for(let n of e.split(ye.delimiter))n&&t.push(n);return t}function Tk(e=process.env.PATH??""){let t=new Set,n=[];for(let r of xk(e))try{let s=ye.join(r,vk);Ot.accessSync(s,Ot.constants.X_OK);let o=ye.resolve(s);t.has(o)||(t.add(o),n.push(s))}catch{}return n}function ny(e){try{let t=Ot.readFileSync(ye.join(e,"package.json"),"utf-8"),n=JSON.parse(t);if(n.name==="@visa/cli"&&typeof n.version=="string")return n.version}catch{}}function Ck(e){let t=ye.resolve(e).split(ye.sep);for(let n=t.length-bu.length;n>=0;n--)if(bu.every((r,s)=>t[n+s]===r)){let r=t.slice(0,n+bu.length).join(ye.sep)||ye.sep;if(ny(r))return r}}function kk(e){if(!e)return;let t=ye.normalize(e),n=t.split(ye.sep),r=o=>o.every((a,c)=>n[n.length-o.length+c]===a)?n.slice(0,-o.length).join(ye.sep)||ye.parse(t).root:void 0,s=r(["lib","node_modules","@visa","cli"]);if(s)return s;if(process.platform==="win32")return r(["node_modules","@visa","cli"])}function Ek(e,t){let n=ye.resolve(e);try{n=Ot.realpathSync(e)}catch{}let r=Ck(n);return{binPath:e,realPath:n,packageRoot:r,version:r?ny(r):void 0,prefix:kk(r),isActive:n===t}}function Ak(e,t=process.env.PATH??""){let n=e??process.argv[1],r=n?ye.resolve(n):"";try{n&&(r=Ot.realpathSync(n))}catch{}let s=e?[e]:[n,...Tk(t)].filter(Boolean),o=new Map;for(let d of s){let p=Ek(d,r),f=o.get(p.realPath);o.set(p.realPath,f?{...p,binPath:f.binPath}:p)}let i=[...o.values()],a=i.find(d=>d.isActive);!a&&i.length>0&&!e&&(a={...i[0],isActive:!0},i[0]=a);let c=new Set(i.map(d=>d.packageRoot).filter(Boolean)),l=!!a?.packageRoot&&c.size>1,u=a?.prefix;return{active:a,installs:i,hasConflictingInstalls:l,recommendedPrefix:u}}function Rk(e,t=process.platform){return/^[A-Za-z0-9_./:@+-]+$/.test(e)?e:t==="win32"?`"${e.replace(/"/g,'""')}"`:`'${e.replace(/'/g,"'\\''")}'`}function wu(e,t,n,r={}){let s=t??Sk(n)??"npm",o=r.withDiagnostics?Ak(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 ${Rk(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 Ik(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 Su(e,t){if(!e.hasConflictingInstalls)return null;let n=["Multiple Visa CLI installs detected.",...e.installs.map(Ik)];return t&&(e.recommendedPrefix?n.push("The update command below targets the active install so your shell actually picks up the new version."):n.push("The update command is shown below; remove duplicate installs if your shell still picks up an older version."),n.push(` ${t}`)),n.join(`
172
- `)}var Ua=R(ts());function $k(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function ry(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=$k(e);return e.attestationRequired!==!1||t?{canContinue:!1,message:"Biometric attestation is unavailable, but this account requires a registered local attestation key.",hint:"Re-run setup from an interactive device with Touch ID (Mac) or Windows Hello (PC), or use an already-registered device to recover or change biometric policy."}:{canContinue:!0,message:"Biometric attestation is unavailable; continuing only because server biometric policy is disabled and no attestation key is registered."}}async function sy(){await K.deleteSessionToken()}var ay=R(require("crypto"));pa();var Ge=R(require("fs")),Aa=R(require("os")),xs=R(require("path")),cy=R(require("node:readline")),xu="3.3.1-rc.3",Pk=process.env.PORTER_API_URL??"https://porter-travel.up.railway.app",Ok=process.env.TAP_REGISTRY_URL??"https://tap-production-eff9.up.railway.app",ko=xs.join(Aa.homedir(),".visa-cli","agents");function Mk(){return!!(process.env.VISA_DEV==="1"||xu==="0.0.0"||xu.startsWith("0.0.")||/-rc\.|-beta\./.test(xu))}function Nk(){Ge.mkdirSync(ko,{recursive:!0,mode:448})}function ku(e){return xs.join(ko,`${e}.json`)}function Tu(){return Ge.existsSync(ko)?Ge.readdirSync(ko).filter(e=>e.endsWith(".json")).map(e=>xs.join(ko,e)):[]}function Lk(e){let t=ku(e);return Ge.existsSync(t)?JSON.parse(Ge.readFileSync(t,"utf8")):null}function Uk(e){Nk();let t=ku(e.agent_id);Ge.writeFileSync(t,JSON.stringify(e,null,2),{mode:384})}async function Cu(e,t,n,r){let s=`${e.replace(/\/+$/,"")}${n}`,o=await fetch(s,{method:t,headers:{"Content-Type":"application/json"},body:r!==void 0?JSON.stringify(r):void 0}),i=await o.json().catch(()=>({}));if(!o.ok||i.errors?.length){let a=i.errors?.[0];throw new Error(`${t} ${s} failed (${o.status}): ${a?.code??"unknown"} \u2014 ${a?.message??"no message"}`)}if(i.data===void 0)throw new Error(`${t} ${s}: empty response data`);return i.data}var oy=Cu;function Dk(){let{secretKey:e}=lh(),t=dh(e);return{publicKeyB64url:t.x,privateJwk:t}}function ly(e,t){let n=ho(t);return ms(go(n,new TextEncoder().encode(e)))}async function jk(e){let{publicKeyB64url:t,privateJwk:n}=Dk(),r=new Date().toISOString(),s=`tap:register:v1:${e.name}:${r}`,o=ly(s,n),i=await Cu(e.registryUrl,"POST","/api/v1/agents",{name:e.name,public_key:t,signed_at:r,signature:o,visibility:"public",capabilities:["porter:book","visa:authorize_payment"]}),a=await Cu(e.porterUrl,"POST","/api/v1/tap/accounts",{public_key:t,name:e.name}),c={agent_id:i.agent_id,tap_registry_url:e.registryUrl,porter_url:e.porterUrl,tap_account_id:a.id,public_key_b64url:t,private_key_jwk:n,name:e.name,created_at:new Date().toISOString()};return Uk(c),c}async function uy(e){let t=await oy(e.porter_url,"GET",`/api/v1/tap/challenge?public_key=${encodeURIComponent(e.public_key_b64url)}`),n=ly(t.challenge,e.private_key_jwk),r=await oy(e.porter_url,"POST","/api/v1/tap/verify",{public_key:e.public_key_b64url,challenge:t.challenge,signature:n});return{token:r.token,expiresInSeconds:r.expires_in}}function Bk(e,t,n){let r=JSON.stringify(t),s=JSON.stringify(n),o=Buffer.from(r).toString("base64url"),i=Buffer.from(s).toString("base64url"),a=`${o}.${i}`,c=ho(e),l=go(c,new TextEncoder().encode(a));return`${a}.${ms(l)}`}var Fk=["visa_authorize_payment"],Hk={name:"visa_authorize_payment",description:["Mint a signed payment-authorization JWT (visa_payment_id) for a merchant.","Pass the returned JWT into the merchant's checkout/booking call (e.g. porter_checkout).","The signing key is the agent's Ed25519 keypair held by visa-cli (kernel-sealed in production).","No money is moved here \u2014 the JWT only authorizes the merchant to settle later for up to `amount`."].join(" "),inputSchema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",additionalProperties:!1,properties:{merchant:{type:"string",description:'Merchant identifier \u2014 must match the merchant\'s `aud` claim. Today: "porter".'},amount:{type:"integer",minimum:1,description:"Amount in minor units (cents for USD). MUST equal or exceed the merchant transaction total."},currency:{type:"string",minLength:3,maxLength:3,description:'ISO 4217 currency code, e.g. "USD".'},idem_key:{type:"string",description:"Merchant-stable transaction binding. For porter: the cart_id from porter_add_to_cart."},description:{type:"string",description:'Human-readable purpose of the payment, e.g. "JFK\u2192CDG business 2026-09-15".'}},required:["merchant","amount","currency","idem_key"]}};function Vk(e){if(e===null||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"visa_authorize_payment: arguments must be an object"};let t=e;return typeof t.merchant!="string"||t.merchant.length===0?{ok:!1,error:"visa_authorize_payment: merchant must be a non-empty string"}:typeof t.idem_key!="string"||t.idem_key.length===0?{ok:!1,error:"visa_authorize_payment: idem_key must be a non-empty string"}:typeof t.currency!="string"||!/^[A-Za-z]{3}$/.test(t.currency)?{ok:!1,error:"visa_authorize_payment: currency must be a 3-letter ISO 4217 code"}:typeof t.amount!="number"||!Number.isFinite(t.amount)||!Number.isSafeInteger(t.amount)||t.amount<1?{ok:!1,error:"visa_authorize_payment: amount must be a positive safe-integer (minor units, \u22651)"}:{ok:!0,value:{merchant:t.merchant,amount:t.amount,currency:t.currency,idem_key:t.idem_key,description:typeof t.description=="string"?t.description:void 0}}}function qk(e,t){let n=Math.floor(Date.now()/1e3),r=n+300,s=`vpid_${ay.randomBytes(16).toString("hex")}`,o=process.env.VISACLI_ISSUER??e.tap_registry_url??e.porter_url;return{jwt:Bk(e.private_key_jwk,{alg:"EdDSA",typ:"JWT",kid:e.agent_id},{iss:o,aud:t.merchant,sub:e.agent_id,amount:t.amount,currency:t.currency.toUpperCase(),idem_key:t.idem_key,iat:n,nbf:n,exp:r,jti:s}),jti:s,expiresAt:r}}async function Kk(e){let t=`${e.porter_url.replace(/\/+$/,"")}/api/mcp`,n=null,r=0;async function s(p=!1){if(!p&&n&&Date.now()<r-6e4)return n;let{token:f,expiresInSeconds:m}=await uy(e);return n=f,r=Date.now()+m*1e3,f}function o(p){process.stdout.write(JSON.stringify(p)+`
173
- `)}function i(p,f,m){o({jsonrpc:"2.0",id:p??null,error:{code:f,message:m}})}function a(p,f,m){if(f==="visa_authorize_payment"){let h=Vk(m);if(!h.ok){i(p,-32602,h.error);return}let w=h.value;try{let{jwt:C,jti:b,expiresAt:v}=qk(e,w);o({jsonrpc:"2.0",id:p,result:{content:[{type:"text",text:["\u2713 Payment authorized \u2014 pass this JWT as visa_payment_id at checkout:","",C,"",` agent: ${e.agent_id}`,` merchant: ${w.merchant}`,` amount: ${w.amount} ${w.currency.toUpperCase()}`,` jti: ${b}`,` expires: ${new Date(v*1e3).toISOString()}`].join(`
174
- `)},{type:"text",text:JSON.stringify({visa_payment_id:C,jti:b,agent_id:e.agent_id,amount:w.amount,currency:w.currency.toUpperCase(),merchant:w.merchant,expires_at:v})}]}})}catch(C){i(p,-32603,`failed to sign visa_payment_id: ${C instanceof Error?C.message:String(C)}`)}return}i(p,-32601,`unknown synthetic tool: ${f}`)}async function c(p){if(p.method==="tools/call"){let m=p.params??{};if(typeof m.name=="string"&&Fk.includes(m.name)){a(p.id,m.name,m.arguments??{});return}}let f=0;for(;f<2;){f+=1;let m=await s(f>1),h;try{h=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","X-TAP-Token":m},body:JSON.stringify(p)})}catch(C){i(p.id,-32e3,`network error talking to porter: ${C instanceof Error?C.message:String(C)}`);return}if(h.status===401&&f===1){n=null;continue}if(!h.ok){let C=await h.text().catch(()=>"");i(p.id,-32e3,`porter returned ${h.status}: ${C.slice(0,400)}`);return}if((h.headers.get("content-type")??"").includes("text/event-stream"))await u(h,p);else{let C=await h.text();if(C.trim()){let b=JSON.parse(C);l(p,b),o(b)}}return}}function l(p,f){if(p.method!=="tools/list")return;let m=f.result;!m||!Array.isArray(m.tools)||m.tools.some(h=>h.name==="visa_authorize_payment")||m.tools.push(Hk)}async function u(p,f){let m=p.body?.getReader();if(!m)return;let h=new TextDecoder,w="";for(;;){let{done:C,value:b}=await m.read();if(C)break;w+=h.decode(b,{stream:!0});let v;for(;(v=w.indexOf(`
171
+ `}function CC(e){return e.tool_name!=null}function AC(e){return Eo(e.amount)===0&&e.status==="failed"}function EC(e){return CC(e)&&!AC(e)}function RC(e,t=1/0){let n=new Set,r=[];for(let s of e){if(r.length>=t)break;let o=Ot(s.merchant_name,"Unknown merchant"),i=Ot(s.tool_name,"unknown_tool"),a=`${o} :: ${i}`;n.has(a)||(n.add(a),r.push(`${o} [${i}]`))}return r}function IC(e){let t=Ot(e.merchant_name,"Unknown merchant"),n=Ot(e.tool_name,"unknown_tool"),r=ks(Eo(e.amount)),s=Ot(e.status,"unknown"),o=OC(e.created_at);return`${r} ${s.padEnd(9)} ${t} [${n}] ${o}`}function $C(e){let t=Ot(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function PC(e){return{dailyLimit:Eo(e?.daily_limit??e?.dailyLimit??0)}}function Eo(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function ks(e){return`$${e.toFixed(2)}`}function cy(e,t=kC){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function Ot(e,t){let n=Mr(e??"").trim();return n.length>0?n:t}function OC(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?Ot(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function Mr(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 MC=/^[1-9]\d{0,9}$/;function ku(e){if(!MC.test(e))throw new Error("card id must be a positive integer with up to 10 digits. Run `visa-cli cards list` first.");return Number(e)}function uy(e){let t=Mr(e.brand||"Visa"),n=Mr(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 Mt=R(require("fs")),_e=R(require("path")),NC=["npm","pnpm","yarn","bun"],LC=/\s+/,UC=process.platform==="win32"?"visa-cli.cmd":"visa-cli",Cu=["node_modules","@visa","cli"];function DC(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(LC)[0]??"",r=n.indexOf("/"),s=r===-1?n:n.slice(0,r);return NC.includes(s)?s:void 0}function Au(e){if(!e)return;let t=e;try{t=Mt.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 jC(e=process.argv[1]){return DC()??Au(process.env.npm_execpath)??Au(process.env.npm_node_execpath)??Au(e)}function BC(e=process.env.PATH??""){let t=[];for(let n of e.split(_e.delimiter))n&&t.push(n);return t}function FC(e=process.env.PATH??""){let t=new Set,n=[];for(let r of BC(e))try{let s=_e.join(r,UC);Mt.accessSync(s,Mt.constants.X_OK);let o=_e.resolve(s);t.has(o)||(t.add(o),n.push(s))}catch{}return n}function dy(e){try{let t=Mt.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 HC(e){let t=_e.resolve(e).split(_e.sep);for(let n=t.length-Cu.length;n>=0;n--)if(Cu.every((r,s)=>t[n+s]===r)){let r=t.slice(0,n+Cu.length).join(_e.sep)||_e.sep;if(dy(r))return r}}function VC(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 qC(e,t){let n=_e.resolve(e);try{n=Mt.realpathSync(e)}catch{}let r=HC(n);return{binPath:e,realPath:n,packageRoot:r,version:r?dy(r):void 0,prefix:VC(r),isActive:n===t}}function KC(e,t=process.env.PATH??""){let n=e??process.argv[1],r=n?_e.resolve(n):"";try{n&&(r=Mt.realpathSync(n))}catch{}let s=e?[e]:[n,...FC(t)].filter(Boolean),o=new Map;for(let d of s){let m=qC(d,r),f=o.get(m.realPath);o.set(m.realPath,f?{...m,binPath:f.binPath}:m)}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 GC(e,t=process.platform){return/^[A-Za-z0-9_./:@+-]+$/.test(e)?e:t==="win32"?`"${e.replace(/"/g,'""')}"`:`'${e.replace(/'/g,"'\\''")}'`}function Eu(e,t,n,r={}){let s=t??jC(n)??"npm",o=r.withDiagnostics?KC(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 ${GC(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 WC(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 Ru(e,t){if(!e.hasConflictingInstalls)return null;let n=["Multiple Visa CLI installs detected.",...e.installs.map(WC)];return t&&(e.recommendedPrefix?n.push("The update command below targets the active install so your shell actually picks up the new version."):n.push("The update command is shown below; remove duplicate installs if your shell still picks up an older version."),n.push(` ${t}`)),n.join(`
172
+ `)}var Fa=R(ss());function YC(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function fy(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=YC(e);return e.attestationRequired!==!1||t?{canContinue:!1,message:"Biometric attestation is unavailable, but this account requires a registered local attestation key.",hint:"Re-run setup from an interactive device with Touch ID (Mac) or Windows Hello (PC), or use an already-registered device to recover or change biometric policy."}:{canContinue:!0,message:"Biometric attestation is unavailable; continuing only because server biometric policy is disabled and no attestation key is registered."}}async function my(){await G.deleteSessionToken()}var hy=R(require("crypto"));ya();var Ge=R(require("fs")),Pa=R(require("os")),Cs=R(require("path")),yy=R(require("node:readline")),Iu="3.4.0-rc.5",zC=process.env.PORTER_API_URL??"https://porter-travel.up.railway.app",JC=process.env.TAP_REGISTRY_URL??"https://tap-production-eff9.up.railway.app",Ro=Cs.join(Pa.homedir(),".visa-cli","agents");function XC(){return!!(process.env.VISA_DEV==="1"||Iu==="0.0.0"||Iu.startsWith("0.0.")||/-rc\.|-beta\./.test(Iu))}function ZC(){Ge.mkdirSync(Ro,{recursive:!0,mode:448})}function Ou(e){return Cs.join(Ro,`${e}.json`)}function $u(){return Ge.existsSync(Ro)?Ge.readdirSync(Ro).filter(e=>e.endsWith(".json")).map(e=>Cs.join(Ro,e)):[]}function QC(e){let t=Ou(e);return Ge.existsSync(t)?JSON.parse(Ge.readFileSync(t,"utf8")):null}function eA(e){ZC();let t=Ou(e.agent_id);Ge.writeFileSync(t,JSON.stringify(e,null,2),{mode:384})}async function Pu(e,t,n,r){let s=`${e.replace(/\/+$/,"")}${n}`,o=await fetch(s,{method:t,headers:{"Content-Type":"application/json"},body:r!==void 0?JSON.stringify(r):void 0}),i=await o.json().catch(()=>({}));if(!o.ok||i.errors?.length){let a=i.errors?.[0];throw new Error(`${t} ${s} failed (${o.status}): ${a?.code??"unknown"} \u2014 ${a?.message??"no message"}`)}if(i.data===void 0)throw new Error(`${t} ${s}: empty response data`);return i.data}var py=Pu;function tA(){let{secretKey:e}=_h(),t=vh(e);return{publicKeyB64url:t.x,privateJwk:t}}function _y(e,t){let n=bo(t);return ys(_o(n,new TextEncoder().encode(e)))}async function nA(e){let{publicKeyB64url:t,privateJwk:n}=tA(),r=new Date().toISOString(),s=`tap:register:v1:${e.name}:${r}`,o=_y(s,n),i=await Pu(e.registryUrl,"POST","/api/v1/agents",{name:e.name,public_key:t,signed_at:r,signature:o,visibility:"public",capabilities:["porter:book","visa:authorize_payment"]}),a=await Pu(e.porterUrl,"POST","/api/v1/tap/accounts",{public_key:t,name:e.name}),c={agent_id:i.agent_id,tap_registry_url:e.registryUrl,porter_url:e.porterUrl,tap_account_id:a.id,public_key_b64url:t,private_key_jwk:n,name:e.name,created_at:new Date().toISOString()};return eA(c),c}async function by(e){let t=await py(e.porter_url,"GET",`/api/v1/tap/challenge?public_key=${encodeURIComponent(e.public_key_b64url)}`),n=_y(t.challenge,e.private_key_jwk),r=await py(e.porter_url,"POST","/api/v1/tap/verify",{public_key:e.public_key_b64url,challenge:t.challenge,signature:n});return{token:r.token,expiresInSeconds:r.expires_in}}function rA(e,t,n){let r=JSON.stringify(t),s=JSON.stringify(n),o=Buffer.from(r).toString("base64url"),i=Buffer.from(s).toString("base64url"),a=`${o}.${i}`,c=bo(e),l=_o(c,new TextEncoder().encode(a));return`${a}.${ys(l)}`}var sA=["visa_authorize_payment"],oA={name:"visa_authorize_payment",description:["Mint a signed payment-authorization JWT (visa_payment_id) for a merchant.","Pass the returned JWT into the merchant's checkout/booking call (e.g. porter_checkout).","The signing key is the agent's Ed25519 keypair held by visa-cli (kernel-sealed in production).","No money is moved here \u2014 the JWT only authorizes the merchant to settle later for up to `amount`."].join(" "),inputSchema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",additionalProperties:!1,properties:{merchant:{type:"string",description:'Merchant identifier \u2014 must match the merchant\'s `aud` claim. Today: "porter".'},amount:{type:"integer",minimum:1,description:"Amount in minor units (cents for USD). MUST equal or exceed the merchant transaction total."},currency:{type:"string",minLength:3,maxLength:3,description:'ISO 4217 currency code, e.g. "USD".'},idem_key:{type:"string",description:"Merchant-stable transaction binding. For porter: the cart_id from porter_add_to_cart."},description:{type:"string",description:'Human-readable purpose of the payment, e.g. "JFK\u2192CDG business 2026-09-15".'}},required:["merchant","amount","currency","idem_key"]}};function iA(e){if(e===null||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"visa_authorize_payment: arguments must be an object"};let t=e;return typeof t.merchant!="string"||t.merchant.length===0?{ok:!1,error:"visa_authorize_payment: merchant must be a non-empty string"}:typeof t.idem_key!="string"||t.idem_key.length===0?{ok:!1,error:"visa_authorize_payment: idem_key must be a non-empty string"}:typeof t.currency!="string"||!/^[A-Za-z]{3}$/.test(t.currency)?{ok:!1,error:"visa_authorize_payment: currency must be a 3-letter ISO 4217 code"}:typeof t.amount!="number"||!Number.isFinite(t.amount)||!Number.isSafeInteger(t.amount)||t.amount<1?{ok:!1,error:"visa_authorize_payment: amount must be a positive safe-integer (minor units, \u22651)"}:{ok:!0,value:{merchant:t.merchant,amount:t.amount,currency:t.currency,idem_key:t.idem_key,description:typeof t.description=="string"?t.description:void 0}}}function aA(e,t){let n=Math.floor(Date.now()/1e3),r=n+300,s=`vpid_${hy.randomBytes(16).toString("hex")}`,o=process.env.VISACLI_ISSUER??e.tap_registry_url??e.porter_url;return{jwt:rA(e.private_key_jwk,{alg:"EdDSA",typ:"JWT",kid:e.agent_id},{iss:o,aud:t.merchant,sub:e.agent_id,amount:t.amount,currency:t.currency.toUpperCase(),idem_key:t.idem_key,iat:n,nbf:n,exp:r,jti:s}),jti:s,expiresAt:r}}async function cA(e){let t=`${e.porter_url.replace(/\/+$/,"")}/api/mcp`,n=null,r=0;async function s(m=!1){if(!m&&n&&Date.now()<r-6e4)return n;let{token:f,expiresInSeconds:p}=await by(e);return n=f,r=Date.now()+p*1e3,f}function o(m){process.stdout.write(JSON.stringify(m)+`
173
+ `)}function i(m,f,p){o({jsonrpc:"2.0",id:m??null,error:{code:f,message:p}})}function a(m,f,p){if(f==="visa_authorize_payment"){let h=iA(p);if(!h.ok){i(m,-32602,h.error);return}let w=h.value;try{let{jwt:k,jti:b,expiresAt:v}=aA(e,w);o({jsonrpc:"2.0",id:m,result:{content:[{type:"text",text:["\u2713 Payment authorized \u2014 pass this JWT as visa_payment_id at checkout:","",k,"",` agent: ${e.agent_id}`,` merchant: ${w.merchant}`,` amount: ${w.amount} ${w.currency.toUpperCase()}`,` jti: ${b}`,` expires: ${new Date(v*1e3).toISOString()}`].join(`
174
+ `)},{type:"text",text:JSON.stringify({visa_payment_id:k,jti:b,agent_id:e.agent_id,amount:w.amount,currency:w.currency.toUpperCase(),merchant:w.merchant,expires_at:v})}]}})}catch(k){i(m,-32603,`failed to sign visa_payment_id: ${k instanceof Error?k.message:String(k)}`)}return}i(m,-32601,`unknown synthetic tool: ${f}`)}async function c(m){if(m.method==="tools/call"){let p=m.params??{};if(typeof p.name=="string"&&sA.includes(p.name)){a(m.id,p.name,p.arguments??{});return}}let f=0;for(;f<2;){f+=1;let p=await s(f>1),h;try{h=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","X-TAP-Token":p},body:JSON.stringify(m)})}catch(k){i(m.id,-32e3,`network error talking to porter: ${k instanceof Error?k.message:String(k)}`);return}if(h.status===401&&f===1){n=null;continue}if(!h.ok){let k=await h.text().catch(()=>"");i(m.id,-32e3,`porter returned ${h.status}: ${k.slice(0,400)}`);return}if((h.headers.get("content-type")??"").includes("text/event-stream"))await u(h,m);else{let k=await h.text();if(k.trim()){let b=JSON.parse(k);l(m,b),o(b)}}return}}function l(m,f){if(m.method!=="tools/list")return;let p=f.result;!p||!Array.isArray(p.tools)||p.tools.some(h=>h.name==="visa_authorize_payment")||p.tools.push(oA)}async function u(m,f){let p=m.body?.getReader();if(!p)return;let h=new TextDecoder,w="";for(;;){let{done:k,value:b}=await p.read();if(k)break;w+=h.decode(b,{stream:!0});let v;for(;(v=w.indexOf(`
175
175
 
176
- `))>=0;){let S=w.slice(0,v);w=w.slice(v+2);for(let A of S.split(`
177
- `))if(A.startsWith("data: ")){let I=A.slice(6).trim();if(!I)continue;try{let y=JSON.parse(I);l(f,y),o(y)}catch{}}}}}await s().catch(()=>{});let d=cy.createInterface({input:process.stdin,terminal:!1});for await(let p of d){let f=p.trim();if(!f)continue;let m;try{m=JSON.parse(f)}catch{continue}c(m)}}function iy(e){let t=Tu();if(t.length===0)throw new Error("No agents registered. Run `visa-cli agent register` first.");if(e){let n=Lk(e);if(!n)throw new Error(`Agent not found: ${e}`);return n}if(t.length>1){let n=t.map(r=>xs.basename(r,".json")).map(r=>` - ${r}`).join(`
176
+ `))>=0;){let S=w.slice(0,v);w=w.slice(v+2);for(let E of S.split(`
177
+ `))if(E.startsWith("data: ")){let I=E.slice(6).trim();if(!I)continue;try{let y=JSON.parse(I);l(f,y),o(y)}catch{}}}}}await s().catch(()=>{});let d=yy.createInterface({input:process.stdin,terminal:!1});for await(let m of d){let f=m.trim();if(!f)continue;let p;try{p=JSON.parse(f)}catch{continue}c(p)}}function gy(e){let t=$u();if(t.length===0)throw new Error("No agents registered. Run `visa-cli agent register` first.");if(e){let n=QC(e);if(!n)throw new Error(`Agent not found: ${e}`);return n}if(t.length>1){let n=t.map(r=>Cs.basename(r,".json")).map(r=>` - ${r}`).join(`
178
178
  `);throw new Error(`Multiple agents registered \u2014 pass --agent <id>:
179
- ${n}`)}return JSON.parse(Ge.readFileSync(t[0],"utf8"))}function dy(e){if(!Mk())return;let t=e.command("agent").description("(dev/rc) Manage agent identities for AI clients. Pre-kernel fallback \u2014 graduates to kernel signing once available.");t.command("register").description("Provision an Ed25519 keypair, publish in the tap-stack registry, and authorize with porter.").option("--porter <url>","Porter merchant URL",Pk).option("--registry <url>","TAP registry URL (publishes the JWKS)",Ok).option("--name <name>","Human-readable name for this agent",`${process.env.USER??"user"}@${Aa.hostname()}`).action(async n=>{try{let r=await jk({registryUrl:n.registry,porterUrl:n.porter,name:n.name}),s=Tu().length>1?` --agent ${r.agent_id}`:"";process.stdout.write(["\u2713 Agent registered",` agent_id: ${r.agent_id} (kid for visa_payment_id JWTs)`,` tap registry: ${r.tap_registry_url}`,` porter: ${r.porter_url}`,` tap_account: ${r.tap_account_id} (porter x-tap-token)`,` name: ${r.name}`,` key file: ${ku(r.agent_id)}`,"","Next \u2014 add porter to your AI client (visa-cli will inject the TAP token automatically):","",` claude mcp add porter -- visa-cli agent proxy${s}`,"",'Now ask Claude: "search flights from JFK to CDG on 2026-09-15."',""].join(`
179
+ ${n}`)}return JSON.parse(Ge.readFileSync(t[0],"utf8"))}function vy(e){if(!XC())return;let t=e.command("agent").description("(dev/rc) Manage agent identities for AI clients. Pre-kernel fallback \u2014 graduates to kernel signing once available.");t.command("register").description("Provision an Ed25519 keypair, publish in the tap-stack registry, and authorize with porter.").option("--porter <url>","Porter merchant URL",zC).option("--registry <url>","TAP registry URL (publishes the JWKS)",JC).option("--name <name>","Human-readable name for this agent",`${process.env.USER??"user"}@${Pa.hostname()}`).action(async n=>{try{let r=await nA({registryUrl:n.registry,porterUrl:n.porter,name:n.name}),s=$u().length>1?` --agent ${r.agent_id}`:"";process.stdout.write(["\u2713 Agent registered",` agent_id: ${r.agent_id} (kid for visa_payment_id JWTs)`,` tap registry: ${r.tap_registry_url}`,` porter: ${r.porter_url}`,` tap_account: ${r.tap_account_id} (porter x-tap-token)`,` name: ${r.name}`,` key file: ${Ou(r.agent_id)}`,"","Next \u2014 add porter to your AI client (visa-cli will inject the TAP token automatically):","",` claude mcp add porter -- visa-cli agent proxy${s}`,"",'Now ask Claude: "search flights from JFK to CDG on 2026-09-15."',""].join(`
180
180
  `))}catch(r){process.stderr.write(`agent register failed: ${r instanceof Error?r.message:String(r)}
181
- `),process.exit(1)}}),t.command("token").description("Mint a fresh 24h TAP token for the registered agent.").option("--agent <id>","Specific agent_id (required if more than one is registered)").option("--export","Print as `export X_TAP_TOKEN=\u2026` for shell sourcing",!1).action(async n=>{try{let r=iy(n.agent),{token:s,expiresInSeconds:o}=await uy(r);n.export?process.stdout.write(`export X_TAP_TOKEN='${s}'
181
+ `),process.exit(1)}}),t.command("token").description("Mint a fresh 24h TAP token for the registered agent.").option("--agent <id>","Specific agent_id (required if more than one is registered)").option("--export","Print as `export X_TAP_TOKEN=\u2026` for shell sourcing",!1).action(async n=>{try{let r=gy(n.agent),{token:s,expiresInSeconds:o}=await by(r);n.export?process.stdout.write(`export X_TAP_TOKEN='${s}'
182
182
  `):process.stdout.write(`${s}
183
183
  `),process.stderr.write(`# expires in ${Math.round(o/3600)}h \xB7 agent ${r.agent_id}
184
184
  `)}catch(r){process.stderr.write(`agent token failed: ${r instanceof Error?r.message:String(r)}
185
- `),process.exit(1)}}),t.command("proxy").description("Run as a stdio MCP server that proxies to porter. Inject X-TAP-Token automatically. Used by AI clients (claude mcp add porter -- visa-cli agent proxy).").option("--agent <id>","Specific agent_id (required if more than one is registered)").action(async n=>{try{let r=iy(n.agent);await Kk(r)}catch(r){process.stderr.write(`agent proxy failed: ${r instanceof Error?r.message:String(r)}
186
- `),process.exit(1)}}),t.command("list").description("List registered agents.").action(()=>{let n=Tu();if(n.length===0){process.stdout.write("No agents registered. Run `visa-cli agent register` to add one.\n");return}for(let r of n){let s=JSON.parse(Ge.readFileSync(r,"utf8"));process.stdout.write(`${s.agent_id} ${s.porter_url} ${s.name}
187
- `)}})}Ll();bo();var Gk="3.3.1-rc.3";async function fy(e){let t=await nu(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 Ra=(e,t)=>{console.error(`\u2717 ${e} failed: ${t instanceof Error?t.message:String(t)}`),process.exitCode=1};function py(e){if(!Ql(Gk))return;e.command("register <name>").description(`Register a name on the "${Xe}" Subway mesh (reuses your CLI agent key \u2014 no TAP setup needed).`).action(async n=>{try{await fy(n)}catch(r){Ra("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 fy(n)}catch(r){Ra("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=ha(s.as),i=await ru(o,n,r);console.log(`\u2713 sent to ${i.to} as ${i.as}`)}catch(o){Ra("send",o)}}),t.command("listen").description("Stay connected and print inbound messages (Ctrl-C to stop).").option("--as <name>","Registered name to listen as (default: the only one registered)").option("--room <topic>","Also subscribe to a room topic").action(async n=>{try{let r=ha(n.as),s=ys(r,{autoReconnect:!0});await _s(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 ${xr(r)} on "${Xe}" 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){Ra("listen",r)}}),t.command("whoami").description("List names this CLI has registered on the relay.").action(()=>{let n=su();if(n.length===0){console.log("No Subway names registered. Run `visa register <name>`.");return}for(let r of n)console.log(`${r.relayName} mesh=${r.mesh} peer=${r.peerId??"?"} ${r.tapAgentId?`tap=${r.tapAgentId}`:"(standalone key)"} registered=${r.registeredAt}`)})}_t();Ht();var Wk=["get_status","add_card","pay","get_visa_smi","get_cards","remove_card","set_default_card","buy_credits","transaction_history","update_spending_controls","config_list","config_set","config_unset","biometric_status","biometric_on","biometric_off","reset","login","start_session","close_session","get_session_status","set_session_mode","generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card","feedback","suggest_meme_templates","batch","discover_tools","execute_tool"];function Yk(){let e=new Set;for(let t of Wk)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of ro)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var J2=Yk();var Eu=new Set(["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"]);var t$=new Set(ro),n$=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...Eu,...ro]);Ht();var G=R(require("fs")),F=R(require("path")),my=R(require("os")),fe=my.homedir(),zk=["Claude_","Anthropic.ClaudeDesktop_"],Ts=class extends Error{constructor(n,r,s){super(Xk(n,r,s));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function gy(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
188
- `)}function Jk(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=gy(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function Xk(e,t,n){let r=t.replace(fe,"~"),s=gy(n).split(`
189
- `).find(Boolean),o=s?` (${s})`:"";return e.id==="codex"?`Could not update Codex MCP config at ${r}: filesystem access was denied${o}. In Codex, rerun with elevated filesystem access or run \`visa-cli install codex\` outside the sandbox.`:`Could not update ${e.displayName} MCP config at ${r}: filesystem access was denied${o}.`}function Eo(){return process.env.APPDATA||F.join(fe,"AppData","Roaming")}function Zk(){return process.env.LOCALAPPDATA||F.join(fe,"AppData","Local")}function Au(e){return process.platform==="win32"?e.win32:e.posix}function hy(){if(process.platform!=="win32")return;let e=F.join(Zk(),"Packages");if(G.existsSync(e))try{let t=G.readdirSync(e,"utf-8");for(let n of zk){let r=t.filter(s=>s.startsWith(n)).sort()[0];if(r)return F.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function yy(){if(process.platform==="win32"){let e=hy();return e?F.join(e,"claude_desktop_config.json"):F.join(Eo(),"Claude","claude_desktop_config.json")}return F.join(fe,"Library","Application Support","Claude","claude_desktop_config.json")}function _y(){if(process.platform!=="win32")return[F.join(fe,"Library","Application Support","Claude")];let e=[F.join(Eo(),"Claude")],t=hy();return t&&e.push(t),e}function Ia(e){return e.id==="claude-desktop"?yy():e.globalConfigPath}function Qk(e){return e.id==="claude-desktop"?_y():e.detectPaths}var ft=[{id:"claude",displayName:"Claude Code",globalConfigPath:F.join(fe,".claude.json"),configKey:"mcpServers",detectPaths:[F.join(fe,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:yy(),configKey:"mcpServers",detectPaths:_y(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:F.join(fe,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[F.join(fe,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:F.join(fe,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[F.join(fe,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:F.join(fe,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[F.join(fe,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:Au({win32:F.join(Eo(),"Roo","mcp_settings.json"),posix:F.join(fe,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[F.join(fe,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:F.join(fe,".vscode","mcp.json"),configKey:"servers",detectPaths:[F.join(fe,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:Au({win32:F.join(Eo(),"Zed","settings.json"),posix:F.join(fe,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:Au({win32:[F.join(Eo(),"Zed")],posix:[F.join(fe,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:F.join(fe,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[F.join(fe,".codex")],postInstallHint:"Restart Codex to connect."}];function Ru(e){return ft.find(t=>t.id===e)}function Ao(e){return Qk(e).some(t=>{if(t.includes("*")){let n=F.dirname(t),r=F.basename(t).replaceAll("*","");if(!G.existsSync(n))return!1;try{return G.readdirSync(n).some(s=>s.startsWith(r))}catch{return!1}}return G.existsSync(t)})}function by(){return{command:"node",args:[F.resolve(__dirname,"mcp-server/index.js")]}}function Iu(e,t){return t==="project"?"json":e.configFormat??"json"}function eE(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 $u(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 Pu(e,t){let n=e.split(`
190
- `),r=$u(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]]=eE(i[2]))}return Object.keys(s).length>0?s:void 0}function tE(e,t,n){let r=`[${n.args.map(c=>`"${c}"`).join(", ")}]`,s=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],o=e.split(`
191
- `),i=$u(o,t);if(i){o.splice(i.start,i.end-i.start,...s);let c=o.join(`
185
+ `),process.exit(1)}}),t.command("proxy").description("Run as a stdio MCP server that proxies to porter. Inject X-TAP-Token automatically. Used by AI clients (claude mcp add porter -- visa-cli agent proxy).").option("--agent <id>","Specific agent_id (required if more than one is registered)").action(async n=>{try{let r=gy(n.agent);await cA(r)}catch(r){process.stderr.write(`agent proxy failed: ${r instanceof Error?r.message:String(r)}
186
+ `),process.exit(1)}}),t.command("list").description("List registered agents.").action(()=>{let n=$u();if(n.length===0){process.stdout.write("No agents registered. Run `visa-cli agent register` to add one.\n");return}for(let r of n){let s=JSON.parse(Ge.readFileSync(r,"utf8"));process.stdout.write(`${s.agent_id} ${s.porter_url} ${s.name}
187
+ `)}})}Vl();So();var lA="3.4.0-rc.5";async function wy(e){let t=await lu(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: ${wo} (mesh="${t.mesh}")`),console.log(` chat: visa subway listen --as ${e} | visa subway send --as ${e} <to> "<text>"`)}var Oa=(e,t)=>{console.error(`\u2717 ${e} failed: ${t instanceof Error?t.message:String(t)}`),process.exitCode=1};function Sy(e){if(!iu(lA))return;e.command("register <name>").description(`Register a name on the "${Xe}" Subway mesh (reuses your CLI agent key \u2014 no TAP setup needed).`).action(async n=>{try{await wy(n)}catch(r){Oa("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 wy(n)}catch(r){Oa("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=va(s.as),i=await uu(o,n,r);console.log(`\u2713 sent to ${i.to} as ${i.as}`)}catch(o){Oa("send",o)}}),t.command("listen").description("Stay connected and print inbound messages (Ctrl-C to stop).").option("--as <name>","Registered name to listen as (default: the only one registered)").option("--room <topic>","Also subscribe to a room topic").action(async n=>{try{let r=va(n.as),s=vs(r,{autoReconnect:!0});await ws(s);let o=a=>new Date(a).toLocaleTimeString();s.onMessage(a=>{let c=a.verified?"":" (unverified)";console.log(`[${o(a.timestampMs)}] ${a.fromName}${c}: ${a.payload}`)}),n.room&&s.subscribe(n.room,a=>{console.log(`[${o(a.timestampMs)}] #${a.topic} ${a.fromName}: ${a.payload}`)}),console.log(`\u2026 listening as ${kr(r)} on "${Xe}" 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){Oa("listen",r)}}),t.command("whoami").description("List names this CLI has registered on the relay.").action(()=>{let n=du();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}`)})}bt();Vt();var uA=["get_status","add_card","pay","get_visa_smi","get_cards","remove_card","set_default_card","buy_credits","transaction_history","update_spending_controls","config_list","config_set","config_unset","biometric_status","biometric_on","biometric_off","reset","login","start_session","close_session","get_session_status","set_session_mode","generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card","feedback","suggest_meme_templates","batch","discover_tools","execute_tool"];function dA(){let e=new Set;for(let t of uA)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of io)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var g$=dA();var Mu=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 v$=new Set(io),w$=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...Mu,...io]);Vt();var W=R(require("fs")),F=R(require("path")),xy=R(require("os")),me=xy.homedir(),fA=["Claude_","Anthropic.ClaudeDesktop_"],As=class extends Error{constructor(n,r,s){super(pA(n,r,s));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function Ty(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
188
+ `)}function mA(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=Ty(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function pA(e,t,n){let r=t.replace(me,"~"),s=Ty(n).split(`
189
+ `).find(Boolean),o=s?` (${s})`:"";return e.id==="codex"?`Could not update Codex MCP config at ${r}: filesystem access was denied${o}. In Codex, rerun with elevated filesystem access or run \`visa-cli install codex\` outside the sandbox.`:`Could not update ${e.displayName} MCP config at ${r}: filesystem access was denied${o}.`}function Io(){return process.env.APPDATA||F.join(me,"AppData","Roaming")}function gA(){return process.env.LOCALAPPDATA||F.join(me,"AppData","Local")}function Nu(e){return process.platform==="win32"?e.win32:e.posix}function ky(){if(process.platform!=="win32")return;let e=F.join(gA(),"Packages");if(W.existsSync(e))try{let t=W.readdirSync(e,"utf-8");for(let n of fA){let r=t.filter(s=>s.startsWith(n)).sort()[0];if(r)return F.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function Cy(){if(process.platform==="win32"){let e=ky();return e?F.join(e,"claude_desktop_config.json"):F.join(Io(),"Claude","claude_desktop_config.json")}return F.join(me,"Library","Application Support","Claude","claude_desktop_config.json")}function Ay(){if(process.platform!=="win32")return[F.join(me,"Library","Application Support","Claude")];let e=[F.join(Io(),"Claude")],t=ky();return t&&e.push(t),e}function Ma(e){return e.id==="claude-desktop"?Cy():e.globalConfigPath}function hA(e){return e.id==="claude-desktop"?Ay():e.detectPaths}var mt=[{id:"claude",displayName:"Claude Code",globalConfigPath:F.join(me,".claude.json"),configKey:"mcpServers",detectPaths:[F.join(me,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:Cy(),configKey:"mcpServers",detectPaths:Ay(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:F.join(me,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[F.join(me,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:F.join(me,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[F.join(me,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:F.join(me,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[F.join(me,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:Nu({win32:F.join(Io(),"Roo","mcp_settings.json"),posix:F.join(me,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[F.join(me,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:F.join(me,".vscode","mcp.json"),configKey:"servers",detectPaths:[F.join(me,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:Nu({win32:F.join(Io(),"Zed","settings.json"),posix:F.join(me,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:Nu({win32:[F.join(Io(),"Zed")],posix:[F.join(me,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:F.join(me,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[F.join(me,".codex")],postInstallHint:"Restart Codex to connect."}];function Lu(e){return mt.find(t=>t.id===e)}function $o(e){return hA(e).some(t=>{if(t.includes("*")){let n=F.dirname(t),r=F.basename(t).replaceAll("*","");if(!W.existsSync(n))return!1;try{return W.readdirSync(n).some(s=>s.startsWith(r))}catch{return!1}}return W.existsSync(t)})}function Ey(){return{command:"node",args:[F.resolve(__dirname,"mcp-server/index.js")]}}function Uu(e,t){return t==="project"?"json":e.configFormat??"json"}function yA(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 Du(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 ju(e,t){let n=e.split(`
190
+ `),r=Du(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]]=yA(i[2]))}return Object.keys(s).length>0?s:void 0}function _A(e,t,n){let r=`[${n.args.map(c=>`"${c}"`).join(", ")}]`,s=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],o=e.split(`
191
+ `),i=Du(o,t);if(i){o.splice(i.start,i.end-i.start,...s);let c=o.join(`
192
192
  `);return c.endsWith(`
193
193
  `)?c:c+`
194
194
  `}let a=e.trimEnd();return a+(a.length>0?`
195
195
 
196
196
  `:"")+s.join(`
197
197
  `)+`
198
- `}function nE(e,t){let n=e.split(`
199
- `),r=$u(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
198
+ `}function bA(e,t){let n=e.split(`
199
+ `),r=Du(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
200
200
  `).replace(/\n{3,}/g,`
201
201
 
202
- `)):e}function Ro(e,t="global"){let n=t==="project"?F.join(process.cwd(),".mcp.json"):Ia(e);try{let r=F.dirname(n);G.existsSync(r)||G.mkdirSync(r,{recursive:!0});let s=Iu(e,t),o=by();if(s==="toml"){let i=G.existsSync(n)?G.readFileSync(n,"utf-8"):"",a=tE(i,"visa-cli",o);G.writeFileSync(n,a)}else{let i={};if(G.existsSync(n))try{i=JSON.parse(G.readFileSync(n,"utf-8"))}catch{i={}}i[e.configKey]=i[e.configKey]||{},i[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(o):o,G.writeFileSync(n,JSON.stringify(i,null,2)+`
203
- `)}}catch(r){throw Jk(r)?new Ts(e,n,r):r}return{installed:!0,configPath:n,message:e.postInstallHint}}function Ou(e,t="global"){let n=t==="project"?F.join(process.cwd(),".mcp.json"):Ia(e);if(!G.existsSync(n))return{removed:!1,configPath:n};if(Iu(e,t)==="toml"){let i=G.readFileSync(n,"utf-8");return Pu(i,"visa-cli")?(G.writeFileSync(n,nE(i,"visa-cli")),{removed:!0,configPath:n}):{removed:!1,configPath:n}}let s;try{s=JSON.parse(G.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"],G.writeFileSync(n,JSON.stringify(s,null,2)+`
204
- `),{removed:!0,configPath:n})}function vy(e,t="global"){let n=t==="project"?F.join(process.cwd(),".mcp.json"):Ia(e);if(!G.existsSync(n))return!1;if(Iu(e,t)==="toml")try{let s=G.readFileSync(n,"utf-8");return!!Pu(s,"visa-cli")}catch{return!1}try{return!!JSON.parse(G.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function rE(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 sE(e,t){if(e===t)return!0;let n=F.resolve(e),r=F.resolve(t);if(n===r)return!0;try{let s=G.realpathSync(n),o=G.realpathSync(r);return s===o}catch{return!1}}function Io(){let e=by(),t=e.args[e.args.length-1],n=[];for(let r of ft){let s=Ia(r);if(!G.existsSync(s))continue;let o=r.configFormat??"json",i;if(o==="toml")try{let l=G.readFileSync(s,"utf-8");i=Pu(l,"visa-cli")}catch{continue}else{let l;try{l=JSON.parse(G.readFileSync(s,"utf-8"))}catch{continue}i=l?.[r.configKey]?.["visa-cli"]}if(!i)continue;let a=rE(i);if(!a||sE(a,t))continue;let c=G.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:s,currentPath:a,expectedPath:t,staleReason:c})}return n}function Mu(e){return{configPath:Ro(e.client,"global").configPath}}var Du=(0,Iy.promisify)(Ry.execFile);function Nu(){let e=Dt();setImmediate(()=>{gc(e,{getCommand:()=>si(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 lE(e){let t=ne.homedir(),n=s=>s.replace(t,"~"),r=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
205
- ${r}: ${n(e.currentPath)}`}function $y(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(lE(n))}function wy(e){console.log(` ! ${e.client.displayName} skipped: ${e.message}`)}function pt(){this.help({error:!1})}var z=new Ay.Command,uE=new Set(["pay",...Eu]),Oa=null,$o=!1;function pe(){return Oa=new Ve(()=>K.getSessionToken()),Oa}function Sy(e){if(e instanceof Jn)return!0;let t=e instanceof Error?e.message:"";return/attestation required|invalid signature|rotate biometric key|biometric key/i.test(t)}var xy=0,Ty="",dE="attestation-key-rotation",fE="api-keys-create",Cy=0,ky="",pE=12e3;async function mE(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:xy,merchant:Ty,context:dE})).toString("base64");return{signature:await Cn(n,"verify Visa CLI Touch ID setup"),nonce:t,amount:xy,merchant:Ty}}async function gE(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:Cy,merchant:ky,context:fE})).toString("base64");return{signature:await Cn(n,"create a Visa Key",{timeoutMs:pE}),nonce:t,amount:Cy,merchant:ky}}async function hE(e){let t=await e.getStatus();return t.attestationRequired!==!1||Tt(t)}async function yE(e){let t=await zp(),n=await mE(e);await e.registerAttestationKey(t,n)}async function Py(e,t,n=!1){let r=await Ei();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 Lu(e){if(!await Fu(e))throw new Error("Could not clear stale server biometric state. Run `visa-cli config reset`, then `visa-cli setup`.");await Py(e,!0,!0)}function Da(e){return async()=>{let t=await Fu(e);return{success:t,...t?{}:{message:"Biometric recovery was not completed."}}}}async function _E(e){let r=Date.now()+3e5;for(;Date.now()<r;)try{let s=await globalThis.fetch(`${Ue()}/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 fn(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 fn(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 Fu(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(!Tt(t))return!1;let n=La.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 oc(r.recoveryUrl),await _E(n),console.log(" Server biometric state cleared."),!0}function Po(e){return`$${(e/100).toFixed(2)}`}function bE(e){return typeof e=="number"?Po(e):"no cap"}function Ma(e,t,n=!1){if(!e){let i=Po(t);return n&&t>=0?`+${i}`:i}let r=(0,Ua.fromWire)(e),s=r%10000n===0n?2:6,o=(0,Ua.toDisplay)(r,{decimals:s});return n&&r>=0n?`+${o}`:o}function vE(e){return Ma(e,0)}function wE(e){let t=`visa-cli-${ne.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 SE(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=>uE.has(o));if(s)throw new Error(`Tool id "${s}" is retired for direct API-key access. Use category meta-tools or discover/execute instead.`);return n}var ju=!1;async function Oy(e){let t=(0,Bu.createInterface)({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function xE(e,t=!1){let n=Ef(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 ju=!0,500;let s=await Oy("Daily cap USD (1-100): ");if(!s)throw new Error("--daily-cap is required when declining the recommended daily cap.");return Sc(s)}async function TE(e,t=!1){let n=Af(e,{json:t,isTTY:process.stdin.isTTY===!0,recommendedCapsAccepted:ju});if(n!==void 0)return ju=!1,n;let r=await Oy("Cumulative cap USD (1-10000, default 25): ");return xc(r||"25")}function CE(e){return e&&e.length>0?e.join(", "):"all tools"}function My(e,t){if(!e)return{};try{let n=JSON.parse(e);if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`${t} must be a JSON object.`);return n}catch(n){throw new Error(`${t} must be valid JSON: ${n.message}`)}}function ja(e,t={}){let n=t.format&&Go(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=Ur(c);if(d){let p=typeof e?.merchantName=="string"?e.merchantName:"media",f=typeof e?.transactionId=="string"?`${p}-${e.transactionId}`:p,m=$s(d,{tag:f}),h=ec(i,e);h.success&&(h.filePath=m.filePath,h.mime=m.mime,h.bytes=m.bytes,u&&u.startsWith("data:")&&(h.urls=void 0)),Ns(h,a);return}}catch(d){Ns(Ps(i,`Failed to save inline media: ${d instanceof Error?d.message:String(d)}`),a),process.exitCode=Ly;return}Ns(ec(i,e),a);return}if(e?.content?.[0]?.text&&typeof e.content[0].text=="string"){try{let i=Ur(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=$s(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(console.log("Done"),typeof e?.merchantName=="string"&&console.log(`Merchant: ${e.merchantName}`),typeof e?.amount=="number"&&console.log(`Cost: $${e.amount.toFixed(2)}`),typeof e?.transactionId=="string"&&console.log(`Transaction: ${e.transactionId}`),s.length>0){console.log(`
202
+ `)):e}function Po(e,t="global"){let n=t==="project"?F.join(process.cwd(),".mcp.json"):Ma(e);try{let r=F.dirname(n);W.existsSync(r)||W.mkdirSync(r,{recursive:!0});let s=Uu(e,t),o=Ey();if(s==="toml"){let i=W.existsSync(n)?W.readFileSync(n,"utf-8"):"",a=_A(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)+`
203
+ `)}}catch(r){throw mA(r)?new As(e,n,r):r}return{installed:!0,configPath:n,message:e.postInstallHint}}function Bu(e,t="global"){let n=t==="project"?F.join(process.cwd(),".mcp.json"):Ma(e);if(!W.existsSync(n))return{removed:!1,configPath:n};if(Uu(e,t)==="toml"){let i=W.readFileSync(n,"utf-8");return ju(i,"visa-cli")?(W.writeFileSync(n,bA(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)+`
204
+ `),{removed:!0,configPath:n})}function Ry(e,t="global"){let n=t==="project"?F.join(process.cwd(),".mcp.json"):Ma(e);if(!W.existsSync(n))return!1;if(Uu(e,t)==="toml")try{let s=W.readFileSync(n,"utf-8");return!!ju(s,"visa-cli")}catch{return!1}try{return!!JSON.parse(W.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function vA(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 wA(e,t){if(e===t)return!0;let n=F.resolve(e),r=F.resolve(t);if(n===r)return!0;try{let s=W.realpathSync(n),o=W.realpathSync(r);return s===o}catch{return!1}}function Oo(){let e=Ey(),t=e.args[e.args.length-1],n=[];for(let r of mt){let s=Ma(r);if(!W.existsSync(s))continue;let o=r.configFormat??"json",i;if(o==="toml")try{let l=W.readFileSync(s,"utf-8");i=ju(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=vA(i);if(!a||wA(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 Fu(e){return{configPath:Po(e.client,"global").configPath}}var Ku=(0,jy.promisify)(Dy.execFile);function Hu(){let e=jt();setImmediate(()=>{wc(e,{getCommand:()=>ai(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 CA(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)})
205
+ ${r}: ${n(e.currentPath)}`}function By(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(CA(n))}function Iy(e){console.log(` ! ${e.client.displayName} skipped: ${e.message}`)}function pt(){this.help({error:!1})}var J=new Uy.Command,AA=new Set(["pay",...Mu]),Ua=null,Mo=!1;function pe(){return Ua=new Ve(()=>G.getSessionToken()),Ua}function $y(e){if(e instanceof Zn)return!0;let t=e instanceof Error?e.message:"";return/attestation required|invalid signature|rotate biometric key|biometric key/i.test(t)}var Py=0,Oy="",EA="attestation-key-rotation",RA="api-keys-create",My=0,Ny="",IA=12e3;async function $A(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:Py,merchant:Oy,context:EA})).toString("base64");return{signature:await An(n,"verify Visa CLI Touch ID setup"),nonce:t,amount:Py,merchant:Oy}}async function PA(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:My,merchant:Ny,context:RA})).toString("base64");return{signature:await An(n,"create a Visa Key",{timeoutMs:IA}),nonce:t,amount:My,merchant:Ny}}async function OA(e){let t=await e.getStatus();return t.attestationRequired!==!1||kt(t)}async function MA(e){let t=await op(),n=await $A(e);await e.registerAttestationKey(t,n)}async function Fy(e,t,n=!1){let r=await $i();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 Vu(e){if(!await Yu(e))throw new Error("Could not clear stale server biometric state. Run `visa-cli config reset`, then `visa-cli setup`.");await Fy(e,!0,!0)}function Ha(e){return async()=>{let t=await Yu(e);return{success:t,...t?{}:{message:"Biometric recovery was not completed."}}}}async function NA(e){let r=Date.now()+3e5;for(;Date.now()<r;)try{let s=await globalThis.fetch(`${Ue()}/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 pn(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 pn(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 Yu(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=Ba.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 dc(r.recoveryUrl),await NA(n),console.log(" Server biometric state cleared."),!0}function No(e){return`$${(e/100).toFixed(2)}`}function LA(e){return typeof e=="number"?No(e):"no cap"}function Da(e,t,n=!1){if(!e){let i=No(t);return n&&t>=0?`+${i}`:i}let r=(0,Fa.fromWire)(e),s=r%10000n===0n?2:6,o=(0,Fa.toDisplay)(r,{decimals:s});return n&&r>=0n?`+${o}`:o}function UA(e){return Da(e,0)}function DA(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 jA(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=>AA.has(o));if(s)throw new Error(`Tool id "${s}" is retired for direct API-key access. Use category meta-tools or discover/execute instead.`);return n}var Gu=!1;async function Hy(e){let t=(0,Wu.createInterface)({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function BA(e,t=!1){let n=Mf(e,{json:t,isTTY:process.stdin.isTTY===!0});if(n!==void 0)return n;if(await Cc("Use recommended Visa Key caps ($5/day and $25 total)? Without caps, leaked keys can spend from prepaid balance until revoked.",!0))return Gu=!0,500;let s=await Hy("Daily cap USD (1-100): ");if(!s)throw new Error("--daily-cap is required when declining the recommended daily cap.");return Ec(s)}async function FA(e,t=!1){let n=Nf(e,{json:t,isTTY:process.stdin.isTTY===!0,recommendedCapsAccepted:Gu});if(n!==void 0)return Gu=!1,n;let r=await Hy("Cumulative cap USD (1-10000, default 25): ");return Rc(r||"25")}function HA(e){return e&&e.length>0?e.join(", "):"all tools"}function Vy(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 Va(e,t={}){let n=t.format&&zo(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=jr(c);if(d){let m=typeof e?.merchantName=="string"?e.merchantName:"media",f=typeof e?.transactionId=="string"?`${m}-${e.transactionId}`:m,p=Ms(d,{tag:f}),h=ic(i,e);h.success&&(h.filePath=p.filePath,h.mime=p.mime,h.bytes=p.bytes,u&&u.startsWith("data:")&&(h.urls=void 0)),Ds(h,a);return}}catch(d){Ds(Ns(i,`Failed to save inline media: ${d instanceof Error?d.message:String(d)}`),a),process.exitCode=Ky;return}Ds(ic(i,e),a);return}if(e?.content?.[0]?.text&&typeof e.content[0].text=="string"){try{let i=jr(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=Ms(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(wd(e)){console.log("In Queue"),oc(e),console.log(`
206
+ \u2139 Your request is processing. Poll for the result with:
207
+ visa merchants run check_fal_status_card --prompt <request_id>`);let i=JSON.stringify(e,null,2);i&&i!=="{}"&&(console.log(`
208
+ Result:`),console.log(i));return}if(console.log("Done"),oc(e),s.length>0){console.log(`
206
209
  Result URLs:`);for(let i of s)console.log(` ${i}`);return}let o=JSON.stringify(e,null,2);o&&o!=="{}"&&(console.log(`
207
- Result:`),console.log(o))}var kE=new Set(["INVALID_TOOL_PARAMS","MISSING_TOOL_ID","UNKNOWN_TOOL"]),Ny=0,Ly=1,EE=2;function AE(e){if(e?.success!==!1)return Ny;let n=(typeof e?.error_code=="string"?e.error_code:typeof e?.code=="string"?e.code:"").toUpperCase();return kE.has(n)?EE:Ly}function Ba(e){let t=AE(e);t!==Ny&&(process.exitCode=t)}function Cs(e,t,n={}){let r=typeof n=="boolean"?{json:n}:n,s=t instanceof Error?t.message:String(t),o=r.format&&Go(r.format)?r.format:void 0;if(r.json||o!==void 0){let i=o??"json";Ns(Ps(e,s),i)}else console.error("Error:",s);process.exit(1)}async function RE(e,t={}){let n=await e.catalogSearch(t.query,t.category,"discover_tools",{limit:t.limit,offset:t.offset});return Array.isArray(n.tools)?n.tools:[]}var Hu=100,Vu=200;function Na(e){let t=Number.parseInt(e,10);return Number.isNaN(t)?Number.NaN:t}function IE(e){let t=typeof e.limit=="number"&&Number.isInteger(e.limit)?Math.max(1,Math.min(e.limit,Vu)):Hu,n=typeof e.offset=="number"&&Number.isInteger(e.offset)?Math.max(0,e.offset):0;return{limit:t,offset:n}}function $E(e){let t=`
210
+ Result:`),console.log(o))}var VA=new Set(["INVALID_TOOL_PARAMS","MISSING_TOOL_ID","UNKNOWN_TOOL"]),qy=0,Ky=1,qA=2;function KA(e){if(e?.success!==!1)return qy;let n=(typeof e?.error_code=="string"?e.error_code:typeof e?.code=="string"?e.code:"").toUpperCase();return VA.has(n)?qA:Ky}function qa(e){let t=KA(e);t!==qy&&(process.exitCode=t)}function Es(e,t,n={}){let r=typeof n=="boolean"?{json:n}:n,s=t instanceof Error?t.message:String(t),o=r.format&&zo(r.format)?r.format:void 0;if(r.json||o!==void 0){let i=o??"json";Ds(Ns(e,s),i)}else console.error("Error:",s);process.exit(1)}async function GA(e,t={}){let n=await e.catalogSearch(t.query,t.category,"discover_tools",{limit:t.limit,offset:t.offset});return Array.isArray(n.tools)?n.tools:[]}var zu=100,Ju=200;function ja(e){let t=Number.parseInt(e,10);return Number.isNaN(t)?Number.NaN:t}function WA(e){let t=typeof e.limit=="number"&&Number.isInteger(e.limit)?Math.max(1,Math.min(e.limit,Ju)):zu,n=typeof e.offset=="number"&&Number.isInteger(e.offset)?Math.max(0,e.offset):0;return{limit:t,offset:n}}function YA(e){let t=`
208
211
  Options:
209
212
  `,n=`
210
213
  Commands:
211
- `,r=e.indexOf(t),s=e.indexOf(n);if(r===-1||s===-1||r>s)return e;let o=p=>{let m=e.slice(p+1).search(/\n[A-Z][A-Za-z ]+:\n/);return m===-1?e.length:p+1+m},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 PE(e){if(!e.startsWith("Usage: "))return e;let t=e.indexOf(`
214
+ `,r=e.indexOf(t),s=e.indexOf(n);if(r===-1||s===-1||r>s)return e;let o=m=>{let p=e.slice(m+1).search(/\n[A-Z][A-Za-z ]+:\n/);return p===-1?e.length:m+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 zA(e){if(!e.startsWith("Usage: "))return e;let t=e.indexOf(`
212
215
 
213
216
  `);if(t===-1)return e;let n=e.slice(0,t),r=e.slice(t+2),s=r.indexOf(`
214
217
 
@@ -216,18 +219,18 @@ Commands:
216
219
 
217
220
  ${n}
218
221
 
219
- ${i}`:e}function OE(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(`
220
- `).map(ME).join(`
221
- `);return`${n}${r}${o}`})}function ME(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 NE(e){return e.replace(/^(Usage: .+?) \[options\](?= |$)/gm,"$1")}function LE(e){return e.replace(/^Options:$/gm,"Flags:")}function Uy(e){let t=e.helpInformation.bind(e);e.helpInformation=()=>LE(NE(OE($E(PE(t())))));for(let n of e.commands)Uy(n)}function UE(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(Is().version).addHelpCommand(!1).action(pt);z.hook("preAction",async()=>{await pd()});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(`
222
+ ${i}`:e}function JA(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(`
223
+ `).map(XA).join(`
224
+ `);return`${n}${r}${o}`})}function XA(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 ZA(e){return e.replace(/^(Usage: .+?) \[options\](?= |$)/gm,"$1")}function QA(e){return e.replace(/^Options:$/gm,"Flags:")}function Gy(e){let t=e.helpInformation.bind(e);e.helpInformation=()=>QA(ZA(JA(YA(zA(t())))));for(let n of e.commands)Gy(n)}function eE(e){let t=new Map(e.map((r,s)=>[r,s]));J.commands.sort((r,s)=>{let o=t.get(r.name())??Number.MAX_SAFE_INTEGER,i=t.get(s.name())??Number.MAX_SAFE_INTEGER;return o-i})}J.name("visa-cli").description("Visa CLI - set up MCP payments, manage credentials, and monitor AI spend").version(Os().version).addHelpCommand(!1).action(pt);J.hook("preAction",async()=>{await bd()});J.command("setup").description("Register MCP server, authenticate, and generate attestation key").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--yes","Accept setup prompts without asking for unattended setup").option("--hud","Install the Visa HUD during setup without prompting").option("--no-hud","Skip installing the Visa HUD during setup").action(async e=>{let t=!1,n=()=>{t||(t=!0,console.log(`
222
225
 
223
- 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=Io();$y(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=Io(),o=new Map(s.map(v=>[v.client.id,v])),i=new Set,a=new Set,c=new Set;for(let v of ft)if(Ao(v)){let S;try{S=Ro(v)}catch(y){if(y instanceof Ts){wy(y),a.add(v.displayName),c.add(v.id);continue}throw y}let A=o.get(v.id),I=A?` \u2014 repaired stale ${A.staleReason} entry`:"";console.log(` \u2713 ${v.displayName} (${S.configPath.replace(ne.homedir(),"~")})${I}`),A&&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{Mu(v)}catch(S){if(S instanceof Ts){wy(S),a.add(v.client.displayName),c.add(v.client.id);continue}throw S}console.log(` \u2713 ${v.client.displayName} (${v.configPath.replace(ne.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(`
224
- Step 2: Checking authentication...`);let p=await K.getSessionToken();if(p)try{await new Ve(()=>Promise.resolve(p)).getStatus(),console.log(" Already authenticated.")}catch(v){let S=v instanceof Error?v.message:"";S.includes("session has expired")||S.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await sy(),p=null):console.log(` Couldn't verify session (${S||"unknown error"}) \u2014 continuing with existing token.`)}if(!p){let v=null;try{let{stdout:S}=await Du("gh",["auth","token"],{timeout:5e3});v=S.trim()}catch{}if(v||(v=process.env.GITHUB_TOKEN||null),v)try{console.log(" Found GitHub token \u2014 attempting headless login...");let S=await globalThis.fetch(`${Ue()}/v1/auth/token-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({github_token:v}),signal:AbortSignal.timeout(1e4)});if(S.ok){let A=await S.json();if(A.success&&A.sessionToken){let I=A.sessionToken;p=I,await K.saveSessionToken(I),console.log(` Signed in as ${A.user} (headless).`)}}else(await S.json().catch(()=>({}))).hint==="card_required"&&console.log(" GitHub token valid but no card on file \u2014 opening browser to finish onboarding...")}catch{}}if(p||(console.log(" No session found. Opening browser for GitHub login..."),p=await new Promise(async(v,S)=>{let A=La.randomUUID(),I=`${Ue()}/login?state=${A}`;await oc(I);let y=3e4,T=300*1e3,Y=Date.now()+T;for(;Date.now()<Y;)try{let X=await globalThis.fetch(`${Ue()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:A,timeout:y}),signal:AbortSignal.timeout(y+5e3)});if(!X.ok){await fn(X,_e=>{g.warn("auth_status:retry_after_http_error",{status:X.status,delayMs:_e})});continue}let H=await X.json();if(H.status==="pending")continue;if(H.status==="expired"){S(new Error("Session expired. Please run setup again."));return}if(H.status==="complete"&&H.sessionToken){console.log(` Signed in as ${H.user}.`),v(H.sessionToken);return}}catch{await fn(void 0,X=>{g.warn("auth_status:retry_after_network_error",{delayMs:X})})}S(new Error("Login timed out after 5 minutes. Please run setup again."))}),await K.saveSessionToken(p),console.log(" Session token saved.")),console.log(`
225
- Step 3: Setting up authentication...`),ue()){try{await Du("clang",["--version"])}catch{console.error(" Xcode Command Line Tools are required for payment authentication."),console.error(" Install them by running: xcode-select --install"),console.error(" Then re-run: visa-cli setup"),process.exit(1)}let v=pe();try{let S=await v.getStatus(),A=!0;if(Tt(S))if(await Ai())try{await yE(v),console.log(" Attestation key already registered with server."),console.log(" Existing local Touch ID key verified and preserved."),A=!1}catch(I){if(!Sy(I))throw I;console.log(" Existing local Touch ID key does not match server biometric state."),await Lu(v),A=!1}else console.log(" Server already has a biometric key, but this device has no local key."),await Lu(v),A=!1;A&&await Py(v,S.attestationRequired===!1)}catch(S){let A=S?.message||"unknown error";if(Sy(S)){console.log(" Server already has a biometric key for this account, but this device cannot prove access to it.");let I=!1;try{await Lu(v),I=!0}catch(y){console.error(` Biometric recovery failed: ${y?.message||"unknown error"}`)}if(!I){let y=S instanceof Jn&&S.hint?S.hint:"Run `visa-cli config reset` to clear server-side biometric state through GitHub, then run `visa-cli setup` again.";console.error(` ${y}`),process.exit(1)}}else console.error(` Biometric setup failed: ${A}`),process.exit(1)}}else{let v=pe(),S;try{S=await v.getStatus()}catch(I){console.error(" Biometric attestation (Touch ID or Windows Hello) is unavailable in this process."),console.error(` Could not verify server biometric policy: ${I?.message||"unknown error"}`),console.error(" Re-run setup from an interactive device with Touch ID (Mac) or Windows Hello (PC) before using payment commands."),process.exit(1)}let A=ry(S);A.canContinue||(console.error(` ${A.message}`),A.hint&&console.error(` ${A.hint}`),process.exit(1)),console.log(` ${A.message}`)}let f=Dt(),m=ae.existsSync(et.join(ne.homedir(),".claude.json")),h=e.hud===!0;if(e.hud===void 0&&m&&!e.yes&&process.stdin.isTTY&&(console.log(`
226
- Step 4: Visa HUD`),console.log(" Pin balance, card, spend, model, and session activity below the Claude Code input."),console.log(vf()),h=await vc(" Install the Visa HUD now?",!1)),h)if(!m)console.log(`
226
+ 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=Oo();By(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=Oo(),o=new Map(s.map(v=>[v.client.id,v])),i=new Set,a=new Set,c=new Set;for(let v of mt)if($o(v)){let S;try{S=Po(v)}catch(y){if(y instanceof As){Iy(y),a.add(v.displayName),c.add(v.id);continue}throw y}let E=o.get(v.id),I=E?` \u2014 repaired stale ${E.staleReason} entry`:"";console.log(` \u2713 ${v.displayName} (${S.configPath.replace(re.homedir(),"~")})${I}`),E&&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{Fu(v)}catch(S){if(S instanceof As){Iy(S),a.add(v.client.displayName),c.add(v.client.id);continue}throw S}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(`
227
+ Step 2: Checking authentication...`);let m=await G.getSessionToken();if(m)try{await new Ve(()=>Promise.resolve(m)).getStatus(),console.log(" Already authenticated.")}catch(v){let S=v instanceof Error?v.message:"";S.includes("session has expired")||S.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await my(),m=null):console.log(` Couldn't verify session (${S||"unknown error"}) \u2014 continuing with existing token.`)}if(!m){let v=null;try{let{stdout:S}=await Ku("gh",["auth","token"],{timeout:5e3});v=S.trim()}catch{}if(v||(v=process.env.GITHUB_TOKEN||null),v)try{console.log(" Found GitHub token \u2014 attempting headless login...");let S=await globalThis.fetch(`${Ue()}/v1/auth/token-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({github_token:v}),signal:AbortSignal.timeout(1e4)});if(S.ok){let E=await S.json();if(E.success&&E.sessionToken){let I=E.sessionToken;m=I,await G.saveSessionToken(I),console.log(` Signed in as ${E.user} (headless).`)}}else(await S.json().catch(()=>({}))).hint==="card_required"&&console.log(" GitHub token valid but no card on file \u2014 opening browser to finish onboarding...")}catch{}}if(m||(console.log(" No session found. Opening browser for GitHub login..."),m=await new Promise(async(v,S)=>{let E=Ba.randomUUID(),I=`${Ue()}/login?state=${E}`;await dc(I);let y=3e4,T=300*1e3,z=Date.now()+T;for(;Date.now()<z;)try{let Z=await globalThis.fetch(`${Ue()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:E,timeout:y}),signal:AbortSignal.timeout(y+5e3)});if(!Z.ok){await pn(Z,be=>{g.warn("auth_status:retry_after_http_error",{status:Z.status,delayMs:be})});continue}let H=await Z.json();if(H.status==="pending")continue;if(H.status==="expired"){S(new Error("Session expired. Please run setup again."));return}if(H.status==="complete"&&H.sessionToken){console.log(` Signed in as ${H.user}.`),v(H.sessionToken);return}}catch{await pn(void 0,Z=>{g.warn("auth_status:retry_after_network_error",{delayMs:Z})})}S(new Error("Login timed out after 5 minutes. Please run setup again."))}),await G.saveSessionToken(m),console.log(" Session token saved.")),console.log(`
228
+ Step 3: Setting up authentication...`),de()){try{await Ku("clang",["--version"])}catch{console.error(" Xcode Command Line Tools are required for payment authentication."),console.error(" Install them by running: xcode-select --install"),console.error(" Then re-run: visa-cli setup"),process.exit(1)}let v=pe();try{let S=await v.getStatus(),E=!0;if(kt(S))if(await Pi())try{await MA(v),console.log(" Attestation key already registered with server."),console.log(" Existing local Touch ID key verified and preserved."),E=!1}catch(I){if(!$y(I))throw I;console.log(" Existing local Touch ID key does not match server biometric state."),await Vu(v),E=!1}else console.log(" Server already has a biometric key, but this device has no local key."),await Vu(v),E=!1;E&&await Fy(v,S.attestationRequired===!1)}catch(S){let E=S?.message||"unknown error";if($y(S)){console.log(" Server already has a biometric key for this account, but this device cannot prove access to it.");let I=!1;try{await Vu(v),I=!0}catch(y){console.error(` Biometric recovery failed: ${y?.message||"unknown error"}`)}if(!I){let y=S instanceof Zn&&S.hint?S.hint:"Run `visa-cli config reset` to clear server-side biometric state through GitHub, then run `visa-cli setup` again.";console.error(` ${y}`),process.exit(1)}}else console.error(` Biometric setup failed: ${E}`),process.exit(1)}}else{let v=pe(),S;try{S=await v.getStatus()}catch(I){console.error(" Biometric attestation (Touch ID or Windows Hello) is unavailable in this process."),console.error(` Could not verify server biometric policy: ${I?.message||"unknown error"}`),console.error(" Re-run setup from an interactive device with Touch ID (Mac) or Windows Hello (PC) before using payment commands."),process.exit(1)}let E=fy(S);E.canContinue||(console.error(` ${E.message}`),E.hint&&console.error(` ${E.hint}`),process.exit(1)),console.log(` ${E.message}`)}let f=jt(),p=ce.existsSync(et.join(re.homedir(),".claude.json")),h=e.hud===!0;if(e.hud===void 0&&p&&!e.yes&&process.stdin.isTTY&&(console.log(`
229
+ Step 4: Visa HUD`),console.log(" Pin balance, card, spend, model, and session activity below the Claude Code input."),console.log(Af()),h=await Cc(" Install the Visa HUD now?",!1)),h)if(!p)console.log(`
227
230
  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(`
228
- Step 4: Enabling the Visa spend HUD...`);let v=Hs(f),S=v.installed==="new"||v.installed==="already-visa"||v.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${S}${v.message}`);try{let A=pe(),I=await A.getStatus(),y={currentVersion:A.getClientVersion(),latestVersion:A.lastSignals?.updateAvailable?.latestVersion,updateCheckDisabled:bt()},T=uc(I,y);dc(T,I),console.log(` Preview: ${T.split(`
231
+ Step 4: Enabling the Visa spend HUD...`);let v=Ks(f),S=v.installed==="new"||v.installed==="already-visa"||v.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${S}${v.message}`);try{let E=pe(),I=await E.getStatus(),y={currentVersion:E.getClientVersion(),latestVersion:E.lastSignals?.updateAvailable?.latestVersion,updateCheckDisabled:vt()},T=hc(I,y);yc(T,I),console.log(` Preview: ${T.split(`
229
232
  `)[0]}`)}catch{}}else e.hud!==!1&&(console.log(`
230
- Step 4: Visa HUD not installed.`),console.log(" Enable later with: visa-cli config hud enable"));let w="\x1B[1m",C="\x1B[2m",b="\x1B[0m";console.log(`
233
+ Step 4: Visa HUD not installed.`),console.log(" Enable later with: visa-cli config hud enable"));let w="\x1B[1m",k="\x1B[2m",b="\x1B[0m";console.log(`
231
234
  \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
232
235
  \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
233
236
  \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
@@ -249,76 +252,76 @@ Step 4: Visa HUD not installed.`),console.log(" Enable later with: visa-cli co
249
252
  \u2502 Shows your balance, active card, and recent tool usage \u2502
250
253
  \u2502 on every prompt. \u2502
251
254
  \u2502 \u2502
252
- \u2502 ${C}$${b} visa-cli config hud enable \u2502
255
+ \u2502 ${k}$${b} visa-cli config hud enable \u2502
253
256
  \u2502 \u2502
254
257
  \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
255
258
 
256
259
  ${w}Verify:${b} visa-cli status
257
260
  ${w}Docs:${b} https://visacli.sh
258
- `),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=Io();$y(o,"MCP config check:"),o.length>0&&process.exit(1);return}if(t.repair){let o=Io();if(o.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of o)Mu(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(ne.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
261
+ `),r()}catch(s){console.error("Error:",s.message),r(),process.exit(1)}});J.command("install [client]",{hidden:!0}).description("Register MCP server with an AI client (claude, cursor, windsurf, cline, zed, ...)").option("--all","Install for all detected clients").option("--list","Show supported clients and install status").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--repair","Repair stale MCP client configs without re-running the full setup flow").option("--scope <scope>","Install scope: global or project","global").action(async(e,t)=>{try{if(t.check){let o=Oo();By(o,"MCP config check:"),o.length>0&&process.exit(1);return}if(t.repair){let o=Oo();if(o.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of o)Fu(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(re.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
259
262
  Repaired ${o.length} stale MCP config ${o.length===1?"entry":"entries"}.`);return}if(t.list){console.log(`
260
263
  \x1B[1mSupported MCP Clients\x1B[0m
261
- `),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 ft){let c=Ao(a),l=vy(a),u=c?"Yes":"No",d=l?"Yes":"No",p=a.globalConfigPath.replace(ne.homedir(),"~");console.log(` ${a.displayName.padEnd(18)} ${u.padEnd(10)} ${d.padEnd(11)} ${p}`)}console.log("");return}let n=t.scope==="project"?"project":"global";if(t.all){let o=[],i=[];for(let a of ft){if(!Ao(a)){i.push(a.displayName);continue}Ro(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(`
262
- Supported clients: ${ft.map(o=>o.id).join(", ")}`),process.exit(1));let r=Ru(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${ft.map(o=>o.id).join(", ")}`),process.exit(1)),n==="global"&&!Ao(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let s=Ro(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()=>{$o=!1;try{let e=pe(),[t,n]=await Promise.all([e.getStatus(),e.getTransactions().catch(s=>{if(process.env.VISA_CLI_DEBUG){let o=s instanceof Error?s.message:String(s);process.stderr.write(`[visa-cli] getTransactions failed (HUD will omit): ${o}
263
- `)}return{transactions:[]}})]),r={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:bt()};process.stdout.write(ey(t,Array.isArray(n?.transactions)?n.transactions:[],ue(),r)),$o=!0}catch(e){$o=!1,console.error("Error:",e.message),process.exit(1)}});function DE(e){let t=e.map(ty),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(`
264
+ `),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 mt){let c=$o(a),l=Ry(a),u=c?"Yes":"No",d=l?"Yes":"No",m=a.globalConfigPath.replace(re.homedir(),"~");console.log(` ${a.displayName.padEnd(18)} ${u.padEnd(10)} ${d.padEnd(11)} ${m}`)}console.log("");return}let n=t.scope==="project"?"project":"global";if(t.all){let o=[],i=[];for(let a of mt){if(!$o(a)){i.push(a.displayName);continue}Po(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(`
265
+ Supported clients: ${mt.map(o=>o.id).join(", ")}`),process.exit(1));let r=Lu(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${mt.map(o=>o.id).join(", ")}`),process.exit(1)),n==="global"&&!$o(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let s=Po(r,n);console.log(`Registered visa-cli MCP server in ${s.configPath}`),console.log(s.message)}catch(n){console.error("Error:",n.message),process.exit(1)}});J.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{Mo=!1;try{let e=pe(),[t,n]=await Promise.all([e.getStatus(),e.getTransactions().catch(s=>{if(process.env.VISA_CLI_DEBUG){let o=s instanceof Error?s.message:String(s);process.stderr.write(`[visa-cli] getTransactions failed (HUD will omit): ${o}
266
+ `)}return{transactions:[]}})]),r={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:vt()};process.stdout.write(ly(t,Array.isArray(n?.transactions)?n.transactions:[],de(),r)),Mo=!0}catch(e){Mo=!1,console.error("Error:",e.message),process.exit(1)}});function tE(e){let t=e.map(uy),n=Math.max(2,...t.map(i=>i.id.length)),r=Math.max(5,...t.map(i=>i.brand.length)),s=Math.max(4,...t.map(i=>i.card.length)),o=7;console.log(`
264
267
  Cards
265
268
  `),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(`
266
269
  Use:`),console.log(" visa-cli cards default <id>"),console.log(` visa-cli cards remove <id>
267
- `)}async function Dy(e,t){if(t.yes)return"confirmed";if(!process.stdin.isTTY)return"refused-non-tty";let n=(0,Bu.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 Fa=z.command("cards").description("Manage enrolled payment cards").addHelpCommand(!1).action(pt);Fa.command("list").alias("ls").description("List enrolled payment cards").action(async()=>{try{let e=await it.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}DE(t)}catch(e){console.error("Error:",e.message),process.exit(1)}});Fa.command("add").description("Add a new Visa card").action(async()=>{try{let e=await it.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)}});Fa.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=_u(e),r=await Dy(`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 it.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)}});Fa.command("default <card-id>").alias("set-default").description("Set the default payment card").action(async e=>{try{let t=_u(e),n=await it.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 jE(e){return/timed out waiting for touch id\/device approval|attestation[_\s-]?required/i.test(e)}function qu(e){let t=e instanceof Error?e.message:String(e);console.error("Error:",t),jE(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 BE(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 Ku(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 Gu=z.command("keys").description("Create and manage Visa Keys for apps and agents").addHelpCommand(!1).action(pt);Gu.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 xE(t.dailyCap,t.json),r=await TE(t.totalCap,t.json),s=await Ku(async()=>{let o=pe(),i={label:wE(e),allowed_tools:SE(t.tools),daily_cap_cents:n,total_cap_cents:r};return await hE(o)?await hr(o,async()=>{let a=await gE(o);return o.createAppApiKey({...i,attestation:a})},Da(o)):await o.createAppApiKey(i)});if(t.json){console.log(JSON.stringify(s,null,2));return}process.stdout.write(Cf(s,{authUrl:Ue()}))}catch(n){qu(n)}});Gu.command("list").description("List Visa Keys for the authenticated user").option("--json","Output raw JSON").action(async e=>{try{let t=await Ku(async()=>await pe().listAllAppApiKeys());if(e.json){console.log(JSON.stringify(t,null,2));return}let n=t.keys||[];if(n.length===0){console.log("No Visa Keys found. Create one with: visa-cli keys create");return}console.log("Visa Keys"),console.log("");for(let r of n)console.log(`${r.id}. ${r.label} (${r.key_prefix})`),console.log(` Status: ${r.status}`),console.log(` Owner: ${r.owner}`),console.log(` Allowed tools: ${CE(r.allowed_tools)}`),console.log(` Daily cap: ${Po(r.daily_cap_cents)}/day`),console.log(` Total cap: ${bE(r.total_cap_cents)}`),console.log(` Last used: ${r.last_used_at||"never"}`)}catch(t){qu(t)}});Gu.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 Ku(async()=>await pe().revokeAppApiKey(t));console.log(`Revoked Visa Key ${n.revoked}.`)}catch(t){qu(t)}});async function FE(){if(await K.clearAll(),console.log(" Keychain credentials cleared."),ue())try{await Ri(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}}async function jy(e={}){try{if(console.log(`Resetting Visa CLI...
268
- `),e.localOnly)console.log(" Local-only reset: skipping server logout and biometric recovery.");else{let t=pe();await Fu(t);try{await t.logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}}await FE(),console.log(`
269
- 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(jy);var Wu=z.command("balance").description("Manage prepaid balance").addHelpCommand(!1).action(pt);Wu.command("show").description("Show prepaid balance + recent ledger entries").action(async()=>{try{let t=await new Ve(()=>K.getSessionToken()).getBalance();if(console.log(`
270
- Balance: ${Ma(t.balanceMicros,t.balanceCents)}
270
+ `)}async function Wy(e,t){if(t.yes)return"confirmed";if(!process.stdin.isTTY)return"refused-non-tty";let n=(0,Wu.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 Ka=J.command("cards").description("Manage enrolled payment cards").addHelpCommand(!1).action(pt);Ka.command("list").alias("ls").description("List enrolled payment cards").action(async()=>{try{let e=await at.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}tE(t)}catch(e){console.error("Error:",e.message),process.exit(1)}});Ka.command("add").description("Add a new Visa card").action(async()=>{try{let e=await at.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)}});Ka.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=ku(e),r=await Wy(`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 at.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)}});Ka.command("default <card-id>").alias("set-default").description("Set the default payment card").action(async e=>{try{let t=ku(e),n=await at.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 nE(e){return/timed out waiting for touch id\/device approval|attestation[_\s-]?required/i.test(e)}function Xu(e){let t=e instanceof Error?e.message:String(e);console.error("Error:",t),nE(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 rE(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 Zu(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 Qu=J.command("keys").description("Create and manage Visa Keys for apps and agents").addHelpCommand(!1).action(pt);Qu.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 BA(t.dailyCap,t.json),r=await FA(t.totalCap,t.json),s=await Zu(async()=>{let o=pe(),i={label:DA(e),allowed_tools:jA(t.tools),daily_cap_cents:n,total_cap_cents:r};return await OA(o)?await _r(o,async()=>{let a=await PA(o);return o.createAppApiKey({...i,attestation:a})},Ha(o)):await o.createAppApiKey(i)});if(t.json){console.log(JSON.stringify(s,null,2));return}process.stdout.write(Pf(s,{authUrl:Ue()}))}catch(n){Xu(n)}});Qu.command("list").description("List Visa Keys for the authenticated user").option("--json","Output raw JSON").action(async e=>{try{let t=await Zu(async()=>await pe().listAllAppApiKeys());if(e.json){console.log(JSON.stringify(t,null,2));return}let n=t.keys||[];if(n.length===0){console.log("No Visa Keys found. Create one with: visa-cli keys create");return}console.log("Visa Keys"),console.log("");for(let r of n)console.log(`${r.id}. ${r.label} (${r.key_prefix})`),console.log(` Status: ${r.status}`),console.log(` Owner: ${r.owner}`),console.log(` Allowed tools: ${HA(r.allowed_tools)}`),console.log(` Daily cap: ${No(r.daily_cap_cents)}/day`),console.log(` Total cap: ${LA(r.total_cap_cents)}`),console.log(` Last used: ${r.last_used_at||"never"}`)}catch(t){Xu(t)}});Qu.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 Zu(async()=>await pe().revokeAppApiKey(t));console.log(`Revoked Visa Key ${n.revoked}.`)}catch(t){Xu(t)}});async function sE(){if(await G.clearAll(),console.log(" Keychain credentials cleared."),de())try{await Oi(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}}async function Yy(e={}){try{if(console.log(`Resetting Visa CLI...
271
+ `),e.localOnly)console.log(" Local-only reset: skipping server logout and biometric recovery.");else{let t=pe();await Yu(t);try{await t.logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}}await sE(),console.log(`
272
+ Reset complete.`),e.localOnly&&console.log("Run `visa-cli setup` to sign in with the GitHub account you want to use.")}catch(t){console.error("Error:",t.message),process.exit(1)}}J.command("reset",{hidden:!0}).description("Deprecated alias for `config reset`").option("--local-only","Only clear local credentials and the local biometric key; skip server-side biometric recovery").action(Yy);var ed=J.command("balance").description("Manage prepaid balance").addHelpCommand(!1).action(pt);ed.command("show").description("Show prepaid balance + recent ledger entries").action(async()=>{try{let t=await new Ve(()=>G.getSessionToken()).getBalance();if(console.log(`
273
+ Balance: ${Da(t.balanceMicros,t.balanceCents)}
271
274
  `),t.ledger.length===0){console.log(` (no ledger entries \u2014 top up to begin: visa-cli balance topup --amount 5)
272
- `);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 p=(u.createdAt||"").slice(0,19),f=Ma(u.deltaMicros,u.deltaCents,!0),m=vE(r[d]),h=(u.reason??"").slice(0,l),w=u.toolName??"";console.log(` ${p.padEnd(i)} ${f.padStart(a)} ${m.padStart(c)} ${h.padEnd(l)} ${w}`)}),console.log()}catch(e){e instanceof nt&&(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)}});Wu.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=Di(e.amount);if(!t.ok)throw new Error(t.error);let n=t.cents,r=n/100,s=new Ve(()=>K.getSessionToken());if(!ue())throw new Error(ji);let o=La.randomUUID(),i=await hr(s,async()=>{let a;if(ue()){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 Cn(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})},Da(s));if(i.success)console.log(`Top-up complete: +$${(n/100).toFixed(2)} \u2192 balance now ${Ma(i.balanceMicros,i.balanceCents??0)}`),i.transactionId&&console.log(`Transaction: ${i.transactionId}`),Hd();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 nt&&(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 By=Wu.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(pt);By.command("show").description("Show current auto-topup configuration").action(async()=>{try{let t=await new Ve(()=>K.getSessionToken()).getAutoTopup();if(t.targetCents==null||t.targetCents===0){console.log(`
275
+ `);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 m=(u.createdAt||"").slice(0,19),f=Da(u.deltaMicros,u.deltaCents,!0),p=UA(r[d]),h=(u.reason??"").slice(0,l),w=u.toolName??"";console.log(` ${m.padEnd(i)} ${f.padStart(a)} ${p.padStart(c)} ${h.padEnd(l)} ${w}`)}),console.log()}catch(e){e instanceof nt&&(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)}});ed.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=Hi(e.amount);if(!t.ok)throw new Error(t.error);let n=t.cents,r=n/100,s=new Ve(()=>G.getSessionToken());if(!de())throw new Error(Vi);let o=Ba.randomUUID(),i=await _r(s,async()=>{let a;if(de()){let{nonce:c}=await s.getAttestationChallenge(),l=Buffer.from(JSON.stringify({nonce:c,amount:r,merchant:"Visa CLI Balance",context:"balance-topup"})).toString("base64");a={signature:await An(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})},Ha(s));if(i.success)console.log(`Top-up complete: +$${(n/100).toFixed(2)} \u2192 balance now ${Da(i.balanceMicros,i.balanceCents??0)}`),i.transactionId&&console.log(`Transaction: ${i.transactionId}`),zd();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 nt&&(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 zy=ed.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(pt);zy.command("show").description("Show current auto-topup configuration").action(async()=>{try{let t=await new Ve(()=>G.getSessionToken()).getAutoTopup();if(t.targetCents==null||t.targetCents===0){console.log(`
273
276
  Auto-topup: disabled
274
- `);return}let n=Po(t.targetCents),r=Po(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)}});By.command("disable").description("Disable auto-topup").action(async()=>{try{let t=await new Ve(()=>K.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 HE=z.command("session",{hidden:!0}).description("Inspect session budgets");HE.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 Ve(()=>K.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(`
277
+ `);return}let n=No(t.targetCents),r=No(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)}});zy.command("disable").description("Disable auto-topup").action(async()=>{try{let t=await new Ve(()=>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 oE=J.command("session",{hidden:!0}).description("Inspect session budgets");oE.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 Ve(()=>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(`
275
278
  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(`
276
279
  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(`
277
- (no PSP references yet \u2014 no holds placed)`);console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});async function Fy(e){(!e||e.trim().length===0)&&(console.log('Usage: visa-cli feedback "your message"'),process.exit(1));try{await K.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await pe().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}}z.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action(Fy);z.command("update").description("Update Visa CLI to the latest stable version").action(async()=>{let e=wu(void 0,void 0,void 0,{withDiagnostics:!0}),t=e.diagnostics?Su(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 Du(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=gc(Dt(),{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 Mt=z.command("config").description("Manage CLI configuration and local integrations").addHelpCommand(!1).action(pt);function Hy(e){return[et.join(e,".zshrc"),et.join(e,".bashrc"),et.join(e,".bash_profile"),et.join(e,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),et.join(e,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),et.join(e,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),et.join(e,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),et.join(e,".config","powershell","Microsoft.PowerShell_profile.ps1")]}function VE(e){let t=new Map;for(let n of Hy(e))try{ae.existsSync(n)&&t.set(n,ae.readFileSync(n,"utf-8"))}catch{}return t}function qE(e){let t=[];for(let[n,r]of e)try{(ae.existsSync(n)?ae.readFileSync(n,"utf-8"):"")!==r&&t.push(n)}catch{}return t}function KE(e){let t=[];for(let n of Hy(e))try{if(!ae.existsSync(n))continue;let r=ae.readFileSync(n,"utf-8");Bs(r)!==r.trimEnd()&&t.push(n)}catch{}return t}Mt.command("feedback",{hidden:!0}).description("Deprecated alias for `feedback`").argument("[message]","Your feedback message").action(Fy);Mt.command("list").description("Show resolved config values (env vars, server state, defaults) with their source").option("--json","Output as JSON for scripting / agent consumption").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").option("--verbose","Show one-line hints beneath entries that have them").action(async e=>{try{let t=pe(),n=await so({api:t,includeDev:!!e.dev});if(e.json){console.log(om(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(sm(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});Mt.command("get <key>").description("Print the resolved value of a single config key (pipe-friendly)").option("--raw","Print the underlying value as JSON instead of the formatted display string").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").action(async(e,t)=>{try{let n=pe(),s=(await so({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 GE(){return Object.entries(Zn).map(([e,t])=>` ${e.padEnd(22)} (${t.type}) ${t.description}`).join(`
278
- `)}Mt.command("set <key> <value>").description("Persist a CLI setting to ~/.visa-mcp/settings.json").addHelpText("after",`
280
+ (no PSP references yet \u2014 no holds placed)`);console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});async function Jy(e){(!e||e.trim().length===0)&&(console.log('Usage: visa-cli feedback "your message"'),process.exit(1));try{await G.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await pe().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}}J.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action(Jy);J.command("update").description("Update Visa CLI to the latest stable version").action(async()=>{let e=Eu(void 0,void 0,void 0,{withDiagnostics:!0}),t=e.diagnostics?Ru(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 Ku(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=wc(jt(),{force:!0});for(let o of s.messages)console.log(o);console.log("Visa CLI update complete. Restart any running MCP clients to use the new version.")}catch(n){console.error(`Update failed while running: ${e.display}`),console.error(n?.message??String(n)),process.exit(1)}});var Nt=J.command("config").description("Manage CLI configuration and local integrations").addHelpCommand(!1).action(pt);function Xy(e){return[et.join(e,".zshrc"),et.join(e,".bashrc"),et.join(e,".bash_profile"),et.join(e,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),et.join(e,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),et.join(e,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),et.join(e,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),et.join(e,".config","powershell","Microsoft.PowerShell_profile.ps1")]}function iE(e){let t=new Map;for(let n of Xy(e))try{ce.existsSync(n)&&t.set(n,ce.readFileSync(n,"utf-8"))}catch{}return t}function aE(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 cE(e){let t=[];for(let n of Xy(e))try{if(!ce.existsSync(n))continue;let r=ce.readFileSync(n,"utf-8");Vs(r)!==r.trimEnd()&&t.push(n)}catch{}return t}Nt.command("feedback",{hidden:!0}).description("Deprecated alias for `feedback`").argument("[message]","Your feedback message").action(Jy);Nt.command("list").description("Show resolved config values (env vars, server state, defaults) with their source").option("--json","Output as JSON for scripting / agent consumption").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").option("--verbose","Show one-line hints beneath entries that have them").action(async e=>{try{let t=pe(),n=await ao({api:t,includeDev:!!e.dev});if(e.json){console.log(pp(n));return}n.statusError&&(console.error(`Warning: could not reach auth server (${n.statusError}).`),console.error("Server-sourced entries show '\u2014'. Log in with `visa-cli setup` if you expected values here."),console.error("")),console.log(mp(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});Nt.command("get <key>").description("Print the resolved value of a single config key (pipe-friendly)").option("--raw","Print the underlying value as JSON instead of the formatted display string").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").action(async(e,t)=>{try{let n=pe(),s=(await ao({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 lE(){return Object.entries(er).map(([e,t])=>` ${e.padEnd(22)} (${t.type}) ${t.description}`).join(`
281
+ `)}Nt.command("set <key> <value>").description("Persist a CLI setting to ~/.visa-mcp/settings.json").addHelpText("after",`
279
282
  Settable keys:
280
- ${GE()}`).action((e,t)=>{try{let n=mi(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 rt||n instanceof Ft||n instanceof hn?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});Mt.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=gi(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)}});Mt.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(jy);var Yu=Mt.command("biometric").description("Manage Touch ID / biometric attestation enforcement").addHelpCommand(!1).action(pt);Yu.command("status").description("Show current biometric enforcement state").action(async()=>{try{await K.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let n=await pe().getStatus(),r=n.attestationRequired!==!1,s=!!n.hasAttestationKey,o=ue();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)}});Yu.command("on").description("Require Touch ID for payments (security upgrade \u2014 no Touch ID needed)").action(async()=>{try{await K.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=pe(),n=await Ii(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)}});Yu.command("off").description("Disable Touch ID requirement (security downgrade \u2014 one Touch ID confirmation required)").action(async()=>{try{await K.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=pe(),n=await t.getStatus();if(n.attestationRequired===!1){console.log("Touch ID is already disabled.");return}n.hasAttestationKey&&!ue()&&(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 hr(t,async()=>{let s;if(n.hasAttestationKey&&ue())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 Cn(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})},Da(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 K.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=pe();(await t.getStatus()).hasAttestationKey||(console.error("No biometric key is registered on this account."),console.error("Run `visa-cli biometric on` to set up Touch ID first, then retry."),process.exit(1)),ue()||(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 hr(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"),p=await Cn(d,`authorize web passkey${i}`);return t.authorizeWebAuthenticator({credentialId:o.credentialId,attestation:{signature:p,nonce:c,amount:l,merchant:u}})},Da(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 Mr=Mt.command("shell-hud").description("Manage the shell prompt HUD (opt-in \u2014 prefer: visa-cli config hud enable)").addHelpCommand(!1).action(pt);function Vy(){let e=Qo();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function qy(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 WE(){qy(bc(void 0,{homeDir:ne.homedir(),installVisaStatusLine:Hs,installShellHud:Qo}))}function Ky(){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"),WE()}function Ha(){let e=Ut();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}Mr.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Vy);Mr.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(Ky);Mr.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Ha);Mr.command("disable").description("Disable the persistent shell HUD").action(Ha);Mr.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${ei()}
281
- `)});Mr.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,r=(d,p,f)=>{console.log(` ${p?"\u2713":"\u2717"} ${d}: ${f}`),p||(n=!1)};console.log(`Shell HUD Doctor
282
- `);let s=Hr();if(r("Shell detected",!!s,s??"none (zsh, bash, or PowerShell required)"),s){let d=js(s),p=e(d);if(r("RC file exists",p,d.replace(ne.homedir(),"~")),p){let m=t(d,"utf-8").includes("visa-cli shell hud v2");r("HUD block installed",!!m,m?"found in rc file":"missing \u2014 run: visa-cli config hud enable shell")}}let o=pn(),i=e(o);if(r("Cache file",i,i?o.replace(ne.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let d=JSON.parse(t(o,"utf-8")),p=Date.now()-(d.renderedAt??0),f=Math.round(p/1e3),m=f<=30;console.log(` ${m?"\u2713":"\u26A0"} Cache freshness: ${f}s old${m?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{r("Cache readable",!1,"corrupt JSON")}let a=Ds(),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 K.getSessionToken()}catch{}if(r("Auth token",u,u?"found in keychain":"missing \u2014 run: visa-cli setup"),u)try{await pe().getStatus(),r("API connectivity",!0,"GET /v1/status OK")}catch(d){let p=d instanceof Error?d.message:"unknown error";r("API connectivity",!1,p)}console.log(n?`
283
+ ${lE()}`).action((e,t)=>{try{let n=yi(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 rt||n instanceof Ht||n instanceof _n?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});Nt.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=_i(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)}});Nt.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(Yy);var td=Nt.command("biometric").description("Manage Touch ID / biometric attestation enforcement").addHelpCommand(!1).action(pt);td.command("status").description("Show current biometric enforcement state").action(async()=>{try{await G.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let n=await pe().getStatus(),r=n.attestationRequired!==!1,s=!!n.hasAttestationKey,o=de();console.log(`Server policy: Touch ID ${r?"REQUIRED":"NOT required"}`),console.log(`Attestation key registered: ${s?"yes":"no"}`),console.log(`Touch ID available on this device: ${o?"yes":"no"}`)}catch(e){console.error("Error:",e.message),process.exit(1)}});td.command("on").description("Require Touch ID for payments (security upgrade \u2014 no Touch ID needed)").action(async()=>{try{await G.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=pe(),n=await Mi(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)}});td.command("off").description("Disable Touch ID requirement (security downgrade \u2014 one Touch ID confirmation required)").action(async()=>{try{await G.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=pe(),n=await t.getStatus();if(n.attestationRequired===!1){console.log("Touch ID is already disabled.");return}n.hasAttestationKey&&!de()&&(console.error("Touch ID is unavailable on this device but the server has a registered key."),console.error("Disable Touch ID from a device that can sign, or contact support."),process.exit(1));let r=await _r(t,async()=>{let s;if(n.hasAttestationKey&&de())try{let{nonce:o}=await t.getAttestationChallenge(),i=0,a="",c=Buffer.from(JSON.stringify({nonce:o,amount:i,merchant:a,context:"biometric-preference"})).toString("base64");s={signature:await An(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})},Ha(t));r.success||(console.error(`Failed: ${r.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is no longer required for payments.")}catch(e){console.error("Error:",e.message),process.exit(1)}});J.command("authorize-web-authenticator").description("Activate a passkey you registered in the browser (one Touch ID confirmation)").action(async()=>{try{await G.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=pe();(await t.getStatus()).hasAttestationKey||(console.error("No biometric key is registered on this account."),console.error("Run `visa-cli biometric on` to set up Touch ID first, then retry."),process.exit(1)),de()||(console.error("Touch ID is unavailable on this device but the server has a registered key."),console.error("Run this from a device that can sign with your registered key."),process.exit(1));let{pending:r}=await t.getPendingWebAuthenticators();if(!r||r.length===0){console.log("No passkeys are awaiting authorization."),console.log("Register a passkey at https://app.visacli.sh/account first, then re-run this.");return}console.log(`${r.length} passkey${r.length===1?"":"s"} awaiting authorization.`);let s=0;for(let o of r){let i=o.deviceLabel?` (${o.deviceLabel})`:"",a=await _r(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"),m=await An(d,`authorize web passkey${i}`);return t.authorizeWebAuthenticator({credentialId:o.credentialId,attestation:{signature:m,nonce:c,amount:l,merchant:u}})},Ha(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 Lr=Nt.command("shell-hud").description("Manage the shell prompt HUD (opt-in \u2014 prefer: visa-cli config hud enable)").addHelpCommand(!1).action(pt);function Zy(){let e=ni();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function Qy(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 uE(){Qy(kc(void 0,{homeDir:re.homedir(),installVisaStatusLine:Ks,installShellHud:ni}))}function e_(){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"),uE()}function Ga(){let e=Dt();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}Lr.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Zy);Lr.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(e_);Lr.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Ga);Lr.command("disable").description("Disable the persistent shell HUD").action(Ga);Lr.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${ri()}
284
+ `)});Lr.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,r=(d,m,f)=>{console.log(` ${m?"\u2713":"\u2717"} ${d}: ${f}`),m||(n=!1)};console.log(`Shell HUD Doctor
285
+ `);let s=qr();if(r("Shell detected",!!s,s??"none (zsh, bash, or PowerShell required)"),s){let d=Hs(s),m=e(d);if(r("RC file exists",m,d.replace(re.homedir(),"~")),m){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=gn(),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")),m=Date.now()-(d.renderedAt??0),f=Math.round(m/1e3),p=f<=30;console.log(` ${p?"\u2713":"\u26A0"} Cache freshness: ${f}s old${p?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{r("Cache readable",!1,"corrupt JSON")}let a=Fs(),c=e(a),l="missing";if(c)try{l=t(a,"utf-8").trim().slice(0,80)}catch{l="unreadable"}r("Line file",c,l);let u=!1;try{u=!!await G.getSessionToken()}catch{}if(r("Auth token",u,u?"found in keychain":"missing \u2014 run: visa-cli setup"),u)try{await pe().getStatus(),r("API connectivity",!0,"GET /v1/status OK")}catch(d){let m=d instanceof Error?d.message:"unknown error";r("API connectivity",!1,m)}console.log(n?`
283
286
  All checks passed.`:`
284
- Some checks failed \u2014 see above.`),n||process.exit(1)});async function Gy(e){if(!(!e.force&&Bd()))try{await ic();let t=pe(),[n,r,s,o]=await Promise.allSettled([t.getStatus(),t.getBalance(),t.listAllAppApiKeys(),t.getTransactions({limit:1})]);if(n.status==="rejected")throw n.reason;let i=n.value,a=i.prepaidBalance?.cents;if(typeof a=="number"){i.balanceCents=a;let u=i.prepaidBalance?.balanceMicros;typeof u=="string"&&(i.balanceMicros=u);let d=i.prepaidBalance?.amountUsd;i.amountUsd=typeof d=="number"?d:a/100}if(r.status==="fulfilled"&&r.value.success&&(i.balanceCents=r.value.balanceCents,i.balanceMicros=r.value.balanceMicros,i.amountUsd=r.value.amountUsd),s.status==="fulfilled"&&s.value.success?i.apiKeyCount=Array.isArray(s.value.keys)?s.value.keys.length:0:s.status==="rejected"&&BE(s.reason)&&(i.apiKeyStatus="rollout_locked"),o.status==="fulfilled"){let u=o.value,p=(Array.isArray(u)?u:Array.isArray(u.transactions)?u.transactions:[]).find(f=>f&&typeof f.tool_name=="string"&&f.tool_name.length>0);p&&p.created_at&&(i.lastService={toolName:p.tool_name,createdAt:p.created_at})}let c={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:bt()},l=uc(i,c);dc(l,i)}catch(t){let n=t instanceof Error?t.message:"unknown refresh failure";Fd(n)}finally{Gn()}}Mr.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(Gy);var Nr=z.command("shell-hud",{hidden:!0}).description("Deprecated alias for `config shell-hud`");Nr.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Vy);Nr.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(Ky);Nr.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Ha);Nr.command("disable").description("Disable the persistent shell HUD").action(Ha);Nr.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${ei()}
285
- `)});Nr.command("doctor").description("Show the new shell HUD doctor command").action(()=>{console.log("Run: visa-cli config shell-hud doctor")});Nr.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(Gy);async function Wy(e){try{await ic();let t=await nf(),n=ei(),r=n,s=n.split(`
286
- `)[0],o=Vd();if(!t&&s.includes("loading")){process.stdout.write(`VISA | HUD not initialized \u2014 run: visa-cli config hud enable
287
- `),Nu();return}if(e.json){let a=await lf(r,t,o);process.stdout.write(`${JSON.stringify(a,null,2)}
288
- `),Nu();return}let i=await of(r,t,o);process.stdout.write(`${i}
289
- `),Nu()}catch(t){let n=t instanceof Error?t.message:"unknown error";console.error(`Failed to render Visa HUD: ${n}`),process.exit(1)}}Mt.command("statusline").description("Output the Visa HUD for agent statusline integrations").option("--json","Output structured JSON for clients that render their own HUD").action(Wy);z.command("statusline",{hidden:!0}).description("Deprecated alias for `config statusline`").option("--json","Output structured JSON for clients that render their own HUD").action(Wy);var ks=Mt.command("hud").description("Manage the Visa spend HUD \u2014 one command for all surfaces").addHelpCommand(!1);ks.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(`
287
+ Some checks failed \u2014 see above.`),n||process.exit(1)});async function t_(e){if(!(!e.force&&Wd()))try{await fc();let t=pe(),[n,r,s,o]=await Promise.allSettled([t.getStatus(),t.getBalance(),t.listAllAppApiKeys(),t.getTransactions({limit:1})]);if(n.status==="rejected")throw n.reason;let i=n.value,a=i.prepaidBalance?.cents;if(typeof a=="number"){i.balanceCents=a;let u=i.prepaidBalance?.balanceMicros;typeof u=="string"&&(i.balanceMicros=u);let d=i.prepaidBalance?.amountUsd;i.amountUsd=typeof d=="number"?d:a/100}if(r.status==="fulfilled"&&r.value.success&&(i.balanceCents=r.value.balanceCents,i.balanceMicros=r.value.balanceMicros,i.amountUsd=r.value.amountUsd),s.status==="fulfilled"&&s.value.success?i.apiKeyCount=Array.isArray(s.value.keys)?s.value.keys.length:0:s.status==="rejected"&&rE(s.reason)&&(i.apiKeyStatus="rollout_locked"),o.status==="fulfilled"){let u=o.value,m=(Array.isArray(u)?u:Array.isArray(u.transactions)?u.transactions:[]).find(f=>f&&typeof f.tool_name=="string"&&f.tool_name.length>0);m&&m.created_at&&(i.lastService={toolName:m.tool_name,createdAt:m.created_at})}let c={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:vt()},l=hc(i,c);yc(l,i)}catch(t){let n=t instanceof Error?t.message:"unknown refresh failure";Yd(n)}finally{Yn()}}Lr.command("refresh").description("Refresh the shell HUD cache (no-op if cache is fresh unless --force)").option("--force","Bypass the cache freshness gate and always refresh").action(t_);var Ur=J.command("shell-hud",{hidden:!0}).description("Deprecated alias for `config shell-hud`");Ur.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Zy);Ur.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(e_);Ur.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Ga);Ur.command("disable").description("Disable the persistent shell HUD").action(Ga);Ur.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${ri()}
288
+ `)});Ur.command("doctor").description("Show the new shell HUD doctor command").action(()=>{console.log("Run: visa-cli config shell-hud doctor")});Ur.command("refresh").description("Refresh the shell HUD cache (no-op if cache is fresh unless --force)").option("--force","Bypass the cache freshness gate and always refresh").action(t_);async function n_(e){try{await fc();let t=await uf(),n=ri(),r=n,s=n.split(`
289
+ `)[0],o=Jd();if(!t&&s.includes("loading")){process.stdout.write(`VISA | HUD not initialized \u2014 run: visa-cli config hud enable
290
+ `),Hu();return}if(e.json){let a=await hf(r,t,o);process.stdout.write(`${JSON.stringify(a,null,2)}
291
+ `),Hu();return}let i=await mf(r,t,o);process.stdout.write(`${i}
292
+ `),Hu()}catch(t){let n=t instanceof Error?t.message:"unknown error";console.error(`Failed to render Visa HUD: ${n}`),process.exit(1)}}Nt.command("statusline").description("Output the Visa HUD for agent statusline integrations").option("--json","Output structured JSON for clients that render their own HUD").action(n_);J.command("statusline",{hidden:!0}).description("Deprecated alias for `config statusline`").option("--json","Output structured JSON for clients that render their own HUD").action(n_);var Rs=Nt.command("hud").description("Manage the Visa spend HUD \u2014 one command for all surfaces").addHelpCommand(!1);Rs.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(`
290
293
  ${e}Visa HUD Status${s}
291
- `);let o=Dt(),i=!1,a=!1;try{if(ae.existsSync(o)){let m=JSON.parse(ae.readFileSync(o,"utf-8")),h=typeof m.statusLine=="object"?m.statusLine.command:"";i=gn(h),a=!!m.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=Yn(ne.homedir()),d=u.length>0||Zo(),p=d?`${n}\u2713${s}`:`${t}\u2717${s}`,f=d?`installed in shell rc file${u.length>0?` (${u.map(m=>m.replace(ne.homedir(),"~")).join(", ")})`:""}`:"not installed (opt-in)";console.log(` ${p} ${e}Shell prompt${s} ${f}`),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(`
292
- ${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()});ks.command("enable").description("Enable the Visa HUD \u2014 claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{qy(bc(e,{homeDir:ne.homedir(),installVisaStatusLine:Hs,installShellHud:Qo}))});ks.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=Ut();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=Dt(),i=hc(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&&!ii()&&Yn(ne.homedir()).length>0){let l=Ut();l.removed&&l.rcPaths&&l.rcPaths.length>0&&(console.log(`Also cleaned legacy shell-prompt HUD block from ${l.rcPaths.map(u=>u.replace(ne.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=Ut();console.log(o.message),o.removed&&(s=!0),!o.removed&&n!=="all"&&(r=!0)}n==="all"&&!s&&(r=!0),r&&process.exit(1)});ks.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=(f,m,h)=>{console.log(` ${m?"\u2713":"\u2717"} ${f}: ${h}`),m||(t=!1)};console.log(`Visa HUD Doctor
293
- `);let r=[],s=wu(void 0,void 0,void 0,{withDiagnostics:!0}),o=s.diagnostics?Su(s.diagnostics,s.display):null;o&&(console.log(`\u26A0 ${o}`),console.log(""));let i=Dt(),a=!1;try{if(ae.existsSync(i)){let f=JSON.parse(ae.readFileSync(i,"utf-8")),m=typeof f.statusLine=="object"?f.statusLine.command:"";a=gn(m)}}catch{}n("Claude Code statusLine",a,a?"registered":"not registered \u2014 run: visa-cli config hud enable");let c=KE(ne.homedir()),l=Hr();if(n("Shell detected",!!l,l??"none (zsh, bash, or PowerShell required)"),l){let f=js(l),m=ae.existsSync(f);if(n("RC file exists",m,f.replace(ne.homedir(),"~")),m){let w=ae.readFileSync(f,"utf-8").includes("visa-cli shell hud v2");console.log(` ${w?"\u2713":"\u2013"} Shell HUD block: ${w?"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(f=>f.replace(ne.homedir(),"~")).join(", ")}`),a&&c.length>0&&e.fix){let f=c.map(h=>h.replace(ne.homedir(),"~")).join(", "),m=e.yes===!0;if(!m&&process.stdin.isTTY&&(m=await Dy(`Remove shell prompt HUD block from ${f}?`,{})==="confirmed"),m){let h=VE(ne.homedir());Ut();let w=qE(h);if(w.length>0){let C=w.map(b=>b.replace(ne.homedir(),"~")).join(", ");console.log(` \u2713 --fix: cleaned legacy shell-prompt HUD block from ${C}`),r.push(`removed shell precmd block from ${C}`)}}else console.log(` ! --fix: preserving shell prompt HUD block in ${f}; 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=pn(),d=ae.existsSync(u);if(n("HUD cache file",d,d?u.replace(ne.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),d)try{let f=JSON.parse(ae.readFileSync(u,"utf-8")),m=Date.now()-(f.renderedAt??0),h=Math.round(m/1e3),w=h<=30,C=typeof f.line=="string"?f.line:"",b=C.length>0&&ti(C);if(console.log(` ${w?"\u2713":"\u26A0"} Cache freshness: ${h}s old${w?"":" (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&&(!w||b)){let v=!1;try{ae.rmSync(u,{force:!0}),v=!0}catch{}try{let S=Ds();ae.existsSync(S)&&(ae.rmSync(S,{force:!0}),v=!0)}catch{}if(v){let S=b?"cache held legacy placeholder":`cache was ${h}s stale`;console.log(` \u2713 --fix: cleared HUD cache (${S}); next prompt will trigger a fresh refresh`),r.push("cleared HUD cache");let A=et.join(ne.homedir(),".visa-cli","shell-hud.lock");ae.existsSync(A)&&(Gn(),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{ae.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 f=et.join(ne.homedir(),".visa-cli","shell-hud.lock");ae.existsSync(f)&&(Gn(),console.log(" \u2713 --fix: cleared shell HUD refresh lock"),r.push("cleared shell HUD refresh lock"))}catch{t=!1}else t=!1}let p=!1;try{p=!!await K.getSessionToken()}catch{}if(n("Auth token",p,p?"found in keychain":"missing \u2014 run: visa-cli setup"),p)try{await pe().getStatus(),n("API connectivity",!0,"GET /v1/status OK")}catch(f){let m=f instanceof Error?f.message:"unknown error";n("API connectivity",!1,m)}e.fix&&(r.length===0?console.log(`
294
+ `);let o=jt(),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=yn(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=Jn(re.homedir()),d=u.length>0||ti(),m=d?`${n}\u2713${s}`:`${t}\u2717${s}`,f=d?`installed in shell rc file${u.length>0?` (${u.map(p=>p.replace(re.homedir(),"~")).join(", ")})`:""}`:"not installed (opt-in)";console.log(` ${m} ${e}Shell prompt${s} ${f}`),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(`
295
+ ${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()});Rs.command("enable").description("Enable the Visa HUD \u2014 claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{Qy(kc(e,{homeDir:re.homedir(),installVisaStatusLine:Ks,installShellHud:ni}))});Rs.command("disable").description("Disable the Visa HUD from a surface: claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{let t=e??"claude";if(t==="shell"||t==="prompt"){let o=Dt();o.removed||(console.error(o.message),process.exit(1)),console.log(o.message);return}let n=di(t);n||(console.error(`Unknown HUD surface: ${t}`),console.error("Supported: claude (default), shell, all"),process.exit(1));let r=!1,s=!1;if(n==="claude"||n==="claude-code"||n==="all"){let o=jt(),i=Sc(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&&!li()&&Jn(re.homedir()).length>0){let l=Dt();l.removed&&l.rcPaths&&l.rcPaths.length>0&&(console.log(`Also cleaned legacy shell-prompt HUD block from ${l.rcPaths.map(u=>u.replace(re.homedir(),"~")).join(", ")} (was leaking output above every shell prompt). Set VISA_HUD_KEEP_SHELL=1 (or true / yes / on) if you want the shell surface to stay.`),s=!0,(i.status==="missing-settings"||i.status==="missing-statusline")&&(r=!1))}}if(n==="all"){let o=Dt();console.log(o.message),o.removed&&(s=!0),!o.removed&&n!=="all"&&(r=!0)}n==="all"&&!s&&(r=!0),r&&process.exit(1)});Rs.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=(f,p,h)=>{console.log(` ${p?"\u2713":"\u2717"} ${f}: ${h}`),p||(t=!1)};console.log(`Visa HUD Doctor
296
+ `);let r=[],s=Eu(void 0,void 0,void 0,{withDiagnostics:!0}),o=s.diagnostics?Ru(s.diagnostics,s.display):null;o&&(console.log(`\u26A0 ${o}`),console.log(""));let i=jt(),a=!1;try{if(ce.existsSync(i)){let f=JSON.parse(ce.readFileSync(i,"utf-8")),p=typeof f.statusLine=="object"?f.statusLine.command:"";a=yn(p)}}catch{}n("Claude Code statusLine",a,a?"registered":"not registered \u2014 run: visa-cli config hud enable");let c=cE(re.homedir()),l=qr();if(n("Shell detected",!!l,l??"none (zsh, bash, or PowerShell required)"),l){let f=Hs(l),p=ce.existsSync(f);if(n("RC file exists",p,f.replace(re.homedir(),"~")),p){let w=ce.readFileSync(f,"utf-8").includes("visa-cli shell hud v2");console.log(` ${w?"\u2713":"\u2013"} Shell HUD block: ${w?"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(f=>f.replace(re.homedir(),"~")).join(", ")}`),a&&c.length>0&&e.fix){let f=c.map(h=>h.replace(re.homedir(),"~")).join(", "),p=e.yes===!0;if(!p&&process.stdin.isTTY&&(p=await Wy(`Remove shell prompt HUD block from ${f}?`,{})==="confirmed"),p){let h=iE(re.homedir());Dt();let w=aE(h);if(w.length>0){let k=w.map(b=>b.replace(re.homedir(),"~")).join(", ");console.log(` \u2713 --fix: cleaned legacy shell-prompt HUD block from ${k}`),r.push(`removed shell precmd block from ${k}`)}}else console.log(` ! --fix: preserving shell prompt HUD block in ${f}; 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=gn(),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 f=JSON.parse(ce.readFileSync(u,"utf-8")),p=Date.now()-(f.renderedAt??0),h=Math.round(p/1e3),w=h<=30,k=typeof f.line=="string"?f.line:"",b=k.length>0&&si(k);if(console.log(` ${w?"\u2713":"\u26A0"} Cache freshness: ${h}s old${w?"":" (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&&(!w||b)){let v=!1;try{ce.rmSync(u,{force:!0}),v=!0}catch{}try{let S=Fs();ce.existsSync(S)&&(ce.rmSync(S,{force:!0}),v=!0)}catch{}if(v){let S=b?"cache held legacy placeholder":`cache was ${h}s stale`;console.log(` \u2713 --fix: cleared HUD cache (${S}); next prompt will trigger a fresh refresh`),r.push("cleared HUD cache");let E=et.join(re.homedir(),".visa-cli","shell-hud.lock");ce.existsSync(E)&&(Yn(),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 f=et.join(re.homedir(),".visa-cli","shell-hud.lock");ce.existsSync(f)&&(Yn(),console.log(" \u2713 --fix: cleared shell HUD refresh lock"),r.push("cleared shell HUD refresh lock"))}catch{t=!1}else t=!1}let m=!1;try{m=!!await G.getSessionToken()}catch{}if(n("Auth token",m,m?"found in keychain":"missing \u2014 run: visa-cli setup"),m)try{await pe().getStatus(),n("API connectivity",!0,"GET /v1/status OK")}catch(f){let p=f instanceof Error?f.message:"unknown error";n("API connectivity",!1,p)}e.fix&&(r.length===0?console.log(`
294
297
  --fix: no locally fixable issues found.`):console.log(`
295
298
  --fix: applied ${r.length} change${r.length===1?"":"s"} \u2014 ${r.join("; ")}.`)),console.log(t?`
296
299
  All checks passed.`:`
297
- Some checks failed \u2014 see above.`),t||process.exit(1)});ks.command("enable-claude").description("Alias for: hud enable claude").action(()=>{let e=Dt(),t=Hs(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});ks.command("disable-claude").description("Alias for: hud disable claude").action(()=>{let e=Dt(),t=hc(e);console.log(t.message),t.removed||process.exit(1)});var Or=z.command("merchants").description("Discover and run paid merchant tools").addHelpCommand(!1).action(pt);Or.command("list").description("List live platform merchants").option("--json","Print machine-readable JSON").action(async e=>{try{let n=await new Ve(()=>K.getSessionToken()).listPublicMerchants();if(n.length===0){e.json?console.log(JSON.stringify({merchants:[]},null,2)):console.log(`
300
+ Some checks failed \u2014 see above.`),t||process.exit(1)});Rs.command("enable-claude").description("Alias for: hud enable claude").action(()=>{let e=jt(),t=Ks(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});Rs.command("disable-claude").description("Alias for: hud disable claude").action(()=>{let e=jt(),t=Sc(e);console.log(t.message),t.removed||process.exit(1)});var Nr=J.command("merchants").description("Discover and run paid merchant tools").addHelpCommand(!1).action(pt);Nr.command("list").description("List live platform merchants").option("--json","Print machine-readable JSON").action(async e=>{try{let n=await new Ve(()=>G.getSessionToken()).listPublicMerchants();if(n.length===0){e.json?console.log(JSON.stringify({merchants:[]},null,2)):console.log(`
298
301
  No live platform merchants on this auth server.
299
302
  `);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(`
300
303
  ${s}Run 'visa-cli merchants tools' to browse tools by merchant.${o}
301
- `)}catch(t){console.error("Error:",t.message),process.exit(1)}});var YE=new Set(["list","tools","describe","run","refresh"]);async function zu(e){try{let n=await pe().catalogTool(e,"discover_tools");n||(console.error(`Tool not found: ${e}`),console.error('Search with: visa-cli tools --query "what you want to do"'),process.exit(1)),console.log(`
304
+ `)}catch(t){console.error("Error:",t.message),process.exit(1)}});var dE=new Set(["list","tools","describe","run","refresh"]);async function nd(e){try{let n=await pe().catalogTool(e,"discover_tools");n||(console.error(`Tool not found: ${e}`),console.error('Search with: visa-cli tools --query "what you want to do"'),process.exit(1)),console.log(`
302
305
  ${n.id}
303
306
  `),console.log(n.description),console.log(`
304
- Price`),console.log(` ${Xs(n.priceCents,n.priceDisplay)}`),console.log(`
307
+ Price`),console.log(` ${eo(n.priceCents,n.priceDisplay)}`),console.log(`
305
308
  Provider`),console.log(` ${n.provider} \xB7 ${n.category}`),console.log(`
306
- 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=yf(l),p=d?` ${d.padEnd(8)}`:" ",f=l?.description?` - ${l.description}`:"";console.log(` ${c.padEnd(a)} ${u}${p}${f}`)}}else console.log(" No published schema. Use --json with the request body.");console.log(`
307
- Examples`);let s=Zh(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 Ju(e){try{let t=pe();if(e.merchant){let o=e.merchant,i=await t.getPublicMerchantDiscover(o);i||(console.error(`Merchant not found: ${o}`),console.error("List merchants with: visa-cli merchants list"),process.exit(1));let a=i.routes.filter(l=>l.tool_id).map(l=>({id:l.tool_id,name:l.tool_id,description:l.description||"",provider:i.upstream_display??i.title,model:l.tool_id,category:l.category||"utility",priceCents:l.price_cents??0,inputSchema:l.request?.body_schema??{}})),c=e.category?a.filter(l=>l.category===e.category):a;if(e.json){console.log(JSON.stringify({merchant:o,tools:c},null,2));return}if(c.length===0){console.log(`No tools found for merchant "${o}".`);return}e.verbose?Nc(c):Jf(o,c);return}let{limit:n,offset:r}=IE(e),s=await RE(t,{query:e.query,category:e.category,limit:n,offset:r});if(e.json){console.log(JSON.stringify({tools:s},null,2));return}if(s.length===0){console.log("No merchant tools found. Try: visa-cli tools --category image");return}e.verbose?Nc(s):zf(s)}catch(t){console.error("Error:",t.message),process.exit(1)}}Or.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 ${Hu}, max ${Vu})`,Na).option("--offset <n>","Pagination offset (default 0)",Na).action(Ju);Or.command("describe <tool>").description("Show tool schema, price, and examples").action(async e=>{await zu(e)});function zE(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 Va(e,t,n){return zE(e)?it.shortcut(e,t,n):it.executeTool({tool_id:e,params:t},n,"execute_tool")}Or.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=My(t.json,"--json");t.prompt&&(n.prompt=t.prompt),Os({yes:t.yes}),console.log(`Running ${e}`);let r=await Va(e,n,`visa-cli merchants run ${e}`);ja(r),Ba(r)}catch(n){console.error("Error:",n.message),process.exit(1)}});Or.command("refresh").description("Hint: restart the MCP server (Claude/Cursor) to refresh discovered tools \u2014 discovery is in-process").action(()=>{console.log(`
309
+ 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=Tf(l),m=d?` ${d.padEnd(8)}`:" ",f=l?.description?` - ${l.description}`:"";console.log(` ${c.padEnd(a)} ${u}${m}${f}`)}}else console.log(" No published schema. Use --json with the request body.");console.log(`
310
+ Examples`);let s=ay(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 rd(e){try{let t=pe();if(e.merchant){let o=e.merchant,i=await t.getPublicMerchantDiscover(o);i||(console.error(`Merchant not found: ${o}`),console.error("List merchants with: visa-cli merchants list"),process.exit(1));let a=i.routes.filter(l=>l.tool_id).map(l=>({id:l.tool_id,name:l.tool_id,description:l.description||"",provider:i.upstream_display??i.title,model:l.tool_id,category:l.category||"utility",priceCents:l.price_cents??0,inputSchema:l.request?.body_schema??{}})),c=e.category?a.filter(l=>l.category===e.category):a;if(e.json){console.log(JSON.stringify({merchant:o,tools:c},null,2));return}if(c.length===0){console.log(`No tools found for merchant "${o}".`);return}e.verbose?Fc(c):rm(o,c);return}let{limit:n,offset:r}=WA(e),s=await GA(t,{query:e.query,category:e.category,limit:n,offset:r});if(e.json){console.log(JSON.stringify({tools:s},null,2));return}if(s.length===0){console.log("No merchant tools found. Try: visa-cli tools --category image");return}e.verbose?Fc(s):nm(s)}catch(t){console.error("Error:",t.message),process.exit(1)}}Nr.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 ${zu}, max ${Ju})`,ja).option("--offset <n>","Pagination offset (default 0)",ja).action(rd);Nr.command("describe <tool>").description("Show tool schema, price, and examples").action(async e=>{await nd(e)});function fE(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 Wa(e,t,n){return fE(e)?at.shortcut(e,t,n):at.executeTool({tool_id:e,params:t},n,"execute_tool")}Nr.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=Vy(t.json,"--json");t.prompt&&(n.prompt=t.prompt),Ls({yes:t.yes}),console.log(`Running ${e}`);let r=await Wa(e,n,`visa-cli merchants run ${e}`);Va(r),qa(r)}catch(n){console.error("Error:",n.message),process.exit(1)}});Nr.command("refresh").description("Hint: restart the MCP server (Claude/Cursor) to refresh discovered tools \u2014 discovery is in-process").action(()=>{console.log(`
308
311
  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.
309
- `)});Or.on("command:*",async function(e){let t=e[0],n=e[1],r=e.slice(2);if(!t||YE.has(t)){console.error(`Unknown merchants subcommand: ${t}`),Or.help({error:!0});return}if(!n||n==="tools"){let s=r.indexOf("--category"),o=s!==-1?r[s+1]:void 0,i=r.includes("--verbose"),a=r.includes("--json");await Ju({category:o,verbose:i,json:a,merchant:t});return}if(n==="describe"){let s=r[0];s||(console.error(`Usage: visa-cli merchants ${t} describe <tool>`),process.exit(1));try{let o=pe(),i=await o.getPublicMerchantDiscover(t);if(i||(console.error(`Merchant not found: ${t}`),console.error("List merchants with: visa-cli merchants list"),process.exit(1)),!await o.catalogTool(s,"discover_tools")){let c=i.routes.find(l=>l.tool_id===s);c||(console.error(`Tool "${s}" not found for merchant "${t}"`),console.error(`Browse with: visa-cli merchants ${t} tools`),process.exit(1)),console.log(`
312
+ `)});Nr.on("command:*",async function(e){let t=e[0],n=e[1],r=e.slice(2);if(!t||dE.has(t)){console.error(`Unknown merchants subcommand: ${t}`),Nr.help({error:!0});return}if(!n||n==="tools"){let s=r.indexOf("--category"),o=s!==-1?r[s+1]:void 0,i=r.includes("--verbose"),a=r.includes("--json");await rd({category:o,verbose:i,json:a,merchant:t});return}if(n==="describe"){let s=r[0];s||(console.error(`Usage: visa-cli merchants ${t} describe <tool>`),process.exit(1));try{let o=pe(),i=await o.getPublicMerchantDiscover(t);if(i||(console.error(`Merchant not found: ${t}`),console.error("List merchants with: visa-cli merchants list"),process.exit(1)),!await o.catalogTool(s,"discover_tools")){let c=i.routes.find(l=>l.tool_id===s);c||(console.error(`Tool "${s}" not found for merchant "${t}"`),console.error(`Browse with: visa-cli merchants ${t} tools`),process.exit(1)),console.log(`
310
313
  ${s}
311
314
  `),c.description&&console.log(c.description),console.log(`
312
- Price`),console.log(` ${Xs(c.price_cents)}`),console.log(`
315
+ Price`),console.log(` ${eo(c.price_cents)}`),console.log(`
313
316
  Examples`),console.log(` visa-cli merchants run ${s} --json '${JSON.stringify(c.request?.body_example??{})}'`),console.log(` visa-cli merchants ${t} run ${s}
314
- `);return}await zu(s)}catch(o){console.error("Error:",o.message),process.exit(1)}return}if(n==="run"){let s=r[0];s||(console.error(`Usage: visa-cli merchants ${t} run <tool> [--json '{...}']`),process.exit(1));let o=a=>{let c=r.indexOf(a);return c!==-1?r[c+1]:void 0},i=r.includes("--yes");try{let a=o("--json"),c=My(a,"--json"),l=o("--prompt");l&&(c.prompt=l),Os({yes:i}),console.log(`Running ${s}`);let u=await Va(s,c,`visa-cli merchants ${t} run ${s}`);ja(u),Ba(u)}catch(a){console.error("Error:",a.message),process.exit(1)}return}console.error(`Unknown subcommand "${n}" for merchant "${t}"`),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 ${Hu}, max ${Vu})`,Na).option("--offset <n>","Pagination offset (default 0)",Na).action(Ju);z.command("describe <tool>").description("Show schema, price, and examples for a tool (alias for: merchants describe)").action(async e=>{await zu(e)});var Oo=z.command("generate").description("Generate media with merchant tools").addHelpCommand(!1).action(pt);async function Mo(e){Os({yes:e.yes}),e.json||e.format&&Go(e.format)||(console.log(`
317
+ `);return}await nd(s)}catch(o){console.error("Error:",o.message),process.exit(1)}return}if(n==="run"){let s=r[0];s||(console.error(`Usage: visa-cli merchants ${t} run <tool> [--json '{...}']`),process.exit(1));let o=a=>{let c=r.indexOf(a);return c!==-1?r[c+1]:void 0},i=r.includes("--yes");try{let a=o("--json"),c=Vy(a,"--json"),l=o("--prompt");l&&(c.prompt=l),Ls({yes:i}),console.log(`Running ${s}`);let u=await Wa(s,c,`visa-cli merchants ${t} run ${s}`);Va(u),qa(u)}catch(a){console.error("Error:",a.message),process.exit(1)}return}console.error(`Unknown subcommand "${n}" for merchant "${t}"`),console.error("Available: tools, describe <tool>, run <tool>"),process.exit(1)});J.command("tools").description("List available merchant tools (alias for: merchants tools)").option("--category <category>","Filter by category (image, video, audio, 3d, llm)").option("--query <query>","Search by intent or keyword").option("--merchant <slug>","Scope to a single merchant (e.g. fal, openrouter)").option("--verbose","Show grouped cards with descriptions").option("--json","Print machine-readable JSON").option("--limit <n>",`Maximum tools to return (default ${zu}, max ${Ju})`,ja).option("--offset <n>","Pagination offset (default 0)",ja).action(rd);J.command("describe <tool>").description("Show schema, price, and examples for a tool (alias for: merchants describe)").action(async e=>{await nd(e)});var Lo=J.command("generate").description("Generate media with merchant tools").addHelpCommand(!1).action(pt);async function Uo(e){Ls({yes:e.yes}),e.json||e.format&&zo(e.format)||(console.log(`
315
318
  ${e.kind}
316
319
  `),console.log(`Using: ${e.toolId}`),console.log(`Prompt: ${e.prompt}
317
- `));let n=await Va(e.toolId,e.params,`visa-cli generate ${e.kind.toLowerCase()}: ${e.prompt}`);ja(n,{json:e.json,format:e.format,command:e.command??`generate.${e.kind.toLowerCase().replace(/\s+/g,"_")}`}),Ba(n)}var Vn=(e,t)=>n=>(t.includes(n)||z.error(`error: option '${e}' accepts ${t.map(r=>`'${r}'`).join(", ")} (got '${n}')`,{exitCode:2}),n);Oo.command("image [prompt]").description("Generate an image from a prompt (accepts stdin via `-` or --stdin)").option("--quality <quality>","Image quality: standard or high",Vn("--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)",Vn("--format",dn)).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 qn(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 Mo({kind:"Image generation",toolId:r,params:s,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.image"})}catch(n){Cs("generate.image",n,{json:t.json,format:t.format})}});Oo.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)",Vn("--format",dn)).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 qn(e,t),r={prompt:n};t.aspectRatio&&(r.aspect_ratio=t.aspectRatio),t.duration&&(r.duration=Number(t.duration)),await Mo({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){Cs("generate.video",n,{json:t.json,format:t.format})}});Oo.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)",Vn("--format",dn)).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 qn(e,t),r={prompt:n};t.instrumental&&(r.instrumental=!0),t.duration&&(r.duration=Number(t.duration)),await Mo({kind:"Music generation",toolId:t.tool??kn("generate_music"),params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.music"})}catch(n){Cs("generate.music",n,{json:t.json,format:t.format})}});Oo.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)",Vn("--format",dn)).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 qn(e,t),s={text:r,audio_url:n};await Mo({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){Cs("generate.speech",n,{json:t.json,format:t.format})}});Oo.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)",Vn("--format",dn)).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 qn(e,t),r={image_url:n};await Mo({kind:"3D generation",toolId:t.tool??kn("generate_3d"),params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.3d"})}catch(n){Cs("generate.3d",n,{json:t.json,format:t.format})}});var Uu="reasoning",Ey=Object.keys(no.run_llm.tiers);z.command("run-llm [prompt]").description(`Run a chat-completion against an OpenRouter-backed LLM (default tier: ${Uu})`).option("--tier <tier>",`LLM tier: ${Ey.join(" | ")} (resolves to a catalog tool id via the run_llm meta-tool)`,Vn("--tier",Ey),Uu).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)",Vn("--format",dn)).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 nc(),u=JSON.parse(l),d=yd(u,t.fromStdin);n=n??d}let r=await qn(e,{stdin:t.stdin&&!t.fromStdin});Os({yes:t.yes});let s={prompt:r},o=await bd(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??Uu,a=t.model??kn("run_llm",i);if(!t.json){console.log(`
320
+ `));let n=await Wa(e.toolId,e.params,`visa-cli generate ${e.kind.toLowerCase()}: ${e.prompt}`);Va(n,{json:e.json,format:e.format,command:e.command??`generate.${e.kind.toLowerCase().replace(/\s+/g,"_")}`}),qa(n)}var Kn=(e,t)=>n=>(t.includes(n)||J.error(`error: option '${e}' accepts ${t.map(r=>`'${r}'`).join(", ")} (got '${n}')`,{exitCode:2}),n);Lo.command("image [prompt]").description("Generate an image from a prompt (accepts stdin via `-` or --stdin)").option("--quality <quality>","Image quality: standard or high",Kn("--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)",Kn("--format",mn)).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 Gn(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 Uo({kind:"Image generation",toolId:r,params:s,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.image"})}catch(n){Es("generate.image",n,{json:t.json,format:t.format})}});Lo.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)",Kn("--format",mn)).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 Gn(e,t),r={prompt:n};t.aspectRatio&&(r.aspect_ratio=t.aspectRatio),t.duration&&(r.duration=Number(t.duration)),await Uo({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){Es("generate.video",n,{json:t.json,format:t.format})}});Lo.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)",Kn("--format",mn)).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 Gn(e,t),r={prompt:n};t.instrumental&&(r.instrumental=!0),t.duration&&(r.duration=Number(t.duration)),await Uo({kind:"Music generation",toolId:t.tool??En("generate_music"),params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.music"})}catch(n){Es("generate.music",n,{json:t.json,format:t.format})}});Lo.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)",Kn("--format",mn)).option("--stdin","Read text from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=t.audioUrl??t.refAudioUrl;n||J.error("error: option '--audio-url <url>' is required for visa-cli generate speech",{exitCode:2});let r=await Gn(e,t),s={text:r,audio_url:n};await Uo({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){Es("generate.speech",n,{json:t.json,format:t.format})}});Lo.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)",Kn("--format",mn)).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 Gn(e,t),r={image_url:n};await Uo({kind:"3D generation",toolId:t.tool??En("generate_3d"),params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.3d"})}catch(n){Es("generate.3d",n,{json:t.json,format:t.format})}});var qu="reasoning",Ly=Object.keys(oo.run_llm.tiers);J.command("run-llm [prompt]").description(`Run a chat-completion against an OpenRouter-backed LLM (default tier: ${qu})`).option("--tier <tier>",`LLM tier: ${Ly.join(" | ")} (resolves to a catalog tool id via the run_llm meta-tool)`,Kn("--tier",Ly),qu).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)",Kn("--format",mn)).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 cc(),u=JSON.parse(l),d=Td(u,t.fromStdin);n=n??d}let r=await Gn(e,{stdin:t.stdin&&!t.fromStdin});Ls({yes:t.yes});let s={prompt:r},o=await Cd(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??qu,a=t.model??En("run_llm",i);if(!t.json){console.log(`
318
321
  LLM completion
319
322
  `),console.log(`Using: ${a}`);let l=r.length>200?`${r.slice(0,200)}\u2026`:r;console.log(`Prompt: ${l}
320
- `)}let c=await Va(a,s,"visa-cli run-llm");ja(c,{json:t.json,format:t.format,command:"run-llm"}),Ba(c)}catch(n){Cs("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 ft)Ou(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(`
321
- Supported clients: ${ft.map(o=>o.id).join(", ")}`),process.exit(1));let r=Ru(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${ft.map(o=>o.id).join(", ")}`),process.exit(1));let s=Ou(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($o){$o=!1;return}Oa&&Xh(Oa.lastSignals)});dy(z);py(z);UE(["setup","install","status","cards","keys","balance","tools","describe","merchants","generate","run-llm","config","feedback","update","uninstall"]);Uy(z);z.parseAsync().catch(async e=>{console.error("Error:",e instanceof Error?e.message:String(e));let{reportFatal:t}=await Promise.resolve().then(()=>(Pa(),$a));await t(e)});process.on("uncaughtException",async e=>{console.error("Uncaught exception:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(Pa(),$a));await t(e)});process.on("unhandledRejection",async e=>{console.error("Unhandled rejection:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(Pa(),$a));await t(e)});0&&(module.exports={printGroupHelpAndExit});
323
+ `)}let c=await Wa(a,s,"visa-cli run-llm");Va(c,{json:t.json,format:t.format,command:"run-llm"}),qa(c)}catch(n){Es("run-llm",n,{json:t.json,format:t.format})}});J.command("uninstall [client]").description("Remove MCP server from an AI client").option("--all","Remove from all clients").option("--scope <scope>","Uninstall scope: global or project","global").action(async(e,t)=>{try{let n=t.scope==="project"?"project":"global";if(t.all){let o=[];for(let i of mt)Bu(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(`
324
+ Supported clients: ${mt.map(o=>o.id).join(", ")}`),process.exit(1));let r=Lu(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${mt.map(o=>o.id).join(", ")}`),process.exit(1));let s=Bu(r,n);s.removed?console.log(`Removed visa-cli from ${s.configPath}`):console.log(`visa-cli was not installed for ${r.displayName}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});J.hook("postAction",()=>{if(Mo){Mo=!1;return}Ua&&iy(Ua.lastSignals)});vy(J);Sy(J);eE(["setup","install","status","cards","keys","balance","tools","describe","merchants","generate","run-llm","config","feedback","update","uninstall"]);Gy(J);J.parseAsync().catch(async e=>{console.error("Error:",e instanceof Error?e.message:String(e));let{reportFatal:t}=await Promise.resolve().then(()=>(La(),Na));await t(e)});process.on("uncaughtException",async e=>{console.error("Uncaught exception:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(La(),Na));await t(e)});process.on("unhandledRejection",async e=>{console.error("Unhandled rejection:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(La(),Na));await t(e)});0&&(module.exports={printGroupHelpAndExit});
322
325
  /*! Bundled license information:
323
326
 
324
327
  @noble/ed25519/index.js: