@visa/cli 3.0.0 → 3.0.1

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,8 +1,8 @@
1
- "use strict";var Lm=Object.create;var oo=Object.defineProperty;var Um=Object.getOwnPropertyDescriptor;var Dm=Object.getOwnPropertyNames;var jm=Object.getPrototypeOf,Fm=Object.prototype.hasOwnProperty;var Vm=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var za=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},Os=(e,t)=>{for(var n in t)oo(e,n,{get:t[n],enumerable:!0})},Ja=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Dm(t))!Fm.call(e,o)&&o!==n&&oo(e,o,{get:()=>t[o],enumerable:!(r=Um(t,o))||r.enumerable});return e};var T=(e,t,n)=>(n=e!=null?Lm(jm(e)):{},Ja(t||!e||!e.__esModule?oo(n,"default",{value:e,enumerable:!0}):n,e)),qm=e=>Ja(oo({},"__esModule",{value:!0}),e);var dr=za((Yv,tp)=>{tp.exports={name:"@visa/cli",version:"3.0.0",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{"sync:server-json":"node scripts/sync-server-json.mjs","check:server-json":"node scripts/sync-server-json.mjs --check",prebuild:"node scripts/sync-server-json.mjs && pnpm --filter @visa/money build && pnpm --filter @visa-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/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.61.1","@typescript-eslint/parser":"^8.61.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.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"]}});var Fr=za(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.micros=oy;ue.fromCents=sy;ue.fromUsdc=iy;ue.fromUsd=ay;ue.toCents=cy;ue.toCentsForAcquirer=ly;ue.toUsdc=uy;ue.toWire=dy;ue.fromWire=my;ue.toDisplay=py;ue.toUsdRounded2dp=fy;ue.add=gy;ue.sub=hy;ue.clampNonNegative=yy;ue.isNonNegative=_y;ue.max=by;ue.min=vy;var xt=10000n,td=1000000n;function oy(e){return e}function sy(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*xt}function iy(e){return e}function ay(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function cy(e){if(e>=0n)return Number(e/xt);let t=e/xt,n=e%xt;return Number(n===0n?t:t-1n)}function ly(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/xt)}function uy(e){return e}function dy(e){return e.toString()}function my(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 py(e,t={}){let n=t.decimals??2,r=t.symbol??"$",o=e<0n,s=o?-e:e,i=s/td,a=s%td,c=o?"-":"";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 fy(e){let t=e<0n,n=t?-e:e,r=n/xt,s=n%xt*2n,i;s<xt?i=r:s>xt?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function gy(e,t){return e+t}function hy(e,t){return e-t}function yy(e){return e<0n?0n:e}function _y(e){return e>=0n}function by(e,t){return e>t?e:t}function vy(e,t){return e<t?e:t}});var Ss={};Os(Ss,{initSentry:()=>Qb,isSentryConfigured:()=>Zb,reportFatal:()=>ev});function Zb(){return!1}async function Qb(){return null}async function ev(e,t){process.exit(t?.exitCode??1)}var xs=Vm(()=>{});var Bv={};Os(Bv,{printGroupHelpAndExit:()=>Je});module.exports=qm(Bv);var hm=require("commander"),Ts=T(require("crypto")),X=T(require("fs")),J=T(require("os")),De=T(require("path")),ym=require("child_process"),Na=require("node:readline/promises"),_m=require("util");var ao=require("child_process"),sc=require("util"),Rt=T(require("fs")),co=T(require("os")),js=T(require("path"));var Qa=T(require("crypto"));var dt="e9501a252b778bce5a3d77710667afdd9198a750d1d989d95fb32d80e485bf15";var ec="VISA_ALLOW_INSECURE_MOCKS",Ya,Xa,Za;function Ms(e){return`${e}-${Qa.randomBytes(24).toString("base64url")}`}function tc(e=process.env){return e.NODE_ENV==="test"||e[ec]==="true"}function Et(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&tc(e)}function On(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&tc(e)}function Ns(){return`Set ${ec}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function nc(){return Ya??=Ms("mock-session"),Ya}function rc(e=process.env){return e.NODE_ENV==="test"?dt:(Xa??=Ms("mock-rc"),Xa)}function oc(){return Za??=Ms("mock-signature"),Za}var Ye=(0,sc.promisify)(ao.execFile),Fs=js.join(co.homedir(),".visa-mcp"),ur=js.join(Fs,"session-token"),Pe="visa-cli",At="session-token",so="rc-access",Bm=5e3,io=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function Hm(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
2
- `)}function ic(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=Hm(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function Km(){try{let{stdout:e}=await Ye("security",["find-generic-password","-s",Pe,"-a",At,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(ic(e))throw new io("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 Gm(e){try{try{await Ye("security",["delete-generic-password","-s",Pe,"-a",At],{timeout:5e3})}catch{}return await Ye("security",["add-generic-password","-s",Pe,"-a",At,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function Wm(){try{await Ye("security",["delete-generic-password","-s",Pe,"-a",At],{timeout:5e3})}catch{}}async function zm(){if(!Vs())return null;try{let{stdout:e}=await Ye("secret-tool",["lookup","service",Pe,"account",At],{timeout:5e3});return e.trim()||null}catch{return null}}async function Jm(e){if(!Vs())return!1;try{let t=(0,ao.execFile)("secret-tool",["store","--label",`${Pe} ${At}`,"service",Pe,"account",At]);return t.stdin?(t.stdin.write(e),t.stdin.end(),await Promise.race([new Promise((n,r)=>{t.on("exit",o=>o===0?n():r(new Error(`secret-tool exited ${o}`))),t.on("error",r)}),new Promise((n,r)=>setTimeout(()=>{t.kill(),r(new Error("secret-tool timed out"))},Bm))]),!0):!1}catch{return!1}}async function Ym(){if(Vs())try{await Ye("secret-tool",["clear","service",Pe,"account",At],{timeout:5e3})}catch{}}function Vs(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function Xm(){try{let{stdout:e}=await Ye("security",["find-generic-password","-s",Pe,"-a",so,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Zm(e){try{try{await Ye("security",["delete-generic-password","-s",Pe,"-a",so],{timeout:5e3})}catch{}await Ye("security",["add-generic-password","-s",Pe,"-a",so,"-w",e],{timeout:5e3})}catch{}}async function Qm(){try{await Ye("security",["delete-generic-password","-s",Pe,"-a",so],{timeout:5e3})}catch{}}function Us(){try{return Rt.readFileSync(ur,"utf-8").trim()||null}catch(e){if(ic(e))throw new io(`Unable to read Visa CLI credentials from ${ur}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function ac(e){Rt.mkdirSync(Fs,{recursive:!0,mode:448}),Rt.writeFileSync(ur,e,{mode:384}),process.platform==="win32"&&ep(ur)}function Ds(){try{Rt.unlinkSync(ur)}catch{}}function ep(e){try{let t=co.userInfo().username;(0,ao.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 Ls(){switch(process.platform){case"darwin":return{get:Km,store:Gm,delete:Wm};case"linux":return{get:zm,store:Jm,delete:Ym};default:return{get:async()=>Us(),store:async e=>{try{return ac(e),!0}catch{return!1}},delete:async()=>Ds(),storesInSessionFile:!0}}}var V=class{static async getSessionToken(){if(Et())return Promise.resolve(nc());let t=Ls(),n=await t.get();if(n)return n;let r=Us();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(Et())return;let n=Ls();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||Ds();return}await n.delete()}if(ac(t),Us()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${Fs} is writable.`))}static async getRcAccessToken(){return Et()?rc():Xm()}static async saveRcAccessToken(t){Et()||await Zm(t)}static async deleteSessionToken(){if(Et())return;await Ls().delete(),Ds()}static async clearAll(){await this.deleteSessionToken(),await Qm()}};var lo=T(require("crypto")),uo=T(require("tty")),mo=T(require("fs"));function np(e){return/-rc\.|-beta\./.test(e)}function qs(e){return lo.createHash("sha256").update(e.trim()).digest("hex")}function cc(e){return dt==="SKIP"?!0:lo.timingSafeEqual(Buffer.from(qs(e)),Buffer.from(dt))}function rp(){try{let e=mo.openSync("/dev/tty","r+"),t=new uo.ReadStream(e),n=new uo.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{mo.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 op(e){return new Promise((t,n)=>{let r;try{r=rp()}catch(u){n(u);return}let{input:o,output:s,cleanupStreams:i}=r,a=()=>{o.off("data",l);try{o.setRawMode?.(!1)}catch{}i()};s.write(e),o.setRawMode?.(!0),o.resume(),o.setEncoding("utf8");let c="",l=u=>{u==="\r"||u===`
1
+ "use strict";var cf=Object.create;var To=Object.defineProperty;var lf=Object.getOwnPropertyDescriptor;var uf=Object.getOwnPropertyNames;var df=Object.getPrototypeOf,mf=Object.prototype.hasOwnProperty;var pf=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Dc=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},ci=(e,t)=>{for(var n in t)To(e,n,{get:t[n],enumerable:!0})},jc=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of uf(t))!mf.call(e,o)&&o!==n&&To(e,o,{get:()=>t[o],enumerable:!(r=lf(t,o))||r.enumerable});return e};var E=(e,t,n)=>(n=e!=null?cf(df(e)):{},jc(t||!e||!e.__esModule?To(n,"default",{value:e,enumerable:!0}):n,e)),ff=e=>jc(To({},"__esModule",{value:!0}),e);var Rr=Dc((mS,Ef)=>{Ef.exports={name:"@visa/cli",version:"3.0.1",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 @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:*","@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.61.1","@typescript-eslint/parser":"^8.61.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.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"]}});var dr=Dc(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.micros=c_;fe.fromCents=l_;fe.fromUsdc=u_;fe.fromUsd=d_;fe.toCents=m_;fe.toCentsForAcquirer=p_;fe.toUsdc=f_;fe.toWire=g_;fe.fromWire=h_;fe.toDisplay=y_;fe.toUsdRounded2dp=__;fe.add=b_;fe.sub=v_;fe.clampNonNegative=w_;fe.isNonNegative=S_;fe.max=x_;fe.min=T_;var At=10000n,hd=1000000n;function c_(e){return e}function l_(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*At}function u_(e){return e}function d_(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function m_(e){if(e>=0n)return Number(e/At);let t=e/At,n=e%At;return Number(n===0n?t:t-1n)}function p_(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/At)}function f_(e){return e}function g_(e){return e.toString()}function h_(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 y_(e,t={}){let n=t.decimals??2,r=t.symbol??"$",o=e<0n,s=o?-e:e,i=s/hd,a=s%hd,c=o?"-":"";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 __(e){let t=e<0n,n=t?-e:e,r=n/At,s=n%At*2n,i;s<At?i=r:s>At?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function b_(e,t){return e+t}function v_(e,t){return e-t}function w_(e){return e<0n?0n:e}function S_(e){return e>=0n}function x_(e,t){return e>t?e:t}function T_(e,t){return e<t?e:t}});var Ys={};ci(Ys,{initSentry:()=>gw,isSentryConfigured:()=>fw,reportFatal:()=>hw});function fw(){return!1}async function gw(){return null}async function hw(e,t){process.exit(t?.exitCode??1)}var Xs=pf(()=>{});var sS={};ci(sS,{printGroupHelpAndExit:()=>et});module.exports=ff(sS);var Vp=require("commander"),ti=E(require("crypto")),Q=E(require("fs")),X=E(require("os")),Be=E(require("path")),Bp=require("child_process"),Cc=require("node:readline/promises"),Hp=require("util");var Eo=require("child_process"),Jc=require("util"),Ut=E(require("fs")),Ao=E(require("os")),fi=E(require("path"));var Hc=E(require("crypto"));var yt="e9501a252b778bce5a3d77710667afdd9198a750d1d989d95fb32d80e485bf15";var qc="VISA_ALLOW_INSECURE_MOCKS",Fc,Vc,Bc;function li(e){return`${e}-${Hc.randomBytes(24).toString("base64url")}`}function Kc(e=process.env){return e.NODE_ENV==="test"||e[qc]==="true"}function Nt(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&Kc(e)}function Gn(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&Kc(e)}function ui(){return`Set ${qc}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function Gc(){return Fc??=li("mock-session"),Fc}function Wc(e=process.env){return e.NODE_ENV==="test"?yt:(Vc??=li("mock-rc"),Vc)}function zc(){return Bc??=li("mock-signature"),Bc}var tt=(0,Jc.promisify)(Eo.execFile),gi=fi.join(Ao.homedir(),".visa-mcp"),Ar=fi.join(gi,"session-token"),Le="visa-cli",Lt="session-token",Co="rc-access",gf=5e3,ko=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function hf(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
2
+ `)}function Yc(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=hf(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function yf(){try{let{stdout:e}=await tt("security",["find-generic-password","-s",Le,"-a",Lt,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(Yc(e))throw new ko("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 tt("security",["delete-generic-password","-s",Le,"-a",Lt],{timeout:5e3})}catch{}return await tt("security",["add-generic-password","-s",Le,"-a",Lt,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function bf(){try{await tt("security",["delete-generic-password","-s",Le,"-a",Lt],{timeout:5e3})}catch{}}async function vf(){if(!hi())return null;try{let{stdout:e}=await tt("secret-tool",["lookup","service",Le,"account",Lt],{timeout:5e3});return e.trim()||null}catch{return null}}async function wf(e){if(!hi())return!1;try{let t=(0,Eo.execFile)("secret-tool",["store","--label",`${Le} ${Lt}`,"service",Le,"account",Lt]);return t.stdin?(t.stdin.write(e),t.stdin.end(),await Promise.race([new Promise((n,r)=>{t.on("exit",o=>o===0?n():r(new Error(`secret-tool exited ${o}`))),t.on("error",r)}),new Promise((n,r)=>setTimeout(()=>{t.kill(),r(new Error("secret-tool timed out"))},gf))]),!0):!1}catch{return!1}}async function Sf(){if(hi())try{await tt("secret-tool",["clear","service",Le,"account",Lt],{timeout:5e3})}catch{}}function hi(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function xf(){try{let{stdout:e}=await tt("security",["find-generic-password","-s",Le,"-a",Co,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Tf(e){try{try{await tt("security",["delete-generic-password","-s",Le,"-a",Co],{timeout:5e3})}catch{}await tt("security",["add-generic-password","-s",Le,"-a",Co,"-w",e],{timeout:5e3})}catch{}}async function Cf(){try{await tt("security",["delete-generic-password","-s",Le,"-a",Co],{timeout:5e3})}catch{}}function mi(){try{return Ut.readFileSync(Ar,"utf-8").trim()||null}catch(e){if(Yc(e))throw new ko(`Unable to read Visa CLI credentials from ${Ar}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function Xc(e){Ut.mkdirSync(gi,{recursive:!0,mode:448}),Ut.writeFileSync(Ar,e,{mode:384}),process.platform==="win32"&&kf(Ar)}function pi(){try{Ut.unlinkSync(Ar)}catch{}}function kf(e){try{let t=Ao.userInfo().username;(0,Eo.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 di(){switch(process.platform){case"darwin":return{get:yf,store:_f,delete:bf};case"linux":return{get:vf,store:wf,delete:Sf};default:return{get:async()=>mi(),store:async e=>{try{return Xc(e),!0}catch{return!1}},delete:async()=>pi(),storesInSessionFile:!0}}}var B=class{static async getSessionToken(){if(Nt())return Promise.resolve(Gc());let t=di(),n=await t.get();if(n)return n;let r=mi();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(Nt())return;let n=di();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||pi();return}await n.delete()}if(Xc(t),mi()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${gi} is writable.`))}static async getRcAccessToken(){return Nt()?Wc():xf()}static async saveRcAccessToken(t){Nt()||await Tf(t)}static async deleteSessionToken(){if(Nt())return;await di().delete(),pi()}static async clearAll(){await this.deleteSessionToken(),await Cf()}};var Ro=E(require("crypto")),Io=E(require("tty")),$o=E(require("fs"));function Af(e){return/-rc\.|-beta\./.test(e)}function yi(e){return Ro.createHash("sha256").update(e.trim()).digest("hex")}function Zc(e){return yt==="SKIP"?!0:Ro.timingSafeEqual(Buffer.from(yi(e)),Buffer.from(yt))}function Rf(){try{let e=$o.openSync("/dev/tty","r+"),t=new Io.ReadStream(e),n=new Io.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{$o.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 If(e){return new Promise((t,n)=>{let r;try{r=Rf()}catch(u){n(u);return}let{input:o,output:s,cleanupStreams:i}=r,a=()=>{o.off("data",l);try{o.setRawMode?.(!1)}catch{}i()};s.write(e),o.setRawMode?.(!0),o.resume(),o.setEncoding("utf8");let c="",l=u=>{u==="\r"||u===`
3
3
  `?(s.write(`
4
4
  `),a(),t(c)):u===""?(s.write(`
5
- `),a(),n(new Error("Cancelled"))):u==="\x7F"||u==="\b"?c.length>0&&(c=c.slice(0,-1),s.write("\b \b")):(c+=u,s.write("\u2022"))};o.on("data",l)})}var sp=`
5
+ `),a(),n(new Error("Cancelled"))):u==="\x7F"||u==="\b"?c.length>0&&(c=c.slice(0,-1),s.write("\b \b")):(c+=u,s.write("\u2022"))};o.on("data",l)})}var $f=`
6
6
  \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
7
7
  \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
8
8
  \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
@@ -11,25 +11,25 @@
11
11
  \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D
12
12
 
13
13
  This is a Release Candidate build. Access is restricted to Visa employees.
14
- `;async function lc(e={}){let t=e.version??dr().version;if(!np(t))return;let n=process.env.VISA_RC_CODE;if(n&&cc(n)){await V.saveRcAccessToken(qs(n));return}if(e.isMcp??!1){let i=await V.getRcAccessToken();if(i&&(dt==="SKIP"||i===dt))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
15
- `),process.exit(1)}let o=await V.getRcAccessToken();if(o&&(dt==="SKIP"||o===dt))return;console.log(sp);let s=3;for(let i=1;i<=s;i++){let a;try{a=await op(" Enter RC access code: ")}catch{process.exit(1)}if(cc(a)){await V.saveRcAccessToken(qs(a)),console.log(`
14
+ `;async function Qc(e={}){let t=e.version??Rr().version;if(!Af(t))return;let n=process.env.VISA_RC_CODE;if(n&&Zc(n)){await B.saveRcAccessToken(yi(n));return}if(e.isMcp??!1){let i=await B.getRcAccessToken();if(i&&(yt==="SKIP"||i===yt))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
15
+ `),process.exit(1)}let o=await B.getRcAccessToken();if(o&&(yt==="SKIP"||o===yt))return;console.log($f);let s=3;for(let i=1;i<=s;i++){let a;try{a=await If(" Enter RC access code: ")}catch{process.exit(1)}if(Zc(a)){await B.saveRcAccessToken(yi(a)),console.log(`
16
16
  Access granted. Welcome.
17
17
  `);return}i<s&&console.log(`
18
18
  Invalid code. ${s-i} attempt(s) remaining.
19
19
  `)}console.log(`
20
20
  Invalid code. Contact your team lead.
21
- `),process.exit(1)}var po=T(require("fs")),uc=T(require("os")),Bs=T(require("path")),ip=[{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"}}],ap=/^data:(image\/(png|jpeg|jpg|gif|webp));base64,([A-Za-z0-9+/=]+)$/;function Mn(e){if(typeof e!="string"||e.length===0)return null;let t=e.trim(),n=ap.exec(t);if(n){let o=n[2]==="jpg"?"jpeg":n[2],s=o==="png"?{mime:"image/png",ext:"png"}:o==="jpeg"?{mime:"image/jpeg",ext:"jpg"}:o==="gif"?{mime:"image/gif",ext:"gif"}:{mime:"image/webp",ext:"webp"};return{base64:n[3],sig:s}}if(!/^[A-Za-z0-9+/=\s]+$/.test(t)||t.length<64)return null;let r=t.replace(/\s+/g,"");for(let{prefix:o,sig:s}of ip)if(r.startsWith(o))return{base64:r,sig:s};return null}function mr(e,t={}){let n=t.outputDir??Bs.join(uc.tmpdir(),"visa-cli");po.mkdirSync(n,{recursive:!0});let r=(t.tag??"media").toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"media",o=new Date().toISOString().replace(/[:.]/g,"-"),s=Bs.join(n,`${r}-${o}.${e.sig.ext}`),i=Buffer.from(e.base64,"base64");return po.writeFileSync(s,i,{mode:384}),{filePath:s,bytes:i.length,mime:e.sig.mime}}function cp(e,t={}){let n={success:!0,command:e,ts:new Date().toISOString()};for(let[r,o]of Object.entries(t))o!==void 0&&(n[r]=o);return n}function pr(e,t,n={}){let r={success:!1,command:e,ts:new Date().toISOString(),error:t};for(let[o,s]of Object.entries(n))s!==void 0&&(r[o]=s);return r}function Hs(e,t){if(!t||typeof t!="object")return pr(e,"No result payload from tool");let n=t;if(n.success===!1)return pr(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,o=n.data&&typeof n.data=="object"?n.data:void 0,s=n.result&&typeof n.result=="object"?n.result:void 0,i=s&&Array.isArray(s.choices)?s.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(o&&typeof o.content=="string")l=o.content;else if(o&&typeof o.text=="string")l=o.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 cp(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 Ks=require("process");async function Gs(){let e="";Ks.stdin.setEncoding("utf8");for await(let t of Ks.stdin)e+=t;return e.endsWith(`
22
- `)?e.slice(0,-1):e}async function en(e,t){if(e==="-"||t.stdin===!0&&!e){let o=(await Gs()).trim();if(!o)throw new Error("stdin was empty \u2014 pipe a prompt or pass it as the positional argument");return o}if(e&&e.length>0)return e;throw new Error("prompt required (positional arg, `-`, or --stdin)")}function fr(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 fc=T(require("fs")),fo=T(require("path"));var It=class extends Error{constructor(t){super(t),this.name="FromStdinFieldError"}},dc=new Set;function lp(e){dc.add(e)}function mc(e){return dc.has(e)}function pc(e,t){if(!t.startsWith("."))throw new It(`--from-stdin path must start with "." (got: "${t}")`);let n=up(t),r=e;for(let s of n){if(r==null)throw new It(`--from-stdin path "${t}" failed: hit ${r===null?"null":"undefined"} at segment "${s}"`);if(typeof r!="object")throw new It(`--from-stdin path "${t}" failed: cannot descend into primitive at segment "${s}"`);if(typeof s=="number"){if(!Array.isArray(r))throw new It(`--from-stdin path "${t}" failed: expected array at segment [${s}], got object`);r=r[s]}else r=r[s]}if(r==null)throw new It(`--from-stdin path "${t}" resolved to ${r===null?"null":"undefined"}`);if(typeof r=="object")throw new It(`--from-stdin path "${t}" resolved to ${Array.isArray(r)?"an array":"an object"} \u2014 refusing to coerce non-primitive to flag value`);let o=String(r);return lp(o),o}function up(e){let t=e.slice(1),n=[];for(let r of t.split(".")){if(!r)continue;let o=/^([^[\]]+)|\[(\d+)\]/g,s;for(;(s=o.exec(r))!==null;)s[1]!==void 0?/^\d+$/.test(s[1])?n.push(Number(s[1])):n.push(s[1]):s[2]!==void 0&&n.push(Number(s[2]))}return n}var Ws=class extends Error{constructor(t){super(t),this.name="FileShorthandStdinSourceError"}};async function gc(e){if(e===void 0)return;if(!e.startsWith("@"))return e;if(mc(e))throw new Ws("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("~")?fo.join(process.env.HOME??"",t.slice(1)):fo.resolve(process.cwd(),t),r=await fc.promises.readFile(n,"utf8");return r.endsWith(`
23
- `)?r.slice(0,-1):r}var gr=require("process"),$t=["json","yaml","tsv","table"];function go(e){return $t.includes(e)}function hr(e,t){switch(t){case"json":gr.stdout.write(JSON.stringify(e)+`
24
- `);return;case"yaml":gr.stdout.write(dp(e)+`
25
- `);return;case"tsv":gr.stdout.write(mp(e)+`
26
- `);return;case"table":gr.stdout.write(pp(e)+`
27
- `);return}}function dp(e){let t=[];for(let[n,r]of Object.entries(e))if(r!==void 0)if(Array.isArray(r)){t.push(`${n}:`);for(let o of r)t.push(` - ${hc(o)}`)}else r!==null&&typeof r=="object"?t.push(`${n}: ${JSON.stringify(r)}`):t.push(`${n}: ${hc(r)}`);return t.join(`
28
- `)}function hc(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 mp(e){let t=[];for(let[n,r]of Object.entries(e)){if(r===void 0)continue;let o=Array.isArray(r)||r!==null&&typeof r=="object"?JSON.stringify(r):String(r);t.push(`${n} ${o}`)}return t.join(`
29
- `)}function pp(e){let t=[];for(let[r,o]of Object.entries(e)){if(o===void 0)continue;let s=Array.isArray(o)||o!==null&&typeof o=="object"?JSON.stringify(o):String(o);t.push([r,s])}let n=Math.max(...t.map(([r])=>r.length),1);return t.map(([r,o])=>`${r.padEnd(n)} ${o}`).join(`
30
- `)}var _c=require("child_process");function zs(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 fp(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(`
31
- `)}function yr(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 bc(e,t){let n=yr(e);if(!n)return null;let r,o;try{r=new URL(n),o=new URL(t)}catch{return null}return r.origin===o.origin?n:null}function vc(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 wc(e,t=process.platform){let n=yr(e);return n?vc(n,t):null}function yc(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function Js(e,t={}){let n=t.log??(l=>console.log(l)),r=t.env??process.env,o=t.platform??process.platform,s=yr(e),i=t.spawn??((l,u,d)=>{(0,_c.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 fp(s??e).split(`
32
- `))n(` ${l}`);if(n(""),!s){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=zs(r,o);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=vc(s,o);if(!c){n(` No known browser-open command for platform "${o}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(l=>{let u=d=>{d?yc(n,d):(n(" Opened browser. Waiting for you to sign in..."),n("")),l()};try{i(c.cmd,c.args,u)}catch(d){yc(n,d instanceof Error?d:new Error(String(d))),l()}})}function gp(e){return new Promise(t=>setTimeout(t,e))}function Sc(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 xc(e){return!Number.isFinite(e)||e===null||e<=0?1e3:Math.min(Math.max(Math.ceil(e),1e3),3e4)}async function hp(e,t=Math.random()*250){let n=o=>Math.min(o+Math.max(0,Math.ceil(t)),3e4);if(!e||e.status!==429)return n(1e3);let r=Sc(e.headers?.get("Retry-After"));if(r!==null)return n(xc(r));if(typeof e.json=="function")try{let o=await e.json();return n(xc(Sc(o?.retryAfter)))}catch{return n(1e3)}return n(1e3)}async function Pt(e,t){let n=await hp(e);return t?.(n),await gp(n),n}var qc=T(require("crypto")),Bc=require("child_process"),de=T(require("fs")),Hc=T(require("os")),we=T(require("path"));var B=T(require("fs")),rn=T(require("os")),H=T(require("path")),Ic=require("child_process"),Zs=require("crypto");var Ln=T(require("fs")),ho=T(require("tty"));function Cc(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 Tc(e,t){let n=(o,s,i)=>`\x1B[38;2;${o};${s};${i}m`,r=o=>`\x1B[38;5;${o}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 Ec(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 kc(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]),o=n(t[2]),s=n(t[3]);return[r,o,s].some(i=>!Number.isFinite(i))?null:.299*r+.587*o+.114*s}var yp=80,_p="/dev/tty";function bp(e=_p){if(process.platform==="win32")return null;let t,n;try{t=Ln.openSync(e,"r"),n=Ln.openSync(e,"w");let r=new ho.ReadStream(t),o=new ho.WriteStream(n);return{stdin:r,stdout:o,close:()=>{try{r.destroy?.()}catch{}try{o.destroy?.()}catch{}}}}catch{try{t!==void 0&&Ln.closeSync(t)}catch{}try{n!==void 0&&Ln.closeSync(n)}catch{}return null}}function vp(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 s=(e.openControllingTerminal??bp)(e.ttyPath);return s?.stdout.isTTY&&s.stdin.isTTY&&typeof s.stdin.setRawMode=="function"?s:(s?.close?.(),null)}async function wp(e={}){let t=vp(e);if(!t)return null;let{stdin:n,stdout:r}=t,o=e.timeoutMs??yp,s=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=y=>{l+=typeof y=="string"?y:y.toString("utf-8");let w=kc(l),N=l.includes("\x07")||l.includes("\x1B\\");w!==null&&N&&m(w>.5?"light":"dark")},p=()=>{try{n.removeListener("data",d)}catch{}try{i(g)}catch{}try{!u&&typeof n.setRawMode=="function"&&n.setRawMode(!1)}catch{}try{n.pause?.()}catch{}try{n.unref?.()}catch{}try{t.close?.()}catch{}},m=y=>{c||(c=!0,p(),a(y))},g=s(()=>{let y=kc(l);m(y!==null?y>.5?"light":"dark":null)},o);try{u||n.setRawMode?.(!0),n.resume?.(),n.on("data",d),r.write("\x1B]11;?\x1B\\")}catch{m(null)}})}var tn,_r;function Sp(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=Ec(e.COLORFGBG);return n||"dark"}function yo(e=process.env){return tn!==void 0||(tn=Sp(e)),tn}function _e(e=process.env){if(_r!==void 0)return _r;let t=yo(e),n=Cc(e);return _r=Tc(t==="light"?"light":"dark",n),_r}function _o(e=process.env){return yo(e)==="no-color"}async function Ys(e={}){if(tn!==void 0)return tn;let t=e.env??process.env;if((t.NO_COLOR??"")!=="")return Nn("no-color",t);let n=(t.VISA_CLI_HUD_THEME??"").toLowerCase().trim();if(n==="light")return Nn("light",t);if(n==="dark")return Nn("dark",t);let r=Ec(t.COLORFGBG);if(r)return Nn(r,t);let o=await wp(e);return Nn(o||"dark",t)}function Nn(e,t){tn=e;let n=Cc(t);return _r=Tc(e==="light"?"light":"dark",n),e}var xp=2,bo="# >>> visa-cli shell hud v2 >>>",vo="# <<< visa-cli shell hud v2 <<<",kp="# >>> visa-cli shell hud >>>",Cp="# <<< visa-cli shell hud <<<",$c=3e4,Tp=6e4,Ep="VISA | HUD not ready \u2014 run: visa-cli config hud doctor",Ap={currentVersion:"0.0.0"},Rp=15e3;function Qs(){try{return H.join(ni(),".visa-cli")}catch{return H.join(rn.tmpdir(),".visa-cli")}}function Ot(){return H.join(Qs(),"shell-hud.json")}function br(){return H.join(Qs(),"shell-hud.line")}function Pc(){return H.join(Qs(),"shell-hud.lock")}function jn(e){let t=e??process.env.SHELL;if(!t)return null;let n=H.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 vr(e){let t=ni();if(e==="zsh")return H.join(t,".zshrc");if(e==="bash")return H.join(t,".bashrc");let n=(process.platform==="win32","PowerShell");return H.join(t,"Documents",n,"Microsoft.PowerShell_profile.ps1")}function Oc(e,t){let n=t??ni(),r=[{shell:"zsh",rcPath:H.join(n,".zshrc")},{shell:"bash",rcPath:H.join(n,".bashrc")},{shell:"bash",rcPath:H.join(n,".bash_profile")},{shell:"powershell",rcPath:H.join(n,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:H.join(n,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:H.join(n,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:H.join(n,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:H.join(n,".config","powershell","Microsoft.PowerShell_profile.ps1")}];if(!e)return r;let o=r.filter(i=>i.shell===e),s=r.filter(i=>i.shell!==e);return[...o,...s]}function Ip(e){let t="$HOME/.visa-cli/shell-hud.line",n=zp(e),r=Jp(e);if(e==="zsh")return`${bo}
21
+ `),process.exit(1)}var Po=E(require("fs")),el=E(require("os")),_i=E(require("path")),Pf=[{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"}}],Of=/^data:(image\/(png|jpeg|jpg|gif|webp));base64,([A-Za-z0-9+/=]+)$/;function Wn(e){if(typeof e!="string"||e.length===0)return null;let t=e.trim(),n=Of.exec(t);if(n){let o=n[2]==="jpg"?"jpeg":n[2],s=o==="png"?{mime:"image/png",ext:"png"}:o==="jpeg"?{mime:"image/jpeg",ext:"jpg"}:o==="gif"?{mime:"image/gif",ext:"gif"}:{mime:"image/webp",ext:"webp"};return{base64:n[3],sig:s}}if(!/^[A-Za-z0-9+/=\s]+$/.test(t)||t.length<64)return null;let r=t.replace(/\s+/g,"");for(let{prefix:o,sig:s}of Pf)if(r.startsWith(o))return{base64:r,sig:s};return null}function Ir(e,t={}){let n=t.outputDir??_i.join(el.tmpdir(),"visa-cli");Po.mkdirSync(n,{recursive:!0});let r=(t.tag??"media").toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"media",o=new Date().toISOString().replace(/[:.]/g,"-"),s=_i.join(n,`${r}-${o}.${e.sig.ext}`),i=Buffer.from(e.base64,"base64");return Po.writeFileSync(s,i,{mode:384}),{filePath:s,bytes:i.length,mime:e.sig.mime}}function Mf(e,t={}){let n={success:!0,command:e,ts:new Date().toISOString()};for(let[r,o]of Object.entries(t))o!==void 0&&(n[r]=o);return n}function $r(e,t,n={}){let r={success:!1,command:e,ts:new Date().toISOString(),error:t};for(let[o,s]of Object.entries(n))s!==void 0&&(r[o]=s);return r}function bi(e,t){if(!t||typeof t!="object")return $r(e,"No result payload from tool");let n=t;if(n.success===!1)return $r(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,o=n.data&&typeof n.data=="object"?n.data:void 0,s=n.result&&typeof n.result=="object"?n.result:void 0,i=s&&Array.isArray(s.choices)?s.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(o&&typeof o.content=="string")l=o.content;else if(o&&typeof o.text=="string")l=o.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 Mf(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 vi=require("process");async function wi(){let e="";vi.stdin.setEncoding("utf8");for await(let t of vi.stdin)e+=t;return e.endsWith(`
22
+ `)?e.slice(0,-1):e}async function un(e,t){if(e==="-"||t.stdin===!0&&!e){let o=(await wi()).trim();if(!o)throw new Error("stdin was empty \u2014 pipe a prompt or pass it as the positional argument");return o}if(e&&e.length>0)return e;throw new Error("prompt required (positional arg, `-`, or --stdin)")}function Pr(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 ol=E(require("fs")),Oo=E(require("path"));var Dt=class extends Error{constructor(t){super(t),this.name="FromStdinFieldError"}},tl=new Set;function Nf(e){tl.add(e)}function nl(e){return tl.has(e)}function rl(e,t){if(!t.startsWith("."))throw new Dt(`--from-stdin path must start with "." (got: "${t}")`);let n=Lf(t),r=e;for(let s of n){if(r==null)throw new Dt(`--from-stdin path "${t}" failed: hit ${r===null?"null":"undefined"} at segment "${s}"`);if(typeof r!="object")throw new Dt(`--from-stdin path "${t}" failed: cannot descend into primitive at segment "${s}"`);if(typeof s=="number"){if(!Array.isArray(r))throw new Dt(`--from-stdin path "${t}" failed: expected array at segment [${s}], got object`);r=r[s]}else r=r[s]}if(r==null)throw new Dt(`--from-stdin path "${t}" resolved to ${r===null?"null":"undefined"}`);if(typeof r=="object")throw new Dt(`--from-stdin path "${t}" resolved to ${Array.isArray(r)?"an array":"an object"} \u2014 refusing to coerce non-primitive to flag value`);let o=String(r);return Nf(o),o}function Lf(e){let t=e.slice(1),n=[];for(let r of t.split(".")){if(!r)continue;let o=/^([^[\]]+)|\[(\d+)\]/g,s;for(;(s=o.exec(r))!==null;)s[1]!==void 0?/^\d+$/.test(s[1])?n.push(Number(s[1])):n.push(s[1]):s[2]!==void 0&&n.push(Number(s[2]))}return n}var Si=class extends Error{constructor(t){super(t),this.name="FileShorthandStdinSourceError"}};async function sl(e){if(e===void 0)return;if(!e.startsWith("@"))return e;if(nl(e))throw new Si("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("~")?Oo.join(process.env.HOME??"",t.slice(1)):Oo.resolve(process.cwd(),t),r=await ol.promises.readFile(n,"utf8");return r.endsWith(`
23
+ `)?r.slice(0,-1):r}var Or=require("process"),jt=["json","yaml","tsv","table"];function Mo(e){return jt.includes(e)}function Mr(e,t){switch(t){case"json":Or.stdout.write(JSON.stringify(e)+`
24
+ `);return;case"yaml":Or.stdout.write(Uf(e)+`
25
+ `);return;case"tsv":Or.stdout.write(Df(e)+`
26
+ `);return;case"table":Or.stdout.write(jf(e)+`
27
+ `);return}}function Uf(e){let t=[];for(let[n,r]of Object.entries(e))if(r!==void 0)if(Array.isArray(r)){t.push(`${n}:`);for(let o of r)t.push(` - ${il(o)}`)}else r!==null&&typeof r=="object"?t.push(`${n}: ${JSON.stringify(r)}`):t.push(`${n}: ${il(r)}`);return t.join(`
28
+ `)}function il(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 Df(e){let t=[];for(let[n,r]of Object.entries(e)){if(r===void 0)continue;let o=Array.isArray(r)||r!==null&&typeof r=="object"?JSON.stringify(r):String(r);t.push(`${n} ${o}`)}return t.join(`
29
+ `)}function jf(e){let t=[];for(let[r,o]of Object.entries(e)){if(o===void 0)continue;let s=Array.isArray(o)||o!==null&&typeof o=="object"?JSON.stringify(o):String(o);t.push([r,s])}let n=Math.max(...t.map(([r])=>r.length),1);return t.map(([r,o])=>`${r.padEnd(n)} ${o}`).join(`
30
+ `)}var cl=require("child_process");function xi(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 Ff(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(`
31
+ `)}function Nr(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 ll(e,t){let n=Nr(e);if(!n)return null;let r,o;try{r=new URL(n),o=new URL(t)}catch{return null}return r.origin===o.origin?n:null}function ul(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 dl(e,t=process.platform){let n=Nr(e);return n?ul(n,t):null}function al(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function Ti(e,t={}){let n=t.log??(l=>console.log(l)),r=t.env??process.env,o=t.platform??process.platform,s=Nr(e),i=t.spawn??((l,u,d)=>{(0,cl.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 Ff(s??e).split(`
32
+ `))n(` ${l}`);if(n(""),!s){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=xi(r,o);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=ul(s,o);if(!c){n(` No known browser-open command for platform "${o}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(l=>{let u=d=>{d?al(n,d):(n(" Opened browser. Waiting for you to sign in..."),n("")),l()};try{i(c.cmd,c.args,u)}catch(d){al(n,d instanceof Error?d:new Error(String(d))),l()}})}function Vf(e){return new Promise(t=>setTimeout(t,e))}function ml(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 pl(e){return!Number.isFinite(e)||e===null||e<=0?1e3:Math.min(Math.max(Math.ceil(e),1e3),3e4)}async function Bf(e,t=Math.random()*250){let n=o=>Math.min(o+Math.max(0,Math.ceil(t)),3e4);if(!e||e.status!==429)return n(1e3);let r=ml(e.headers?.get("Retry-After"));if(r!==null)return n(pl(r));if(typeof e.json=="function")try{let o=await e.json();return n(pl(ml(o?.retryAfter)))}catch{return n(1e3)}return n(1e3)}async function Ft(e,t){let n=await Bf(e);return t?.(n),await Vf(n),n}var Pl=E(require("crypto")),Ol=require("child_process"),ge=E(require("fs")),Ml=E(require("os")),Ce=E(require("path"));var q=E(require("fs")),pn=E(require("os")),G=E(require("path")),vl=require("child_process"),Ei=require("crypto");var Jn=E(require("fs")),No=E(require("tty"));function gl(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 hl(e,t){let n=(o,s,i)=>`\x1B[38;2;${o};${s};${i}m`,r=o=>`\x1B[38;5;${o}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 yl(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 fl(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]),o=n(t[2]),s=n(t[3]);return[r,o,s].some(i=>!Number.isFinite(i))?null:.299*r+.587*o+.114*s}var Hf=80,qf="/dev/tty";function Kf(e=qf){if(process.platform==="win32")return null;let t,n;try{t=Jn.openSync(e,"r"),n=Jn.openSync(e,"w");let r=new No.ReadStream(t),o=new No.WriteStream(n);return{stdin:r,stdout:o,close:()=>{try{r.destroy?.()}catch{}try{o.destroy?.()}catch{}}}}catch{try{t!==void 0&&Jn.closeSync(t)}catch{}try{n!==void 0&&Jn.closeSync(n)}catch{}return null}}function Gf(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 s=(e.openControllingTerminal??Kf)(e.ttyPath);return s?.stdout.isTTY&&s.stdin.isTTY&&typeof s.stdin.setRawMode=="function"?s:(s?.close?.(),null)}async function Wf(e={}){let t=Gf(e);if(!t)return null;let{stdin:n,stdout:r}=t,o=e.timeoutMs??Hf,s=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=fl(l),$=l.includes("\x07")||l.includes("\x1B\\");w!==null&&$&&m(w>.5?"light":"dark")},p=()=>{try{n.removeListener("data",d)}catch{}try{i(g)}catch{}try{!u&&typeof n.setRawMode=="function"&&n.setRawMode(!1)}catch{}try{n.pause?.()}catch{}try{n.unref?.()}catch{}try{t.close?.()}catch{}},m=h=>{c||(c=!0,p(),a(h))},g=s(()=>{let h=fl(l);m(h!==null?h>.5?"light":"dark":null)},o);try{u||n.setRawMode?.(!0),n.resume?.(),n.on("data",d),r.write("\x1B]11;?\x1B\\")}catch{m(null)}})}var dn,Lr;function zf(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=yl(e.COLORFGBG);return n||"dark"}function Lo(e=process.env){return dn!==void 0||(dn=zf(e)),dn}function we(e=process.env){if(Lr!==void 0)return Lr;let t=Lo(e),n=gl(e);return Lr=hl(t==="light"?"light":"dark",n),Lr}function Uo(e=process.env){return Lo(e)==="no-color"}async function Ci(e={}){if(dn!==void 0)return dn;let t=e.env??process.env;if((t.NO_COLOR??"")!=="")return zn("no-color",t);let n=(t.VISA_CLI_HUD_THEME??"").toLowerCase().trim();if(n==="light")return zn("light",t);if(n==="dark")return zn("dark",t);let r=yl(t.COLORFGBG);if(r)return zn(r,t);let o=await Wf(e);return zn(o||"dark",t)}function zn(e,t){dn=e;let n=gl(t);return Lr=hl(e==="light"?"light":"dark",n),e}var Jf=2,Do="# >>> visa-cli shell hud v2 >>>",jo="# <<< visa-cli shell hud v2 <<<",Yf="# >>> visa-cli shell hud >>>",Xf="# <<< visa-cli shell hud <<<",wl=3e4,Zf=6e4,Qf="VISA | HUD not ready \u2014 run: visa-cli config hud doctor",eg={currentVersion:"0.0.0"},tg=15e3;function Ai(){try{return G.join($i(),".visa-cli")}catch{return G.join(pn.tmpdir(),".visa-cli")}}function Vt(){return G.join(Ai(),"shell-hud.json")}function Ur(){return G.join(Ai(),"shell-hud.line")}function Sl(){return G.join(Ai(),"shell-hud.lock")}function Zn(e){let t=e??process.env.SHELL;if(!t)return null;let n=G.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 Dr(e){let t=$i();if(e==="zsh")return G.join(t,".zshrc");if(e==="bash")return G.join(t,".bashrc");let n=(process.platform==="win32","PowerShell");return G.join(t,"Documents",n,"Microsoft.PowerShell_profile.ps1")}function xl(e,t){let n=t??$i(),r=[{shell:"zsh",rcPath:G.join(n,".zshrc")},{shell:"bash",rcPath:G.join(n,".bashrc")},{shell:"bash",rcPath:G.join(n,".bash_profile")},{shell:"powershell",rcPath:G.join(n,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:G.join(n,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:G.join(n,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:G.join(n,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:G.join(n,".config","powershell","Microsoft.PowerShell_profile.ps1")}];if(!e)return r;let o=r.filter(i=>i.shell===e),s=r.filter(i=>i.shell!==e);return[...o,...s]}function ng(e){let t="$HOME/.visa-cli/shell-hud.line",n=vg(e),r=wg(e);if(e==="zsh")return`${Do}
33
33
  _visa_cli_shell_hud_precmd() {
34
34
  setopt localoptions no_bg_nice
35
35
  if [[ -f "${t}" ]]; then
@@ -46,7 +46,7 @@ autoload -Uz add-zsh-hook
46
46
  if [[ -z "\${precmd_functions[(r)_visa_cli_shell_hud_precmd]}" ]]; then
47
47
  add-zsh-hook precmd _visa_cli_shell_hud_precmd
48
48
  fi
49
- ${vo}`;if(e==="powershell"){let o="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${bo}
49
+ ${jo}`;if(e==="powershell"){let o="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${Do}
50
50
  if (-not (Test-Path Function:\\global:__visa_cli_original_prompt)) {
51
51
  $function:global:__visa_cli_original_prompt = if (Test-Path Function:\\prompt) { $function:prompt } else { { '' } }
52
52
  }
@@ -65,7 +65,7 @@ function global:prompt {
65
65
  }
66
66
  & $function:global:__visa_cli_original_prompt
67
67
  }
68
- ${vo}`}return`${bo}
68
+ ${jo}`}return`${Do}
69
69
  __visa_cli_shell_hud_precmd() {
70
70
  if [ -f "${t}" ]; then
71
71
  cat "${t}"
@@ -82,63 +82,63 @@ case ";$PROMPT_COMMAND;" in
82
82
  *";__visa_cli_shell_hud_precmd;"*) ;;
83
83
  *) PROMPT_COMMAND="__visa_cli_shell_hud_precmd\${PROMPT_COMMAND:+;$PROMPT_COMMAND}" ;;
84
84
  esac
85
- ${vo}`}function $p(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 Pp(e,t,n){let r=new RegExp(`(^|\\n)([ \\t]*${Rc(t)}[ \\t]*\\r?\\n)([\\s\\S]*?)(\\r?\\n[ \\t]*${Rc(n)}[ \\t]*)(?=\\r?\\n|$)(\\r?\\n)?`,"g");return e.replace(r,(o,s,i,a,c,l,u)=>{if(!$p(a))return o;let d=u>0?e[u-1]:"";return s===`
85
+ ${jo}`}function rg(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 og(e,t,n){let r=new RegExp(`(^|\\n)([ \\t]*${bl(t)}[ \\t]*\\r?\\n)([\\s\\S]*?)(\\r?\\n[ \\t]*${bl(n)}[ \\t]*)(?=\\r?\\n|$)(\\r?\\n)?`,"g");return e.replace(r,(o,s,i,a,c,l,u)=>{if(!rg(a))return o;let d=u>0?e[u-1]:"";return s===`
86
86
  `&&d!==`
87
87
  `?`
88
- `:""})}function wr(e){let t=e;for(let[n,r]of[[bo,vo],[kp,Cp]])t=Pp(t,n,r);return t.trimEnd()}function Mc(e){return wr(e)!==e.trimEnd()}function Op(e,t){let n=wr(e).trimEnd(),r=Ip(t);return n.length>0?`${n}
88
+ `:""})}function jr(e){let t=e;for(let[n,r]of[[Do,jo],[Yf,Xf]])t=og(t,n,r);return t.trimEnd()}function Tl(e){return jr(e)!==e.trimEnd()}function sg(e,t){let n=jr(e).trimEnd(),r=ng(t);return n.length>0?`${n}
89
89
 
90
90
  ${r}
91
91
  `:`${r}
92
- `}function wo(e=jn()){if(!e)return!1;try{let t=vr(e),n=B.readFileSync(t,"utf-8");return Mc(n)}catch{return!1}}function on(e=rn.homedir()){let t=[],n=Mp(e);for(let r of n)try{if(!B.existsSync(r))continue;let o=B.readFileSync(r,"utf-8");Mc(o)&&t.push(r)}catch{}return t}function Mp(e){return Oc(null,e).map(t=>t.rcPath)}function So(e=jn()){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=vr(e);let n=B.existsSync(t)?B.readFileSync(t,"utf-8"):"",r=Op(n,e),o=r!==n;return o&&Dn(t,r),{installed:!0,changed:o,shell:e,rcPath:t,message:o?`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}: ${Xs(n)}`}}}function mt(e=jn(),t){let n=[],r=[],o=[];try{for(let s of Oc(e,t))if(r.push(s.rcPath),!!B.existsSync(s.rcPath))try{let i=B.readFileSync(s.rcPath,"utf-8"),a=wr(i);if(a===i.trimEnd())continue;Dn(s.rcPath,a.length>0?`${a}
93
- `:""),n.push(s.rcPath)}catch(i){o.push(`${s.rcPath}: ${Xs(i)}`)}return n.length>0?{removed:!0,shell:e,rcPath:n[0],rcPaths:n,message:o.length>0?`Removed persistent shell HUD from ${n.join(", ")}. Some rc files could not be updated: ${o.join("; ")}.`:`Removed persistent shell HUD from ${n.join(", ")}.`}:o.length>0?{removed:!1,shell:e,rcPath:r[0],rcPaths:r,message:`Failed to remove persistent shell HUD: ${o.join("; ")}`}:{removed:!0,shell:e,rcPath:r[0],rcPaths:r,message:"Persistent shell HUD was not installed in any supported shell rc file."}}catch(s){return{removed:!1,shell:e,message:`Failed to remove persistent shell HUD: ${Xs(s)}`}}}function ei(e,t){let n=t??Ap,r=n.currentVersion==="0.0.0"&&e.version?e.version:n.currentVersion,o=Mt(r),s=` ${W("\u2502",K.chrome)} `,i=Nc(n),a=jp(n,i),c=n.updateCheckDisabled?"":i,l=Dp(o,c);if(!e.enrolled)return[l,W("setup needed",K.visaGold),a].filter(Boolean).join(s);let u=Wp(e),d=Up(e),p=Mt(rn.hostname().split(".")[0]),m=[l,p?W(p,K.muted):"",W(u,K.visaGold),a].filter(Boolean).join(s),g=[d,Np(e)].filter(Boolean),y=g.length>0?g.join(s):"";return y?`${m}
94
- ${y}`:m}function Np(e){let t=` ${W("\u2502",K.chrome)} `,n=[];if(typeof e.spentToday=="number"&&Number.isFinite(e.spentToday)&&n.push(W(`spent today ${Un(Math.max(0,e.spentToday))}`,K.muted)),e.lastService&&typeof e.lastService.toolName=="string"&&e.lastService.toolName.length>0){let r=Gp(Mt(e.lastService.toolName)),o=Lp(e.lastService.createdAt),s=W(o?`last ${r} ${o}`:`last ${r}`,K.muted);n.push(s)}if(typeof e.apiKeyCount=="number"&&Number.isFinite(e.apiKeyCount)){let r=Math.max(0,Math.floor(e.apiKeyCount)),o=r===1?"VISA Key":"VISA Keys";n.push(W(`${r} ${o}`,K.muted))}else e.apiKeyStatus==="rollout_locked"&&n.push(W("VISA Key \u{1F51C}",K.muted));return n.join(t)}function Lp(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 o=Math.floor(r/60);if(o<60)return`${o}m`;let s=Math.floor(o/60);return s<24?`${s}h`:`${Math.floor(s/24)}d`}function Up(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 W("balance unknown",K.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`${Kp(l)} ${W(`${Un(a/100)} in session`,K.green)} ${W(`(${Un(c/100)}/${Un(i/100)} cap)`,K.muted)} ${W("\xB7",K.chrome)} ${W(`${Un(r)} balance`,K.muted)}`}let o=10,s=`balance ${Un(r)}`;return t>=o?W(s,K.green):W(`${s} \u2014 top up via buy_credits`,K.visaGold)}function Dp(e,t){let n=e,r=`${W("VISA CLI",K.visaBlue)} ${W(`v${n}`,K.visaBlueSoft)}`;if(!t)return r;let o=t;return`${r} ${W("\u2B06 update",K.visaGold)} ${W(`v${o}`,K.visaGold)}`}function jp(e,t){return t&&!e.updateCheckDisabled?W("run: visa-cli update",K.visaGold):t?null:Fp(e)}function Nc(e){return e.latestVersion?Mt(e.latestVersion):""}function Fp(e){let t=Nc(e);return t?W(`update ready v${t}`,K.visaGold):null}function Lc(){let e=Sr();return!(!e||Date.now()-e.renderedAt>$c||e.cwd&&e.cwd!==process.cwd())}function xo(){let e=Sr(),t=Date.now();if(e&&t-e.renderedAt<=$c||(qp(),e?.line))return Ac(e.line,e,t);try{let n=br();if(B.existsSync(n)){let r=B.readFileSync(n,"utf-8").trimEnd();if(r&&!ko(r))return r}}catch{}return Ep}function Ac(e,t,n){let r=n-t.renderedAt,o=typeof t.refreshFailedAt=="number"&&t.refreshFailedAt>t.renderedAt,s=[];if(r>=Tp&&s.push(`stale ${Vp(r)}`),o&&s.push("\u26A0 refresh failed"),s.length===0)return e;let i=` ${W("\xB7",K.chrome)} ${W(s.join(" \xB7 "),K.visaGold)}`,a=e.split(`
92
+ `}function Fo(e=Zn()){if(!e)return!1;try{let t=Dr(e),n=q.readFileSync(t,"utf-8");return Tl(n)}catch{return!1}}function fn(e=pn.homedir()){let t=[],n=ig(e);for(let r of n)try{if(!q.existsSync(r))continue;let o=q.readFileSync(r,"utf-8");Tl(o)&&t.push(r)}catch{}return t}function ig(e){return xl(null,e).map(t=>t.rcPath)}function Vo(e=Zn()){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=Dr(e);let n=q.existsSync(t)?q.readFileSync(t,"utf-8"):"",r=sg(n,e),o=r!==n;return o&&Xn(t,r),{installed:!0,changed:o,shell:e,rcPath:t,message:o?`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}: ${ki(n)}`}}}function _t(e=Zn(),t){let n=[],r=[],o=[];try{for(let s of xl(e,t))if(r.push(s.rcPath),!!q.existsSync(s.rcPath))try{let i=q.readFileSync(s.rcPath,"utf-8"),a=jr(i);if(a===i.trimEnd())continue;Xn(s.rcPath,a.length>0?`${a}
93
+ `:""),n.push(s.rcPath)}catch(i){o.push(`${s.rcPath}: ${ki(i)}`)}return n.length>0?{removed:!0,shell:e,rcPath:n[0],rcPaths:n,message:o.length>0?`Removed persistent shell HUD from ${n.join(", ")}. Some rc files could not be updated: ${o.join("; ")}.`:`Removed persistent shell HUD from ${n.join(", ")}.`}:o.length>0?{removed:!1,shell:e,rcPath:r[0],rcPaths:r,message:`Failed to remove persistent shell HUD: ${o.join("; ")}`}:{removed:!0,shell:e,rcPath:r[0],rcPaths:r,message:"Persistent shell HUD was not installed in any supported shell rc file."}}catch(s){return{removed:!1,shell:e,message:`Failed to remove persistent shell HUD: ${ki(s)}`}}}function Ri(e,t){let n=t??eg,r=n.currentVersion==="0.0.0"&&e.version?e.version:n.currentVersion,o=Bt(r),s=` ${J("\u2502",W.chrome)} `,i=Cl(n),a=dg(n,i),c=n.updateCheckDisabled?"":i,l=ug(o,c);if(!e.enrolled)return[l,J("setup needed",W.visaGold),a].filter(Boolean).join(s);let u=bg(e),d=lg(e),p=Bt(pn.hostname().split(".")[0]),m=[l,p?J(p,W.muted):"",J(u,W.visaGold),a].filter(Boolean).join(s),g=[d,ag(e)].filter(Boolean),h=g.length>0?g.join(s):"";return h?`${m}
94
+ ${h}`:m}function ag(e){let t=` ${J("\u2502",W.chrome)} `,n=[];if(typeof e.spentToday=="number"&&Number.isFinite(e.spentToday)&&n.push(J(`spent today ${Yn(Math.max(0,e.spentToday))}`,W.muted)),e.lastService&&typeof e.lastService.toolName=="string"&&e.lastService.toolName.length>0){let r=_g(Bt(e.lastService.toolName)),o=cg(e.lastService.createdAt),s=J(o?`last ${r} ${o}`:`last ${r}`,W.muted);n.push(s)}if(typeof e.apiKeyCount=="number"&&Number.isFinite(e.apiKeyCount)){let r=Math.max(0,Math.floor(e.apiKeyCount)),o=r===1?"VISA Key":"VISA Keys";n.push(J(`${r} ${o}`,W.muted))}else e.apiKeyStatus==="rollout_locked"&&n.push(J("VISA Key \u{1F51C}",W.muted));return n.join(t)}function cg(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 o=Math.floor(r/60);if(o<60)return`${o}m`;let s=Math.floor(o/60);return s<24?`${s}h`:`${Math.floor(s/24)}d`}function lg(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 J("balance unknown",W.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`${yg(l)} ${J(`${Yn(a/100)} in session`,W.green)} ${J(`(${Yn(c/100)}/${Yn(i/100)} cap)`,W.muted)} ${J("\xB7",W.chrome)} ${J(`${Yn(r)} balance`,W.muted)}`}let o=10,s=`balance ${Yn(r)}`;return t>=o?J(s,W.green):J(`${s} \u2014 top up via buy_credits`,W.visaGold)}function ug(e,t){let n=e,r=`${J("VISA CLI",W.visaBlue)} ${J(`v${n}`,W.visaBlueSoft)}`;if(!t)return r;let o=t;return`${r} ${J("\u2B06 update",W.visaGold)} ${J(`v${o}`,W.visaGold)}`}function dg(e,t){return t&&!e.updateCheckDisabled?J("run: visa-cli update",W.visaGold):t?null:mg(e)}function Cl(e){return e.latestVersion?Bt(e.latestVersion):""}function mg(e){let t=Cl(e);return t?J(`update ready v${t}`,W.visaGold):null}function kl(){let e=Fr();return!(!e||Date.now()-e.renderedAt>wl||e.cwd&&e.cwd!==process.cwd())}function Bo(){let e=Fr(),t=Date.now();if(e&&t-e.renderedAt<=wl||(fg(),e?.line))return _l(e.line,e,t);try{let n=Ur();if(q.existsSync(n)){let r=q.readFileSync(n,"utf-8").trimEnd();if(r&&!Ho(r))return r}}catch{}return Qf}function _l(e,t,n){let r=n-t.renderedAt,o=typeof t.refreshFailedAt=="number"&&t.refreshFailedAt>t.renderedAt,s=[];if(r>=Zf&&s.push(`stale ${pg(r)}`),o&&s.push("\u26A0 refresh failed"),s.length===0)return e;let i=` ${J("\xB7",W.chrome)} ${J(s.join(" \xB7 "),W.visaGold)}`,a=e.split(`
95
95
  `);for(let c=a.length-1;c>=0;c--)if(a[c].length>0)return a[c]=`${a[c]}${i}`,a.join(`
96
- `);return`${e}${i}`}function Vp(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 ti(e,t){try{let n=H.dirname(Ot());B.mkdirSync(n,{recursive:!0});let r=e.split(`
97
- `).map(s=>Hp(s)).filter(s=>s.length>0).join(`
98
- `),o={hudVersion:xp,renderedAt:Date.now(),line:r,cwd:process.cwd(),status:t};Dn(Ot(),JSON.stringify(o)+`
99
- `),Dn(br(),r+`
100
- `)}catch{}}function Uc(e){try{let t=Sr();if(!t)return;let n=Math.max(Date.now(),t.renderedAt+1),r={...t,refreshFailedAt:n,refreshErrorReason:Mt(e).slice(0,200)};Dn(Ot(),JSON.stringify(r)+`
101
- `)}catch{}}function Dc(){try{let e=Sr();if(!e)return;let t={...e,renderedAt:0};Dn(Ot(),JSON.stringify(t)+`
102
- `)}catch{}}function nn(){try{B.unlinkSync(Pc())}catch{}}function Sr(){let e=Ot();if(!B.existsSync(e))return null;try{let t=JSON.parse(B.readFileSync(e,"utf-8"));return typeof t?.line=="string"&&ko(t.line)?null:t}catch{return null}}function ko(e){for(let t of e.split(`
103
- `)){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 jc(){return Sr()?.status??null}function qp(){if(process.env.JEST_WORKER_ID)return;let e=Pc();try{if(B.mkdirSync(H.dirname(e),{recursive:!0}),!Yp(e))return;let t=process.argv[1]?H.resolve(process.argv[1]):"";if(!t){nn();return}let n=yo(),r=(process.env.VISA_CLI_HUD_THEME??"").toLowerCase().trim(),o=n==="no-color"||r==="light"||r==="dark"?{}:{VISA_CLI_HUD_THEME:n},s=(0,Ic.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,...o,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});s.once("error",nn),s.unref()}catch{nn()}}function Mt(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 Bp=/^\u001B\[(?:0|38;2;\d{1,3};\d{1,3};\d{1,3}|38;5;\d{1,3})m$/;function Hp(e){let t=[],n=`__VISA_CLI_HUD_SGR_${(0,Zs.randomBytes)(8).toString("hex")}_`,r=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,s=>{if(!Bp.test(s))return"";let i=`${n}${t.length}__`;return t.push(s),i}),o=new RegExp(`${n}(\\d+)__`,"g");return Mt(r).replace(o,(s,i)=>t[Number(i)]??"")}function Kp(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),o="\u2591".repeat(10-n);return`${W(r||"",K.green)}${W(o||"",K.chrome)}`}function Un(e){return`$${e.toFixed(2)}`}function Gp(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 o=t.split("/").filter(Boolean);t=o[o.length-1]||t}return t=t.replace(/^fal-ai\//,""),t=t.replace(/^fal-/,""),t=t.replace(/^or-/,""),t=t.split("/").filter(Boolean).map(o=>o.replace(/^v\d+(?:\.\d+)?-?/,"")||null).filter(o=>o!==null&&o.length>0).join(" "),t=t.replace(/_card$/,""),t.length>28&&(t=t.slice(0,28).trimEnd()),t||e}function Wp(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:"????",o=Mt(n.toUpperCase()),s=Mt(r);return`${t.isDefault?"default":"active"} ${o} ****${s}`}var K={get reset(){return _e().reset},get visaBlue(){return _e().visaBlue},get visaBlueSoft(){return _e().visaBlueSoft},get visaGold(){return _e().visaGold},get green(){return _e().green},get muted(){return _e().muted},get chrome(){return _e().chrome}};function W(e,t){return e.length===0||process.env.NO_COLOR||_o()?e:`${t}${e}${K.reset}`}function Rc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ni(){let e=rn.homedir();if(!e||!H.isAbsolute(e))throw new Error("unable to determine a valid home directory");return H.resolve(e)}function zp(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function Jp(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function Yp(e){for(let t=0;t<2;t+=1){let n;try{return n=B.openSync(e,"wx"),B.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let o=B.statSync(e);if(Date.now()-o.mtimeMs<=Rp)return!1;B.unlinkSync(e)}catch{}}finally{n!==void 0&&B.closeSync(n)}}return!1}function Xs(e){return e instanceof Error?e.message:"unknown file system error"}function Dn(e,t){B.mkdirSync(H.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${(0,Zs.randomBytes)(8).toString("hex")}.tmp`;try{B.writeFileSync(n,t),B.renameSync(n,e)}catch(r){try{B.unlinkSync(n)}catch{}throw r}}var Xp=1440*60*1e3;function To(e,t){de.mkdirSync(we.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${qc.randomBytes(8).toString("hex")}.tmp`;try{de.writeFileSync(n,JSON.stringify(t,null,2)+`
104
- `),de.renameSync(n,e)}catch(r){try{de.unlinkSync(n)}catch{}throw r}}function Fc(e){return`'${e.replace(/'/g,"'\\''")}'`}var oi="# visa-cli-hud-v1";function Eo(e,t){if(!e&&!t&&Zp())return`visa-cli config statusline ${oi}`;let n=e??process.execPath,r=t??process.argv[1]??"",o=r?we.resolve(r):"";return`${o?`${Fc(n)} ${Fc(o)} config statusline`:"visa-cli config statusline"} ${oi}`}function Zp(){try{return(0,Bc.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function Nt(e){return typeof e!="string"?!1:e.includes(oi)?!0:e.includes("visa-cli")&&e.includes("statusline")}function Qp(){return"3.0.0"}function Ao(e){let t=we.dirname(we.resolve(e));return we.basename(t)===".claude"?we.dirname(t):Hc.homedir()}function Co(e,t){let n=we.relative(t,e);return!n.startsWith("..")&&!we.isAbsolute(n)?`~/${n}`:e}function ef(e){return we.join(Ao(e),".visa-cli","hud-self-heal.json")}function tf(e,t,n,r){try{if(!de.existsSync(e))return!1;let o=JSON.parse(de.readFileSync(e,"utf-8"));return o.version===t&&typeof o.checkedAt=="number"&&n-o.checkedAt<r}catch{return!1}}function ri(e,t,n){try{To(e,{version:t,checkedAt:n})}catch{}}function nf(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function si(e,t={}){let n=t.now??Date.now(),r=t.version??Qp(),o=t.stampPath??ef(e),s=t.minIntervalMs??Xp,i=[],a=!1,c=!1;if(!t.force&&tf(o,r,n,s))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:i,skippedReason:"recently checked"};try{if(!de.existsSync(e))return ri(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let l=JSON.parse(de.readFileSync(e,"utf-8")),u=l.statusLine,d=u&&typeof u=="object"&&!Array.isArray(u)?u.command:"";if(!Nt(d))return ri(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let p=(t.getCommand??Eo)();if(d!==p&&(l.statusLine=nf(u,p),To(e,l),a=!0,i.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!Ro()){let m=Ao(e);if(on(m).length>0){let y=mt(null,m);if(y.removed&&y.rcPaths&&y.rcPaths.length>0){let w=y.rcPaths.map(N=>Co(N,m)).join(", ");c=!0,i.push(`Cleaned legacy shell-prompt HUD block from ${w}.`)}}}return ri(o,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
105
- `)}catch{}}return{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i}}}function rf(e,t){let n=Ao(t),r=on(n);if(r.length===0)return e;let o=r.map(s=>Co(s,n)).join(", ");return`${e}
106
- Note: a shell-prompt HUD block was detected in ${o}. If it is unintended, remove it with: visa-cli config hud disable shell`}function Ro(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 Vc(e,t){let n=Ao(t),r=on(n);if(r.length===0)return e;let o=r.map(i=>Co(i,n)).join(", ");if(Ro())return`${e}
107
- Note: a legacy shell-prompt HUD block was detected in ${o}. VISA_HUD_KEEP_SHELL set \u2014 leaving it in place. Remove it any time with: visa-cli config hud disable shell`;let s=mt(null,n);if(s.removed&&s.rcPaths&&s.rcPaths.length>0){let i=s.rcPaths.map(a=>Co(a,n)).join(", ");return`${e}
96
+ `);return`${e}${i}`}function pg(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 Ii(e,t){try{let n=G.dirname(Vt());q.mkdirSync(n,{recursive:!0});let r=e.split(`
97
+ `).map(s=>hg(s)).filter(s=>s.length>0).join(`
98
+ `),o={hudVersion:Jf,renderedAt:Date.now(),line:r,cwd:process.cwd(),status:t};Xn(Vt(),JSON.stringify(o)+`
99
+ `),Xn(Ur(),r+`
100
+ `)}catch{}}function El(e){try{let t=Fr();if(!t)return;let n=Math.max(Date.now(),t.renderedAt+1),r={...t,refreshFailedAt:n,refreshErrorReason:Bt(e).slice(0,200)};Xn(Vt(),JSON.stringify(r)+`
101
+ `)}catch{}}function Al(){try{let e=Fr();if(!e)return;let t={...e,renderedAt:0};Xn(Vt(),JSON.stringify(t)+`
102
+ `)}catch{}}function mn(){try{q.unlinkSync(Sl())}catch{}}function Fr(){let e=Vt();if(!q.existsSync(e))return null;try{let t=JSON.parse(q.readFileSync(e,"utf-8"));return typeof t?.line=="string"&&Ho(t.line)?null:t}catch{return null}}function Ho(e){for(let t of e.split(`
103
+ `)){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 Rl(){return Fr()?.status??null}function fg(){if(process.env.JEST_WORKER_ID)return;let e=Sl();try{if(q.mkdirSync(G.dirname(e),{recursive:!0}),!Sg(e))return;let t=process.argv[1]?G.resolve(process.argv[1]):"";if(!t){mn();return}let n=Lo(),r=(process.env.VISA_CLI_HUD_THEME??"").toLowerCase().trim(),o=n==="no-color"||r==="light"||r==="dark"?{}:{VISA_CLI_HUD_THEME:n},s=(0,vl.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,...o,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});s.once("error",mn),s.unref()}catch{mn()}}function Bt(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 gg=/^\u001B\[(?:0|38;2;\d{1,3};\d{1,3};\d{1,3}|38;5;\d{1,3})m$/;function hg(e){let t=[],n=`__VISA_CLI_HUD_SGR_${(0,Ei.randomBytes)(8).toString("hex")}_`,r=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,s=>{if(!gg.test(s))return"";let i=`${n}${t.length}__`;return t.push(s),i}),o=new RegExp(`${n}(\\d+)__`,"g");return Bt(r).replace(o,(s,i)=>t[Number(i)]??"")}function yg(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),o="\u2591".repeat(10-n);return`${J(r||"",W.green)}${J(o||"",W.chrome)}`}function Yn(e){return`$${e.toFixed(2)}`}function _g(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 o=t.split("/").filter(Boolean);t=o[o.length-1]||t}return t=t.replace(/^fal-ai\//,""),t=t.replace(/^fal-/,""),t=t.replace(/^or-/,""),t=t.split("/").filter(Boolean).map(o=>o.replace(/^v\d+(?:\.\d+)?-?/,"")||null).filter(o=>o!==null&&o.length>0).join(" "),t=t.replace(/_card$/,""),t.length>28&&(t=t.slice(0,28).trimEnd()),t||e}function bg(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:"????",o=Bt(n.toUpperCase()),s=Bt(r);return`${t.isDefault?"default":"active"} ${o} ****${s}`}var W={get reset(){return we().reset},get visaBlue(){return we().visaBlue},get visaBlueSoft(){return we().visaBlueSoft},get visaGold(){return we().visaGold},get green(){return we().green},get muted(){return we().muted},get chrome(){return we().chrome}};function J(e,t){return e.length===0||process.env.NO_COLOR||Uo()?e:`${t}${e}${W.reset}`}function bl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $i(){let e=pn.homedir();if(!e||!G.isAbsolute(e))throw new Error("unable to determine a valid home directory");return G.resolve(e)}function vg(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function wg(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function Sg(e){for(let t=0;t<2;t+=1){let n;try{return n=q.openSync(e,"wx"),q.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let o=q.statSync(e);if(Date.now()-o.mtimeMs<=tg)return!1;q.unlinkSync(e)}catch{}}finally{n!==void 0&&q.closeSync(n)}}return!1}function ki(e){return e instanceof Error?e.message:"unknown file system error"}function Xn(e,t){q.mkdirSync(G.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${(0,Ei.randomBytes)(8).toString("hex")}.tmp`;try{q.writeFileSync(n,t),q.renameSync(n,e)}catch(r){try{q.unlinkSync(n)}catch{}throw r}}var xg=1440*60*1e3;function Ko(e,t){ge.mkdirSync(Ce.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Pl.randomBytes(8).toString("hex")}.tmp`;try{ge.writeFileSync(n,JSON.stringify(t,null,2)+`
104
+ `),ge.renameSync(n,e)}catch(r){try{ge.unlinkSync(n)}catch{}throw r}}function Il(e){return`'${e.replace(/'/g,"'\\''")}'`}var Oi="# visa-cli-hud-v1";function Go(e,t){if(!e&&!t&&Tg())return`visa-cli config statusline ${Oi}`;let n=e??process.execPath,r=t??process.argv[1]??"",o=r?Ce.resolve(r):"";return`${o?`${Il(n)} ${Il(o)} config statusline`:"visa-cli config statusline"} ${Oi}`}function Tg(){try{return(0,Ol.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function Ht(e){return typeof e!="string"?!1:e.includes(Oi)?!0:e.includes("visa-cli")&&e.includes("statusline")}function Cg(){return"3.0.1"}function Wo(e){let t=Ce.dirname(Ce.resolve(e));return Ce.basename(t)===".claude"?Ce.dirname(t):Ml.homedir()}function qo(e,t){let n=Ce.relative(t,e);return!n.startsWith("..")&&!Ce.isAbsolute(n)?`~/${n}`:e}function kg(e){return Ce.join(Wo(e),".visa-cli","hud-self-heal.json")}function Eg(e,t,n,r){try{if(!ge.existsSync(e))return!1;let o=JSON.parse(ge.readFileSync(e,"utf-8"));return o.version===t&&typeof o.checkedAt=="number"&&n-o.checkedAt<r}catch{return!1}}function Pi(e,t,n){try{Ko(e,{version:t,checkedAt:n})}catch{}}function Ag(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function Mi(e,t={}){let n=t.now??Date.now(),r=t.version??Cg(),o=t.stampPath??kg(e),s=t.minIntervalMs??xg,i=[],a=!1,c=!1;if(!t.force&&Eg(o,r,n,s))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:i,skippedReason:"recently checked"};try{if(!ge.existsSync(e))return Pi(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let l=JSON.parse(ge.readFileSync(e,"utf-8")),u=l.statusLine,d=u&&typeof u=="object"&&!Array.isArray(u)?u.command:"";if(!Ht(d))return Pi(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let p=(t.getCommand??Go)();if(d!==p&&(l.statusLine=Ag(u,p),Ko(e,l),a=!0,i.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!zo()){let m=Wo(e);if(fn(m).length>0){let h=_t(null,m);if(h.removed&&h.rcPaths&&h.rcPaths.length>0){let w=h.rcPaths.map($=>qo($,m)).join(", ");c=!0,i.push(`Cleaned legacy shell-prompt HUD block from ${w}.`)}}}return Pi(o,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
105
+ `)}catch{}}return{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i}}}function Rg(e,t){let n=Wo(t),r=fn(n);if(r.length===0)return e;let o=r.map(s=>qo(s,n)).join(", ");return`${e}
106
+ Note: a shell-prompt HUD block was detected in ${o}. If it is unintended, remove it with: visa-cli config hud disable shell`}function zo(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 $l(e,t){let n=Wo(t),r=fn(n);if(r.length===0)return e;let o=r.map(i=>qo(i,n)).join(", ");if(zo())return`${e}
107
+ Note: a legacy shell-prompt HUD block was detected in ${o}. VISA_HUD_KEEP_SHELL set \u2014 leaving it in place. Remove it any time with: visa-cli config hud disable shell`;let s=_t(null,n);if(s.removed&&s.rcPaths&&s.rcPaths.length>0){let i=s.rcPaths.map(a=>qo(a,n)).join(", ");return`${e}
108
108
  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}
109
- Note: a legacy shell-prompt HUD block was detected in ${o} but could not be auto-removed (${s.message}). Remove it manually with: visa-cli config hud disable shell`}function xr(e,t=Eo){let n={},r=!1;if(de.existsSync(e)){r=!0;try{n=JSON.parse(de.readFileSync(e,"utf-8"))}catch(o){return{installed:"malformed-json",message:`~/.claude/settings.json is not valid JSON (${o.message}). Fix the file manually, then run: visa-cli config hud enable claude`}}}if(n.statusLine){let o=typeof n.statusLine=="object"?n.statusLine.command:"";return Nt(o)?{installed:"already-visa",message:Vc("Visa HUD already registered in ~/.claude/settings.json.",e)}:{installed:"other-hud-present",message:rf("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()},To(e,n),{installed:"new",message:Vc(`Visa HUD registered in ~/.claude/settings.json${r?"":" (new file)"}. Restart Claude Code to see it pinned below the input.`,e)}}catch(o){return{installed:"error",message:`Failed to write settings: ${o.message}. Enable manually later with: visa-cli config hud enable claude`}}}function ii(e){if(!de.existsSync(e))return{removed:!1,status:"missing-settings",message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(de.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(!Nt(n))return{removed:!1,status:"foreign-statusline",message:"statusLine is owned by another tool \u2014 leaving it alone."};delete t.statusLine;try{To(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 Kc=T(require("os")),Gc=T(require("path"));function pt(e=Kc.homedir()){return Gc.join(e,".claude","settings.json")}var ft=T(require("fs")),Xe=T(require("path"));var of=1,sn={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},sf=["terminal","claude","claude-code","all"];function $o(e){let t=e.toLowerCase();return sf.includes(t)?t:null}var af=50,cf=64*1024,Wc=10,ai=80,A={get reset(){return _e().reset},get visaBlue(){return _e().visaBlue},get visaBlueSoft(){return _e().visaBlueSoft},get visaGold(){return _e().visaGold},get green(){return _e().green},get muted(){return _e().muted},get chrome(){return _e().chrome}};function R(e,t){return e.length===0||process.env.NO_COLOR||_o()?e:`${t}${e}${A.reset}`}function zc(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function Zc(e=process.stdin){return e.isTTY?null:new Promise(t=>{let n=[],r=!1,o=()=>{e.removeListener("data",i),e.removeListener("end",a),e.removeListener("error",c),clearTimeout(l)},s=u=>{r||(r=!0,o(),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 s(null);try{let d=JSON.parse(u);s(d&&typeof d=="object"?d:null)}catch{s(null)}},c=()=>s(null),l=setTimeout(()=>{n.length>0?a():s(null)},af);e.on("data",i),e.on("end",a),e.on("error",c)})}function kr(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),o="\u2591".repeat(10-n);return`${R(r||"",A.visaBlueSoft)}${R(o||"",A.chrome)}`}function Cr(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 lf(e){if(cl(e))return df(e);let t=` ${R("\u2502",A.chrome)} `,n=Io(e)||"claude",r=e.cwd?re(Xe.basename(e.cwd)):"",o=Po(e.workspace),s=r||o,i=o&&o!==s?` ${R(`@${o}`,A.visaBlueSoft)}`:"",a=[R(`[${n}]`,A.visaBlueSoft)];s&&a.push(`${R(s,A.visaGold)}${i}`);let c=re(e.git_branch??e.branch??"");c&&a.push(`${R("git:(",A.muted)}${R(c,A.visaBlueSoft)}${R(")",A.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,m=[p?.input_tokens,p?.output_tokens,p?.cache_creation_input_tokens,p?.cache_read_input_tokens].filter(O=>typeof O=="number"&&Number.isFinite(O)),g=m.length>0?m.reduce((O,_)=>O+_,0):null,y=Number(e.context_window?.total_input_tokens??g??p?.input_tokens??0),w=d!==null?Math.max(0,Math.min(1,d/100)):u>0?Math.max(0,Math.min(1,y/u)):0,N=d!==null&&u>0?Math.round(w*u):y,U;if(u>0||d!==null){let O=`${String(Math.round(w*100)).padStart(2," ")}%`,_=u>0?` ${R(`(${Cr(N)}/${Cr(u)})`,A.muted)}`:"";U=`${R("Context",A.muted)} ${kr(w)} ${R(O,A.green)}${_}`}else U=`${R("Context",A.muted)} ${R("-",A.muted)}`;let v=Qc(e.rate_limits),x=[U];v&&x.push(v);let $=x.join(t);return`${l}
110
- ${$}`}function uf(e){if(cl(e))return null;let t=` ${R("\u2502",A.chrome)} `,n=Io(e)||"claude",r=e.cwd?re(Xe.basename(e.cwd)):"",o=Po(e.workspace),s=r||o,i=o&&o!==s?` ${R(`@${o}`,A.visaBlueSoft)}`:"",a=[R(`[${n}]`,A.visaBlueSoft)];s&&a.push(`${R(s,A.visaGold)}${i}`);let c=re(e.git_branch??e.branch??"");c&&a.push(`${R("git:(",A.muted)}${R(c,A.visaBlueSoft)}${R(")",A.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(x=>typeof x=="number"&&Number.isFinite(x)),m=p.length>0?p.reduce((x,$)=>x+$,0):null,g=Number(e.context_window?.total_input_tokens??m??d?.input_tokens??0),y=u!==null?Math.max(0,Math.min(1,u/100)):l>0?Math.max(0,Math.min(1,g/l)):0,w=u!==null&&l>0?Math.round(y*l):g,N;if(l>0||u!==null){let x=`${String(Math.round(y*100)).padStart(2," ")}%`,$=l>0?` ${R(`(${Cr(w)}/${Cr(l)})`,A.muted)}`:"";N=`${R("Context",A.muted)} ${kr(y)} ${R(x,A.green)}${$}`}else N=`${R("Context",A.muted)} ${R("-",A.muted)}`;let U=Qc(e.rate_limits),v=[N];return U&&v.push(U),{identity:a.join(t),metrics:v.join(t)}}function df(e){let t=` ${R("\u2502",A.chrome)} `,n=ll(e),r=n.model||"codex",o=[R(`[${r}]`,A.visaBlueSoft)];n.project&&o.push(R(n.project,A.visaGold)),n.gitBranch&&o.push(`${R("git",A.muted)} ${R(n.gitBranch,A.visaGold)}`);let s=o.join(t),i=[];if(typeof n.contextUsedPercent=="number"){let c=Math.max(0,Math.min(1,n.contextUsedPercent/100));i.push(`${R("Context",A.muted)} ${kr(c)} ${R(`${Math.round(n.contextUsedPercent)}%`,A.green)}`)}else if(typeof n.contextRemainingPercent=="number"){let c=100-n.contextRemainingPercent,l=Math.max(0,Math.min(1,c/100));i.push(`${R("Context",A.muted)} ${kr(l)} ${R(`${Math.round(c)}%`,A.green)}`)}typeof n.usedTokens=="number"&&i.push(`${R("Tokens",A.muted)} ${Cr(n.usedTokens)}`),n.status&&i.push(`${R("Status",A.muted)} ${R(n.status,A.visaBlueSoft)}`),n.threadTitle&&i.push(`${R("Thread",A.muted)} ${R(n.threadTitle,A.visaBlueSoft)}`);let a=i.length>0?i.join(t):`${R("Context",A.muted)} ${R("-",A.muted)}`;return`${s}
111
- ${a}`}function mf(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),o=Math.floor(r/60),s=r%60;return o>0?`${o}h ${s}m`:`${s}m`}function Jc(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,o=kr(r),s=n>=90?"\x1B[38;5;196m":n>=70?A.visaGold:A.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=mf(e.resets_at),c=a?` ${R(`(${a} / ${t})`,A.muted)}`:` ${R(`(${t})`,A.muted)}`;return`${o} ${R(i,s)}${c}`}function Qc(e){if(!e)return null;let t=Jc(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?Jc(e.seven_day,"7d"):null;if(!t&&!r)return null;let o=` ${R("\u2502",A.chrome)} `,s=[t,r].filter(Boolean);return`${R("Usage",A.muted)} ${s.join(o)}`}function el(e){let t;try{let n=ft.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let o=Math.min(r,cf),s=r-o;t=ft.openSync(e,"r");let i=Buffer.alloc(o);ft.readSync(t,i,0,o,s);let a=i.toString("utf-8");if(s>0){let c=Buffer.alloc(1);if(ft.readSync(t,c,0,1,s-1),c[0]!==10){let l=a.indexOf(`
112
- `);l>=0&&(a=a.slice(l+1))}}return a}catch{return null}finally{if(t!==void 0)try{ft.closeSync(t)}catch{}}}function pf(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 o=t[r];if(typeof o=="string"&&o.length>0){if(r.endsWith("_path")||r==="path"){let s=Xe.basename(Xe.dirname(o)),i=Xe.basename(o);return s&&s!=="."&&s!=="/"?`${s}/${i}`:i}return o}}}function ff(e){let t=e.split(`
113
- `),n=[],r=new Set;for(let o=t.length-1;o>=0&&n.length<Wc*3;o-=1){let s=t[o].trim();if(!s)continue;let i;try{i=JSON.parse(s)}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:"",m=p.length>0?!r.has(p):!1;n.push({name:d.name,target:pf(d.input),running:m})}}}return n.reverse(),n.slice(Math.max(0,n.length-Wc))}function gf(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 hf(e){let t=e.running?R("\u25D0",A.visaGold):R("\u2713",A.green),n=e.running?A.visaGold:A.visaBlueSoft,r=R(re(e.name),n),o=e.target?re(e.target):"",s=o?`${R(":",A.chrome)} ${R(o,A.muted)}`:"",i=e.count>1?` ${R(`\xD7${e.count}`,A.muted)}`:"";return s?`${t} ${r}${s}${i}`:`${t} ${r}${i}`}function yf(e){let t=` ${R("\u2502",A.chrome)} `,n=zc(t),r=e.slice();for(;r.length>0;){let c=r.join(t);if(zc(c)<=ai)return c;r=r.slice(1)}if(e.length===0)return"";let o="\u2026",i=e[e.length-1].replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,""),a=i.length>ai-n-1?i.slice(0,ai-n-1)+o:i;return`${R(o,A.muted)}${t}${a}`}async function Yc(e){if(!e||typeof e!="string")return null;let t=el(e);if(!t)return null;let n;try{n=ff(t)}catch{return null}if(n.length===0)return null;let o=gf(n).map(hf);return yf(o)||null}async function tl(e,t,n){return(await rl(e,t,n)).join(`
114
- `)}function nl(e,t,n){let r=!!t?.activeSession||e.includes("in session"),o=n?bf(n):!1;return{isActive:r||o,hasSession:r,hasToolActivity:o}}async function rl(e,t,n){let{isActive:r}=nl(e,n,t?.transcript_path),o=e.split(`
115
- `).filter(a=>a.length>0),i=t&&!r?o.map(a=>R(ci(a),A.muted)):[...o];if(t){let a=uf(t);if(a){if(i.push(a.identity),t.transcript_path){let c=await Yc(t.transcript_path);c&&i.push(...c.split(`
116
- `))}i.push(a.metrics)}else{let c=lf(t);if(c&&i.push(...c.split(`
117
- `)),t.transcript_path){let l=await Yc(t.transcript_path);l&&i.push(...l.split(`
118
- `))}}}return i}var _f=["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 bf(e){let t=el(e);if(!t)return!1;let n=t.slice(-16384).toLowerCase();return _f.some(r=>n.includes(`"${r}"`))}async function ol(e,t,n){let r=await rl(e,t,n),o=r.join(`
119
- `),{isActive:s}=nl(e,n,t?.transcript_path);return{schemaVersion:of,client:t?al(t):sn.UNKNOWN,rendered:o,lines:r.map(ci),visa:{spendLine:ci(e),balanceCents:n?.balanceCents,balanceUsd:n?.amountUsd,sessionMode:n?.sessionMode,activeSession:n?.activeSession,isVisaActive:s},context:t?ll(t):{}}}function re(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 Po(e){if(typeof e=="string")return re(Xe.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 re(t?Xe.basename(t):e.name)}function sl(e){return re(e.app_name??e.appName??e.app??e.client)}function Io(e){return re(e.model?.display_name??e.model?.id??e.model_name??e.modelName)}function il(e){return re(e.cwd??e.current_dir??e.project_root)}function Xc(e){let t=re(e.project);if(t)return t;let n=il(e);if(n)return re(Xe.basename(n));let r=Po(e.workspace);return r||""}function je(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function al(e){let t=sl(e).toLowerCase();return t.includes("codex")?sn.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?sn.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||je(e.context_used)!==void 0?sn.CODEX:sn.UNKNOWN}function cl(e){return al(e)===sn.CODEX}function ll(e){let t=sl(e),n=il(e),r=Po(e.workspace),o=je(e.context_used)??je(e.context_window?.used_percentage??void 0),s=je(e.context_remaining)??je(e.context_window?.remaining_percentage??void 0);return{...t?{app:t}:{},...Io(e)?{model:Io(e)}:{},...Xc(e)?{project:Xc(e)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...re(e.git_branch??e.branch)?{gitBranch:re(e.git_branch??e.branch)}:{},...re(e.status??e.run_state??e.runState)?{status:re(e.status??e.run_state??e.runState)}:{},...re(e.thread_title??e.threadTitle)?{threadTitle:re(e.thread_title??e.threadTitle)}:{},...o!==void 0?{contextUsedPercent:o}:{},...s!==void 0?{contextRemainingPercent:s}:{},...je(e.used_tokens)!==void 0?{usedTokens:je(e.used_tokens)}:{},...je(e.total_input_tokens)!==void 0?{totalInputTokens:je(e.total_input_tokens)}:{},...je(e.total_output_tokens)!==void 0?{totalOutputTokens:je(e.total_output_tokens)}:{}}}function ci(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}var dl=T(require("path"));function ul(e){return e instanceof Error?e.message:String(e)}function li(e,t){let n=[],r=[],o=e??"claude",s=$o(o);if(o==="shell"||o==="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: ${ul(a)}`]}}if(!s)return{ok:!1,messages:n,errors:[`Unknown HUD surface: ${o}`,"Supported: claude (default), shell, all"]};let i=!0;if(s==="claude"||s==="claude-code"||s==="all"){let a=dl.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: ${ul(c)}`)}}return{ok:i,messages:n,errors:r}}function ml(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 pl=T(require("os")),fl=require("node:readline/promises"),Tr={card:"default VISA ****7242",balance:"balance $6.38",spentToday:"spent today $0.62",lastActivity:"last Visa tool 38m",model:"Opus 4.6"};async function ui(e,t=!1){if(!process.stdin.isTTY)return t;let n=t?"[Y/n]":"[y/N]",r,o;try{r=(0,fl.createInterface)({input:process.stdin,output:process.stdout});let s=new AbortController;o=()=>s.abort(),r.once("close",o);let i=(await r.question(`${e} ${n} `,{signal:s.signal})).trim();return i?/^y(es)?$/i.test(i):t}catch{return t}finally{r&&o&&r.off("close",o),r?.close()}}function vf(e,t){return e.replace(/[\x00-\x1F\x7F\u202A-\u202E\u2066-\u2069]/g,"").trim()||t}function gl(e=pl.hostname()){let t=dr().version,n=vf(e,"this-machine");return[" Preview if installed (sample):",` VISA CLI v${t} | ${n} | ${Tr.card}`,` ${Tr.balance} | ${Tr.spentToday} | ${Tr.lastActivity}`,` [${Tr.model}] | you`," Activity live"].join(`
120
- `)}function hl(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 di(e){return`$${(e/100).toFixed(2)}`}function yl(e){return typeof e=="number"?di(e):"no cap"}function _l(e){return e.length>0?e.join(", "):"all tools"}var wf=[" \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 Sf(){return[...hl(null),...wf].join(`
121
- `)}var bl="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 xf(e){let t=Math.max(5,...e.map(([s])=>s.length)),n=Math.max(5,...e.map(([,s])=>s.length)),r=`+-${"-".repeat(t)}-+-${"-".repeat(n)}-+`,o=(s,i)=>`| ${s.padEnd(t)} | ${i.padEnd(n)} |`;return[r,o("Field","Value"),r,...e.map(([s,i])=>o(s,i)),r]}function vl(e,t={}){let n=t.authUrl??"https://auth.visacli.sh",r=[...Sf().split(`
122
- `),"","Visa Key active","Scoped agent spend credential ready for apps and agents","",...xf([["Key",e.key],["Label",e.label],["Owner",e.owner],["Daily cap",`${di(e.daily_cap_cents)}/day`],["Total cap",yl(e.total_cap_cents)],["Allowed tools",_l(e.allowed_tools)]]),"","Guardrails",`- Spend: ${di(e.daily_cap_cents)}/day, ${yl(e.total_cap_cents)} total`,`- Tools: ${_l(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("",bl,`Server warning: ${e.biometric_warning}`):e.biometric_enabled&&r.push("",bl),`${r.join(`
109
+ Note: a legacy shell-prompt HUD block was detected in ${o} but could not be auto-removed (${s.message}). Remove it manually with: visa-cli config hud disable shell`}function Vr(e,t=Go){let n={},r=!1;if(ge.existsSync(e)){r=!0;try{n=JSON.parse(ge.readFileSync(e,"utf-8"))}catch(o){return{installed:"malformed-json",message:`~/.claude/settings.json is not valid JSON (${o.message}). Fix the file manually, then run: visa-cli config hud enable claude`}}}if(n.statusLine){let o=typeof n.statusLine=="object"?n.statusLine.command:"";return Ht(o)?{installed:"already-visa",message:$l("Visa HUD already registered in ~/.claude/settings.json.",e)}:{installed:"other-hud-present",message:Rg("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()},Ko(e,n),{installed:"new",message:$l(`Visa HUD registered in ~/.claude/settings.json${r?"":" (new file)"}. Restart Claude Code to see it pinned below the input.`,e)}}catch(o){return{installed:"error",message:`Failed to write settings: ${o.message}. Enable manually later with: visa-cli config hud enable claude`}}}function Ni(e){if(!ge.existsSync(e))return{removed:!1,status:"missing-settings",message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(ge.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(!Ht(n))return{removed:!1,status:"foreign-statusline",message:"statusLine is owned by another tool \u2014 leaving it alone."};delete t.statusLine;try{Ko(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 Nl=E(require("os")),Ll=E(require("path"));function bt(e=Nl.homedir()){return Ll.join(e,".claude","settings.json")}var vt=E(require("fs")),nt=E(require("path"));var Ig=1,gn={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},$g=["terminal","claude","claude-code","all"];function Yo(e){let t=e.toLowerCase();return $g.includes(t)?t:null}var Pg=50,Og=64*1024,Ul=10,Li=80,I={get reset(){return we().reset},get visaBlue(){return we().visaBlue},get visaBlueSoft(){return we().visaBlueSoft},get visaGold(){return we().visaGold},get green(){return we().green},get muted(){return we().muted},get chrome(){return we().chrome}};function O(e,t){return e.length===0||process.env.NO_COLOR||Uo()?e:`${t}${e}${I.reset}`}function Dl(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function Bl(e=process.stdin){return e.isTTY?null:new Promise(t=>{let n=[],r=!1,o=()=>{e.removeListener("data",i),e.removeListener("end",a),e.removeListener("error",c),clearTimeout(l)},s=u=>{r||(r=!0,o(),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 s(null);try{let d=JSON.parse(u);s(d&&typeof d=="object"?d:null)}catch{s(null)}},c=()=>s(null),l=setTimeout(()=>{n.length>0?a():s(null)},Pg);e.on("data",i),e.on("end",a),e.on("error",c)})}function Br(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),o="\u2591".repeat(10-n);return`${O(r||"",I.visaBlueSoft)}${O(o||"",I.chrome)}`}function Hr(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 Mg(e){if(Zl(e))return Lg(e);let t=` ${O("\u2502",I.chrome)} `,n=Jo(e)||"claude",r=e.cwd?ce(nt.basename(e.cwd)):"",o=Xo(e.workspace),s=r||o,i=o&&o!==s?` ${O(`@${o}`,I.visaBlueSoft)}`:"",a=[O(`[${n}]`,I.visaBlueSoft)];s&&a.push(`${O(s,I.visaGold)}${i}`);let c=ce(e.git_branch??e.branch??"");c&&a.push(`${O("git:(",I.muted)}${O(c,I.visaBlueSoft)}${O(")",I.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,m=[p?.input_tokens,p?.output_tokens,p?.cache_creation_input_tokens,p?.cache_read_input_tokens].filter(M=>typeof M=="number"&&Number.isFinite(M)),g=m.length>0?m.reduce((M,_)=>M+_,0):null,h=Number(e.context_window?.total_input_tokens??g??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,$=d!==null&&u>0?Math.round(w*u):h,k;if(u>0||d!==null){let M=`${String(Math.round(w*100)).padStart(2," ")}%`,_=u>0?` ${O(`(${Hr($)}/${Hr(u)})`,I.muted)}`:"";k=`${O("Context",I.muted)} ${Br(w)} ${O(M,I.green)}${_}`}else k=`${O("Context",I.muted)} ${O("-",I.muted)}`;let v=Hl(e.rate_limits),S=[k];v&&S.push(v);let P=S.join(t);return`${l}
110
+ ${P}`}function Ng(e){if(Zl(e))return null;let t=` ${O("\u2502",I.chrome)} `,n=Jo(e)||"claude",r=e.cwd?ce(nt.basename(e.cwd)):"",o=Xo(e.workspace),s=r||o,i=o&&o!==s?` ${O(`@${o}`,I.visaBlueSoft)}`:"",a=[O(`[${n}]`,I.visaBlueSoft)];s&&a.push(`${O(s,I.visaGold)}${i}`);let c=ce(e.git_branch??e.branch??"");c&&a.push(`${O("git:(",I.muted)}${O(c,I.visaBlueSoft)}${O(")",I.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)),m=p.length>0?p.reduce((S,P)=>S+P,0):null,g=Number(e.context_window?.total_input_tokens??m??d?.input_tokens??0),h=u!==null?Math.max(0,Math.min(1,u/100)):l>0?Math.max(0,Math.min(1,g/l)):0,w=u!==null&&l>0?Math.round(h*l):g,$;if(l>0||u!==null){let S=`${String(Math.round(h*100)).padStart(2," ")}%`,P=l>0?` ${O(`(${Hr(w)}/${Hr(l)})`,I.muted)}`:"";$=`${O("Context",I.muted)} ${Br(h)} ${O(S,I.green)}${P}`}else $=`${O("Context",I.muted)} ${O("-",I.muted)}`;let k=Hl(e.rate_limits),v=[$];return k&&v.push(k),{identity:a.join(t),metrics:v.join(t)}}function Lg(e){let t=` ${O("\u2502",I.chrome)} `,n=Ql(e),r=n.model||"codex",o=[O(`[${r}]`,I.visaBlueSoft)];n.project&&o.push(O(n.project,I.visaGold)),n.gitBranch&&o.push(`${O("git",I.muted)} ${O(n.gitBranch,I.visaGold)}`);let s=o.join(t),i=[];if(typeof n.contextUsedPercent=="number"){let c=Math.max(0,Math.min(1,n.contextUsedPercent/100));i.push(`${O("Context",I.muted)} ${Br(c)} ${O(`${Math.round(n.contextUsedPercent)}%`,I.green)}`)}else if(typeof n.contextRemainingPercent=="number"){let c=100-n.contextRemainingPercent,l=Math.max(0,Math.min(1,c/100));i.push(`${O("Context",I.muted)} ${Br(l)} ${O(`${Math.round(c)}%`,I.green)}`)}typeof n.usedTokens=="number"&&i.push(`${O("Tokens",I.muted)} ${Hr(n.usedTokens)}`),n.status&&i.push(`${O("Status",I.muted)} ${O(n.status,I.visaBlueSoft)}`),n.threadTitle&&i.push(`${O("Thread",I.muted)} ${O(n.threadTitle,I.visaBlueSoft)}`);let a=i.length>0?i.join(t):`${O("Context",I.muted)} ${O("-",I.muted)}`;return`${s}
111
+ ${a}`}function Ug(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),o=Math.floor(r/60),s=r%60;return o>0?`${o}h ${s}m`:`${s}m`}function jl(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,o=Br(r),s=n>=90?"\x1B[38;5;196m":n>=70?I.visaGold:I.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=Ug(e.resets_at),c=a?` ${O(`(${a} / ${t})`,I.muted)}`:` ${O(`(${t})`,I.muted)}`;return`${o} ${O(i,s)}${c}`}function Hl(e){if(!e)return null;let t=jl(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?jl(e.seven_day,"7d"):null;if(!t&&!r)return null;let o=` ${O("\u2502",I.chrome)} `,s=[t,r].filter(Boolean);return`${O("Usage",I.muted)} ${s.join(o)}`}function ql(e){let t;try{let n=vt.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let o=Math.min(r,Og),s=r-o;t=vt.openSync(e,"r");let i=Buffer.alloc(o);vt.readSync(t,i,0,o,s);let a=i.toString("utf-8");if(s>0){let c=Buffer.alloc(1);if(vt.readSync(t,c,0,1,s-1),c[0]!==10){let l=a.indexOf(`
112
+ `);l>=0&&(a=a.slice(l+1))}}return a}catch{return null}finally{if(t!==void 0)try{vt.closeSync(t)}catch{}}}function Dg(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 o=t[r];if(typeof o=="string"&&o.length>0){if(r.endsWith("_path")||r==="path"){let s=nt.basename(nt.dirname(o)),i=nt.basename(o);return s&&s!=="."&&s!=="/"?`${s}/${i}`:i}return o}}}function jg(e){let t=e.split(`
113
+ `),n=[],r=new Set;for(let o=t.length-1;o>=0&&n.length<Ul*3;o-=1){let s=t[o].trim();if(!s)continue;let i;try{i=JSON.parse(s)}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:"",m=p.length>0?!r.has(p):!1;n.push({name:d.name,target:Dg(d.input),running:m})}}}return n.reverse(),n.slice(Math.max(0,n.length-Ul))}function Fg(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 Vg(e){let t=e.running?O("\u25D0",I.visaGold):O("\u2713",I.green),n=e.running?I.visaGold:I.visaBlueSoft,r=O(ce(e.name),n),o=e.target?ce(e.target):"",s=o?`${O(":",I.chrome)} ${O(o,I.muted)}`:"",i=e.count>1?` ${O(`\xD7${e.count}`,I.muted)}`:"";return s?`${t} ${r}${s}${i}`:`${t} ${r}${i}`}function Bg(e){let t=` ${O("\u2502",I.chrome)} `,n=Dl(t),r=e.slice();for(;r.length>0;){let c=r.join(t);if(Dl(c)<=Li)return c;r=r.slice(1)}if(e.length===0)return"";let o="\u2026",i=e[e.length-1].replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,""),a=i.length>Li-n-1?i.slice(0,Li-n-1)+o:i;return`${O(o,I.muted)}${t}${a}`}async function Fl(e){if(!e||typeof e!="string")return null;let t=ql(e);if(!t)return null;let n;try{n=jg(t)}catch{return null}if(n.length===0)return null;let o=Fg(n).map(Vg);return Bg(o)||null}async function Kl(e,t,n){return(await Wl(e,t,n)).join(`
114
+ `)}function Gl(e,t,n){let r=!!t?.activeSession||e.includes("in session"),o=n?qg(n):!1;return{isActive:r||o,hasSession:r,hasToolActivity:o}}async function Wl(e,t,n){let{isActive:r}=Gl(e,n,t?.transcript_path),o=e.split(`
115
+ `).filter(a=>a.length>0),i=t&&!r?o.map(a=>O(Ui(a),I.muted)):[...o];if(t){let a=Ng(t);if(a){if(i.push(a.identity),t.transcript_path){let c=await Fl(t.transcript_path);c&&i.push(...c.split(`
116
+ `))}i.push(a.metrics)}else{let c=Mg(t);if(c&&i.push(...c.split(`
117
+ `)),t.transcript_path){let l=await Fl(t.transcript_path);l&&i.push(...l.split(`
118
+ `))}}}return i}var Hg=["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 qg(e){let t=ql(e);if(!t)return!1;let n=t.slice(-16384).toLowerCase();return Hg.some(r=>n.includes(`"${r}"`))}async function zl(e,t,n){let r=await Wl(e,t,n),o=r.join(`
119
+ `),{isActive:s}=Gl(e,n,t?.transcript_path);return{schemaVersion:Ig,client:t?Xl(t):gn.UNKNOWN,rendered:o,lines:r.map(Ui),visa:{spendLine:Ui(e),balanceCents:n?.balanceCents,balanceMicros:n?.balanceMicros,balanceUsd:n?.amountUsd,sessionMode:n?.sessionMode,activeSession:n?.activeSession,isVisaActive:s},context:t?Ql(t):{}}}function ce(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 Xo(e){if(typeof e=="string")return ce(nt.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 ce(t?nt.basename(t):e.name)}function Jl(e){return ce(e.app_name??e.appName??e.app??e.client)}function Jo(e){return ce(e.model?.display_name??e.model?.id??e.model_name??e.modelName)}function Yl(e){return ce(e.cwd??e.current_dir??e.project_root)}function Vl(e){let t=ce(e.project);if(t)return t;let n=Yl(e);if(n)return ce(nt.basename(n));let r=Xo(e.workspace);return r||""}function qe(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function Xl(e){let t=Jl(e).toLowerCase();return t.includes("codex")?gn.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?gn.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||qe(e.context_used)!==void 0?gn.CODEX:gn.UNKNOWN}function Zl(e){return Xl(e)===gn.CODEX}function Ql(e){let t=Jl(e),n=Yl(e),r=Xo(e.workspace),o=qe(e.context_used)??qe(e.context_window?.used_percentage??void 0),s=qe(e.context_remaining)??qe(e.context_window?.remaining_percentage??void 0);return{...t?{app:t}:{},...Jo(e)?{model:Jo(e)}:{},...Vl(e)?{project:Vl(e)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...ce(e.git_branch??e.branch)?{gitBranch:ce(e.git_branch??e.branch)}:{},...ce(e.status??e.run_state??e.runState)?{status:ce(e.status??e.run_state??e.runState)}:{},...ce(e.thread_title??e.threadTitle)?{threadTitle:ce(e.thread_title??e.threadTitle)}:{},...o!==void 0?{contextUsedPercent:o}:{},...s!==void 0?{contextRemainingPercent:s}:{},...qe(e.used_tokens)!==void 0?{usedTokens:qe(e.used_tokens)}:{},...qe(e.total_input_tokens)!==void 0?{totalInputTokens:qe(e.total_input_tokens)}:{},...qe(e.total_output_tokens)!==void 0?{totalOutputTokens:qe(e.total_output_tokens)}:{}}}function Ui(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}var tu=E(require("path"));function eu(e){return e instanceof Error?e.message:String(e)}function Di(e,t){let n=[],r=[],o=e??"claude",s=Yo(o);if(o==="shell"||o==="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: ${eu(a)}`]}}if(!s)return{ok:!1,messages:n,errors:[`Unknown HUD surface: ${o}`,"Supported: claude (default), shell, all"]};let i=!0;if(s==="claude"||s==="claude-code"||s==="all"){let a=tu.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: ${eu(c)}`)}}return{ok:i,messages:n,errors:r}}function nu(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 ru=E(require("os")),ou=require("node:readline/promises"),qr={card:"default VISA ****7242",balance:"balance $6.38",spentToday:"spent today $0.62",lastActivity:"last Visa tool 38m",model:"Opus 4.6"};async function ji(e,t=!1){if(!process.stdin.isTTY)return t;let n=t?"[Y/n]":"[y/N]",r,o;try{r=(0,ou.createInterface)({input:process.stdin,output:process.stdout});let s=new AbortController;o=()=>s.abort(),r.once("close",o);let i=(await r.question(`${e} ${n} `,{signal:s.signal})).trim();return i?/^y(es)?$/i.test(i):t}catch{return t}finally{r&&o&&r.off("close",o),r?.close()}}function Kg(e,t){return e.replace(/[\x00-\x1F\x7F\u202A-\u202E\u2066-\u2069]/g,"").trim()||t}function su(e=ru.hostname()){let t=Rr().version,n=Kg(e,"this-machine");return[" Preview if installed (sample):",` VISA CLI v${t} | ${n} | ${qr.card}`,` ${qr.balance} | ${qr.spentToday} | ${qr.lastActivity}`,` [${qr.model}] | you`," Activity live"].join(`
120
+ `)}function iu(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 Fi(e){return`$${(e/100).toFixed(2)}`}function au(e){return typeof e=="number"?Fi(e):"no cap"}function cu(e){return e.length>0?e.join(", "):"all tools"}var Gg=[" \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 Wg(){return[...iu(null),...Gg].join(`
121
+ `)}var lu="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 zg(e){let t=Math.max(5,...e.map(([s])=>s.length)),n=Math.max(5,...e.map(([,s])=>s.length)),r=`+-${"-".repeat(t)}-+-${"-".repeat(n)}-+`,o=(s,i)=>`| ${s.padEnd(t)} | ${i.padEnd(n)} |`;return[r,o("Field","Value"),r,...e.map(([s,i])=>o(s,i)),r]}function uu(e,t={}){let n=t.authUrl??"https://auth.visacli.sh",r=[...Wg().split(`
122
+ `),"","Visa Key active","Scoped agent spend credential ready for apps and agents","",...zg([["Key",e.key],["Label",e.label],["Owner",e.owner],["Daily cap",`${Fi(e.daily_cap_cents)}/day`],["Total cap",au(e.total_cap_cents)],["Allowed tools",cu(e.allowed_tools)]]),"","Guardrails",`- Spend: ${Fi(e.daily_cap_cents)}/day, ${au(e.total_cap_cents)} total`,`- Tools: ${cu(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("",lu,`Server warning: ${e.biometric_warning}`):e.biometric_enabled&&r.push("",lu),`${r.join(`
123
123
  `)}
124
- `}function wl(e){return e.json===!0||e.isTTY!==!0}function mi(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 pi(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 Sl(e,t){let n=mi(e);if(n!==void 0)return n;if(wl(t))return 500}function xl(e,t){let n=pi(e);if(n!==void 0)return n;if(wl(t)||t.recommendedCapsAccepted===!0)return 2500}async function Ze(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,o=setTimeout(()=>r.abort(),n);try{let{timeoutMs:s,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(o)}}var an=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},Fn=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}},gt=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}},Qe=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}},oe=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(t,n,r,o,s,i,a,c){super(t),this.name="CardDeclinedError",this.retryable=n,this.code=r,this.reason=o,this.paymentErrorClass=s,this.correlationId=i,this.transactionId=a,this.retryAfter=c}},et=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 kl={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 Vn(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&&kl[n]?kl[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.`}var xe=T(require("fs")),hi=T(require("path")),Cl=T(require("os")),gi=hi.join(Cl.homedir(),".visa-mcp"),Er=hi.join(gi,"mcp-server.log"),kf=5*1024*1024,fi=null;function Cf(){xe.existsSync(gi)||xe.mkdirSync(gi,{recursive:!0,mode:448})}function Tf(){if(!fi){if(Cf(),xe.existsSync(Er)&&xe.statSync(Er).size>kf){let t=Er+".1";xe.existsSync(t)&&xe.unlinkSync(t),xe.renameSync(Er,t)}fi=xe.createWriteStream(Er,{flags:"a"})}return fi}function Ef(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function Oo(e,...t){let n=new Date().toISOString(),r=t.map(s=>typeof s=="string"?s:JSON.stringify(s,null,2)).join(" "),o=`[${n}] [${e}] ${r}
125
- `;Ef(e)&&process.stderr.write(o),Tf().write(o)}var f={debug:(...e)=>Oo("DEBUG",...e),info:(...e)=>Oo("INFO",...e),warn:(...e)=>Oo("WARN",...e),error:(...e)=>Oo("ERROR",...e)};var Af=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function El(e,t){let n=Tl(e),r=Tl(t);if(!n||!r)return!1;for(let o=0;o<3;o++)if(n.main[o]!==r.main[o])return n.main[o]>r.main[o];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:Rf(n.pre,r.pre)>0}function Tl(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(Af);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function Rf(e,t){let n=e.split("."),r=t.split("."),o=Math.max(n.length,r.length);for(let s=0;s<o;s++){if(s>=n.length)return-1;if(s>=r.length)return 1;let i=n[s],a=r[s],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 tt(){return!!(Al(process.env.VISA_CLI_NO_UPDATE_CHECK)||Al(process.env.CI)||process.env.NODE_ENV==="test")}function Al(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var Ut=T(require("fs")),vi=require("node:net"),Pl=T(require("os")),Ol=T(require("path"));var Mo=T(require("fs")),Rl=T(require("path")),Il=T(require("os"));var yi=Rl.join(Il.homedir(),".visa-mcp"),Ar=class{static ensureConfigDir(){Mo.existsSync(yi)||Mo.mkdirSync(yi,{recursive:!0,mode:448})}static getConfigDir(){return yi}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 $l(e){let t=Pl.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}var If="settings.json",$f="must use https unless it points at localhost/loopback for local development";function Rr(){return Ol.join(Ar.getConfigDir(),If)}function Ml(e){if((0,vi.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function Pf(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 o=[n>>8&255,n&255,r>>8&255,r&255].join(".");return Ml(o)}function Of(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,vi.isIP)(t);return n===4?Ml(t):n===6?t==="::1"||Pf(t):!1}function _i(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:"&&Of(n.hostname)))throw new Error(`${t} ${$f}`)}var Dt={"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");_i(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(o=>o.trim()).filter(Boolean);for(let o of r)if(!n.test(o))throw new Error(`merchants.discover: "${o}" 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)")}}},wi=500,No={"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."};function cn(){let e=Rr();if(!Ut.existsSync(e))return{};try{let t=Ut.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?(f.warn("settings:corrupt",{path:$l(e),reason:"not_object"}),{}):n}catch(t){return f.warn("settings:corrupt",{path:$l(e),error:t?.message||String(t)}),{}}}function bi(e){Ar.ensureConfigDir();let t=Rr(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
126
- `;Ut.writeFileSync(n,r,{mode:384}),Ut.renameSync(n,t)}function Si(e){let t=cn()[e];return typeof t=="string"?t:void 0}function Lo(e){let t=cn()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function xi(e){let t=cn()[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}}var ht=class extends Error{constructor(t){let n=Object.keys(Dt).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"}},yt=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"}},Lt=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+No[t]),this.name="RetiredSettingKeyError"}},Nl=["biometric.","spending.","account.","cards.","biometric"];function Uo(e,t){if(Nl.some(s=>e.startsWith(s)))throw new yt(e);if(e in No)throw new Lt(e);let n=Dt[e];if(!n)throw new ht(e);let r;if(n.type==="boolean")if(typeof t=="boolean")r=t;else if(typeof t=="string"){let s=t.toLowerCase();if(s==="true")r=!0;else if(s==="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 s=Number(t);if(!Number.isFinite(s))throw new Error(`${e} expects a number (got: ${JSON.stringify(t)})`);r=s}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 o=cn();return o[e]=r,bi(o),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:Rr()}}function Do(e){if(Nl.some(s=>e.startsWith(s)))throw new yt(e);let t=Dt[e];if(e in No){let s=cn(),i=e in s;return i&&(delete s[e],bi(s)),{key:e,removed:i,requiresRestart:!1,path:Rr()}}if(!t)throw new ht(e);let r=cn(),o=e in r;return o&&(delete r[e],bi(r)),{key:e,removed:o,requiresRestart:o&&!!t.requiresRestart,path:Rr()}}function Ll(){let e=cn();return Object.entries(No).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}var Mf="https://auth.visacli.sh",Nf="https://auth-visa-code-preview.up.railway.app";function Lf(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function Uf(){try{let e=dr();return Lf(e.version)}catch{return!1}}function Df(e){return e.envVar!==void 0&&e.envVar!==""?(_i(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(_i(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?Nf:Mf}function Ee(){return Df({envVar:process.env.VISA_AUTH_URL,settingValue:Si("auth.serverUrl"),isPrerelease:Uf()})}function Ul(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":Lo("ui.suppressBrowser")??!1}function Dl(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":Lo("ui.suppressFeed")??!1}function jl(){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=xi("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):wi}var jf="CARD_REENROLLMENT_REQUIRED",Ff="https://auth.visacli.sh/enroll-card";function Vf(){try{return new URL("/enroll-card",Ee()).toString()}catch{return Ff}}function qf(e){let t=Vf();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 f.warn("card-reenroll:reenroll_url_rejected_fallback",{reason:"untrusted_or_malformed_reenroll_url",fallbackPath:"/enroll-card"}),t}var jt="3.0.0",Bf=/^(?:VisaKey_[A-Za-z0-9_-]{16,128}|visakey_[A-Za-z0-9_-]{16,128}|vk_[A-Za-z0-9_-]{32,128})$/;function Hf(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 ki(e){return e==="TOPUP_CHARGE_AMBIGUOUS"||e==="TOPUP_RECONCILIATION_REQUIRED"?e:null}var Kf="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function qn(e){return typeof e=="string"?e.trim():""}function Ir(e){let t=e&&typeof e=="object"?e:{},n=qn(t.error)||qn(t.message);if(!n)return Kf;let r=qn(t.error_code),o=[["surface",qn(t.disabled_surface)],["flag",qn(t.flag)],["correlation_id",qn(t.correlation_id)]].filter(([,i])=>i).map(([i,a])=>`${i}=${a}`),s=o.length?` (${o.join(" ")})`:"";return r?`503 [${r}] ${n}${s}`:`503 ${n}${s}`}function $r(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?Bf.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(`
127
- `)}var Ae=class{constructor(t){this.getSessionToken=t;this.baseUrl=Ee()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!tt()){let r=t.headers.get("X-Latest-Version");r&&El(r,jt)&&(this.lastSignals.updateAvailable={currentVersion:jt,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return jt}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new an(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(Ir(n))}async request(t,n,r,o,s,i){let a=await this.getSessionToken();if(!a)throw new Error($r());let c={Authorization:`Bearer ${a}`};s&&(t==="GET"?c["X-User-Context"]=encodeURIComponent(s.replace(/[\r\n\0]/g," ").slice(0,1e3)):r={...r||{},user_context:s}),i&&(c["X-Visa-Meta-Tool"]=i),r&&(c["Content-Type"]="application/json");let l;try{l=await Ze(`${this.baseUrl}${n}`,{method:t,headers:{...c,"X-Visa-CLI-Version":jt,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:o})}catch(d){throw new Error(Vn(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===jf){let p=typeof u?.last4=="string"?u.last4:"",m=typeof u?.brand=="string"?u.brand:"card",g=qf(u?.reenroll_url),y=p?`${m} ending in ${p}`:"your card";throw new Error(`Please re-add ${y} to keep payments running. Open: ${g}`)}let d=ki(u?.error_code);if(d)throw new et(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 oe(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",m=typeof u?.error_code=="string"?u.error_code:"";throw m==="SPENDING_LIMIT_EXCEEDED"||m==="DAILY_LIMIT_EXCEEDED"||m==="PER_TXN_LIMIT_EXCEEDED"?new Error(`${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,o,s){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,o,s)}async shortcutWithSession(t,n,r,o,s,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error($r());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":jt,"X-Source":"cli","Content-Type":"application/json"};i&&(l["X-Visa-Meta-Tool"]=i);let u={...n,...r};s&&(u.user_context=s.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await Ze(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:o})}catch(g){throw new Error(Vn(g))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let g=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${g}s. Tip: use the batch tool to combine multiple requests into one.`)}let p=d.headers.get("X-Voucher-Receipt"),m;try{m=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(m),d.status===503){if(m?.error_code==="SESSION_LOCK_CONTENDED"){let w=Number(d.headers.get("Retry-After"))||1;throw new gt(m?.message||m?.error||"Session budget is being modified by another request. Retry shortly.",w,d.status)}throw new Error(Ir(m))}let g=Hf(m?.error_code);if(g||d.status===410){let w=g??"BUDGET_CLOSED";throw new Fn(m?.message||m?.error||"Your session was invalidated by the server.",w,{budgetId:n.session_budget_id,status:d.status})}if(m?.declined){let w=Number(m.retryAfter??d.headers.get("Retry-After"));throw new oe(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite(w)&&w>0?w:void 0)}let y=ki(m?.error_code);throw y?new et(m?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",y,{transactionId:typeof m?.transactionId=="string"?m.transactionId:void 0,retryable:!!m?.retryable,reconciliationRequired:m?.reconciliation_required!==!1}):new Error(m?.error||`Request failed (${d.status}). Try again.`)}return{data:m,voucherReceiptHeader:p}}async shortcutParentless(t,n,r,o,s,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error($r());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":jt,"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}:{}};s&&(u.user_context=s.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await Ze(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:o})}catch(g){throw new Error(Vn(g))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let g=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${g}s. Tip: use the batch tool to combine multiple requests into one.`)}let p=d.headers.get("X-Voucher-Receipt"),m;try{m=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):d.status===404?new Qe("Parentless single-call is not available on this server.",{status:404}):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);this.throwIfAttestationDrift(m);let g=typeof m?.error_code=="string"?m.error_code:void 0;if(d.status===404||d.status===410&&g==="DIRECT_SHORTCUT_CARD_SURFACE_RETIRED")throw new Qe(m?.error||"Parentless single-call is not enabled on this server.",{status:d.status,serverErrorCode:g});if(d.status===503){if(m?.error_code==="SESSION_LOCK_CONTENDED"){let w=Number(d.headers.get("Retry-After"))||1;throw new gt(m?.message||m?.error||"Session budget is being modified by another request. Retry shortly.",w,d.status)}throw new Error(Ir(m))}if(m?.declined){let w=Number(m.retryAfter??d.headers.get("Retry-After"));throw new oe(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite(w)&&w>0?w:void 0)}let y=ki(m?.error_code);throw y?new et(m?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",y,{transactionId:typeof m?.transactionId=="string"?m.transactionId:void 0,retryable:!!m?.retryable,reconciliationRequired:m?.reconciliation_required!==!1}):new Error(m?.error||`Request failed (${d.status}). Try again.`)}return{data:m,voucherReceiptHeader:p}}async batchOpen(t){let n="/v1/batch/open",r=await this.getSessionToken();if(!r)throw new Error($r());let o={Authorization:`Bearer ${r}`,"X-Visa-CLI-Version":jt,"X-Source":"cli","Content-Type":"application/json"},s={...t.attestation?{attestation:t.attestation}:{},nonce:t.nonce,approved_total_cents:t.approved_total_cents,batch_id:t.batch_id},i;try{i=await Ze(`${this.baseUrl}${n}`,{method:"POST",headers:o,body:JSON.stringify(s),timeoutMs:void 0})}catch(u){throw new Error(Vn(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 Qe("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===404||i.status===410&&u==="DIRECT_SHORTCUT_CARD_SURFACE_RETIRED")throw new Qe(a?.error||"Parentless batch is not enabled on this server.",{status:i.status,serverErrorCode:u});if(i.status===503)throw new Error(Ir(a));if(a?.declined){let d=Number(a.retryAfter??i.headers.get("Retry-After"));throw new oe(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,o,s,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error($r());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":jt,"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}:{}};s&&(u.user_context=s.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await Ze(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:o})}catch(g){throw new Error(Vn(g))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let g=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${g}s. Tip: use the batch tool to combine multiple requests into one.`)}let p=d.headers.get("X-Voucher-Receipt"),m;try{m=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(m),d.status===503){if(m?.error_code==="SESSION_LOCK_CONTENDED"){let g=Number(d.headers.get("Retry-After"))||1;throw new gt(m?.message||m?.error||"Batch parent is being modified by another request. Retry shortly.",g,d.status)}throw new Error(Ir(m))}if(m?.declined){let g=Number(m.retryAfter??d.headers.get("Retry-After"));throw new oe(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite(g)&&g>0?g:void 0)}throw new Error(m?.error||`Request failed (${d.status}). Try again.`)}return{data:m,voucherReceiptHeader:p}}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async catalogSearch(t,n,r,o){let s=r??"discover_tools",i=new URLSearchParams;t&&i.set("q",t),n&&i.set("category",n),o?.limit!=null&&i.set("limit",String(o.limit)),o?.offset!=null&&i.set("offset",String(o.offset));let a=i.toString();return this.request("GET",`/v1/catalog${a?`?${a}`:""}`,void 0,void 0,void 0,s)}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 Ze(`${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 Ze(`${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 o=r.toString(),s=o?`/v1/transactions?${o}`:"/v1/transactions";return this.request("GET",s,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 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,o=null,s=0;for(;;){let i=await this.listAppApiKeys({limit:100,...r!==void 0?{startingAfter:r}:{}});if(s+=1,o=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{...o??{success:!0,keys:[]},keys:t,limit:100,has_more:!1,next_cursor:null,previous_cursor:null,pages:s}}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 o=r.toString();return this.request("GET",`/v1/feedback${o?"?"+o:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}};function Pr(e,t){return t||(typeof e!="number"||!Number.isFinite(e)?"price unknown":`$${(e/100).toFixed(2)}`)}function Vl(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 Fl(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function Gf(e){let t=new Map;for(let n of e){let r=n.category||"other",o=t.get(r)??[];o.push(n),t.set(r,o)}return new Map([...t.entries()].sort(([n],[r])=>n.localeCompare(r)))}function Wf(e){return Math.max(4,e.reduce((t,n)=>Math.max(t,n.id.length),0))}function zf(e){return Math.max(8,Math.min(14,e.reduce((t,n)=>Math.max(t,(n.category||"").length),0)))}function Jf(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 ql(e){let t=Wf(e),n=7,r=zf(e),o=Jf(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(o,32))}`);for(let s of e)console.log(` ${s.id.padEnd(t)} ${Pr(s.priceCents,s.priceDisplay).padEnd(n)} ${Fl(s.category||"other",r).padEnd(r)} ${Fl(Vl(s),o)}`)}function Bl(e){console.log(`
124
+ `}function du(e){return e.json===!0||e.isTTY!==!0}function Vi(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 Bi(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 mu(e,t){let n=Vi(e);if(n!==void 0)return n;if(du(t))return 500}function pu(e,t){let n=Bi(e);if(n!==void 0)return n;if(du(t)||t.recommendedCapsAccepted===!0)return 2500}async function rt(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,o=setTimeout(()=>r.abort(),n);try{let{timeoutMs:s,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(o)}}var hn=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},Qn=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}},wt=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}},ot=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}},le=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(t,n,r,o,s,i,a,c){super(t),this.name="CardDeclinedError",this.retryable=n,this.code=r,this.reason=o,this.paymentErrorClass=s,this.correlationId=i,this.transactionId=a,this.retryAfter=c}},st=class extends Error{code;transactionId;retryable;reconciliationRequired;constructor(t,n,r={}){super(t),this.name="TopupAmbiguousError",this.code=n,this.transactionId=r.transactionId,this.retryable=r.retryable??!1,this.reconciliationRequired=r.reconciliationRequired??!0}};var fu={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 er(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&&fu[n]?fu[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.`}var Ee=E(require("fs")),Ki=E(require("path")),gu=E(require("os")),qi=Ki.join(gu.homedir(),".visa-mcp"),Kr=Ki.join(qi,"mcp-server.log"),Jg=5*1024*1024,Hi=null;function Yg(){Ee.existsSync(qi)||Ee.mkdirSync(qi,{recursive:!0,mode:448})}function Xg(){if(!Hi){if(Yg(),Ee.existsSync(Kr)&&Ee.statSync(Kr).size>Jg){let t=Kr+".1";Ee.existsSync(t)&&Ee.unlinkSync(t),Ee.renameSync(Kr,t)}Hi=Ee.createWriteStream(Kr,{flags:"a"})}return Hi}function Zg(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function Zo(e,...t){let n=new Date().toISOString(),r=t.map(s=>typeof s=="string"?s:JSON.stringify(s,null,2)).join(" "),o=`[${n}] [${e}] ${r}
125
+ `;Zg(e)&&process.stderr.write(o),Xg().write(o)}var f={debug:(...e)=>Zo("DEBUG",...e),info:(...e)=>Zo("INFO",...e),warn:(...e)=>Zo("WARN",...e),error:(...e)=>Zo("ERROR",...e)};var Qg=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function yu(e,t){let n=hu(e),r=hu(t);if(!n||!r)return!1;for(let o=0;o<3;o++)if(n.main[o]!==r.main[o])return n.main[o]>r.main[o];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:eh(n.pre,r.pre)>0}function hu(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(Qg);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function eh(e,t){let n=e.split("."),r=t.split("."),o=Math.max(n.length,r.length);for(let s=0;s<o;s++){if(s>=n.length)return-1;if(s>=r.length)return 1;let i=n[s],a=r[s],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 it(){return!!(_u(process.env.VISA_CLI_NO_UPDATE_CHECK)||_u(process.env.CI)||process.env.NODE_ENV==="test")}function _u(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var Kt=E(require("fs")),Ji=require("node:net"),Su=E(require("os")),xu=E(require("path"));var Qo=E(require("fs")),bu=E(require("path")),vu=E(require("os"));var Gi=bu.join(vu.homedir(),".visa-mcp"),Gr=class{static ensureConfigDir(){Qo.existsSync(Gi)||Qo.mkdirSync(Gi,{recursive:!0,mode:448})}static getConfigDir(){return Gi}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 wu(e){let t=Su.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}var th="settings.json",nh="must use https unless it points at localhost/loopback for local development";function Wr(){return xu.join(Gr.getConfigDir(),th)}function Tu(e){if((0,Ji.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function rh(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 o=[n>>8&255,n&255,r>>8&255,r&255].join(".");return Tu(o)}function oh(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,Ji.isIP)(t);return n===4?Tu(t):n===6?t==="::1"||rh(t):!1}function Wi(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:"&&oh(n.hostname)))throw new Error(`${t} ${nh}`)}var Gt={"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");Wi(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(o=>o.trim()).filter(Boolean);for(let o of r)if(!n.test(o))throw new Error(`merchants.discover: "${o}" 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)")}}},Yi=500,es={"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."};function yn(){let e=Wr();if(!Kt.existsSync(e))return{};try{let t=Kt.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?(f.warn("settings:corrupt",{path:wu(e),reason:"not_object"}),{}):n}catch(t){return f.warn("settings:corrupt",{path:wu(e),error:t?.message||String(t)}),{}}}function zi(e){Gr.ensureConfigDir();let t=Wr(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
126
+ `;Kt.writeFileSync(n,r,{mode:384}),Kt.renameSync(n,t)}function Xi(e){let t=yn()[e];return typeof t=="string"?t:void 0}function ts(e){let t=yn()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function Zi(e){let t=yn()[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}}var St=class extends Error{constructor(t){let n=Object.keys(Gt).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"}},xt=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"}},qt=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+es[t]),this.name="RetiredSettingKeyError"}},Cu=["biometric.","spending.","account.","cards.","biometric"];function ns(e,t){if(Cu.some(s=>e.startsWith(s)))throw new xt(e);if(e in es)throw new qt(e);let n=Gt[e];if(!n)throw new St(e);let r;if(n.type==="boolean")if(typeof t=="boolean")r=t;else if(typeof t=="string"){let s=t.toLowerCase();if(s==="true")r=!0;else if(s==="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 s=Number(t);if(!Number.isFinite(s))throw new Error(`${e} expects a number (got: ${JSON.stringify(t)})`);r=s}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 o=yn();return o[e]=r,zi(o),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:Wr()}}function rs(e){if(Cu.some(s=>e.startsWith(s)))throw new xt(e);let t=Gt[e];if(e in es){let s=yn(),i=e in s;return i&&(delete s[e],zi(s)),{key:e,removed:i,requiresRestart:!1,path:Wr()}}if(!t)throw new St(e);let r=yn(),o=e in r;return o&&(delete r[e],zi(r)),{key:e,removed:o,requiresRestart:o&&!!t.requiresRestart,path:Wr()}}function ku(){let e=yn();return Object.entries(es).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}var sh="https://auth.visacli.sh",ih="https://auth-visa-code-preview.up.railway.app";function ah(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function ch(){try{let e=Rr();return ah(e.version)}catch{return!1}}function lh(e){return e.envVar!==void 0&&e.envVar!==""?(Wi(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(Wi(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?ih:sh}function $e(){return lh({envVar:process.env.VISA_AUTH_URL,settingValue:Xi("auth.serverUrl"),isPrerelease:ch()})}function Eu(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":ts("ui.suppressBrowser")??!1}function Au(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":ts("ui.suppressFeed")??!1}function Ru(){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=Zi("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):Yi}var uh="CARD_REENROLLMENT_REQUIRED",dh="https://auth.visacli.sh/enroll-card";function mh(){try{return new URL("/enroll-card",$e()).toString()}catch{return dh}}function ph(e){let t=mh();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 f.warn("card-reenroll:reenroll_url_rejected_fallback",{reason:"untrusted_or_malformed_reenroll_url",fallbackPath:"/enroll-card"}),t}var Wt="3.0.1",fh=/^(?:VisaKey_[A-Za-z0-9_-]{16,128}|visakey_[A-Za-z0-9_-]{16,128}|vk_[A-Za-z0-9_-]{32,128})$/;function gh(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 Qi(e){return e==="TOPUP_CHARGE_AMBIGUOUS"||e==="TOPUP_RECONCILIATION_REQUIRED"?e:null}var hh="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function tr(e){return typeof e=="string"?e.trim():""}function zr(e){let t=e&&typeof e=="object"?e:{},n=tr(t.error)||tr(t.message);if(!n)return hh;let r=tr(t.error_code),o=[["surface",tr(t.disabled_surface)],["flag",tr(t.flag)],["correlation_id",tr(t.correlation_id)]].filter(([,i])=>i).map(([i,a])=>`${i}=${a}`),s=o.length?` (${o.join(" ")})`:"";return r?`503 [${r}] ${n}${s}`:`503 ${n}${s}`}function Jr(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?fh.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(`
127
+ `)}var Pe=class{constructor(t){this.getSessionToken=t;this.baseUrl=$e()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!it()){let r=t.headers.get("X-Latest-Version");r&&yu(r,Wt)&&(this.lastSignals.updateAvailable={currentVersion:Wt,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return Wt}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new hn(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(zr(n))}async request(t,n,r,o,s,i){let a=await this.getSessionToken();if(!a)throw new Error(Jr());let c={Authorization:`Bearer ${a}`};s&&(t==="GET"?c["X-User-Context"]=encodeURIComponent(s.replace(/[\r\n\0]/g," ").slice(0,1e3)):r={...r||{},user_context:s}),i&&(c["X-Visa-Meta-Tool"]=i),r&&(c["Content-Type"]="application/json");let l;try{l=await rt(`${this.baseUrl}${n}`,{method:t,headers:{...c,"X-Visa-CLI-Version":Wt,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:o})}catch(d){throw new Error(er(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===uh){let p=typeof u?.last4=="string"?u.last4:"",m=typeof u?.brand=="string"?u.brand:"card",g=ph(u?.reenroll_url),h=p?`${m} ending in ${p}`:"your card";throw new Error(`Please re-add ${h} to keep payments running. Open: ${g}`)}let d=Qi(u?.error_code);if(d)throw new st(u?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",d,{transactionId:typeof u?.transactionId=="string"?u.transactionId:void 0,retryable:!!u?.retryable,reconciliationRequired:u?.reconciliation_required!==!1});if(u?.declined){let p=Number(u.retryAfter??l.headers.get("Retry-After"));throw new le(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",m=typeof u?.error_code=="string"?u.error_code:"";throw m==="SPENDING_LIMIT_EXCEEDED"||m==="DAILY_LIMIT_EXCEEDED"||m==="PER_TXN_LIMIT_EXCEEDED"?new Error(`${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,o,s){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,o,s)}async shortcutWithSession(t,n,r,o,s,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error(Jr());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":Wt,"X-Source":"cli","Content-Type":"application/json"};i&&(l["X-Visa-Meta-Tool"]=i);let u={...n,...r};s&&(u.user_context=s.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await rt(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:o})}catch(g){throw new Error(er(g))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let g=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${g}s. Tip: use the batch tool to combine multiple requests into one.`)}let p=d.headers.get("X-Voucher-Receipt"),m;try{m=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(m),d.status===503){if(m?.error_code==="SESSION_LOCK_CONTENDED"){let w=Number(d.headers.get("Retry-After"))||1;throw new wt(m?.message||m?.error||"Session budget is being modified by another request. Retry shortly.",w,d.status)}throw new Error(zr(m))}let g=gh(m?.error_code);if(g||d.status===410){let w=g??"BUDGET_CLOSED";throw new Qn(m?.message||m?.error||"Your session was invalidated by the server.",w,{budgetId:n.session_budget_id,status:d.status})}if(m?.declined){let w=Number(m.retryAfter??d.headers.get("Retry-After"));throw new le(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite(w)&&w>0?w:void 0)}let h=Qi(m?.error_code);throw h?new st(m?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",h,{transactionId:typeof m?.transactionId=="string"?m.transactionId:void 0,retryable:!!m?.retryable,reconciliationRequired:m?.reconciliation_required!==!1}):new Error(m?.error||`Request failed (${d.status}). Try again.`)}return{data:m,voucherReceiptHeader:p}}async shortcutParentless(t,n,r,o,s,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error(Jr());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":Wt,"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}:{}};s&&(u.user_context=s.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await rt(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:o})}catch(g){throw new Error(er(g))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let g=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${g}s. Tip: use the batch tool to combine multiple requests into one.`)}let p=d.headers.get("X-Voucher-Receipt"),m;try{m=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):d.status===404?new ot("Parentless single-call is not available on this server.",{status:404}):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);this.throwIfAttestationDrift(m);let g=typeof m?.error_code=="string"?m.error_code:void 0;if(d.status===410&&g==="DIRECT_SHORTCUT_CARD_SURFACE_RETIRED")throw new ot(m?.error||"Parentless single-call is not enabled on this server.",{status:d.status,serverErrorCode:g});if(d.status===503){if(m?.error_code==="SESSION_LOCK_CONTENDED"){let w=Number(d.headers.get("Retry-After"))||1;throw new wt(m?.message||m?.error||"Session budget is being modified by another request. Retry shortly.",w,d.status)}throw new Error(zr(m))}if(m?.declined){let w=Number(m.retryAfter??d.headers.get("Retry-After"));throw new le(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite(w)&&w>0?w:void 0)}let h=Qi(m?.error_code);throw h?new st(m?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",h,{transactionId:typeof m?.transactionId=="string"?m.transactionId:void 0,retryable:!!m?.retryable,reconciliationRequired:m?.reconciliation_required!==!1}):new Error(m?.error||`Request failed (${d.status}). Try again.`)}return{data:m,voucherReceiptHeader:p}}async batchOpen(t){let n="/v1/batch/open",r=await this.getSessionToken();if(!r)throw new Error(Jr());let o={Authorization:`Bearer ${r}`,"X-Visa-CLI-Version":Wt,"X-Source":"cli","Content-Type":"application/json"},s={...t.attestation?{attestation:t.attestation}:{},nonce:t.nonce,approved_total_cents:t.approved_total_cents,batch_id:t.batch_id},i;try{i=await rt(`${this.baseUrl}${n}`,{method:"POST",headers:o,body:JSON.stringify(s),timeoutMs:void 0})}catch(u){throw new Error(er(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 ot("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 ot(a?.error||"Parentless batch is not enabled on this server.",{status:i.status,serverErrorCode:u});if(i.status===503)throw new Error(zr(a));if(a?.declined){let d=Number(a.retryAfter??i.headers.get("Retry-After"));throw new le(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,o,s,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error(Jr());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":Wt,"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}:{}};s&&(u.user_context=s.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await rt(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:o})}catch(g){throw new Error(er(g))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let g=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${g}s. Tip: use the batch tool to combine multiple requests into one.`)}let p=d.headers.get("X-Voucher-Receipt"),m;try{m=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(m),d.status===503){if(m?.error_code==="SESSION_LOCK_CONTENDED"){let g=Number(d.headers.get("Retry-After"))||1;throw new wt(m?.message||m?.error||"Batch parent is being modified by another request. Retry shortly.",g,d.status)}throw new Error(zr(m))}if(m?.declined){let g=Number(m.retryAfter??d.headers.get("Retry-After"));throw new le(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite(g)&&g>0?g:void 0)}throw new Error(m?.error||`Request failed (${d.status}). Try again.`)}return{data:m,voucherReceiptHeader:p}}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async catalogSearch(t,n,r,o){let s=r??"discover_tools",i=new URLSearchParams;t&&i.set("q",t),n&&i.set("category",n),o?.limit!=null&&i.set("limit",String(o.limit)),o?.offset!=null&&i.set("offset",String(o.offset));let a=i.toString();return this.request("GET",`/v1/catalog${a?`?${a}`:""}`,void 0,void 0,void 0,s)}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 rt(`${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 rt(`${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 o=r.toString(),s=o?`/v1/transactions?${o}`:"/v1/transactions";return this.request("GET",s,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 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,o=null,s=0;for(;;){let i=await this.listAppApiKeys({limit:100,...r!==void 0?{startingAfter:r}:{}});if(s+=1,o=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{...o??{success:!0,keys:[]},keys:t,limit:100,has_more:!1,next_cursor:null,previous_cursor:null,pages:s}}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 o=r.toString();return this.request("GET",`/v1/feedback${o?"?"+o:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}};function Yr(e,t){return t||(typeof e!="number"||!Number.isFinite(e)?"price unknown":`$${(e/100).toFixed(2)}`)}function $u(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 Iu(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function yh(e){let t=new Map;for(let n of e){let r=n.category||"other",o=t.get(r)??[];o.push(n),t.set(r,o)}return new Map([...t.entries()].sort(([n],[r])=>n.localeCompare(r)))}function _h(e){return Math.max(4,e.reduce((t,n)=>Math.max(t,n.id.length),0))}function bh(e){return Math.max(8,Math.min(14,e.reduce((t,n)=>Math.max(t,(n.category||"").length),0)))}function vh(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 Pu(e){let t=_h(e),n=7,r=bh(e),o=vh(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(o,32))}`);for(let s of e)console.log(` ${s.id.padEnd(t)} ${Yr(s.priceCents,s.priceDisplay).padEnd(n)} ${Iu(s.category||"other",r).padEnd(r)} ${Iu($u(s),o)}`)}function Ou(e){console.log(`
128
128
  Merchant tools
129
- `),ql(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 Ci(e){console.log(`
129
+ `),Pu(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 ea(e){console.log(`
130
130
  Merchant tools
131
- `);for(let[t,n]of Gf(e)){console.log(t[0]?.toUpperCase()+t.slice(1));for(let r of n)console.log(` ${r.id.padEnd(28)} ${Pr(r.priceCents,r.priceDisplay).padEnd(8)} ${r.description}`),console.log(` Params: ${Vl(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"
132
- `)}function Hl(e,t){console.log(`
131
+ `);for(let[t,n]of yh(e)){console.log(t[0]?.toUpperCase()+t.slice(1));for(let r of n)console.log(` ${r.id.padEnd(28)} ${Yr(r.priceCents,r.priceDisplay).padEnd(8)} ${r.description}`),console.log(` Params: ${$u(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"
132
+ `)}function Mu(e,t){console.log(`
133
133
  ${e} tools
134
- `),ql(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>\`
135
- `)}var h={};Os(h,{BRAND:()=>wg,DIRTY:()=>ln,EMPTY_PATH:()=>Qf,INVALID:()=>P,NEVER:()=>sh,OK:()=>be,ParseStatus:()=>ge,Schema:()=>j,ZodAny:()=>qt,ZodArray:()=>wt,ZodBigInt:()=>dn,ZodBoolean:()=>mn,ZodBranded:()=>Mr,ZodCatch:()=>xn,ZodDate:()=>pn,ZodDefault:()=>Sn,ZodDiscriminatedUnion:()=>Vo,ZodEffects:()=>Ne,ZodEnum:()=>vn,ZodError:()=>ke,ZodFirstPartyTypeKind:()=>M,ZodFunction:()=>Bo,ZodIntersection:()=>yn,ZodIssueCode:()=>b,ZodLazy:()=>_n,ZodLiteral:()=>bn,ZodMap:()=>zn,ZodNaN:()=>Yn,ZodNativeEnum:()=>wn,ZodNever:()=>Fe,ZodNull:()=>gn,ZodNullable:()=>ot,ZodNumber:()=>un,ZodObject:()=>Ce,ZodOptional:()=>Oe,ZodParsedType:()=>k,ZodPipeline:()=>Nr,ZodPromise:()=>Bt,ZodReadonly:()=>kn,ZodRecord:()=>qo,ZodSchema:()=>j,ZodSet:()=>Jn,ZodString:()=>Vt,ZodSymbol:()=>Gn,ZodTransformer:()=>Ne,ZodTuple:()=>rt,ZodType:()=>j,ZodUndefined:()=>fn,ZodUnion:()=>hn,ZodUnknown:()=>vt,ZodVoid:()=>Wn,addIssueToContext:()=>S,any:()=>Ig,array:()=>Mg,bigint:()=>Cg,boolean:()=>tu,coerce:()=>oh,custom:()=>Zl,date:()=>Tg,datetimeRegex:()=>Yl,defaultErrorMap:()=>_t,discriminatedUnion:()=>Dg,effect:()=>Yg,enum:()=>Wg,function:()=>Hg,getErrorMap:()=>Bn,getParsedType:()=>nt,instanceof:()=>xg,intersection:()=>jg,isAborted:()=>jo,isAsync:()=>Hn,isDirty:()=>Fo,isValid:()=>Ft,late:()=>Sg,lazy:()=>Kg,literal:()=>Gg,makeIssue:()=>Or,map:()=>qg,nan:()=>kg,nativeEnum:()=>zg,never:()=>Pg,null:()=>Rg,nullable:()=>Zg,number:()=>eu,object:()=>Ng,objectUtil:()=>Ti,oboolean:()=>rh,onumber:()=>nh,optional:()=>Xg,ostring:()=>th,pipeline:()=>eh,preprocess:()=>Qg,promise:()=>Jg,quotelessJson:()=>Yf,record:()=>Vg,set:()=>Bg,setErrorMap:()=>Zf,strictObject:()=>Lg,string:()=>Ql,symbol:()=>Eg,transformer:()=>Yg,tuple:()=>Fg,undefined:()=>Ag,union:()=>Ug,unknown:()=>$g,util:()=>F,void:()=>Og});var F;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},e.getValidEnumValues=o=>{let s=e.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return e.objectValues(i)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},e.find=(o,s)=>{for(let i of o)if(s(i))return i},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(F||(F={}));var Ti;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Ti||(Ti={}));var k=F.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),nt=e=>{switch(typeof e){case"undefined":return k.undefined;case"string":return k.string;case"number":return Number.isNaN(e)?k.nan:k.number;case"boolean":return k.boolean;case"function":return k.function;case"bigint":return k.bigint;case"symbol":return k.symbol;case"object":return Array.isArray(e)?k.array:e===null?k.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?k.promise:typeof Map<"u"&&e instanceof Map?k.map:typeof Set<"u"&&e instanceof Set?k.set:typeof Date<"u"&&e instanceof Date?k.date:k.object;default:return k.unknown}};var b=F.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"]),Yf=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ke=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(s){return s.message},r={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(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 o(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,F.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];n[s]=n[s]||[],n[s].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};ke.create=e=>new ke(e);var Xf=(e,t)=>{let n;switch(e.code){case b.invalid_type:e.received===k.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case b.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,F.jsonStringifyReplacer)}`;break;case b.unrecognized_keys:n=`Unrecognized key(s) in object: ${F.joinValues(e.keys,", ")}`;break;case b.invalid_union:n="Invalid input";break;case b.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${F.joinValues(e.options)}`;break;case b.invalid_enum_value:n=`Invalid enum value. Expected ${F.joinValues(e.options)}, received '${e.received}'`;break;case b.invalid_arguments:n="Invalid function arguments";break;case b.invalid_return_type:n="Invalid function return type";break;case b.invalid_date:n="Invalid date";break;case b.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}"`:F.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case b.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 b.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 b.custom:n="Invalid input";break;case b.invalid_intersection_types:n="Intersection results could not be merged";break;case b.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case b.not_finite:n="Number must be finite";break;default:n=t.defaultError,F.assertNever(e)}return{message:n}},_t=Xf;var Kl=_t;function Zf(e){Kl=e}function Bn(){return Kl}var Or=e=>{let{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=r.filter(l=>!!l).slice().reverse();for(let l of c)a=l(i,{data:t,defaultError:a}).message;return{...o,path:s,message:a}},Qf=[];function S(e,t){let n=Bn(),r=Or({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===_t?void 0:_t].filter(o=>!!o)});e.common.issues.push(r)}var ge=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 o of n){if(o.status==="aborted")return P;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let o of n){let s=await o.key,i=await o.value;r.push({key:s,value:i})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let o of n){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return P;s.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:t.value,value:r}}},P=Object.freeze({status:"aborted"}),ln=e=>({status:"dirty",value:e}),be=e=>({status:"valid",value:e}),jo=e=>e.status==="aborted",Fo=e=>e.status==="dirty",Ft=e=>e.status==="valid",Hn=e=>typeof Promise<"u"&&e instanceof Promise;var E;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(E||(E={}));var Me=class{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}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}},Gl=(e,t)=>{if(Ft(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 ke(e.common.issues);return this._error=n,this._error}}};function L(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:o}=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:o}:{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:o}}var j=class{get description(){return this._def.description}_getType(t){return nt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:nt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ge,ctx:{common:t.parent.common,data:t.data,parsedType:nt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Hn(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:nt(t)},o=this._parseSync({data:t,path:r.path,parent:r});return Gl(r,o)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:nt(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return Ft(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=>Ft(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:nt(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(Hn(o)?o:Promise.resolve(o));return Gl(r,s)}refine(t,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{let i=t(o),a=()=>s.addIssue({code:b.custom,...r(o)});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,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Ne({schema:this,typeName:M.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 Oe.create(this,this._def)}nullable(){return ot.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return wt.create(this)}promise(){return Bt.create(this,this._def)}or(t){return hn.create([this,t],this._def)}and(t){return yn.create(this,t,this._def)}transform(t){return new Ne({...L(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new Sn({...L(this._def),innerType:this,defaultValue:n,typeName:M.ZodDefault})}brand(){return new Mr({typeName:M.ZodBranded,type:this,...L(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new xn({...L(this._def),innerType:this,catchValue:n,typeName:M.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Nr.create(this,t)}readonly(){return kn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},eg=/^c[^\s-]{8,}$/i,tg=/^[0-9a-z]+$/,ng=/^[0-9A-HJKMNP-TV-Z]{26}$/i,rg=/^[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,og=/^[a-z0-9_-]{21}$/i,sg=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ig=/^[-+]?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)?)??$/,ag=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,cg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ei,lg=/^(?:(?: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])$/,ug=/^(?:(?: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])$/,dg=/^(([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]))$/,mg=/^(([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])$/,pg=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,fg=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,zl="((\\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])))",gg=new RegExp(`^${zl}$`);function Jl(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 hg(e){return new RegExp(`^${Jl(e)}$`)}function Yl(e){let t=`${zl}T${Jl(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 yg(e,t){return!!((t==="v4"||!t)&&lg.test(e)||(t==="v6"||!t)&&dg.test(e))}function _g(e,t){if(!sg.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,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function bg(e,t){return!!((t==="v4"||!t)&&ug.test(e)||(t==="v6"||!t)&&mg.test(e))}var Vt=class e extends j{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==k.string){let s=this._getOrReturnCtx(t);return S(s,{code:b.invalid_type,expected:k.string,received:s.parsedType}),P}let r=new ge,o;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),S(o,{code:b.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),S(o,{code:b.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let i=t.data.length>s.value,a=t.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(t,o),i?S(o,{code:b.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&S(o,{code:b.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")ag.test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"email",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Ei||(Ei=new RegExp(cg,"u")),Ei.test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"emoji",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")rg.test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"uuid",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")og.test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"nanoid",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")eg.test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"cuid",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")tg.test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"cuid2",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")ng.test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"ulid",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),S(o,{validation:"url",code:b.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"regex",code:b.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),S(o,{code:b.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),S(o,{code:b.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),S(o,{code:b.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?Yl(s).test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{code:b.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?gg.test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{code:b.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?hg(s).test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{code:b.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?ig.test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"duration",code:b.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?yg(t.data,s.version)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"ip",code:b.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?_g(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"jwt",code:b.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?bg(t.data,s.version)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"cidr",code:b.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?pg.test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"base64",code:b.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?fg.test(t.data)||(o=this._getOrReturnCtx(t,o),S(o,{validation:"base64url",code:b.invalid_string,message:s.message}),r.dirty()):F.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:b.invalid_string,...E.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...E.errToObj(t)})}url(t){return this._addCheck({kind:"url",...E.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...E.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...E.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...E.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...E.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...E.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...E.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...E.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...E.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...E.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...E.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...E.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,...E.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,...E.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...E.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...E.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...E.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...E.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...E.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...E.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...E.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...E.errToObj(n)})}nonempty(t){return this.min(1,E.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}};Vt.create=e=>new Vt({checks:[],typeName:M.ZodString,coerce:e?.coerce??!1,...L(e)});function vg(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/10**o}var un=class e extends j{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==k.number){let s=this._getOrReturnCtx(t);return S(s,{code:b.invalid_type,expected:k.number,received:s.parsedType}),P}let r,o=new ge;for(let s of this._def.checks)s.kind==="int"?F.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),S(r,{code:b.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),S(r,{code:b.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),S(r,{code:b.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?vg(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),S(r,{code:b.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),S(r,{code:b.not_finite,message:s.message}),o.dirty()):F.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,E.toString(n))}gt(t,n){return this.setLimit("min",t,!1,E.toString(n))}lte(t,n){return this.setLimit("max",t,!0,E.toString(n))}lt(t,n){return this.setLimit("max",t,!1,E.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:E.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:E.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:E.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:E.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:E.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:E.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:E.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:E.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:E.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:E.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"&&F.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)}};un.create=e=>new un({checks:[],typeName:M.ZodNumber,coerce:e?.coerce||!1,...L(e)});var dn=class e extends j{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==k.bigint)return this._getInvalidInput(t);let r,o=new ge;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),S(r,{code:b.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),S(r,{code:b.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),S(r,{code:b.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):F.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return S(n,{code:b.invalid_type,expected:k.bigint,received:n.parsedType}),P}gte(t,n){return this.setLimit("min",t,!0,E.toString(n))}gt(t,n){return this.setLimit("min",t,!1,E.toString(n))}lte(t,n){return this.setLimit("max",t,!0,E.toString(n))}lt(t,n){return this.setLimit("max",t,!1,E.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:E.toString(o)}]})}_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:E.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:E.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:E.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:E.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:E.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}};dn.create=e=>new dn({checks:[],typeName:M.ZodBigInt,coerce:e?.coerce??!1,...L(e)});var mn=class extends j{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==k.boolean){let r=this._getOrReturnCtx(t);return S(r,{code:b.invalid_type,expected:k.boolean,received:r.parsedType}),P}return be(t.data)}};mn.create=e=>new mn({typeName:M.ZodBoolean,coerce:e?.coerce||!1,...L(e)});var pn=class e extends j{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==k.date){let s=this._getOrReturnCtx(t);return S(s,{code:b.invalid_type,expected:k.date,received:s.parsedType}),P}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return S(s,{code:b.invalid_date}),P}let r=new ge,o;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),S(o,{code:b.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),S(o,{code:b.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):F.assertNever(s);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:E.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:E.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}};pn.create=e=>new pn({checks:[],coerce:e?.coerce||!1,typeName:M.ZodDate,...L(e)});var Gn=class extends j{_parse(t){if(this._getType(t)!==k.symbol){let r=this._getOrReturnCtx(t);return S(r,{code:b.invalid_type,expected:k.symbol,received:r.parsedType}),P}return be(t.data)}};Gn.create=e=>new Gn({typeName:M.ZodSymbol,...L(e)});var fn=class extends j{_parse(t){if(this._getType(t)!==k.undefined){let r=this._getOrReturnCtx(t);return S(r,{code:b.invalid_type,expected:k.undefined,received:r.parsedType}),P}return be(t.data)}};fn.create=e=>new fn({typeName:M.ZodUndefined,...L(e)});var gn=class extends j{_parse(t){if(this._getType(t)!==k.null){let r=this._getOrReturnCtx(t);return S(r,{code:b.invalid_type,expected:k.null,received:r.parsedType}),P}return be(t.data)}};gn.create=e=>new gn({typeName:M.ZodNull,...L(e)});var qt=class extends j{constructor(){super(...arguments),this._any=!0}_parse(t){return be(t.data)}};qt.create=e=>new qt({typeName:M.ZodAny,...L(e)});var vt=class extends j{constructor(){super(...arguments),this._unknown=!0}_parse(t){return be(t.data)}};vt.create=e=>new vt({typeName:M.ZodUnknown,...L(e)});var Fe=class extends j{_parse(t){let n=this._getOrReturnCtx(t);return S(n,{code:b.invalid_type,expected:k.never,received:n.parsedType}),P}};Fe.create=e=>new Fe({typeName:M.ZodNever,...L(e)});var Wn=class extends j{_parse(t){if(this._getType(t)!==k.undefined){let r=this._getOrReturnCtx(t);return S(r,{code:b.invalid_type,expected:k.void,received:r.parsedType}),P}return be(t.data)}};Wn.create=e=>new Wn({typeName:M.ZodVoid,...L(e)});var wt=class e extends j{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==k.array)return S(n,{code:b.invalid_type,expected:k.array,received:n.parsedType}),P;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(S(n,{code:i?b.too_big:b.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(S(n,{code:b.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(S(n,{code:b.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>o.type._parseAsync(new Me(n,i,n.path,a)))).then(i=>ge.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new Me(n,i,n.path,a)));return ge.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:E.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:E.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:E.toString(n)}})}nonempty(t){return this.min(1,t)}};wt.create=(e,t)=>new wt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...L(t)});function Kn(e){if(e instanceof Ce){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Oe.create(Kn(r))}return new Ce({...e._def,shape:()=>t})}else return e instanceof wt?new wt({...e._def,type:Kn(e.element)}):e instanceof Oe?Oe.create(Kn(e.unwrap())):e instanceof ot?ot.create(Kn(e.unwrap())):e instanceof rt?rt.create(e.items.map(t=>Kn(t))):e}var Ce=class e extends j{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=F.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==k.object){let l=this._getOrReturnCtx(t);return S(l,{code:b.invalid_type,expected:k.object,received:l.parsedType}),P}let{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Fe&&this._def.unknownKeys==="strip"))for(let l in o.data)i.includes(l)||a.push(l);let c=[];for(let l of i){let u=s[l],d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Me(o,d,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Fe){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(l==="strict")a.length>0&&(S(o,{code:b.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=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Me(o,d,o.path,u)),alwaysSet:u in o.data})}}return o.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=>ge.mergeObjectSync(r,l)):ge.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(t){return E.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:E.errToObj(t).message??o}:{message:o}}}:{}})}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:M.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 F.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 F.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return Kn(this)}partial(t){let n={};for(let r of F.objectKeys(this.shape)){let o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let r of F.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Oe;)s=s._def.innerType;n[r]=s}return new e({...this._def,shape:()=>n})}keyof(){return Xl(F.objectKeys(this.shape))}};Ce.create=(e,t)=>new Ce({shape:()=>e,unknownKeys:"strip",catchall:Fe.create(),typeName:M.ZodObject,...L(t)});Ce.strictCreate=(e,t)=>new Ce({shape:()=>e,unknownKeys:"strict",catchall:Fe.create(),typeName:M.ZodObject,...L(t)});Ce.lazycreate=(e,t)=>new Ce({shape:e,unknownKeys:"strip",catchall:Fe.create(),typeName:M.ZodObject,...L(t)});var hn=class extends j{_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new ke(a.ctx.common.issues));return S(n,{code:b.invalid_union,unionErrors:i}),P}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,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"&&!s&&(s={result:u,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new ke(c));return S(n,{code:b.invalid_union,unionErrors:a}),P}}get options(){return this._def.options}};hn.create=(e,t)=>new hn({options:e,typeName:M.ZodUnion,...L(t)});var bt=e=>e instanceof _n?bt(e.schema):e instanceof Ne?bt(e.innerType()):e instanceof bn?[e.value]:e instanceof vn?e.options:e instanceof wn?F.objectValues(e.enum):e instanceof Sn?bt(e._def.innerType):e instanceof fn?[void 0]:e instanceof gn?[null]:e instanceof Oe?[void 0,...bt(e.unwrap())]:e instanceof ot?[null,...bt(e.unwrap())]:e instanceof Mr||e instanceof kn?bt(e.unwrap()):e instanceof xn?bt(e._def.innerType):[],Vo=class e extends j{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==k.object)return S(n,{code:b.invalid_type,expected:k.object,received:n.parsedType}),P;let r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(S(n,{code:b.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),P)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let o=new Map;for(let s of n){let i=bt(s.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(o.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);o.set(a,s)}}return new e({typeName:M.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...L(r)})}};function Ai(e,t){let n=nt(e),r=nt(t);if(e===t)return{valid:!0,data:e};if(n===k.object&&r===k.object){let o=F.objectKeys(t),s=F.objectKeys(e).filter(a=>o.indexOf(a)!==-1),i={...e,...t};for(let a of s){let c=Ai(e[a],t[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===k.array&&r===k.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let s=0;s<e.length;s++){let i=e[s],a=t[s],c=Ai(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return n===k.date&&r===k.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var yn=class extends j{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=(s,i)=>{if(jo(s)||jo(i))return P;let a=Ai(s.value,i.value);return a.valid?((Fo(s)||Fo(i))&&n.dirty(),{status:n.value,value:a.data}):(S(r,{code:b.invalid_intersection_types}),P)};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(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};yn.create=(e,t,n)=>new yn({left:e,right:t,typeName:M.ZodIntersection,...L(n)});var rt=class e extends j{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==k.array)return S(r,{code:b.invalid_type,expected:k.array,received:r.parsedType}),P;if(r.data.length<this._def.items.length)return S(r,{code:b.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),P;!this._def.rest&&r.data.length>this._def.items.length&&(S(r,{code:b.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Me(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>ge.mergeArray(n,i)):ge.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};rt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new rt({items:e,typeName:M.ZodTuple,rest:null,...L(t)})};var qo=class e extends j{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==k.object)return S(r,{code:b.invalid_type,expected:k.object,received:r.parsedType}),P;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new Me(r,a,r.path,a)),value:i._parse(new Me(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?ge.mergeObjectAsync(n,o):ge.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof j?new e({keyType:t,valueType:n,typeName:M.ZodRecord,...L(r)}):new e({keyType:Vt.create(),valueType:t,typeName:M.ZodRecord,...L(n)})}},zn=class extends j{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==k.map)return S(r,{code:b.invalid_type,expected:k.map,received:r.parsedType}),P;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,c],l)=>({key:o._parse(new Me(r,a,r.path,[l,"key"])),value:s._parse(new Me(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 P;(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 P;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}}}};zn.create=(e,t,n)=>new zn({valueType:t,keyType:e,typeName:M.ZodMap,...L(n)});var Jn=class e extends j{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==k.set)return S(r,{code:b.invalid_type,expected:k.set,received:r.parsedType}),P;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(S(r,{code:b.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(S(r,{code:b.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return P;u.status==="dirty"&&n.dirty(),l.add(u.value)}return{status:n.value,value:l}}let a=[...r.data.values()].map((c,l)=>s._parse(new Me(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:E.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:E.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};Jn.create=(e,t)=>new Jn({valueType:e,minSize:null,maxSize:null,typeName:M.ZodSet,...L(t)});var Bo=class e extends j{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==k.function)return S(n,{code:b.invalid_type,expected:k.function,received:n.parsedType}),P;function r(a,c){return Or({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Bn(),_t].filter(l=>!!l),issueData:{code:b.invalid_arguments,argumentsError:c}})}function o(a,c){return Or({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Bn(),_t].filter(l=>!!l),issueData:{code:b.invalid_return_type,returnTypeError:c}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof Bt){let a=this;return be(async function(...c){let l=new ke([]),u=await a._def.args.parseAsync(c,s).catch(m=>{throw l.addIssue(r(c,m)),l}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,s).catch(m=>{throw l.addIssue(o(d,m)),l})})}else{let a=this;return be(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new ke([r(c,l.error)]);let u=Reflect.apply(i,this,l.data),d=a._def.returns.safeParse(u,s);if(!d.success)throw new ke([o(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:rt.create(t).rest(vt.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||rt.create([]).rest(vt.create()),returns:n||vt.create(),typeName:M.ZodFunction,...L(r)})}},_n=class extends j{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})}};_n.create=(e,t)=>new _n({getter:e,typeName:M.ZodLazy,...L(t)});var bn=class extends j{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return S(n,{received:n.data,code:b.invalid_literal,expected:this._def.value}),P}return{status:"valid",value:t.data}}get value(){return this._def.value}};bn.create=(e,t)=>new bn({value:e,typeName:M.ZodLiteral,...L(t)});function Xl(e,t){return new vn({values:e,typeName:M.ZodEnum,...L(t)})}var vn=class e extends j{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return S(n,{expected:F.joinValues(r),received:n.parsedType,code:b.invalid_type}),P}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 S(n,{received:n.data,code:b.invalid_enum_value,options:r}),P}return be(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})}};vn.create=Xl;var wn=class extends j{_parse(t){let n=F.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==k.string&&r.parsedType!==k.number){let o=F.objectValues(n);return S(r,{expected:F.joinValues(o),received:r.parsedType,code:b.invalid_type}),P}if(this._cache||(this._cache=new Set(F.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let o=F.objectValues(n);return S(r,{received:r.data,code:b.invalid_enum_value,options:o}),P}return be(t.data)}get enum(){return this._def.values}};wn.create=(e,t)=>new wn({values:e,typeName:M.ZodNativeEnum,...L(t)});var Bt=class extends j{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==k.promise&&n.common.async===!1)return S(n,{code:b.invalid_type,expected:k.promise,received:n.parsedType}),P;let r=n.parsedType===k.promise?n.data:Promise.resolve(n.data);return be(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Bt.create=(e,t)=>new Bt({type:e,typeName:M.ZodPromise,...L(t)});var Ne=class extends j{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:i=>{S(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return P;let c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?P:c.status==="dirty"?ln(c.value):n.value==="dirty"?ln(c.value):c});{if(n.value==="aborted")return P;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?P:a.status==="dirty"?ln(a.value):n.value==="dirty"?ln(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);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"?P:(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"?P:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Ft(i))return P;let a=o.transform(i.value,s);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=>Ft(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):P);F.assertNever(o)}};Ne.create=(e,t,n)=>new Ne({schema:e,typeName:M.ZodEffects,effect:t,...L(n)});Ne.createWithPreprocess=(e,t,n)=>new Ne({schema:t,effect:{type:"preprocess",transform:e},typeName:M.ZodEffects,...L(n)});var Oe=class extends j{_parse(t){return this._getType(t)===k.undefined?be(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Oe.create=(e,t)=>new Oe({innerType:e,typeName:M.ZodOptional,...L(t)});var ot=class extends j{_parse(t){return this._getType(t)===k.null?be(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};ot.create=(e,t)=>new ot({innerType:e,typeName:M.ZodNullable,...L(t)});var Sn=class extends j{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===k.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Sn.create=(e,t)=>new Sn({innerType:e,typeName:M.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...L(t)});var xn=class extends j{_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Hn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ke(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ke(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};xn.create=(e,t)=>new xn({innerType:e,typeName:M.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...L(t)});var Yn=class extends j{_parse(t){if(this._getType(t)!==k.nan){let r=this._getOrReturnCtx(t);return S(r,{code:b.invalid_type,expected:k.nan,received:r.parsedType}),P}return{status:"valid",value:t.data}}};Yn.create=e=>new Yn({typeName:M.ZodNaN,...L(e)});var wg=Symbol("zod_brand"),Mr=class extends j{_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}},Nr=class e extends j{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?P:s.status==="dirty"?(n.dirty(),ln(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?P:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:M.ZodPipeline})}},kn=class extends j{_parse(t){let n=this._def.innerType._parse(t),r=o=>(Ft(o)&&(o.value=Object.freeze(o.value)),o);return Hn(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};kn.create=(e,t)=>new kn({innerType:e,typeName:M.ZodReadonly,...L(t)});function Wl(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Zl(e,t={},n){return e?qt.create().superRefine((r,o)=>{let s=e(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Wl(t,r),c=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Wl(t,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):qt.create()}var Sg={object:Ce.lazycreate},M;(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"})(M||(M={}));var xg=(e,t={message:`Input not instance of ${e.name}`})=>Zl(n=>n instanceof e,t),Ql=Vt.create,eu=un.create,kg=Yn.create,Cg=dn.create,tu=mn.create,Tg=pn.create,Eg=Gn.create,Ag=fn.create,Rg=gn.create,Ig=qt.create,$g=vt.create,Pg=Fe.create,Og=Wn.create,Mg=wt.create,Ng=Ce.create,Lg=Ce.strictCreate,Ug=hn.create,Dg=Vo.create,jg=yn.create,Fg=rt.create,Vg=qo.create,qg=zn.create,Bg=Jn.create,Hg=Bo.create,Kg=_n.create,Gg=bn.create,Wg=vn.create,zg=wn.create,Jg=Bt.create,Yg=Ne.create,Xg=Oe.create,Zg=ot.create,Qg=Ne.createWithPreprocess,eh=Nr.create,th=()=>Ql().optional(),nh=()=>eu().optional(),rh=()=>tu().optional(),oh={string:(e=>Vt.create({...e,coerce:!0})),number:(e=>un.create({...e,coerce:!0})),boolean:(e=>mn.create({...e,coerce:!0})),bigint:(e=>dn.create({...e,coerce:!0})),date:(e=>pn.create({...e,coerce:!0}))};var sh=P;var ih=/^[A-Za-z0-9._-]+$/,ah=/^[A-Za-z0-9._-]+(\|[A-Za-z0-9._-]+)*$/,nu=new Set([".",".."]),Se=class extends Error{pattern;constructor(t,n){super(`Invalid freeReadPathPattern ${JSON.stringify(n)}: ${t}`),this.pattern=n,this.name="FreePathPatternError"}};function ch(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 Se(`malformed alternation segment ${JSON.stringify(e)}`,t);let o=n?e.slice(1,-2):e.slice(1,-1);if(!ah.test(o))throw new Se(`malformed alternation segment ${JSON.stringify(e)}`,t);let s=o.split("|");if(s.some(i=>nu.has(i)))throw new Se(`alternation segment ${JSON.stringify(e)} may not contain '.' or '..'`,t);return{raw:e,kind:n?"alt-optional":"alt",alternatives:s}}if(ih.test(e)){if(nu.has(e))throw new Se(`literal segment ${JSON.stringify(e)} is not permitted`,t);return{raw:e,kind:"literal"}}throw new Se(`segment ${JSON.stringify(e)} must be '*', '**', a [A-Za-z0-9._-]+ literal, or (a|b) alternation`,t)}function lh(e){if(typeof e!="string"||e.length===0)throw new Se("must be a non-empty string",String(e));if(!e.startsWith("/"))throw new Se("must start with '/'",e);if(e.slice(1).includes("//"))throw new Se("empty segments ('//') are not permitted",e);if(e.length>1&&e.endsWith("/"))throw new Se("must not end with '/'",e);let n=e.slice(1).split("/").map(s=>ch(s,e));if(n.filter(s=>s.kind==="multi").length>1)throw new Se("at most one '**' is permitted per pattern",e);if(n[0]?.kind==="multi")throw new Se("'**' may not be the first segment (a literal prefix anchor is required)",e);let o=n.findIndex(s=>s.kind==="alt-optional");if(o!==-1&&o!==n.length-1)throw new Se("optional alternation '(...)?' is only allowed as the final segment",e);return n}function Ri(e){lh(e)}var ru=["tempo","mpp_self","merchant_self"],ou=["catalog_static","fal_direct","fal_queue","openrouter_chat","openrouter_image","platform_proxy","tempo_gateway","x402_gateway"],su=["image","audio","queued_audio","video","queued_video","model_3d","llm","transcription","utility"],iu=["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 $i=h.object({inputPerMillion:h.number().positive(),outputPerMillion:h.number().positive(),contextWindow:h.number().int().positive().optional(),maxOutput:h.number().int().positive().optional(),perRequestFeeCents:h.number().nonnegative().optional()}),uh=h.object({strategy:h.enum(["flat","token","band"]).optional(),pricingModel:h.enum(["per-call","per-token","band"]).optional(),priceCents:h.number().nonnegative().optional(),currency:h.string().optional(),display:h.string().optional(),estimate:h.boolean().optional(),source:h.string().optional(),priceBand:h.record(h.unknown()).optional(),tokenPricing:$i.optional()}).passthrough(),Pi=h.discriminatedUnion("type",[h.object({type:h.literal("shortcut"),routedPath:h.string().min(1).startsWith("/")}),h.object({type:h.literal("custom"),merchantSlug:h.string().min(1),subPath:h.string().optional()}),h.object({type:h.literal("local"),fn:h.string().min(1)}),h.object({type:h.literal("read")})]),Oi=h.object({amount:h.number().nonnegative(),currency:h.string().length(3).optional(),display:h.string().optional(),free:h.boolean().optional(),batchDiscount:h.number().min(0).max(100).optional()}),au=h.object({attestation:h.boolean().optional(),rateLimitMs:h.number().positive().optional()}),cu=h.object({displayName:h.string().optional(),feedbackEligible:h.boolean().optional(),suggestionEligible:h.boolean().optional(),batchable:h.boolean().optional()}),lu=h.object({enabled:h.boolean().optional(),gatewayPath:h.string().min(1).startsWith("/").optional(),method:h.enum(["GET","POST","PUT","PATCH","DELETE"]).optional(),timeoutMs:h.number().int().positive().max(12e4).optional()}).strict(),dh=h.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),mh=120,ph=120,fh=1200,gh=/^[^\u0000-\u001F\u007F]+$/;function Ii(e,t){return h.string().min(1).max(e).regex(gh,`${t} must not contain control characters`)}var Mi={id:h.string().min(1),name:Ii(mh,"name"),description:Ii(fh,"description"),provider:h.string().min(1),model:h.string().min(1),category:dh,priceCents:h.number().nonnegative(),inputSchema:h.record(h.unknown()),gatewayUrl:h.string().min(1),merchantName:Ii(ph,"merchantName"),isAsync:h.boolean().optional(),pollUrl:h.string().optional(),pollInterval:h.number().positive().optional(),pollTimeout:h.number().positive().optional(),tags:h.array(h.string()).optional(),tokenPricing:$i.optional(),priceDisplay:h.string().optional(),pricingModel:h.enum(["per-call","per-token","band"]).optional(),pricingInfo:uh.optional(),status:h.enum(["available","unavailable"]).optional(),handler:Pi.optional(),pricing:Oi.optional(),security:au.optional(),engagement:cu.optional(),gatewayConfig:lu.optional(),freeReadPathPattern:h.string().optional().superRefine((e,t)=>{if(e!==void 0)try{Ri(e)}catch(n){t.addIssue({code:h.ZodIssueCode.custom,message:n instanceof Error?n.message:String(n)})}}),enabled:h.boolean().optional(),beta:h.boolean().optional(),deprecated:h.boolean().optional(),internal:h.boolean().optional(),replacementTool:h.string().optional(),minCliVersion:h.string().optional(),sunsetAt:h.string().optional(),rail:h.enum(ru).optional(),executionKind:h.enum(ou).optional(),resultKind:h.enum(su).optional(),extractionMode:h.enum(iu).optional(),pricingStrategy:h.enum(["flat","token","band"]).optional()},uu=h.object({...Mi,dispatch:h.literal("routed"),routedPath:h.string().min(1).startsWith("/")}).strict(),du=h.object({...Mi,dispatch:h.literal("enveloped")}).strict(),mu=h.object({...Mi,handler:Pi,pricing:Oi}).strict(),pu=h.union([h.discriminatedUnion("dispatch",[uu,du]),mu]);var Ni=/^[a-z0-9][a-z0-9_-]*$/;var _h="https://fal.run",yu="https://openrouter.mpp.tempo.xyz",Ui=1024,Ko=8192,bh=4096,vh=10;function wh(e){return e>=vh?bh:Ko}function _u(e,t){let n=typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):Ui;return Math.min(n,t)}var Sh=["num_images","num_outputs","num_samples","num_videos","batch_size","n"];function bu(e){for(let t of Sh)delete e[t];return e}function xh(e){let{attestation:t,tool_id:n,...r}=e;return bu(r)}var fu={"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 Ho(e){let{attestation:t,tool_id:n,aspect_ratio:r,image_size:o,...s}=e,i=bu({...s});return typeof o=="string"&&o.length>0?(i.image_size=o,i):(typeof r=="string"&&fu[r]&&(i.image_size=fu[r]),i)}function kh(e){let{attestation:t,tool_id:n,...r}=e;return r}function gu(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 o=new Date(e.start_timestamp).getTime();(new Date(n).getTime()-o)/(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 Ch(e,t,n,r,o,s,i,a,c){return{id:e,name:t,description:n,provider:r,model:o.replace(/^\//,""),category:s,gatewayUrl:`https://${r}${o}`,merchantName:t,inputSchema:a,handler:{type:"custom",merchantSlug:r,subPath:o},pricing:{amount:i,currency:"USD",display:`$${(i/100).toFixed(2)}`},priceCents:i,tags:[],...c}}function Th(e,t,n,r,o,s,i,a){return Ch(e,t,n,"suno-ai",r,o,s,i,{merchantName:"Suno AI",...a})}function se(e,t,n,r,o,s,i,a){return{dispatch:"routed",id:e,name:t,description:n,provider:"fal",model:r,category:o,priceCents:s,inputSchema:i,routedPath:`/api/v1/fal/${r}`,gatewayUrl:`${_h}/${r}`,merchantName:"fal.ai",buildBody:xh,tags:[],...a}}function vu(e,t=Ko){return n=>{let{attestation:r,tool_id:o,model:s,prompt:i,system_prompt:a,max_tokens:c,max_completion_tokens:l,n:u,messages:d,temperature:p,...m}=n;return typeof s=="string"&&s.length>0&&s!==e&&console.warn("[catalog] openrouterBuildBody: caller model override ignored",{catalogModel:e,callerModel:s}),{messages:Array.isArray(d)?d:[...a?[{role:"system",content:a}]:[],{role:"user",content:i}],temperature:p??.7,...m,model:e,max_tokens:_u(c??l,t)}}}function wu(e,t=Ko){return n=>{let{attestation:r,tool_id:o,prompt:s,image_url:i,aspect_ratio:a,max_tokens:c,max_completion_tokens:l,n:u,model:d,messages:p,image_config:m,temperature:g,...y}=n,w=[{type:"text",text:s}];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:g??.7,...y,model:e,...typeof a=="string"&&a.length>0?{image_config:{aspect_ratio:a}}:{},max_tokens:_u(c??l,t)}}}function Q(e,t,n,r,o,s,i){let a=i?.maxOutputTokens??wh(s),c=i?.perRequestFeeCents??0,l=500/1e6*o*100,u=500/1e6*s*100,d=Math.max(1,Math.ceil(l+u+c)),{perRequestFeeCents:p,maxOutputTokens:m,...g}=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: ${Ui}); 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:`${yu}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:vu(r,a),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:o,outputPerMillion:s,...c>0?{perRequestFeeCents:c}:{}},...g}}function Li(e,t,n,r,o,s){let i=s?.maxOutputTokens??Ko,{maxOutputTokens:a,...c}=s??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"image",pricingStrategy:"band",priceCents:o,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: ${Ui}); 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:`${yu}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:wu(r,i),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...c}}var Di=[se("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"]}),se("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:Ho}),se("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:Ho}),se("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:Ho}),se("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"]}),Li("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),Li("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}}),Li("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}}),se("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"]}),se("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"]}),se("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"]}),se("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"]}),se("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"]}),se("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"]}),se("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"]}),se("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"]}),se("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"]}),Th("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:o,...s}=e;return{prompt:r,customMode:!1,instrumental:typeof o=="boolean"?o:!1,model:"V4",...s}}}),se("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"]}),se("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"]}),se("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"]}),se("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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"]}),Q("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:gu,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:kh,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=>Ho({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"]},se("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"}),se("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:gu,tags:["onchain","prices","allium","crypto","legacy"]}];function Xn(e){return Di.find(t=>t.id===e)}var Su=1,xu=["pick_one","fan_out"],ku=["concat","dedupe_by_url","top_k_by_score"],Rh=8,Ih=h.object({type:h.string().min(1),description:h.string().min(1),enum:h.array(h.string()).optional(),default:h.unknown().optional(),minimum:h.number().optional(),maximum:h.number().optional()}),$h=h.object({toolId:h.string().min(1),notes:h.string().min(1)}),Ph=h.string().regex(/^[a-z0-9_-]{1,32}$/,"tier key must be 1-32 chars [a-z0-9_-]"),Oh=h.object({providers:h.array(h.string().min(1)).min(1).max(Rh),merge:h.enum(ku),maxResults:h.number().int().positive().optional()}),Cu=h.object({mode:h.enum(xu).default("pick_one"),intro:h.string().min(1),defaultTier:h.string().min(1),tiers:h.record(Ph,$h).refine(e=>Object.keys(e).length>0,{message:"must have at least one tier"}),fanOut:Oh.optional(),guidance:h.string().min(1),inputProperties:h.record(h.string(),Ih),required:h.array(h.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"]}),Mh=h.object({version:h.literal(Su),generatedAt:h.string().datetime(),tools:h.record(h.string().regex(Ni,"tool name must match MCP naming rules"),Cu).refine(e=>Object.keys(e).length>0,{message:"manifest must have at least one tool"})});var Jo=require("child_process"),Nu=require("util"),Lu=T(require("crypto")),z=T(require("fs")),Uu=T(require("os")),ve=T(require("path"));var Ve=(0,Nu.promisify)(Jo.execFile),Uh=6e4,Dh=()=>process.platform==="darwin",Ht=()=>process.platform==="win32",Kt=ve.join(Uu.homedir(),".visa-mcp","bin"),Cn=ve.join(Kt,"Visa CLI"),St=ve.join(Kt,"visa-keychain-win.exe"),Du=ve.join(__dirname,"..","native"),Tu="6",Eu=ve.join(Kt,"visa-keychain.version"),Au=ve.join(Kt,"visa-keychain.sha256"),Ru="1",Iu=ve.join(Kt,"visa-keychain-win.version"),$u=ve.join(Kt,"visa-keychain-win.sha256"),ju=[ve.join(Du,"bin","win32-x64","visa-keychain-win.exe"),ve.resolve(__dirname,"..","..","native","bin","win32-x64","visa-keychain-win.exe"),ve.resolve(__dirname,"..","native","bin","win32-x64","visa-keychain-win.exe")];function Go(e){let t=z.readFileSync(e);return Lu.createHash("sha256").update(t).digest("hex")}function jh(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 Pu(e){let t=typeof e?.message=="string"?e.message:"";return e?.code==="ETIMEDOUT"||e?.killed===!0||/timed out|timeout/i.test(t)}function Ou(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 ji(){try{if(z.readFileSync(Eu,"utf-8").trim()===Tu&&z.existsSync(Cn)){let r=z.readFileSync(Au,"utf-8").trim();if(Go(Cn)!==r)f.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),z.unlinkSync(Cn);else return Cn}}catch{}let e=ve.join(Du,"visa-keychain.m");if(z.existsSync(e)||(e=ve.resolve(__dirname,"..","..","native","visa-keychain.m")),z.existsSync(e)||(e=ve.resolve(__dirname,"..","native","visa-keychain.m")),!z.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");z.mkdirSync(Kt,{recursive:!0,mode:448});try{await Ve("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",Cn,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=Go(Cn);return z.writeFileSync(Au,t,{mode:384}),z.writeFileSync(Eu,Tu,{mode:384}),Cn}function Fu(){for(let e of ju)if(z.existsSync(e))return e;return null}async function Zn(){try{if(z.readFileSync(Iu,"utf-8").trim()===Ru&&z.existsSync(St)){let r=z.readFileSync($u,"utf-8").trim();if(Go(St)!==r)f.warn("binary:hash-mismatch:win32",{message:"Windows binary hash mismatch. Redeploying."}),z.unlinkSync(St);else return St}}catch{}let e=Fu();if(!e)throw new Error(`visa-keychain-win.exe not found in package. Reinstall @visa/cli.
136
- If building from source, run native/build-win.bat first.`);z.mkdirSync(Kt,{recursive:!0}),z.copyFileSync(e,St);let t=Go(St);return z.writeFileSync($u,t,{mode:384}),z.writeFileSync(Iu,Ru,{mode:384}),St}async function Fh(){return Ht()?Zn():ji()}var Wo="visa-cli",zo="attestation-key";async function Vh(e){try{await Ve("security",["delete-generic-password","-s",Wo,"-a",zo],{timeout:5e3})}catch{}await Ve("security",["add-generic-password","-s",Wo,"-a",zo,"-w",e],{timeout:5e3})}function qh(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:"",o=[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(o)?{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(o)?{state:"denied",usable:!1,message:"The local attestation key exists but Keychain access was denied or unavailable."}:{state:"error",usable:!1,message:o||"Could not read the local attestation key from Keychain."}}async function Bh(){try{let{stdout:e}=await Ve("security",["find-generic-password","-s",Wo,"-a",zo,"-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:qh(e)}}}async function Fi(){let e=await Bh();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 Vu(e){let t=await Fh(),n;try{n=(await Ve(t,e,{timeout:6e4})).stdout}catch(r){n=r.stdout||"";let o=n.trim();throw o.startsWith("ERROR:")?new Error(o.slice(6)):new Error(r.stderr?.trim()||r.message||"Unknown error")}return jh(n)}var Mu=!1;function Hh(){if(!Ht())return!1;try{return z.existsSync(St)||Fu()!==null?!0:(Mu||(Mu=!0,f.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:St,searchedPrebuiltPaths:ju})),!1)}catch{return!1}}function ie(){return On()||Dh()?!0:Ht()?Hh():!1}async function Yo(){if(Ht()){let o=await Zn(),{stdout:s}=await Ve(o,["generate-key"],{timeout:3e4}),i=s.trim();if(i.startsWith("OK:"))return i.slice(3);throw new Error(i.startsWith("ERROR:")?i.slice(6):"Key generation failed")}let e=await Vu(["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 Vh(n),r}async function Xo(){if(Ht())try{let e=await Zn(),{stdout:t}=await Ve(e,["public-key"],{timeout:1e4});return t.trim().startsWith("OK:")}catch{return!1}return await Fi()!==null}async function qu(){if(On())return"mock-public-key-spki";if(Ht()){let n=await Zn(),{stdout:r}=await Ve(n,["public-key"],{timeout:6e4}),o=r.trim();if(o.startsWith("OK:"))return o.slice(3);throw new Error(o.startsWith("ERROR:")?o.slice(6):"Attestation key not found. Run setup to generate a new key.")}let e=await Fi();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await ji();return new Promise((n,r)=>{let o=(0,Jo.execFile)(t,["public-key"],{timeout:6e4},(s,i)=>{let a=(i||"").trim();if(s){a.startsWith("ERROR:")?r(new Error(a.slice(6))):r(new Error(s.stderr?.trim()||s.message||"Unknown error"));return}a.startsWith("OK:")?n(a.slice(3)):r(new Error(a.startsWith("ERROR:")?a.slice(6):"Unknown error"))});o.stdin.write(e),o.stdin.end()})}async function Tn(e,t,n={}){if(On())return Promise.resolve(oc());let r=n.timeoutMs??Uh;if(Ht()){let a=await Zn(),c=["sign",e];t&&c.push(t);let l;try{l=(await Ve(a,c,{timeout:r})).stdout}catch(d){throw Pu(d)?Ou(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 o=await Fi();if(!o)throw new Error("Attestation key not found. Run setup to generate a new key.");let s=await ji(),i=["sign",e];return t&&i.push(t),new Promise((a,c)=>{let l=(0,Jo.execFile)(s,i,{timeout:r},(u,d)=>{let p=(d||"").trim();if(u){p.startsWith("ERROR:")?c(new Error(p.slice(6))):Pu(u)?c(Ou(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(o),l.stdin.end()})}async function Zo(){if(Ht()){try{let e=await Zn();await Ve(e,["delete-key"],{timeout:1e4})}catch{}return}try{await Ve("security",["delete-generic-password","-s",Wo,"-a",zo],{timeout:5e3})}catch{}try{await Vu(["delete-key"])}catch{}}var Kh=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],Gh=[...Kh.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 qi(e,t=Gh){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=Vi(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(Vi(r.match.provider)))&&r.match.keywords.every(o=>n.includes(Vi(o))))return r.targetToolId;return null}function Vi(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}var Ur={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 Gt(e,t,n){if(!Hu(e))return Yh(e,n);let r=Bu[e];if(!r)return e;let o=Object.keys(r.tiers),s=t||o[0],i=Xh(e,s,n);return i||Zh(e,r,s,o)}function Yh(e,t){return qi({requestedTool:e,intentText:t})??e}function Xh(e,t,n){return qi({requestedTool:e,metaTool:e,tier:t,intentText:n})}function Zh(e,t,n,r){let o=t.tiers[n];if(!o)throw new Error(`Unknown tier '${n}' for ${e}. Valid tiers: ${r.join(", ")}`);return o.toolId}var Bu=Ur;function Hu(e){return e in Bu}var Dr=Object.keys(Ur);function Bi(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function Ku(e=process.env){return Bi(e)!==null}function Gu(e=process.env){let t=(e.VISA_CLI_PARENTLESS_SINGLE_CALL??"").trim().toLowerCase();return t==="true"||t==="1"}function Wu(e=process.env){let t=(e.VISA_CLI_PARENTLESS_BATCH??"").trim().toLowerCase();return t==="true"||t==="1"}var Rd=require("child_process"),pe=T(require("crypto")),Ke=T(require("fs")),Kr=T(require("os")),hs=T(require("path"));function st(e,t={}){if(!e||typeof e!="object")return e;let n=e,r=t.tag??(typeof n.merchantName=="string"?n.merchantName:"media"),o=n.content?.[0]?.text,s=typeof o=="string"?Mn(o):null,i=Array.isArray(n.urls)?n.urls[0]:void 0,c=typeof i=="string"&&i.startsWith("data:")?Mn(i):null;if(!s&&!c)return e;let l=s??c,u=s?"content":"urls",d;try{d=mr(l,{tag:Qh(r,n)})}catch(m){return{...n,_inline_media_warning:`Failed to persist inline media to disk: ${m instanceof Error?m.message:String(m)}`}}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 Qh(e,t){let n=typeof t.transactionId=="string"?t.transactionId:typeof t.transaction_id=="string"?t.transaction_id:null;return n?`${e}-${n}`:e}var zu=!1;async function Qn(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")||!ie())throw r;if(f.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(zu)throw f.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;zu=!0,f.info("attestation:starting-browser-recovery");try{let s=await n();if(!s.success)throw f.error("attestation:browser-recovery-failed",{message:s.message}),r;let i=await Yo();return await e.registerAttestationKey(i),await e.setBiometricPreference({required:!0}),f.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),f.info("attestation:key-reregistered-after-recovery"),await t()}catch(s){throw f.error("attestation:recovery-failure",{error:s.message}),r}}throw r}}function it(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}async function Qo(e,t){if(!ie())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 Xo())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 it(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."}}var Ju="3.0.0";function Hi(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function es(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 o=Lo(t);return o!==void 0?{value:o,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function Re(e){return e==null?"\u2014":e?"yes":"no"}function ts(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function ey(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function ty(){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=xi("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:wi,source:{kind:"default"}}}async function jr(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(_){n=_?.message||"unknown error"}let r=[],o=process.env.VISA_AUTH_URL,s=Si("auth.serverUrl"),i=Ee(),a=o!==void 0&&o!==""?{kind:"env",var:"VISA_AUTH_URL"}:s!==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:Re(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:Re(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:Re(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:ie(),formatted:Re(ie()),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:ts(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:ts(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:ts(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:ts(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(_=>_.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 m=ty();r.push({key:"credit.sessionCapCents",value:m.value,formatted:ey(m.value),source:m.source});let g=Ll();g.length>0&&r.push({key:"settings.retired",value:g.map(_=>_.key),formatted:g.map(_=>_.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${g.map(_=>`visa-cli config unset ${_.key}`).join(" && ")}`});let y=es("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:y.value,formatted:Re(y.value),source:y.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let w=es("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:w.value,formatted:Re(w.value),source:w.source});let N=tt(),U;process.env.VISA_CLI_NO_UPDATE_CHECK?U={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?U={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?U={kind:"env",var:"NODE_ENV"}:U={kind:"default"},r.push({key:"ui.updateCheck",value:!N,formatted:Re(!N),source:U});let v=es("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:v.value,formatted:Re(v.value),source:v.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let x=es("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:x.value,formatted:Re(x.value),source:x.source});let $=process.env.VISA_DRY_RUN,O=Ku();if(r.push({key:"tools.dryRun",value:O,formatted:Re(O),source:$===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:Ju,formatted:Ju,source:{kind:"default"}}),e.includeDev){let _=process.env.VISA_MOCK_KEYCHAIN,C=Et();r.push({key:"dev.mockKeychain",value:C,formatted:Re(C),source:Hi("VISA_MOCK_KEYCHAIN",!!_),hint:Ns()});let he=process.env.VISA_MOCK_TOUCHID,ye=On();r.push({key:"dev.mockTouchid",value:ye,formatted:Re(ye),source:Hi("VISA_MOCK_TOUCHID",!!he),hint:Ns()});let Y=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!Y,formatted:Re(!!Y),source:Hi("VISA_CLI_DEBUG",!!Y)})}return{entries:r,statusError:n}}function ny(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 Yu(e,t={}){if(e.length===0)return"";let n=Math.max(...e.map(s=>s.key.length)),r=Math.max(...e.map(s=>s.formatted.length)),o=[];for(let s of e){let i=s.key.padEnd(n+2),a=s.formatted.padEnd(r+2);o.push(`${i}${a}(${ny(s.source)})`),t.verbose&&s.hint&&o.push(` ${"\u21B3".padStart(n)} ${s.hint}`)}return o.join(`
137
- `)}function Xu(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 Zu(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"}]}}}var Wt=require("fs"),ed=require("os"),Ki=require("path"),ry=(0,Ki.join)((0,ed.homedir)(),".visa-mcp"),Qu=(0,Ki.join)(ry,"mcp-session-budget.json");function ns(){try{(0,Wt.existsSync)(Qu)&&(0,Wt.unlinkSync)(Qu)}catch{}}var Wi=require("crypto"),Be=T(Fr()),En=null,Ie=0,er=0,Te=0,zt=null,zi=null,Ji=null,os=Promise.resolve();function wy(e){return Number((0,Be.fromCents)(e))}function rd(e){return(0,Be.toCents)((0,Be.micros)(BigInt(e)))}function nd(e){return(0,Be.toWire)((0,Be.fromCents)(e))}function Gi(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function rs(e){return typeof e=="string"&&/^\d+$/.test(e)}var Sy=43,xy=new RegExp(`^[A-Za-z0-9_-]{${Sy}}$`);function ky(e){return typeof e=="string"&&xy.test(e)}function Cy(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||En&&e.session_id!==En||typeof e.nonce!="string"||e.nonce.length===0||!ky(e.server_signature)||!Gi(e.cumulative)||!Gi(e.remaining)||!Gi(e.delta)||e.cumulative<Ie||Te>0&&e.cumulative>Te||Te>0&&e.remaining>Te||e.cumulative_micros!==void 0&&!rs(e.cumulative_micros)||e.remaining_micros!==void 0&&!rs(e.remaining_micros)||e.delta_micros!==void 0&&!rs(e.delta_micros)||e.reserved_micros!==void 0&&!rs(e.reserved_micros))}function kt(e){En=e,Ie=0,er=0,Te=0,zt=null,zi=null,Ji=null,os=Promise.resolve()}function Vr(e){Te=Math.max(0,Math.floor(e))}function Yi(){return En}function Xi(e){if(!En)return null;let t=Ie+er;return Te>0&&t>Te&&(t=Te),{session_budget_id:En,cumulative_micros:wy(t),nonce:(0,Wi.randomUUID)(),idempotency_key:e||(0,Wi.randomUUID)()}}function qr(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 Cy(r)?(Ie=Math.max(Ie,r.cumulative),er=0,zt=r,r):null}function od(){return zt}function Zi(e){let t=rd(e.cumulative_micros);Ie=Math.max(Ie,t),er=0;let n={status:"accepted",session_id:e.session_budget_id,cumulative:Ie,remaining:Math.max(0,Te-Ie),delta:0,cumulative_micros:nd(Ie),remaining_micros:nd(Math.max(0,Te-Ie)),delta_micros:"0",nonce:e.nonce};return zt=n,n}function Br(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,Be.toCents)((0,Be.micros)(n));if(!Number.isFinite(r)||r<0)return;zi=t;let o=e,s=typeof o.session_id=="string"?o.session_id:En??"";zt?(typeof o.remaining_micros=="string"&&/^\d+$/.test(o.remaining_micros)&&(zt.remaining_micros=o.remaining_micros),typeof o.charged_micros=="string"&&/^\d+$/.test(o.charged_micros)&&(zt.delta_micros=o.charged_micros)):zt={session_id:s,cumulative:r,remaining:0,delta:0,nonce:typeof o.transaction_id=="string"?o.transaction_id:"",remaining_micros:typeof o.remaining_micros=="string"&&/^\d+$/.test(o.remaining_micros)?o.remaining_micros:void 0,delta_micros:typeof o.charged_micros=="string"&&/^\d+$/.test(o.charged_micros)?o.charged_micros:void 0}}function sd(e){let t=e.receipt??null;Ji={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:rd(e.voucher.cumulative_micros),estimatedCumulativeCents:ss(),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 id(){return Ji}function ad(){return Ie}function cd(){return zi}function ss(){let e=Ie+er;return Te>0&&e>Te&&(e=Te),e}function ld(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return os=os.then(()=>{er+=t}),os}var Ty=10,Ey=1,ee=null,ud=Promise.resolve();function Qi(e){let t=ud.catch(()=>{}).then(e);return ud=t.then(()=>{},()=>{}),t}var me=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 ea(e,t,n){return Qi(()=>dd(e,t,n))}async function dd(e,t,n){if(ns(),ee&&new Date(ee.expiresAt).getTime()>Date.now())return Yi()!==ee.budgetId&&(kt(ee.budgetId),Vr(ee.totalCents)),f.info("mcp-session:active-hit",{budgetId:ee.budgetId,tool:n.toolName,remainingEstimatedCents:ee.totalCents-ss()}),{budgetId:ee.budgetId,isFresh:!1,totalCents:ee.totalCents,requestedCapCents:ee.totalCents,appliedCapCents:ee.totalCents,clampedReason:null};ee&&(ee=null,kt(null));let r=await e.getBalance();if(!r.success)throw new Error(`Could not read balance: ${r.error||"unknown error"}`);let o=n.sessionKind??"explicit",s=o==="one_shot"?Ey:Ty,i=Math.max(s,Math.ceil(n.minRequiredCents??s));if(r.balanceCents<i)throw new me(r.balanceCents,i);let a=n.capCentsOverride??jl(),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:o,...u?{attestation:u}:{}});if(!d.success||!d.budget){let m=d.error||"unknown error";throw new Error(`Failed to open credit session: ${m}`)}let p={budgetId:d.budget.id,expiresAt:d.budget.expiresAt,totalCents:d.budget.totalCents,createdAt:d.budget.createdAt};return ee=p,kt(p.budgetId),Vr(p.totalCents),f.info("mcp-session:opened",{budgetId:p.budgetId,capCents:p.totalCents,requestedCapCents:a,clampedReason:l,sessionKind:o,expiresAt:p.expiresAt,tool:n.toolName}),{budgetId:p.budgetId,isFresh:!0,totalCents:p.totalCents,requestedCapCents:a,appliedCapCents:p.totalCents,clampedReason:l}}async function md(e,t,n){return Qi(async()=>{let o=Jt()?await pd(e):null,s=await dd(e,t,n);return{budgetId:s.budgetId,totalCents:s.totalCents,closedPrevious:o,requestedCapCents:s.requestedCapCents,appliedCapCents:s.appliedCapCents,clampedReason:s.clampedReason}})}async function pd(e){let n=Jt()?.budgetId??Yi(),r=!1,o,s;if(n)try{let i=await e.closeSession(n);r=!!i?.success,typeof i?.finalCumulativeCents=="number"&&(o=i.finalCumulativeCents),typeof i?.finalCumulativeMicros=="string"&&(s=i.finalCumulativeMicros)}catch(i){f.warn("mcp-session:close-server-failed",{budgetId:n,error:i?.message||String(i)})}return ns(),ee=null,kt(null),{closedServerSide:r,budgetId:n,finalCumulativeCents:o,finalCumulativeMicros:s}}async function is(e){return Qi(()=>pd(e))}function Jt(){return ns(),ee?new Date(ee.expiresAt).getTime()<=Date.now()?(ee=null,kt(null),null):{budgetId:ee.budgetId,totalCents:ee.totalCents,lastReceiptCumulative:ad(),lastReceiptCumulativeMicros:od()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:cd(),estimatedCumulative:ss(),lastToolSpend:id(),expiresAt:ee.expiresAt}:null}var gd=T(Fr()),fd=10000n;function Ay(e){return e<=0n?0:Number((e+fd-1n)/fd)}function hd(e){return Ay((0,gd.fromUsd)(e))}var as=T(Fr()),Ry=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;function cs(e){if(typeof e!="string"||!Ry.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 o=Number(r);return o<=0?{ok:!1,error:"amount must be greater than $0.00"}:{ok:!0,cents:o,displayUsd:(0,as.toDisplay)((0,as.fromCents)(o),{symbol:""})}}var ls="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.",yd="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.";var _d=Promise.resolve(),bd=!1;function ys(e){let t=_d.catch(()=>{}).then(e);return _d=t.then(()=>{},()=>{}),t}async function Id(e){let t=await fe(()=>ea(I,Ue,{toolName:e.toolId,userContext:e.userContext})),n=Xi(e.idempotencyKey);if(!n)throw new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await Uy(),o,s,i=async()=>I.shortcutWithSession(e.toolId,n,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);try{try{({data:o,voucherReceiptHeader:s}=await i())}catch(u){if(u instanceof gt){let d=Math.min(Math.max(u.retryAfterSecs,0),5)*1e3;f.warn("mcp-session:lock-contended-retrying",{tool:e.toolId,retryAfterSecs:u.retryAfterSecs}),await new Promise(p=>setTimeout(p,d)),{data:o,voucherReceiptHeader:s}=await i()}else throw u}}catch(u){if(u instanceof Fn){if(f.warn("mcp-session:server-invalidated-budget",{code:u.code,budgetId:u.budgetId??t.budgetId,tool:e.toolId}),await is(I),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 bd||(bd=!0,console.error(`[visa-cli] Your session was closed by another process; reopened automatically as pay-as-you-go.
138
- To require an explicit session approval instead, set VISA_REQUIRE_EXPLICIT_SESSION=true.`)),f.info("mcp-session:falling-back-to-payg",{code:u.code,tool:e.toolId}),$d(e)}throw u instanceof gt?(f.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=qr(s)??(n?Zi(n):null);if(Br(o?.receipt_v2),await ld(e.estimatedAmountCents),sd({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),ia(o))return st(o);let c=await sa();if(e.idempotencyKey&&aa(o,c,e.idempotencyKey))return st(o);let l=c?Hr(c):null;return st(ca(o,r,l))}function Le(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function ps(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(ps).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${ps(r)}`).join(",")}}`}function oa(e,t,n,r){let o=pe.createHash("sha256").update(`${n}:${ps(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${o}`}function Iy(e,t){return`${e}:${t}`}function $y(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 fs(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,o=He(r),s=o!==null?o.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=$y(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),c=i!=null?String(i):a;return{batch_id:e,item_id:Iy(e,t),index:t,...c!==void 0?{transaction_id:c}:{},...a!==void 0?{ledger_id:a}:{},...s?{amountMicros:s,amount_micros:s,cost_micros:s}:{}}}async function $d(e){return fe(()=>Oy(e))}async function Pd(e,t,n){if(ia(e))return st(e);let r=await sa();if(n&&aa(e,r,n))return st(e);let o=r?Hr(r):null;return st(ca(e,t,o))}async function Py(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 Ue("shortcut_call",t,e.toolId,n,e.userContext);f.info("parentless-single-call:attempt",{tool:e.toolId,approvedMaxCents:t,attested:!!r});let o=r?.nonce??(await I.getAttestationChallenge()).nonce,{data:s,voucherReceiptHeader:i}=await I.shortcutParentless(e.toolId,{...r?{attestation:r}:{},nonce:o,approved_max_cents:t,idempotency_key:e.idempotencyKey},e.toolParams,e.timeoutMs,e.userContext,e.metaTool);return qr(i),Br(s?.receipt_v2),f.info("parentless-single-call:completed",{tool:e.toolId}),Pd(s,e.beforeBalanceMicros,e.idempotencyKey)}async function Oy(e){let t=Math.max(1,Math.ceil(e.estimatedAmountCents)),n=await I.getBalance();if(!n.success)throw new Error(`Could not read balance: ${n.error||"unknown error"}`);if(n.balanceCents<t)throw new me(n.balanceCents,t);let r=t,o=Hr(n);if(Gu()){let l=e.idempotencyKey??pe.randomUUID();try{return await Py({toolId:e.toolId,toolParams:e.toolParams,estimatedAmountCents:e.estimatedAmountCents,cap:r,beforeBalanceMicros:o,userContext:e.userContext,metaTool:e.metaTool,timeoutMs:e.timeoutMs,idempotencyKey:l})}catch(u){if(u instanceof Qe)f.info("parentless-single-call:falling-back-to-session",{tool:e.toolId,status:u.status,serverErrorCode:u.serverErrorCode});else throw u}}let s=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(r/100).toFixed(2)})`,i=await Ue("session_create",r,"Visa CLI Session",s,e.userContext),a=await I.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;kt(c),Vr(a.budget.totalCents),f.info("on-demand-session:opened",{budgetId:c,capCents:a.budget.totalCents,tool:e.toolId});try{let l=Xi(e.idempotencyKey);if(!l)throw new Error(`Internal: mintVoucher returned null after on-demand session-open ${c}`);let{data:u,voucherReceiptHeader:d}=await I.shortcutWithSession(e.toolId,l,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(qr(d)||Zi(l),Br(u?.receipt_v2),ia(u))return st(u);let p=await sa();if(e.idempotencyKey&&aa(u,p,e.idempotencyKey))return st(u);let m=p?Hr(p):null;return st(ca(u,o,m))}finally{try{await I.closeSession(c)}catch(l){f.warn("on-demand-session:close-failed",{budgetId:c,error:l?.message||String(l)})}kt(null),f.info("on-demand-session:closed",{budgetId:c,tool:e.toolId})}}async function Xt(e){return ys(async()=>Jt()?Id(e):$d(e))}function _s(){return Ee()}var I=new Ae(()=>V.getSessionToken());function He(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function Hr(e){return He(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function My(e){if(e<0n&&(e=0n),e>=1000000n){let r=(e+5000n)/10000n,o=r/100n,s=r%100n;return`$${o.toString()}.${s.toString().padStart(2,"0")}`}let t=e%1000000n;return t===0n?"$0.00":`$0.${t.toString().padStart(6,"0").replace(/0+$/,"")}`}function Ny(e){let t=He(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=He(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=He(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function us(e,t="INVALID_TOOL_PARAMS",n){return{success:!1,error_code:t,code:t,error:e,message:e,...n??{}}}function Ly(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 Uy(){try{let e=await I.getBalance();return e.success?Hr(e):null}catch{return null}}async function sa(){try{let e=await I.getBalance();return e.success?e:null}catch{return null}}function ia(e){if(!e||e.success===!1)return!1;let t=He(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=He(e.amountMicros??e.amount_micros??e.charged_micros),r=t??n;if(r===null||r<=0n)return!1;let o=r.toString();return e.amountMicros??=o,e.amount_micros??=o,e.charged_micros??=o,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),!0}function aa(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 o=He(r.deltaMicros)??BigInt(r.deltaCents)*10000n,s=o<0n?-o:o;if(s<=0n)return!1;let i=s.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(s)/1e6),!0}function ca(e,t,n){if(!e||e.success===!1||t===null||n===null)return e;let r=t-n;if(r<=0n)return e;let o=r.toString();return e.amountMicros??=o,e.amount_micros??=o,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),e}var Dy="3.0.0",Ix=["","","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(`
139
- `);function Ge(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=yr(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(Ul())return{opened:!1,url:t,blockedReason:"suppressed"};let n=zs();if(n.headless)return f.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let r=bc(t,_s());if(!r)return f.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let o=wc(r);return o?((0,Rd.execFile)(o.cmd,o.args,s=>{s&&f.warn(`Browser open failed: ${s.message}. URL: ${r}`)}),{opened:!0,url:r}):(f.info(`No browser command for platform "${Kr.platform()}". URL: ${r}`),{opened:!1,url:r,blockedReason:"unsupported_platform"})}async function fe(e){return Qn(I,e,Fd)}var Od="get_cards",Md="set_default_card";function jy(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 '${Od}' to see enrolled cards and '${Md}' to switch, then retry the original request.`}function Fy(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 '${Od}' to see enrolled cards and '${Md}' to switch. Do not retry automatically.`}function We(e,t){let n=e.retryable?jy(e.code,e.retryAfter):Fy(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 Vy(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 tr=null,qy=3e4;function Nd(){tr=null}var Yt=class extends Error{constructor(n){super(`${gs()} attestation is required for this action, but it is not available in this MCP process. `+la());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function bs(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. `+la()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function By(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:ls,agent_guidance:yd}}function gs(){return process.platform==="darwin"?"Touch ID":"local biometric"}function la(){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 Hy(e){let t=Date.now();if(tr&&tr.expiresAt>t)return{required:tr.required,hasRegisteredKey:tr.hasRegisteredKey};try{let n=await I.getStatus(e),r=n.attestationRequired!==!1,o=it(n);return tr={required:r,hasRegisteredKey:o,expiresAt:t+qy},{required:r,hasRegisteredKey:o}}catch{return{required:!0,hasRegisteredKey:!0}}}async function Ue(e,t,n,r,o,s){if(!s?.forceRequired){let i=await Hy(o);if(!i.required){f.info("attestation:skipped-by-server-policy",{context:e});return}if(!i.hasRegisteredKey){f.info("attestation:skipped-no-registered-key",{context:e});return}}if(!ie())throw f.warn("attestation:unavailable",{context:e}),new Yt(e);f.info("attestation:attempt",{context:e,amount:t,merchant:n});try{let{nonce:i}=await I.getAttestationChallenge(),a=Buffer.from(JSON.stringify({nonce:i,amount:t,merchant:n,context:e})).toString("base64");f.info("touchid:prompt",{context:e,amount:t,merchant:n});let c=await Tn(a,r);return f.info("attestation:success",{context:e,amount:t,merchant:n}),{signature:c,nonce:i,amount:t,merchant:n}}catch(i){throw f.error("attestation:failure",{context:e,amount:t,merchant:n,error:i.message}),i}}var vd="[dry-run] https://placeholder.visa-cli.dev/image.png",Ky=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"]),Gy=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 Wy(e,t){return t==="run_llm"||e.startsWith("or-")?"llm":t==="generate_image"||Ky.has(e)?"image":t==="generate_video"||Gy.has(e)?"video":zy(e)?"media":null}function zy(e){let t=Xn(e);return t?!da(t):!1}function Jy(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function Yy(e){return e==="llm"?"OpenRouter":"fal.ai"}function nr(e,t,n,r){let o={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:Yy(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${Jy(n)}`;return{...o,content:i,data:{content:i,model:t,dry_run:!0}}}return{...o,urls:[vd],data:{[e==="video"?"videoUrl":e==="image"?"imageUrl":"url"]:vd,metadata:{dry_run:!0}}}}async function ta(e){let t=e.mode??"mock",n=t==="preflight"?"/v1/telemetry/preflight":"/v1/telemetry/dry-run",r=t==="preflight"?"preflight":null;try{await I.emitTelemetry([{id:pe.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(o){f.warn("dry_run:telemetry_failed",{tool:e.toolName,error:o?.message||String(o),mode:t})}}var Xy="https://openrouter.ai/api/v1/chat/completions",Zy="openrouter/free",Qy=50,e_=15e3;function t_(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 n_(e,t,n){let r=process.env.OPENROUTER_API_KEY;if(!r)return f.warn("preflight:no_openrouter_key_falling_back_to_mock",{tool:e}),{result:nr("llm",e,t,n),degraded:!0,resolvedModel:null};let o=t_(t),s;try{s=await Ze(Xy,{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:Zy,messages:[{role:"user",content:o}],max_tokens:Qy}),timeoutMs:e_})}catch(u){return f.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:nr("llm",e,t,n),degraded:!0,resolvedModel:null}}if(!s.ok){let u=await s.text().catch(()=>"");return f.warn("preflight:openrouter_http_error_falling_back_to_mock",{tool:e,status:s.status,bodyExcerpt:u.slice(0,200)}),{result:nr("llm",e,t,n),degraded:!0,resolvedModel:null}}let i;try{i=await s.json()}catch(u){return f.warn("preflight:openrouter_invalid_json_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:nr("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 Gr(e,t,n,r){let o=Bi();if(!o)return null;let s=Wy(e,r);if(!s)return null;let i=Date.now();if(o==="mock"){let l=nr(s,e,t,r);return await ta({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:l,userContext:n,startedAt:i,mode:"mock"}),f.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:s,mode:o}),l}if(s!=="llm"){f.warn("preflight:not_supported_for_kind_falling_back_to_mock",{tool:e,kind:s});let l=nr(s,e,t,r);return await ta({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 n_(e,t,r);return await ta({toolName:r??e,resolvedModel:c??(r&&r!==e?e:null),toolParams:t,result:a,userContext:n,startedAt:i,mode:"preflight"}),f.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:s,mode:o}),a}async function Ct(e,t,n){let r=await I.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 Tt(e){return hd(e.amount)}function r_(e,t,n){return n.has(e.resolvedTool)?0:Math.max(1,Tt(t[e.resolvedTool]))}function o_(){return hs.join(Kr.homedir(),".visa-mcp","allium-results")}var $x=16*1024,Px=50*1024*1024;function s_(){let e=o_();try{if(!Ke.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=Ke.readdirSync(e),n=0,r=0;for(let o of t)try{let s=Ke.statSync(hs.join(e,o));s.isFile()&&(n+=s.size,r++)}catch{}return{file_count:r,size_bytes:n,path:e}}catch(t){return f.warn("allium:disk_usage_error",{error:t.message}),{file_count:0,size_bytes:0,path:e}}}var wd=3600*1e3,na=0;function i_(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function Wr(e){if(!Dl()&&!(Date.now()<na))try{if(!await V.getSessionToken())return;await I.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}}),f.info("feed:submitted",{tool:e.tool,mediaType:e.mediaType,transactionId:e.transactionId})}catch(t){if(i_(t)){let n=na===0;na=Date.now()+wd,n&&f.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:wd});return}f.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function a_(e,t){let n=(e.state||"").trim().toUpperCase(),r=(e.county||"").trim(),o=(e.start_date||"").trim(),s=(e.end_date||o).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(o))throw new Error('start_date must be YYYY-MM (e.g. "2025-08").');if(s&&!/^\d{4}-\d{2}$/.test(s))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})`;f.info("payment:attempt",{tool:"get_visa_smi",amount:a,merchant:i});try{return await fe(async()=>{let l=await Ue("get_visa_smi",a,i,c),u=await I.getVisaSmi({state:n,county:r,start_date:o,end_date:s,attestation:l,idempotencyKey:pe.randomUUID()},t);return u.success?f.info("payment:success",{tool:"get_visa_smi",merchant:i,charged_cents:u.charged_cents}):f.warn("payment:declined",{tool:"get_visa_smi",merchant:i,message:u.error}),u})}catch(l){if(l instanceof oe)return f.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:l.code,retryable:l.retryable}),We(l,{amount:a,merchantName:i,description:"Visa SMI data"});throw f.error("payment:failure",{tool:"get_visa_smi",merchant:i,error:l.message}),l}}async function c_(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 Gr("generate_image_card",e,t);if(n)return n;let r=await Ct("generate_image_card",void 0,t),o=pe.randomUUID();f.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await fe(async()=>{let s;try{s=await Xt({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:Tt(r),userContext:t,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof me)return Le(i);throw i}return f.info("payment:success",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Ge(i)),Wr({prompt:e.prompt,tool:"generate_image_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):f.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof oe)return f.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),We(s,r);throw f.error("payment:failure",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function l_(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 Gr("generate_image_fast_card",e,t);if(n)return n;let r=await Ct("generate_image_fast_card",void 0,t),o=pe.randomUUID();f.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await fe(async()=>{let s;try{s=await Xt({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:Tt(r),userContext:t,timeoutMs:6e4,idempotencyKey:o})}catch(i){if(i instanceof me)return Le(i);throw i}return f.info("payment:success",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Ge(i)),Wr({prompt:e.prompt,tool:"generate_image_fast_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):f.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof oe)return f.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),We(s,r);throw f.error("payment:failure",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function u_(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 Gr("generate_video_tempo_card",e,t);if(n)return n;let r=await Ct("generate_video_tempo_card",void 0,t),o=pe.randomUUID();f.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await fe(async()=>{let s;try{s=await Xt({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:Tt(r),userContext:t,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof me)return Le(i);throw i}return f.info("payment:success",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Ge(i)),Wr({prompt:e.prompt,tool:"generate_video_tempo_card",mediaUrl:s.urls[0],mediaType:"video",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):f.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof oe)return f.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),We(s,r);throw f.error("payment:failure",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function d_(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 Ct("generate_music_tempo_card",void 0,t),r=pe.randomUUID();f.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await fe(async()=>{let o;try{o=await Xt({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:Tt(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(s){if(s instanceof me)return Le(s);throw s}return f.info("payment:success",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),o.urls?.length&&o.status!=="processing"?(o.urls.forEach(s=>Ge(s)),Wr({prompt:e.prompt,tool:"generate_music_tempo_card",mediaUrl:o.urls[0],mediaType:"audio",cost:o.amount??n.amount,transactionId:o.transactionId,userContext:t})):o.urls?.length&&o.status==="processing"?(o._preliminary_urls=o.urls,delete o.urls,f.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):f.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof oe)return f.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),We(o,n);throw f.error("payment:failure",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}async function m_(e,t){let n=await Ct("check_music_status_tempo_card",void 0,t),r=pe.randomUUID();f.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await fe(async()=>{let o;try{o=await Xt({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:Tt(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof me)return Le(s);throw s}return f.info("payment:success",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),o.urls?.length&&o.urls.forEach(s=>Ge(s)),o})}catch(o){if(o instanceof oe)return f.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),We(o,n);throw f.error("payment:failure",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}async function p_(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 Ct("query_onchain_prices",void 0,t),r=pe.randomUUID();f.info("payment:attempt",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName});try{return await fe(async()=>{let o;try{o=await Xt({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:Tt(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof me)return Le(s);throw s}if(f.info("payment:success",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,mode:"session"}),Array.isArray(o?.data))o.data=o.data.map(s=>{if("mint"in s&&!("address"in s)){let{mint:i,...a}=s;return{address:i,...a}}return s});else if(o&&"mint"in o&&!("address"in o)){let{mint:s,...i}=o;return{address:s,...i}}return o})}catch(o){if(o instanceof oe)return f.warn("payment:declined",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),We(o,n);throw f.error("payment:failure",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}var f_=["generate_music_tempo_card"],ds=10,Sd=5,xd=new Map;function kd(e){let t=xd.get(e);if(t!==void 0)return t;let r=Xn(e)?.isAsync===!0||f_.includes(e);return xd.set(e,r),r}var g_=36e4,h_=18e4,y_=15e3,__=12e4,b_=2e3;function ra(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}function v_(e,t){return pe.createHash("sha256").update(`${e}:${ps(t)}`).digest("hex")}function w_(e){let{results:t,batchId:n,index:r,item:o,itemResult:s,preview:i,isFree:a,catalogName:c}=e;a&&s&&typeof s=="object"&&!Array.isArray(s)&&s.merchantName==null&&(s.merchantName=c??o.resolvedTool),t.push({success:s?.success!==!1,tool:o.resolvedTool,...s,...fs(n,r,s)});let l=0,u=0n;if(s?.success!==!1){let d=He(s?.amountMicros??s?.amount_micros),p=typeof s?.amount=="number"?s.amount:i?.amount??0;d!==null&&d>0n?u+=d:u+=BigInt(Math.round(p*1e6)),l+=p}return s?.urls&&s.urls.forEach(d=>Ge(d)),{deltaCharged:l,deltaMicros:u}}function S_(e){let{results:t,resolvedItems:n,uniqueTools:r,isHomogeneous:o,primaryTool:s,merchantNames:i,totalAmount:a,totalCharged:c,totalChargedMicros:l,batchId:u,mode:d}=e,p=t.filter(N=>N?.success===!1).length,m=t.length-p,g=t.flatMap(N=>Array.isArray(N?.urls)?N.urls:[]),y=l>0n?Number(l)/1e6:Math.round((c+Number.EPSILON)*100)/100,w=m===0?"failure":p===0?"success":"partial";return f.info("payment:success",{tool:"batch",batchTool:s,count:n.length,totalAmount:a,totalCharged:y,merchant:i,successCount:m,failedCount:p,outcome:w,mode:d,batchId:u}),{success:m>0,outcome:w,batch_id:u,tool:o?r[0]:s,count:n.length,successCount:m,failedCount:p,totalCharged:y,...l>0n?{totalChargedMicros:l.toString(),amountMicros:l.toString(),amount_micros:l.toString()}:{},merchantName:i,results:t,...g.length?{urls:g}:{}}}async function x_(e){let{resolvedItems:t,previews:n,freeTools:r,catalogEntries:o,itemCeilingCents:s,batchCeilingCents:i,uniqueTools:a,isHomogeneous:c,primaryTool:l,merchantNames:u,totalAmount:d,timeoutMs:p,batchId:m,userContext:g}=e,y=i,w=await I.getBalance();if(!w.success)throw new Error(`Could not read balance: ${w.error||"unknown error"}`);if(w.balanceCents<y)throw new me(w.balanceCents,y);let N=`batch-${m}`,U=`spend up to $${(y/100).toFixed(2)} across a batch of ${t.length}`,{batchParentId:v}=await fe(async()=>{let _=await Ue("batch_open",y,N,U,g,{forceRequired:!0}),C=_?.nonce??(await I.getAttestationChallenge()).nonce;f.info("parentless-batch:open-attempt",{batchTool:l,count:t.length,approvedTotalCents:y,attested:!!_});let{batch_parent_id:he}=await I.batchOpen({..._?{attestation:_}:{},nonce:C,approved_total_cents:y,batch_id:m});return{batchParentId:he}});f.info("parentless-batch:opened",{batchTool:l,count:t.length,batchParentId:v});let x=[],$=0,O=0n;try{for(let _=0;_<t.length;_+=1){let C=t[_],he=n[C.resolvedTool],ye=r.has(C.resolvedTool);try{let Y;if(ye)Y=await I.shortcut(C.resolvedTool,C.params,p,g,"batch");else{let{data:ne,voucherReceiptHeader:cr}=await I.shortcutParentlessBatchItem(C.resolvedTool,{batch_parent_id:v,batch_id:m,batch_index:_,batch_request_hash:v_(C.resolvedTool,C.params),item_ceiling_cents:s[_],idempotency_key:oa(m,_,C.resolvedTool,C.params)},C.params,p,g,"batch");qr(cr),Br(ne?.receipt_v2),Y=await Pd(ne,null,oa(m,_,C.resolvedTool,C.params))}let{deltaCharged:Qt,deltaMicros:le}=w_({results:x,batchId:m,index:_,item:C,itemResult:Y,preview:he,isFree:ye,catalogName:o[C.resolvedTool]?.name});$+=Qt,O+=le}catch(Y){if(Y instanceof me&&x.length===0)return Le(Y);f.warn("payment:batch-item-failed",{tool:C.resolvedTool,index:_,error:Y?.message||String(Y)}),x.push({success:!1,tool:C.resolvedTool,...fs(m,_),error:Y?.message||String(Y)})}}return S_({results:x,resolvedItems:t,uniqueTools:a,isHomogeneous:c,primaryTool:l,merchantNames:u,totalAmount:d,totalCharged:$,totalChargedMicros:O,batchId:m,mode:"parentless"})}catch(_){if(_ instanceof oe)return f.warn("payment:declined",{tool:"batch",batchTool:l,count:t.length,totalAmount:d,merchant:u,code:_.code,retryable:_.retryable}),We(_,{amount:d,merchantName:u});throw f.error("payment:failure",{tool:"batch",batchTool:l,count:t.length,totalAmount:d,merchant:u,error:_.message}),_}}async function k_(e,t){let n;if(e.requests?.some(_=>_.tool||_.tool_id)&&e.requests)n=e.requests.map(_=>{let C=_.tool||_.tool_id||e.tool;if(!C)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let he=Gt(C,_.tier||e.tier,_.prompt??t),{tool:ye,tool_id:Y,tier:Qt,params:le,...ne}=_,cr=le&&typeof le=="object"?{...le,...ne}:ne;return{resolvedTool:he,params:cr}});else if(e.tool){let _=Gt(e.tool,e.tier,e.params?.prompt??t);if(e.count!==void 0){if(!Number.isSafeInteger(e.count)||e.count<1)return ra("BATCH_INVALID_COUNT","Batch count must be a positive integer.");if(e.count>ds)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${ds} items. Please split into smaller batches.`}}n=(e.requests||(e.count!==void 0&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(he=>({resolvedTool:_,params:he}))}else return ra("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return ra("BATCH_EMPTY","Batch requires at least one item.");if(n.length>ds)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${ds} items. Please split into smaller batches.`};if([...new Set(n.map(_=>_.resolvedTool))].some(kd)&&n.length>Sd)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${Sd} items. Please use multiple batches for more.`};let i=[...new Set(n.map(_=>_.resolvedTool))],a=i.length===1,c={};for(let _ of i)c[_]=await Vd(_);let l=new Set(i.filter(_=>c[_]&&da(c[_]))),u={};for(let _ of i)l.has(_)||(u[_]=await Ct(_,void 0,t));let d=0;for(let _ of n)d+=u[_.resolvedTool]?.amount??0;let p=n.map(_=>r_(_,u,l)),m=p.reduce((_,C)=>_+C,0),g=[...new Set([...Object.values(u).map(_=>_.merchantName),...i.filter(_=>l.has(_)).map(_=>c[_]?.name??_)])].join(", "),y=a?i[0]:"mixed";f.info("payment:attempt",{tool:"batch",batchTool:y,count:n.length,totalAmount:d,merchant:g,heterogeneous:!a});let w=n.some(_=>kd(_.resolvedTool)),N=n.some(_=>_.resolvedTool.startsWith("or-")||_.resolvedTool==="run_llm"||_.resolvedTool==="execute_tool"),U=w?g_:N?h_+n.length*y_:__+n.length*b_,v=pe.randomUUID(),x=[],$=0,O=0n;return ys(async()=>{let _=!Jt();if(Wu()&&_&&m>0)try{return await x_({resolvedItems:n,previews:u,freeTools:l,catalogEntries:c,itemCeilingCents:p,batchCeilingCents:m,uniqueTools:i,isHomogeneous:a,primaryTool:y,merchantNames:g,totalAmount:d,timeoutMs:U,batchId:v,userContext:t})}catch(C){if(C instanceof Qe)f.info("parentless-batch:falling-back-to-session",{batchTool:y,count:n.length,status:C.status,serverErrorCode:C.serverErrorCode});else{if(C instanceof me)return Le(C);throw C}}if(_&&m>0)try{let C=m;await fe(()=>ea(I,Ue,{toolName:"batch",userContext:t,sessionKind:"one_shot",minRequiredCents:C,capCentsOverride:C}))}catch(C){return C instanceof me?Le(C):(f.warn("payment:batch-prewarm-failed",{batchTool:y,count:n.length,error:C?.message||String(C)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:C?.message||"Failed to authenticate batch session",tool:y,count:n.length,failedCount:n.length,results:[]})}try{for(let le=0;le<n.length;le+=1){let ne=n[le],cr=u[ne.resolvedTool];try{let Z=l.has(ne.resolvedTool)?await I.shortcut(ne.resolvedTool,ne.params,U,t,"batch"):await Id({toolId:ne.resolvedTool,toolParams:ne.params,estimatedAmountCents:p[le],userContext:t,metaTool:"batch",timeoutMs:U,idempotencyKey:oa(v,le,ne.resolvedTool,ne.params)});if(l.has(ne.resolvedTool)&&Z&&typeof Z=="object"&&!Array.isArray(Z)&&Z.merchantName==null&&(Z.merchantName=c[ne.resolvedTool]?.name??ne.resolvedTool),x.push({success:Z?.success!==!1,tool:ne.resolvedTool,...Z,...fs(v,le,Z)}),Z?.success!==!1){let lr=He(Z?.amountMicros??Z?.amount_micros),Wa=typeof Z?.amount=="number"?Z.amount:cr?.amount??0;lr!==null&&lr>0n?O+=lr:O+=BigInt(Math.round(Wa*1e6)),$+=Wa}Z?.urls&&Z.urls.forEach(lr=>Ge(lr))}catch(Z){if(Z instanceof me&&x.length===0)return Le(Z);f.warn("payment:batch-item-failed",{tool:ne.resolvedTool,index:le,error:Z?.message||String(Z)}),x.push({success:!1,tool:ne.resolvedTool,...fs(v,le),error:Z?.message||String(Z)})}}let C=x.filter(le=>le?.success===!1).length,he=x.length-C,ye=x.flatMap(le=>Array.isArray(le?.urls)?le.urls:[]),Y=O>0n?Number(O)/1e6:Math.round(($+Number.EPSILON)*100)/100,Qt=he===0?"failure":C===0?"success":"partial";return f.info("payment:success",{tool:"batch",batchTool:y,count:n.length,totalAmount:d,totalCharged:Y,merchant:g,successCount:he,failedCount:C,outcome:Qt,mode:"session",batchId:v}),{success:he>0,outcome:Qt,batch_id:v,tool:a?i[0]:y,count:n.length,successCount:he,failedCount:C,totalCharged:Y,...O>0n?{totalChargedMicros:O.toString(),amountMicros:O.toString(),amount_micros:O.toString()}:{},merchantName:g,results:x,...ye.length?{urls:ye}:{}}}catch(C){if(C instanceof oe)return f.warn("payment:declined",{tool:"batch",batchTool:y,count:n.length,totalAmount:d,merchant:g,code:C.code,retryable:C.retryable}),We(C,{amount:d,merchantName:g});throw f.error("payment:failure",{tool:"batch",batchTool:y,count:n.length,totalAmount:d,merchant:g,error:C.message}),C}finally{if(_){let C=await is(I);f.info("batch-session:closed",{budgetId:C.budgetId,closedServerSide:C.closedServerSide})}}})}function C_(){let e=!1,t;try{let r=hs.join(Kr.homedir(),".claude","settings.json");if(Ke.existsSync(r)){let o=JSON.parse(Ke.readFileSync(r,"utf-8")),s=typeof o.statusLine=="object"?o.statusLine.command:"";e=Nt(s)}}catch{}let n=wo();return n||(t="visa-cli config hud enable"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function T_(e){let[t,n]=await Promise.all([I.getStatus(e),I.getBalance().catch(s=>(f.warn("get_status:balance_fetch_failed",{error:s?.message||String(s)}),null))]);typeof t?.dailyRemaining=="number"&&(t.dailyRemaining=Math.round(t.dailyRemaining*100)/100);let r=s_();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=C_(),!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=Dy,Array.isArray(t.cards)&&(t.cards=t.cards.map(s=>({...s,displayName:ua(s)})),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.amountUsd=n.amountUsd);let o=Jt();if(t.sessionMode=!!o,o){let s=Math.max(0,o.totalCents-o.estimatedCumulative);t.activeSession={budgetId:o.budgetId,capCents:o.totalCents,capUsd:o.totalCents/100,lastReceiptCumulativeCents:o.lastReceiptCumulative,estimatedCumulativeCents:o.estimatedCumulative,spentCents:o.estimatedCumulative,spentUsd:o.estimatedCumulative/100,estimatedRemainingCents:s,estimatedRemainingUsd:s/100,...o.lastToolSpend?{lastToolSpend:{toolName:o.lastToolSpend.toolName,resolvedToolId:o.lastToolSpend.resolvedToolId,estimatedAmountCents:o.lastToolSpend.estimatedAmountCents,estimatedAmountUsd:o.lastToolSpend.estimatedAmountCents/100,voucherCumulativeCents:o.lastToolSpend.voucherCumulativeCents,estimatedCumulativeCents:o.lastToolSpend.estimatedCumulativeCents,receiptDeltaCents:o.lastToolSpend.receiptDeltaCents,receiptCumulativeCents:o.lastToolSpend.receiptCumulativeCents,receiptRemainingCents:o.lastToolSpend.receiptRemainingCents,recordedAt:o.lastToolSpend.recordedAt}}:{},expiresAt:o.expiresAt}}return t}function ua(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",o=e.isDefault===!0?" (default)":"";return`${n} ending in ${r}${o}`}async function Ld(e,t){try{let r=((await I.getStatus(t)).cards||[]).find(o=>o?.id===e);if(r)return ua(r)}catch(n){f.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function E_(e){let n=(await I.getStatus(e)).cards||[];return n.length===0?{cards:[],message:"No cards enrolled. Use the add_card tool to add a payment card."}:n.some(o=>!Number.isInteger(o?.id)||o.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(o=>({...o,displayName:ua(o)})),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 A_(e,t){return await I.getTransactions({limit:e.limit,offset:e.offset},t)}async function R_(e,t){return await I.feedback(e.message,e.transaction_id,t)}async function I_(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return An("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=cs(String(e.amount));if(n.ok===!1)return{success:!1,error:n.error};let r=n.cents,o=r/100,s=pe.randomUUID();f.info("buy_credits:attempt",{amountCents:r});try{return await fe(async()=>{let i=await Ue("balance-topup",o,"Visa CLI Balance",`top up balance with $${n.displayUsd}`,t,{forceRequired:!0}),a=await I.topupBalance({amount_cents:r,idempotency_key:s,attestation:i});if(a.success){f.info("buy_credits:success",{amountCents:r,balanceCents:a.balanceCents});let c=((a.balanceCents??0)/100).toFixed(2),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 f.warn("buy_credits:failed",{amountCents:r,error:a.error}),a})}catch(i){if(i instanceof Yt)return By();if(i instanceof et)return f.warn("buy_credits:ambiguous",{amountCents:r,code:i.code,transactionId:i.transactionId}),Vy(i);throw f.error("buy_credits:failure",{amountCents:r,error:i.message}),i}}function An(e,t){return{success:!1,error:t,code:e,message:t}}async function $_(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return An("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 An("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 An("INVALID_VALUE","dailyLimit must be at least $1");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return An("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");f.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await fe(async()=>{let n=await Ue("spending-controls",0,"","update spending controls"),r=await I.updateSpendingControls({maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit,confirm:!0,attestation:n},t);return f.info("spending_controls:success",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit}),r})}catch(n){if(f.error("spending_controls:failure",{error:n.message}),n instanceof Yt)return bs(n,"update_spending_controls");if(String(n?.message||n).includes("Attestation required"))return An("ATTESTATION_REQUIRED","Changing spending controls requires local attestation, even when payment biometric prompts are disabled.");throw n}}async function P_(e){let t=await jr({api:I,includeDev:!!e.includeDev});return{config:t.entries.map(n=>({key:n.key,value:n.value,source:n.source,hint:n.hint})),statusError:t.statusError}}async function O_(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."};f.info("config:set",{key:e.key});try{let t=Uo(e.key,e.value);return f.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 ht?"UNKNOWN_KEY":t instanceof yt?"SERVER_CONTROLLED":t instanceof Lt?"RETIRED_KEY":"INVALID_VALUE";return f.warn("config:set:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(Dt).sort()}}}async function M_(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."};f.info("config:unset",{key:e.key});try{let t=Do(e.key);return f.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 ht?"UNKNOWN_KEY":t instanceof yt?"SERVER_CONTROLLED":t instanceof Lt?"RETIRED_KEY":"INVALID_VALUE";return f.warn("config:unset:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(Dt).sort()}}}async function N_(e){let t=await I.getStatus(e),n=t.attestationRequired!==!1,r=it(t),o=ie(),s=n?r?o?`${gs()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${gs()} is not available in this process. ${la()}`:"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:o,platform:process.platform,effectiveRequiredOnThisDevice:n&&r&&o,canDisableFromThisDevice:!n||!r||o,message:s}}async function L_(e){f.info("biometric:on");let t=await Qo(I,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 I.setBiometricPreference({required:!0},e);return n.success?(Nd(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:n.error||"unknown error"}}async function U_(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return An("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.");f.info("biometric:off");try{return await fe(async()=>{let n=await I.getStatus(t),r;if(it(n)&&(r=await Ue("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${gs()} confirmation required to disable \u2014 not available on this device.`);let o=await I.setBiometricPreference({required:!1,attestation:r},t);if(!o.success)throw new Error(o.error||"unknown error");return Nd(),{success:!0,required:!1,message:"Touch ID is no longer required for payments."}})}catch(n){if(f.error("biometric:off:failure",{error:n.message}),n instanceof Yt)return bs(n,"biometric_off");throw n}}var Cd=3e4,D_=3e5;async function Ud(e,t,n="login"){let r=pe.randomUUID(),o=`${e}${e.includes("?")?"&":"?"}state=${r}`,s=Ge(o);return!s.opened&&s.blockedReason!=="non_internal_host"&&s.blockedReason!=="invalid_url"?Dd(o,s,n):s.opened?{...await jd(r,t,n),browserUrl:o}:{success:!1,browserUrl:o,message:`Could not open the browser URL safely. Please check the configured auth server and try again. URL: ${o}`}}function Dd(e,t,n){let r=n==="enrollment"?"card enrollment":n==="attestation-recovery"?"biometric reset":"login",o=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 ${o}. Open this URL to continue ${r}: ${e}`}}async function jd(e,t,n="login"){let r=Date.now()+D_;for(;Date.now()<r;)try{let s=await fetch(`${_s()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:Cd,...t&&{user_context:t}}),signal:AbortSignal.timeout(Cd+5e3)});if(!s.ok){await Pt(s,a=>{f.warn("auth_status:retry_after_http_error",{status:s.status,delayMs:a})});continue}let i=await s.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 f.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=Zu(a);if(n!=="enrollment"&&i.sessionToken){await V.saveSessionToken(i.sessionToken);let u=i.user||"",d=i.last4||"****";return f.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 f.info("auth:card_added",{last4:l,bonusCents:a}),{success:!0,message:`Card ending in ${l} enrolled and ready for payments.`,...c||{}}}}catch{await Pt(void 0,s=>{f.warn("auth_status:retry_after_network_error",{delayMs:s})})}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 Fd(e){let t=pe.randomUUID(),n;try{n=await I.startAttestationRecovery(t,e)}catch(s){return{success:!1,message:`Could not start biometric reset: ${s?.message||"unknown error"}`}}if(!n.success||!n.recoveryUrl)return{success:!1,message:n.error||"Could not start biometric reset. Please try again."};let r=Ge(n.recoveryUrl);return!r.opened&&r.blockedReason!=="non_internal_host"&&r.blockedReason!=="invalid_url"?Dd(n.recoveryUrl,r,"attestation-recovery"):r.opened?{...await jd(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 j_(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."};f.info("cards:remove_attempt",{cardId:n});let r=`remove-card:${n}`,o=`remove ${await Ld(n,t)}`;try{return await fe(async()=>{let s=await Ue(r,0,"",o,t,{forceRequired:!0}),i=await I.removeCard(n,{attestation:s},t);return f.info("cards:remove_success",{cardId:n,promotedId:i?.promotedId??null}),i})}catch(s){if(f.error("cards:remove_failure",{cardId:n,error:s.message}),s instanceof Yt)return bs(s,"remove_card");throw s}}async function F_(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."};f.info("cards:set_default_attempt",{cardId:n});let r=`set-default-card:${n}`,o=`set ${await Ld(n,t)} as default`;try{return await fe(async()=>{let s=await Ue(r,0,"",o,t,{forceRequired:!0}),i=await I.setDefaultCard(n,{attestation:s},t);return f.info("cards:set_default_success",{cardId:n}),i})}catch(s){if(f.error("cards:set_default_failure",{cardId:n,error:s.message}),s instanceof Yt)return bs(s,"set_default_card");throw s}}async function V_(e){return f.info("auth:login_attempt"),Ud(`${_s()}/login`,e)}function q_(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 B_(e={},t){let n;try{n=q_(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return ys(async()=>{let r=await fe(()=>md(I,Ue,{toolName:"start_session",userContext:t,capCentsOverride:n}));f.info("session:started",{budgetId:r.budgetId,totalCents:r.totalCents,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious});let o=(r.appliedCapCents/100).toFixed(2),s=(r.requestedCapCents/100).toFixed(2),i=`Session started with a $${o} 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 $${s} was clamped to your prepaid balance of $${o}. 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 H_(){let e=Jt();if(!e)return{success:!0,active:!1,message:"No active explicit approval window. Paid calls use a one-shot session in pay-as-you-go mode; see transaction_history for records."};let t=Math.max(0,e.totalCents-e.estimatedCumulative);return{success:!0,active:!0,budgetId:e.budgetId,totalCents:e.totalCents,estimatedCumulativeCents:e.estimatedCumulative,estimatedRemainingCents:t,expiresAt:e.expiresAt,lastToolSpend:e.lastToolSpend,message:`Active explicit approval window: about $${(t/100).toFixed(2)} remaining of $${(e.totalCents/100).toFixed(2)}.`}}async function K_(){return ys(async()=>{let e=Jt();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 is(I);f.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=Ny(e),r=He(t.finalCumulativeMicros),o=r??(typeof t.finalCumulativeCents=="number"?BigInt(Math.max(0,t.finalCumulativeCents))*10000n:n.micros),s=Number(o/10000n);return f.info("session:closed:final-spend",{budgetId:t.budgetId,closedServerSide:t.closedServerSide,finalSpendMicros:o.toString(),finalSpendCents:s,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:s,finalEstimatedCumulativeMicros:o.toString(),totalCents:e.totalCents,message:t.closedServerSide?`Explicit approval window closed. Spent ${My(o)} 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 G_(e){if(f.info("auth:add_card_attempt"),!await V.getSessionToken())return{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."};let{code:n}=await I.createEnrollCode();return Ud(`${_s()}/enroll-card?code=${encodeURIComponent(n)}`,e,"enrollment")}async function Td(){if(await V.clearAll(),ie())try{await Zo()}catch{}}async function W_(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};if(f.info("reset:attempt"),e.localOnly)return await Td(),f.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 I.getStatus(t);if(r&&it(r)){let o=await Fd(t);if(!o.success)return o;n=!0}}catch(r){let o=r?.message||"unknown error";if(!/not logged in|session.*expired|no local credentials/i.test(o))return{success:!1,message:`Could not check server biometric state: ${o}`};f.warn("reset:server_attestation_status_unavailable",{error:o})}try{await I.logout(void 0,t)}catch{}return await Td(),f.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 z_(e){let t=e.query?.trim()||void 0,n=e.category?.trim()||void 0,r=!t&&!n;f.info("catalog:discover",{query:t,category:n,browseAll:r});try{let s=(await I.catalogSearch(t,n)).tools||[];if(s.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 s){let u=l.category||"other";(a[u]??=[]).push(l)}let c=Object.keys(a).sort().map(l=>{let u=a[l].map((p,m)=>`${m+1}. **${p.name}** (${p.id})
134
+ `),Pu(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>\`
135
+ `)}var y={};ci(y,{BRAND:()=>Gh,DIRTY:()=>_n,EMPTY_PATH:()=>Th,INVALID:()=>L,NEVER:()=>Iy,OK:()=>Se,ParseStatus:()=>be,Schema:()=>F,ZodAny:()=>Yt,ZodArray:()=>Et,ZodBigInt:()=>vn,ZodBoolean:()=>wn,ZodBranded:()=>Zr,ZodCatch:()=>Pn,ZodDate:()=>Sn,ZodDefault:()=>$n,ZodDiscriminatedUnion:()=>is,ZodEffects:()=>je,ZodEnum:()=>Rn,ZodError:()=>Ae,ZodFirstPartyTypeKind:()=>U,ZodFunction:()=>cs,ZodIntersection:()=>kn,ZodIssueCode:()=>b,ZodLazy:()=>En,ZodLiteral:()=>An,ZodMap:()=>ar,ZodNaN:()=>lr,ZodNativeEnum:()=>In,ZodNever:()=>Ke,ZodNull:()=>Tn,ZodNullable:()=>lt,ZodNumber:()=>bn,ZodObject:()=>Re,ZodOptional:()=>Ue,ZodParsedType:()=>C,ZodPipeline:()=>Qr,ZodPromise:()=>Xt,ZodReadonly:()=>On,ZodRecord:()=>as,ZodSchema:()=>F,ZodSet:()=>cr,ZodString:()=>Jt,ZodSymbol:()=>sr,ZodTransformer:()=>je,ZodTuple:()=>ct,ZodType:()=>F,ZodUndefined:()=>xn,ZodUnion:()=>Cn,ZodUnknown:()=>kt,ZodVoid:()=>ir,addIssueToContext:()=>x,any:()=>ty,array:()=>sy,bigint:()=>Yh,boolean:()=>Ku,coerce:()=>Ry,custom:()=>Bu,date:()=>Xh,datetimeRegex:()=>Fu,defaultErrorMap:()=>Tt,discriminatedUnion:()=>ly,effect:()=>wy,enum:()=>_y,function:()=>gy,getErrorMap:()=>nr,getParsedType:()=>at,instanceof:()=>zh,intersection:()=>uy,isAborted:()=>os,isAsync:()=>rr,isDirty:()=>ss,isValid:()=>zt,late:()=>Wh,lazy:()=>hy,literal:()=>yy,makeIssue:()=>Xr,map:()=>py,nan:()=>Jh,nativeEnum:()=>by,never:()=>ry,null:()=>ey,nullable:()=>xy,number:()=>qu,object:()=>iy,objectUtil:()=>ta,oboolean:()=>Ay,onumber:()=>Ey,optional:()=>Sy,ostring:()=>ky,pipeline:()=>Cy,preprocess:()=>Ty,promise:()=>vy,quotelessJson:()=>wh,record:()=>my,set:()=>fy,setErrorMap:()=>xh,strictObject:()=>ay,string:()=>Hu,symbol:()=>Zh,transformer:()=>wy,tuple:()=>dy,undefined:()=>Qh,union:()=>cy,unknown:()=>ny,util:()=>V,void:()=>oy});var V;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},e.getValidEnumValues=o=>{let s=e.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return e.objectValues(i)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},e.find=(o,s)=>{for(let i of o)if(s(i))return i},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(V||(V={}));var ta;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(ta||(ta={}));var C=V.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),at=e=>{switch(typeof e){case"undefined":return C.undefined;case"string":return C.string;case"number":return Number.isNaN(e)?C.nan:C.number;case"boolean":return C.boolean;case"function":return C.function;case"bigint":return C.bigint;case"symbol":return C.symbol;case"object":return Array.isArray(e)?C.array:e===null?C.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?C.promise:typeof Map<"u"&&e instanceof Map?C.map:typeof Set<"u"&&e instanceof Set?C.set:typeof Date<"u"&&e instanceof Date?C.date:C.object;default:return C.unknown}};var b=V.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),wh=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),Ae=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(s){return s.message},r={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(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 o(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,V.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];n[s]=n[s]||[],n[s].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Ae.create=e=>new Ae(e);var Sh=(e,t)=>{let n;switch(e.code){case b.invalid_type:e.received===C.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case b.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,V.jsonStringifyReplacer)}`;break;case b.unrecognized_keys:n=`Unrecognized key(s) in object: ${V.joinValues(e.keys,", ")}`;break;case b.invalid_union:n="Invalid input";break;case b.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${V.joinValues(e.options)}`;break;case b.invalid_enum_value:n=`Invalid enum value. Expected ${V.joinValues(e.options)}, received '${e.received}'`;break;case b.invalid_arguments:n="Invalid function arguments";break;case b.invalid_return_type:n="Invalid function return type";break;case b.invalid_date:n="Invalid date";break;case b.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:V.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case b.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 b.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 b.custom:n="Invalid input";break;case b.invalid_intersection_types:n="Intersection results could not be merged";break;case b.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case b.not_finite:n="Number must be finite";break;default:n=t.defaultError,V.assertNever(e)}return{message:n}},Tt=Sh;var Nu=Tt;function xh(e){Nu=e}function nr(){return Nu}var Xr=e=>{let{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=r.filter(l=>!!l).slice().reverse();for(let l of c)a=l(i,{data:t,defaultError:a}).message;return{...o,path:s,message:a}},Th=[];function x(e,t){let n=nr(),r=Xr({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Tt?void 0:Tt].filter(o=>!!o)});e.common.issues.push(r)}var be=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 o of n){if(o.status==="aborted")return L;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let o of n){let s=await o.key,i=await o.value;r.push({key:s,value:i})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let o of n){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return L;s.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:t.value,value:r}}},L=Object.freeze({status:"aborted"}),_n=e=>({status:"dirty",value:e}),Se=e=>({status:"valid",value:e}),os=e=>e.status==="aborted",ss=e=>e.status==="dirty",zt=e=>e.status==="valid",rr=e=>typeof Promise<"u"&&e instanceof Promise;var R;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(R||(R={}));var De=class{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}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}},Lu=(e,t)=>{if(zt(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 Ae(e.common.issues);return this._error=n,this._error}}};function D(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:o}=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:o}:{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:o}}var F=class{get description(){return this._def.description}_getType(t){return at(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:at(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new be,ctx:{common:t.parent.common,data:t.data,parsedType:at(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(rr(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:at(t)},o=this._parseSync({data:t,path:r.path,parent:r});return Lu(r,o)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:at(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return zt(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=>zt(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:at(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(rr(o)?o:Promise.resolve(o));return Lu(r,s)}refine(t,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{let i=t(o),a=()=>s.addIssue({code:b.custom,...r(o)});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,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new je({schema:this,typeName:U.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 Ue.create(this,this._def)}nullable(){return lt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Et.create(this)}promise(){return Xt.create(this,this._def)}or(t){return Cn.create([this,t],this._def)}and(t){return kn.create(this,t,this._def)}transform(t){return new je({...D(this._def),schema:this,typeName:U.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new $n({...D(this._def),innerType:this,defaultValue:n,typeName:U.ZodDefault})}brand(){return new Zr({typeName:U.ZodBranded,type:this,...D(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new Pn({...D(this._def),innerType:this,catchValue:n,typeName:U.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Qr.create(this,t)}readonly(){return On.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Ch=/^c[^\s-]{8,}$/i,kh=/^[0-9a-z]+$/,Eh=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ah=/^[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,Rh=/^[a-z0-9_-]{21}$/i,Ih=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,$h=/^[-+]?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)?)??$/,Ph=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Oh="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",na,Mh=/^(?:(?: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])$/,Nh=/^(?:(?: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])$/,Lh=/^(([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]))$/,Uh=/^(([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])$/,Dh=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,jh=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Du="((\\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])))",Fh=new RegExp(`^${Du}$`);function ju(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 Vh(e){return new RegExp(`^${ju(e)}$`)}function Fu(e){let t=`${Du}T${ju(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 Bh(e,t){return!!((t==="v4"||!t)&&Mh.test(e)||(t==="v6"||!t)&&Lh.test(e))}function Hh(e,t){if(!Ih.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,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function qh(e,t){return!!((t==="v4"||!t)&&Nh.test(e)||(t==="v6"||!t)&&Uh.test(e))}var Jt=class e extends F{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==C.string){let s=this._getOrReturnCtx(t);return x(s,{code:b.invalid_type,expected:C.string,received:s.parsedType}),L}let r=new be,o;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),x(o,{code:b.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),x(o,{code:b.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let i=t.data.length>s.value,a=t.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(t,o),i?x(o,{code:b.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&x(o,{code:b.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")Ph.test(t.data)||(o=this._getOrReturnCtx(t,o),x(o,{validation:"email",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")na||(na=new RegExp(Oh,"u")),na.test(t.data)||(o=this._getOrReturnCtx(t,o),x(o,{validation:"emoji",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")Ah.test(t.data)||(o=this._getOrReturnCtx(t,o),x(o,{validation:"uuid",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")Rh.test(t.data)||(o=this._getOrReturnCtx(t,o),x(o,{validation:"nanoid",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")Ch.test(t.data)||(o=this._getOrReturnCtx(t,o),x(o,{validation:"cuid",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")kh.test(t.data)||(o=this._getOrReturnCtx(t,o),x(o,{validation:"cuid2",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")Eh.test(t.data)||(o=this._getOrReturnCtx(t,o),x(o,{validation:"ulid",code:b.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),x(o,{validation:"url",code:b.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),x(o,{validation:"regex",code:b.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),x(o,{code:b.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),x(o,{code:b.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),x(o,{code:b.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?Fu(s).test(t.data)||(o=this._getOrReturnCtx(t,o),x(o,{code:b.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?Fh.test(t.data)||(o=this._getOrReturnCtx(t,o),x(o,{code:b.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?Vh(s).test(t.data)||(o=this._getOrReturnCtx(t,o),x(o,{code:b.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?$h.test(t.data)||(o=this._getOrReturnCtx(t,o),x(o,{validation:"duration",code:b.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?Bh(t.data,s.version)||(o=this._getOrReturnCtx(t,o),x(o,{validation:"ip",code:b.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?Hh(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),x(o,{validation:"jwt",code:b.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?qh(t.data,s.version)||(o=this._getOrReturnCtx(t,o),x(o,{validation:"cidr",code:b.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?Dh.test(t.data)||(o=this._getOrReturnCtx(t,o),x(o,{validation:"base64",code:b.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?jh.test(t.data)||(o=this._getOrReturnCtx(t,o),x(o,{validation:"base64url",code:b.invalid_string,message:s.message}),r.dirty()):V.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:b.invalid_string,...R.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...R.errToObj(t)})}url(t){return this._addCheck({kind:"url",...R.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...R.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...R.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...R.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...R.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...R.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...R.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...R.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...R.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...R.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...R.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...R.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,...R.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,...R.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...R.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...R.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...R.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...R.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...R.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...R.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...R.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...R.errToObj(n)})}nonempty(t){return this.min(1,R.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}};Jt.create=e=>new Jt({checks:[],typeName:U.ZodString,coerce:e?.coerce??!1,...D(e)});function Kh(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/10**o}var bn=class e extends F{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==C.number){let s=this._getOrReturnCtx(t);return x(s,{code:b.invalid_type,expected:C.number,received:s.parsedType}),L}let r,o=new be;for(let s of this._def.checks)s.kind==="int"?V.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),x(r,{code:b.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),x(r,{code:b.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),x(r,{code:b.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Kh(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),x(r,{code:b.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),x(r,{code:b.not_finite,message:s.message}),o.dirty()):V.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,R.toString(n))}gt(t,n){return this.setLimit("min",t,!1,R.toString(n))}lte(t,n){return this.setLimit("max",t,!0,R.toString(n))}lt(t,n){return this.setLimit("max",t,!1,R.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:R.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:R.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:R.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:R.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:R.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:R.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:R.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:R.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:R.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:R.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&V.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};bn.create=e=>new bn({checks:[],typeName:U.ZodNumber,coerce:e?.coerce||!1,...D(e)});var vn=class e extends F{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==C.bigint)return this._getInvalidInput(t);let r,o=new be;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),x(r,{code:b.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),x(r,{code:b.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),x(r,{code:b.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):V.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return x(n,{code:b.invalid_type,expected:C.bigint,received:n.parsedType}),L}gte(t,n){return this.setLimit("min",t,!0,R.toString(n))}gt(t,n){return this.setLimit("min",t,!1,R.toString(n))}lte(t,n){return this.setLimit("max",t,!0,R.toString(n))}lt(t,n){return this.setLimit("max",t,!1,R.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:R.toString(o)}]})}_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:R.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:R.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:R.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:R.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:R.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}};vn.create=e=>new vn({checks:[],typeName:U.ZodBigInt,coerce:e?.coerce??!1,...D(e)});var wn=class extends F{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==C.boolean){let r=this._getOrReturnCtx(t);return x(r,{code:b.invalid_type,expected:C.boolean,received:r.parsedType}),L}return Se(t.data)}};wn.create=e=>new wn({typeName:U.ZodBoolean,coerce:e?.coerce||!1,...D(e)});var Sn=class e extends F{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==C.date){let s=this._getOrReturnCtx(t);return x(s,{code:b.invalid_type,expected:C.date,received:s.parsedType}),L}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return x(s,{code:b.invalid_date}),L}let r=new be,o;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),x(o,{code:b.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),x(o,{code:b.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):V.assertNever(s);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:R.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:R.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}};Sn.create=e=>new Sn({checks:[],coerce:e?.coerce||!1,typeName:U.ZodDate,...D(e)});var sr=class extends F{_parse(t){if(this._getType(t)!==C.symbol){let r=this._getOrReturnCtx(t);return x(r,{code:b.invalid_type,expected:C.symbol,received:r.parsedType}),L}return Se(t.data)}};sr.create=e=>new sr({typeName:U.ZodSymbol,...D(e)});var xn=class extends F{_parse(t){if(this._getType(t)!==C.undefined){let r=this._getOrReturnCtx(t);return x(r,{code:b.invalid_type,expected:C.undefined,received:r.parsedType}),L}return Se(t.data)}};xn.create=e=>new xn({typeName:U.ZodUndefined,...D(e)});var Tn=class extends F{_parse(t){if(this._getType(t)!==C.null){let r=this._getOrReturnCtx(t);return x(r,{code:b.invalid_type,expected:C.null,received:r.parsedType}),L}return Se(t.data)}};Tn.create=e=>new Tn({typeName:U.ZodNull,...D(e)});var Yt=class extends F{constructor(){super(...arguments),this._any=!0}_parse(t){return Se(t.data)}};Yt.create=e=>new Yt({typeName:U.ZodAny,...D(e)});var kt=class extends F{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Se(t.data)}};kt.create=e=>new kt({typeName:U.ZodUnknown,...D(e)});var Ke=class extends F{_parse(t){let n=this._getOrReturnCtx(t);return x(n,{code:b.invalid_type,expected:C.never,received:n.parsedType}),L}};Ke.create=e=>new Ke({typeName:U.ZodNever,...D(e)});var ir=class extends F{_parse(t){if(this._getType(t)!==C.undefined){let r=this._getOrReturnCtx(t);return x(r,{code:b.invalid_type,expected:C.void,received:r.parsedType}),L}return Se(t.data)}};ir.create=e=>new ir({typeName:U.ZodVoid,...D(e)});var Et=class e extends F{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==C.array)return x(n,{code:b.invalid_type,expected:C.array,received:n.parsedType}),L;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(x(n,{code:i?b.too_big:b.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(x(n,{code:b.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(x(n,{code:b.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>o.type._parseAsync(new De(n,i,n.path,a)))).then(i=>be.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new De(n,i,n.path,a)));return be.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:R.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:R.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:R.toString(n)}})}nonempty(t){return this.min(1,t)}};Et.create=(e,t)=>new Et({type:e,minLength:null,maxLength:null,exactLength:null,typeName:U.ZodArray,...D(t)});function or(e){if(e instanceof Re){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Ue.create(or(r))}return new Re({...e._def,shape:()=>t})}else return e instanceof Et?new Et({...e._def,type:or(e.element)}):e instanceof Ue?Ue.create(or(e.unwrap())):e instanceof lt?lt.create(or(e.unwrap())):e instanceof ct?ct.create(e.items.map(t=>or(t))):e}var Re=class e extends F{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=V.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==C.object){let l=this._getOrReturnCtx(t);return x(l,{code:b.invalid_type,expected:C.object,received:l.parsedType}),L}let{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ke&&this._def.unknownKeys==="strip"))for(let l in o.data)i.includes(l)||a.push(l);let c=[];for(let l of i){let u=s[l],d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new De(o,d,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Ke){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(l==="strict")a.length>0&&(x(o,{code:b.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=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new De(o,d,o.path,u)),alwaysSet:u in o.data})}}return o.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=>be.mergeObjectSync(r,l)):be.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(t){return R.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:R.errToObj(t).message??o}:{message:o}}}:{}})}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:U.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of V.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let r of V.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return or(this)}partial(t){let n={};for(let r of V.objectKeys(this.shape)){let o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let r of V.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Ue;)s=s._def.innerType;n[r]=s}return new e({...this._def,shape:()=>n})}keyof(){return Vu(V.objectKeys(this.shape))}};Re.create=(e,t)=>new Re({shape:()=>e,unknownKeys:"strip",catchall:Ke.create(),typeName:U.ZodObject,...D(t)});Re.strictCreate=(e,t)=>new Re({shape:()=>e,unknownKeys:"strict",catchall:Ke.create(),typeName:U.ZodObject,...D(t)});Re.lazycreate=(e,t)=>new Re({shape:e,unknownKeys:"strip",catchall:Ke.create(),typeName:U.ZodObject,...D(t)});var Cn=class extends F{_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Ae(a.ctx.common.issues));return x(n,{code:b.invalid_union,unionErrors:i}),L}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,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"&&!s&&(s={result:u,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Ae(c));return x(n,{code:b.invalid_union,unionErrors:a}),L}}get options(){return this._def.options}};Cn.create=(e,t)=>new Cn({options:e,typeName:U.ZodUnion,...D(t)});var Ct=e=>e instanceof En?Ct(e.schema):e instanceof je?Ct(e.innerType()):e instanceof An?[e.value]:e instanceof Rn?e.options:e instanceof In?V.objectValues(e.enum):e instanceof $n?Ct(e._def.innerType):e instanceof xn?[void 0]:e instanceof Tn?[null]:e instanceof Ue?[void 0,...Ct(e.unwrap())]:e instanceof lt?[null,...Ct(e.unwrap())]:e instanceof Zr||e instanceof On?Ct(e.unwrap()):e instanceof Pn?Ct(e._def.innerType):[],is=class e extends F{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==C.object)return x(n,{code:b.invalid_type,expected:C.object,received:n.parsedType}),L;let r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(x(n,{code:b.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),L)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let o=new Map;for(let s of n){let i=Ct(s.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(o.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);o.set(a,s)}}return new e({typeName:U.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...D(r)})}};function ra(e,t){let n=at(e),r=at(t);if(e===t)return{valid:!0,data:e};if(n===C.object&&r===C.object){let o=V.objectKeys(t),s=V.objectKeys(e).filter(a=>o.indexOf(a)!==-1),i={...e,...t};for(let a of s){let c=ra(e[a],t[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===C.array&&r===C.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let s=0;s<e.length;s++){let i=e[s],a=t[s],c=ra(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return n===C.date&&r===C.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var kn=class extends F{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=(s,i)=>{if(os(s)||os(i))return L;let a=ra(s.value,i.value);return a.valid?((ss(s)||ss(i))&&n.dirty(),{status:n.value,value:a.data}):(x(r,{code:b.invalid_intersection_types}),L)};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(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};kn.create=(e,t,n)=>new kn({left:e,right:t,typeName:U.ZodIntersection,...D(n)});var ct=class e extends F{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==C.array)return x(r,{code:b.invalid_type,expected:C.array,received:r.parsedType}),L;if(r.data.length<this._def.items.length)return x(r,{code:b.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),L;!this._def.rest&&r.data.length>this._def.items.length&&(x(r,{code:b.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new De(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>be.mergeArray(n,i)):be.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};ct.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ct({items:e,typeName:U.ZodTuple,rest:null,...D(t)})};var as=class e extends F{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==C.object)return x(r,{code:b.invalid_type,expected:C.object,received:r.parsedType}),L;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new De(r,a,r.path,a)),value:i._parse(new De(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?be.mergeObjectAsync(n,o):be.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof F?new e({keyType:t,valueType:n,typeName:U.ZodRecord,...D(r)}):new e({keyType:Jt.create(),valueType:t,typeName:U.ZodRecord,...D(n)})}},ar=class extends F{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==C.map)return x(r,{code:b.invalid_type,expected:C.map,received:r.parsedType}),L;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,c],l)=>({key:o._parse(new De(r,a,r.path,[l,"key"])),value:s._parse(new De(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 L;(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 L;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}}}};ar.create=(e,t,n)=>new ar({valueType:t,keyType:e,typeName:U.ZodMap,...D(n)});var cr=class e extends F{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==C.set)return x(r,{code:b.invalid_type,expected:C.set,received:r.parsedType}),L;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(x(r,{code:b.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(x(r,{code:b.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return L;u.status==="dirty"&&n.dirty(),l.add(u.value)}return{status:n.value,value:l}}let a=[...r.data.values()].map((c,l)=>s._parse(new De(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:R.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:R.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};cr.create=(e,t)=>new cr({valueType:e,minSize:null,maxSize:null,typeName:U.ZodSet,...D(t)});var cs=class e extends F{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==C.function)return x(n,{code:b.invalid_type,expected:C.function,received:n.parsedType}),L;function r(a,c){return Xr({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,nr(),Tt].filter(l=>!!l),issueData:{code:b.invalid_arguments,argumentsError:c}})}function o(a,c){return Xr({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,nr(),Tt].filter(l=>!!l),issueData:{code:b.invalid_return_type,returnTypeError:c}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof Xt){let a=this;return Se(async function(...c){let l=new Ae([]),u=await a._def.args.parseAsync(c,s).catch(m=>{throw l.addIssue(r(c,m)),l}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,s).catch(m=>{throw l.addIssue(o(d,m)),l})})}else{let a=this;return Se(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new Ae([r(c,l.error)]);let u=Reflect.apply(i,this,l.data),d=a._def.returns.safeParse(u,s);if(!d.success)throw new Ae([o(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:ct.create(t).rest(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||ct.create([]).rest(kt.create()),returns:n||kt.create(),typeName:U.ZodFunction,...D(r)})}},En=class extends F{get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};En.create=(e,t)=>new En({getter:e,typeName:U.ZodLazy,...D(t)});var An=class extends F{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return x(n,{received:n.data,code:b.invalid_literal,expected:this._def.value}),L}return{status:"valid",value:t.data}}get value(){return this._def.value}};An.create=(e,t)=>new An({value:e,typeName:U.ZodLiteral,...D(t)});function Vu(e,t){return new Rn({values:e,typeName:U.ZodEnum,...D(t)})}var Rn=class e extends F{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return x(n,{expected:V.joinValues(r),received:n.parsedType,code:b.invalid_type}),L}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 x(n,{received:n.data,code:b.invalid_enum_value,options:r}),L}return Se(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})}};Rn.create=Vu;var In=class extends F{_parse(t){let n=V.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==C.string&&r.parsedType!==C.number){let o=V.objectValues(n);return x(r,{expected:V.joinValues(o),received:r.parsedType,code:b.invalid_type}),L}if(this._cache||(this._cache=new Set(V.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let o=V.objectValues(n);return x(r,{received:r.data,code:b.invalid_enum_value,options:o}),L}return Se(t.data)}get enum(){return this._def.values}};In.create=(e,t)=>new In({values:e,typeName:U.ZodNativeEnum,...D(t)});var Xt=class extends F{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==C.promise&&n.common.async===!1)return x(n,{code:b.invalid_type,expected:C.promise,received:n.parsedType}),L;let r=n.parsedType===C.promise?n.data:Promise.resolve(n.data);return Se(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Xt.create=(e,t)=>new Xt({type:e,typeName:U.ZodPromise,...D(t)});var je=class extends F{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===U.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:i=>{x(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return L;let c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?L:c.status==="dirty"?_n(c.value):n.value==="dirty"?_n(c.value):c});{if(n.value==="aborted")return L;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?L:a.status==="dirty"?_n(a.value):n.value==="dirty"?_n(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);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"?L:(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"?L:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!zt(i))return L;let a=o.transform(i.value,s);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=>zt(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):L);V.assertNever(o)}};je.create=(e,t,n)=>new je({schema:e,typeName:U.ZodEffects,effect:t,...D(n)});je.createWithPreprocess=(e,t,n)=>new je({schema:t,effect:{type:"preprocess",transform:e},typeName:U.ZodEffects,...D(n)});var Ue=class extends F{_parse(t){return this._getType(t)===C.undefined?Se(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ue.create=(e,t)=>new Ue({innerType:e,typeName:U.ZodOptional,...D(t)});var lt=class extends F{_parse(t){return this._getType(t)===C.null?Se(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};lt.create=(e,t)=>new lt({innerType:e,typeName:U.ZodNullable,...D(t)});var $n=class extends F{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===C.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};$n.create=(e,t)=>new $n({innerType:e,typeName:U.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...D(t)});var Pn=class extends F{_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return rr(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ae(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ae(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Pn.create=(e,t)=>new Pn({innerType:e,typeName:U.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...D(t)});var lr=class extends F{_parse(t){if(this._getType(t)!==C.nan){let r=this._getOrReturnCtx(t);return x(r,{code:b.invalid_type,expected:C.nan,received:r.parsedType}),L}return{status:"valid",value:t.data}}};lr.create=e=>new lr({typeName:U.ZodNaN,...D(e)});var Gh=Symbol("zod_brand"),Zr=class extends F{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Qr=class e extends F{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?L:s.status==="dirty"?(n.dirty(),_n(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?L:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:U.ZodPipeline})}},On=class extends F{_parse(t){let n=this._def.innerType._parse(t),r=o=>(zt(o)&&(o.value=Object.freeze(o.value)),o);return rr(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};On.create=(e,t)=>new On({innerType:e,typeName:U.ZodReadonly,...D(t)});function Uu(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Bu(e,t={},n){return e?Yt.create().superRefine((r,o)=>{let s=e(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Uu(t,r),c=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Uu(t,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Yt.create()}var Wh={object:Re.lazycreate},U;(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"})(U||(U={}));var zh=(e,t={message:`Input not instance of ${e.name}`})=>Bu(n=>n instanceof e,t),Hu=Jt.create,qu=bn.create,Jh=lr.create,Yh=vn.create,Ku=wn.create,Xh=Sn.create,Zh=sr.create,Qh=xn.create,ey=Tn.create,ty=Yt.create,ny=kt.create,ry=Ke.create,oy=ir.create,sy=Et.create,iy=Re.create,ay=Re.strictCreate,cy=Cn.create,ly=is.create,uy=kn.create,dy=ct.create,my=as.create,py=ar.create,fy=cr.create,gy=cs.create,hy=En.create,yy=An.create,_y=Rn.create,by=In.create,vy=Xt.create,wy=je.create,Sy=Ue.create,xy=lt.create,Ty=je.createWithPreprocess,Cy=Qr.create,ky=()=>Hu().optional(),Ey=()=>qu().optional(),Ay=()=>Ku().optional(),Ry={string:(e=>Jt.create({...e,coerce:!0})),number:(e=>bn.create({...e,coerce:!0})),boolean:(e=>wn.create({...e,coerce:!0})),bigint:(e=>vn.create({...e,coerce:!0})),date:(e=>Sn.create({...e,coerce:!0}))};var Iy=L;var $y=/^[A-Za-z0-9._-]+$/,Py=/^[A-Za-z0-9._-]+(\|[A-Za-z0-9._-]+)*$/,Gu=new Set([".",".."]),ke=class extends Error{pattern;constructor(t,n){super(`Invalid freeReadPathPattern ${JSON.stringify(n)}: ${t}`),this.pattern=n,this.name="FreePathPatternError"}};function Oy(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 ke(`malformed alternation segment ${JSON.stringify(e)}`,t);let o=n?e.slice(1,-2):e.slice(1,-1);if(!Py.test(o))throw new ke(`malformed alternation segment ${JSON.stringify(e)}`,t);let s=o.split("|");if(s.some(i=>Gu.has(i)))throw new ke(`alternation segment ${JSON.stringify(e)} may not contain '.' or '..'`,t);return{raw:e,kind:n?"alt-optional":"alt",alternatives:s}}if($y.test(e)){if(Gu.has(e))throw new ke(`literal segment ${JSON.stringify(e)} is not permitted`,t);return{raw:e,kind:"literal"}}throw new ke(`segment ${JSON.stringify(e)} must be '*', '**', a [A-Za-z0-9._-]+ literal, or (a|b) alternation`,t)}function My(e){if(typeof e!="string"||e.length===0)throw new ke("must be a non-empty string",String(e));if(!e.startsWith("/"))throw new ke("must start with '/'",e);if(e.slice(1).includes("//"))throw new ke("empty segments ('//') are not permitted",e);if(e.length>1&&e.endsWith("/"))throw new ke("must not end with '/'",e);let n=e.slice(1).split("/").map(s=>Oy(s,e));if(n.filter(s=>s.kind==="multi").length>1)throw new ke("at most one '**' is permitted per pattern",e);if(n[0]?.kind==="multi")throw new ke("'**' may not be the first segment (a literal prefix anchor is required)",e);let o=n.findIndex(s=>s.kind==="alt-optional");if(o!==-1&&o!==n.length-1)throw new ke("optional alternation '(...)?' is only allowed as the final segment",e);return n}function oa(e){My(e)}var Wu=["tempo","mpp_self","merchant_self"],zu=["catalog_static","fal_direct","fal_queue","openrouter_chat","openrouter_image","platform_proxy","tempo_gateway","x402_gateway"],Ju=["image","audio","queued_audio","video","queued_video","model_3d","llm","transcription","utility"],Yu=["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 ia=y.object({inputPerMillion:y.number().positive(),outputPerMillion:y.number().positive(),contextWindow:y.number().int().positive().optional(),maxOutput:y.number().int().positive().optional(),perRequestFeeCents:y.number().nonnegative().optional()}),Ny=y.object({strategy:y.enum(["flat","token","band"]).optional(),pricingModel:y.enum(["per-call","per-token","band"]).optional(),priceCents:y.number().nonnegative().optional(),currency:y.string().optional(),display:y.string().optional(),estimate:y.boolean().optional(),source:y.string().optional(),priceBand:y.record(y.unknown()).optional(),tokenPricing:ia.optional()}).passthrough(),aa=y.discriminatedUnion("type",[y.object({type:y.literal("shortcut"),routedPath:y.string().min(1).startsWith("/")}),y.object({type:y.literal("custom"),merchantSlug:y.string().min(1),subPath:y.string().optional()}),y.object({type:y.literal("local"),fn:y.string().min(1)}),y.object({type:y.literal("read")})]),ca=y.object({amount:y.number().nonnegative(),currency:y.string().length(3).optional(),display:y.string().optional(),free:y.boolean().optional(),batchDiscount:y.number().min(0).max(100).optional()}),Xu=y.object({attestation:y.boolean().optional(),rateLimitMs:y.number().positive().optional()}),Zu=y.object({displayName:y.string().optional(),feedbackEligible:y.boolean().optional(),suggestionEligible:y.boolean().optional(),batchable:y.boolean().optional()}),Qu=y.object({enabled:y.boolean().optional(),gatewayPath:y.string().min(1).startsWith("/").optional(),method:y.enum(["GET","POST","PUT","PATCH","DELETE"]).optional(),timeoutMs:y.number().int().positive().max(12e4).optional()}).strict(),Ly=y.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),Uy=120,Dy=120,jy=1200,Fy=/^[^\u0000-\u001F\u007F]+$/;function sa(e,t){return y.string().min(1).max(e).regex(Fy,`${t} must not contain control characters`)}var la={id:y.string().min(1),name:sa(Uy,"name"),description:sa(jy,"description"),provider:y.string().min(1),model:y.string().min(1),category:Ly,priceCents:y.number().nonnegative(),inputSchema:y.record(y.unknown()),gatewayUrl:y.string().min(1),merchantName:sa(Dy,"merchantName"),isAsync:y.boolean().optional(),pollUrl:y.string().optional(),pollInterval:y.number().positive().optional(),pollTimeout:y.number().positive().optional(),tags:y.array(y.string()).optional(),tokenPricing:ia.optional(),priceDisplay:y.string().optional(),pricingModel:y.enum(["per-call","per-token","band"]).optional(),pricingInfo:Ny.optional(),status:y.enum(["available","unavailable"]).optional(),handler:aa.optional(),pricing:ca.optional(),security:Xu.optional(),engagement:Zu.optional(),gatewayConfig:Qu.optional(),freeReadPathPattern:y.string().optional().superRefine((e,t)=>{if(e!==void 0)try{oa(e)}catch(n){t.addIssue({code:y.ZodIssueCode.custom,message:n instanceof Error?n.message:String(n)})}}),enabled:y.boolean().optional(),beta:y.boolean().optional(),deprecated:y.boolean().optional(),internal:y.boolean().optional(),replacementTool:y.string().optional(),minCliVersion:y.string().optional(),sunsetAt:y.string().optional(),rail:y.enum(Wu).optional(),executionKind:y.enum(zu).optional(),resultKind:y.enum(Ju).optional(),extractionMode:y.enum(Yu).optional(),pricingStrategy:y.enum(["flat","token","band"]).optional()},ed=y.object({...la,dispatch:y.literal("routed"),routedPath:y.string().min(1).startsWith("/")}).strict(),td=y.object({...la,dispatch:y.literal("enveloped")}).strict(),nd=y.object({...la,handler:aa,pricing:ca}).strict(),rd=y.union([y.discriminatedUnion("dispatch",[ed,td]),nd]);var ua=/^[a-z0-9][a-z0-9_-]*$/;var Hy="https://fal.run",ad="https://openrouter.mpp.tempo.xyz",ma=1024,us=8192,qy=4096,Ky=10;function Gy(e){return e>=Ky?qy:us}function cd(e,t){let n=typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):ma;return Math.min(n,t)}var Wy=["num_images","num_outputs","num_samples","num_videos","batch_size","n"];function ld(e){for(let t of Wy)delete e[t];return e}function zy(e){let{attestation:t,tool_id:n,...r}=e;return ld(r)}var od={"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 ls(e){let{attestation:t,tool_id:n,aspect_ratio:r,image_size:o,...s}=e,i=ld({...s});return typeof o=="string"&&o.length>0?(i.image_size=o,i):(typeof r=="string"&&od[r]&&(i.image_size=od[r]),i)}function Jy(e){let{attestation:t,tool_id:n,...r}=e;return r}function sd(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 o=new Date(e.start_timestamp).getTime();(new Date(n).getTime()-o)/(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 Yy(e,t,n,r,o,s,i,a,c){return{id:e,name:t,description:n,provider:r,model:o.replace(/^\//,""),category:s,gatewayUrl:`https://${r}${o}`,merchantName:t,inputSchema:a,handler:{type:"custom",merchantSlug:r,subPath:o},pricing:{amount:i,currency:"USD",display:`$${(i/100).toFixed(2)}`},priceCents:i,tags:[],...c}}function Xy(e,t,n,r,o,s,i,a){return Yy(e,t,n,"suno-ai",r,o,s,i,{merchantName:"Suno AI",...a})}function ue(e,t,n,r,o,s,i,a){return{dispatch:"routed",id:e,name:t,description:n,provider:"fal",model:r,category:o,priceCents:s,inputSchema:i,routedPath:`/api/v1/fal/${r}`,gatewayUrl:`${Hy}/${r}`,merchantName:"fal.ai",buildBody:zy,tags:[],...a}}function ud(e,t=us){return n=>{let{attestation:r,tool_id:o,model:s,prompt:i,system_prompt:a,max_tokens:c,max_completion_tokens:l,n:u,messages:d,temperature:p,...m}=n;return typeof s=="string"&&s.length>0&&s!==e&&console.warn("[catalog] openrouterBuildBody: caller model override ignored",{catalogModel:e,callerModel:s}),{messages:Array.isArray(d)?d:[...a?[{role:"system",content:a}]:[],{role:"user",content:i}],temperature:p??.7,...m,model:e,max_tokens:cd(c??l,t)}}}function dd(e,t=us){return n=>{let{attestation:r,tool_id:o,prompt:s,image_url:i,aspect_ratio:a,max_tokens:c,max_completion_tokens:l,n:u,model:d,messages:p,image_config:m,temperature:g,...h}=n,w=[{type:"text",text:s}];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:g??.7,...h,model:e,...typeof a=="string"&&a.length>0?{image_config:{aspect_ratio:a}}:{},max_tokens:cd(c??l,t)}}}function ne(e,t,n,r,o,s,i){let a=i?.maxOutputTokens??Gy(s),c=i?.perRequestFeeCents??0,l=500/1e6*o*100,u=500/1e6*s*100,d=Math.max(1,Math.ceil(l+u+c)),{perRequestFeeCents:p,maxOutputTokens:m,...g}=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: ${ma}); 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:`${ad}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:ud(r,a),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:o,outputPerMillion:s,...c>0?{perRequestFeeCents:c}:{}},...g}}function da(e,t,n,r,o,s){let i=s?.maxOutputTokens??us,{maxOutputTokens:a,...c}=s??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"image",pricingStrategy:"band",priceCents:o,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: ${ma}); 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:`${ad}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:dd(r,i),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...c}}var pa=[ue("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"]}),ue("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:ls}),ue("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:ls}),ue("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:ls}),ue("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"]}),da("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),da("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}}),da("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}}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),Xy("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:o,...s}=e;return{prompt:r,customMode:!1,instrumental:typeof o=="boolean"?o:!1,model:"V4",...s}}}),ue("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"]}),ue("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"]}),ue("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"]}),ue("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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:sd,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:Jy,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=>ls({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"]},ue("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"}),ue("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:sd,tags:["onchain","prices","allium","crypto","legacy"]}];function ur(e){return pa.find(t=>t.id===e)}var md=1,pd=["pick_one","fan_out"],fd=["concat","dedupe_by_url","top_k_by_score"],e_=8,t_=y.object({type:y.string().min(1),description:y.string().min(1),enum:y.array(y.string()).optional(),default:y.unknown().optional(),minimum:y.number().optional(),maximum:y.number().optional()}),n_=y.object({toolId:y.string().min(1),notes:y.string().min(1)}),r_=y.string().regex(/^[a-z0-9_-]{1,32}$/,"tier key must be 1-32 chars [a-z0-9_-]"),o_=y.object({providers:y.array(y.string().min(1)).min(1).max(e_),merge:y.enum(fd),maxResults:y.number().int().positive().optional()}),gd=y.object({mode:y.enum(pd).default("pick_one"),intro:y.string().min(1),defaultTier:y.string().min(1),tiers:y.record(r_,n_).refine(e=>Object.keys(e).length>0,{message:"must have at least one tier"}),fanOut:o_.optional(),guidance:y.string().min(1),inputProperties:y.record(y.string(),t_),required:y.array(y.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"]}),s_=y.object({version:y.literal(md),generatedAt:y.string().datetime(),tools:y.record(y.string().regex(ua,"tool name must match MCP naming rules"),gd).refine(e=>Object.keys(e).length>0,{message:"manifest must have at least one tool"})});var Ns=E(dr());var fs=require("child_process"),kd=require("util"),Ed=E(require("crypto")),Y=E(require("fs")),Ad=E(require("os")),xe=E(require("path"));var Ge=(0,kd.promisify)(fs.execFile),C_=6e4,k_=()=>process.platform==="darwin",Zt=()=>process.platform==="win32",Qt=xe.join(Ad.homedir(),".visa-mcp","bin"),Mn=xe.join(Qt,"Visa CLI"),Rt=xe.join(Qt,"visa-keychain-win.exe"),Rd=xe.join(__dirname,"..","native"),yd="6",_d=xe.join(Qt,"visa-keychain.version"),bd=xe.join(Qt,"visa-keychain.sha256"),vd="1",wd=xe.join(Qt,"visa-keychain-win.version"),Sd=xe.join(Qt,"visa-keychain-win.sha256"),Id=[xe.join(Rd,"bin","win32-x64","visa-keychain-win.exe"),xe.resolve(__dirname,"..","..","native","bin","win32-x64","visa-keychain-win.exe"),xe.resolve(__dirname,"..","native","bin","win32-x64","visa-keychain-win.exe")];function ds(e){let t=Y.readFileSync(e);return Ed.createHash("sha256").update(t).digest("hex")}function E_(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 xd(e){let t=typeof e?.message=="string"?e.message:"";return e?.code==="ETIMEDOUT"||e?.killed===!0||/timed out|timeout/i.test(t)}function Td(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 fa(){try{if(Y.readFileSync(_d,"utf-8").trim()===yd&&Y.existsSync(Mn)){let r=Y.readFileSync(bd,"utf-8").trim();if(ds(Mn)!==r)f.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),Y.unlinkSync(Mn);else return Mn}}catch{}let e=xe.join(Rd,"visa-keychain.m");if(Y.existsSync(e)||(e=xe.resolve(__dirname,"..","..","native","visa-keychain.m")),Y.existsSync(e)||(e=xe.resolve(__dirname,"..","native","visa-keychain.m")),!Y.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");Y.mkdirSync(Qt,{recursive:!0,mode:448});try{await Ge("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",Mn,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=ds(Mn);return Y.writeFileSync(bd,t,{mode:384}),Y.writeFileSync(_d,yd,{mode:384}),Mn}function $d(){for(let e of Id)if(Y.existsSync(e))return e;return null}async function mr(){try{if(Y.readFileSync(wd,"utf-8").trim()===vd&&Y.existsSync(Rt)){let r=Y.readFileSync(Sd,"utf-8").trim();if(ds(Rt)!==r)f.warn("binary:hash-mismatch:win32",{message:"Windows binary hash mismatch. Redeploying."}),Y.unlinkSync(Rt);else return Rt}}catch{}let e=$d();if(!e)throw new Error(`visa-keychain-win.exe not found in package. Reinstall @visa/cli.
136
+ If building from source, run native/build-win.bat first.`);Y.mkdirSync(Qt,{recursive:!0}),Y.copyFileSync(e,Rt);let t=ds(Rt);return Y.writeFileSync(Sd,t,{mode:384}),Y.writeFileSync(wd,vd,{mode:384}),Rt}async function A_(){return Zt()?mr():fa()}var ms="visa-cli",ps="attestation-key";async function R_(e){try{await Ge("security",["delete-generic-password","-s",ms,"-a",ps],{timeout:5e3})}catch{}await Ge("security",["add-generic-password","-s",ms,"-a",ps,"-w",e],{timeout:5e3})}function I_(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:"",o=[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(o)?{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(o)?{state:"denied",usable:!1,message:"The local attestation key exists but Keychain access was denied or unavailable."}:{state:"error",usable:!1,message:o||"Could not read the local attestation key from Keychain."}}async function $_(){try{let{stdout:e}=await Ge("security",["find-generic-password","-s",ms,"-a",ps,"-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:I_(e)}}}async function ga(){let e=await $_();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 Pd(e){let t=await A_(),n;try{n=(await Ge(t,e,{timeout:6e4})).stdout}catch(r){n=r.stdout||"";let o=n.trim();throw o.startsWith("ERROR:")?new Error(o.slice(6)):new Error(r.stderr?.trim()||r.message||"Unknown error")}return E_(n)}var Cd=!1;function P_(){if(!Zt())return!1;try{return Y.existsSync(Rt)||$d()!==null?!0:(Cd||(Cd=!0,f.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:Rt,searchedPrebuiltPaths:Id})),!1)}catch{return!1}}function de(){return Gn()||k_()?!0:Zt()?P_():!1}async function gs(){if(Zt()){let o=await mr(),{stdout:s}=await Ge(o,["generate-key"],{timeout:3e4}),i=s.trim();if(i.startsWith("OK:"))return i.slice(3);throw new Error(i.startsWith("ERROR:")?i.slice(6):"Key generation failed")}let e=await Pd(["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 R_(n),r}async function hs(){if(Zt())try{let e=await mr(),{stdout:t}=await Ge(e,["public-key"],{timeout:1e4});return t.trim().startsWith("OK:")}catch{return!1}return await ga()!==null}async function Od(){if(Gn())return"mock-public-key-spki";if(Zt()){let n=await mr(),{stdout:r}=await Ge(n,["public-key"],{timeout:6e4}),o=r.trim();if(o.startsWith("OK:"))return o.slice(3);throw new Error(o.startsWith("ERROR:")?o.slice(6):"Attestation key not found. Run setup to generate a new key.")}let e=await ga();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await fa();return new Promise((n,r)=>{let o=(0,fs.execFile)(t,["public-key"],{timeout:6e4},(s,i)=>{let a=(i||"").trim();if(s){a.startsWith("ERROR:")?r(new Error(a.slice(6))):r(new Error(s.stderr?.trim()||s.message||"Unknown error"));return}a.startsWith("OK:")?n(a.slice(3)):r(new Error(a.startsWith("ERROR:")?a.slice(6):"Unknown error"))});o.stdin.write(e),o.stdin.end()})}async function Nn(e,t,n={}){if(Gn())return Promise.resolve(zc());let r=n.timeoutMs??C_;if(Zt()){let a=await mr(),c=["sign",e];t&&c.push(t);let l;try{l=(await Ge(a,c,{timeout:r})).stdout}catch(d){throw xd(d)?Td(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 o=await ga();if(!o)throw new Error("Attestation key not found. Run setup to generate a new key.");let s=await fa(),i=["sign",e];return t&&i.push(t),new Promise((a,c)=>{let l=(0,fs.execFile)(s,i,{timeout:r},(u,d)=>{let p=(d||"").trim();if(u){p.startsWith("ERROR:")?c(new Error(p.slice(6))):xd(u)?c(Td(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(o),l.stdin.end()})}async function ys(){if(Zt()){try{let e=await mr();await Ge(e,["delete-key"],{timeout:1e4})}catch{}return}try{await Ge("security",["delete-generic-password","-s",ms,"-a",ps],{timeout:5e3})}catch{}try{await Pd(["delete-key"])}catch{}}var O_=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],M_=[...O_.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 ya(e,t=M_){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=ha(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(ha(r.match.provider)))&&r.match.keywords.every(o=>n.includes(ha(o))))return r.targetToolId;return null}function ha(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}var to={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(!Nd(e))return D_(e,n);let r=Md[e];if(!r)return e;let o=Object.keys(r.tiers),s=t||o[0],i=j_(e,s,n);return i||F_(e,r,s,o)}function D_(e,t){return ya({requestedTool:e,intentText:t})??e}function j_(e,t,n){return ya({requestedTool:e,metaTool:e,tier:t,intentText:n})}function F_(e,t,n,r){let o=t.tiers[n];if(!o)throw new Error(`Unknown tier '${n}' for ${e}. Valid tiers: ${r.join(", ")}`);return o.toolId}var Md=to;function Nd(e){return e in Md}var no=Object.keys(to);function _a(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function Ld(e=process.env){return _a(e)!==null}var V_=new Set(["false","0","no","off","disable","disabled"]),B_=new Set(["true","1","yes","on","enable","enabled"]);function Ud(e){let t=(e??"").trim().toLowerCase();return t?V_.has(t)?!1:!!B_.has(t):!0}function Dd(e=process.env){return Ud(e.VISA_CLI_PARENTLESS_SINGLE_CALL)}function jd(e=process.env){return Ud(e.VISA_CLI_PARENTLESS_BATCH)}var Sm=require("child_process"),ye=E(require("crypto")),Ye=E(require("fs")),co=E(require("os")),Ls=E(require("path"));function ut(e,t={}){if(!e||typeof e!="object")return e;let n=e,r=t.tag??(typeof n.merchantName=="string"?n.merchantName:"media"),o=n.content?.[0]?.text,s=typeof o=="string"?Wn(o):null,i=Array.isArray(n.urls)?n.urls[0]:void 0,c=typeof i=="string"&&i.startsWith("data:")?Wn(i):null;if(!s&&!c)return e;let l=s??c,u=s?"content":"urls",d;try{d=Ir(l,{tag:H_(r,n)})}catch(m){return{...n,_inline_media_warning:`Failed to persist inline media to disk: ${m instanceof Error?m.message:String(m)}`}}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 H_(e,t){let n=typeof t.transactionId=="string"?t.transactionId:typeof t.transaction_id=="string"?t.transaction_id:null;return n?`${e}-${n}`:e}var Fd=!1;async function pr(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(f.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(Fd)throw f.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;Fd=!0,f.info("attestation:starting-browser-recovery");try{let s=await n();if(!s.success)throw f.error("attestation:browser-recovery-failed",{message:s.message}),r;let i=await gs();return await e.registerAttestationKey(i),await e.setBiometricPreference({required:!0}),f.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),f.info("attestation:key-reregistered-after-recovery"),await t()}catch(s){throw f.error("attestation:recovery-failure",{error:s.message}),r}}throw r}}function dt(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}async function _s(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 hs())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 dt(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."}}var Vd="3.0.1";function ba(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function bs(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 o=ts(t);return o!==void 0?{value:o,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function Oe(e){return e==null?"\u2014":e?"yes":"no"}function vs(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function q_(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function K_(){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=Zi("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:Yi,source:{kind:"default"}}}async function ro(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(_){n=_?.message||"unknown error"}let r=[],o=process.env.VISA_AUTH_URL,s=Xi("auth.serverUrl"),i=$e(),a=o!==void 0&&o!==""?{kind:"env",var:"VISA_AUTH_URL"}:s!==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:Oe(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:Oe(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:Oe(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:de(),formatted:Oe(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:vs(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:vs(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:vs(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:vs(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(_=>_.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 m=K_();r.push({key:"credit.sessionCapCents",value:m.value,formatted:q_(m.value),source:m.source});let g=ku();g.length>0&&r.push({key:"settings.retired",value:g.map(_=>_.key),formatted:g.map(_=>_.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${g.map(_=>`visa-cli config unset ${_.key}`).join(" && ")}`});let h=bs("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:h.value,formatted:Oe(h.value),source:h.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let w=bs("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:w.value,formatted:Oe(w.value),source:w.source});let $=it(),k;process.env.VISA_CLI_NO_UPDATE_CHECK?k={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?k={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?k={kind:"env",var:"NODE_ENV"}:k={kind:"default"},r.push({key:"ui.updateCheck",value:!$,formatted:Oe(!$),source:k});let v=bs("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:v.value,formatted:Oe(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=bs("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:S.value,formatted:Oe(S.value),source:S.source});let P=process.env.VISA_DRY_RUN,M=Ld();if(r.push({key:"tools.dryRun",value:M,formatted:Oe(M),source:P===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:Vd,formatted:Vd,source:{kind:"default"}}),e.includeDev){let _=process.env.VISA_MOCK_KEYCHAIN,T=Nt();r.push({key:"dev.mockKeychain",value:T,formatted:Oe(T),source:ba("VISA_MOCK_KEYCHAIN",!!_),hint:ui()});let re=process.env.VISA_MOCK_TOUCHID,ae=Gn();r.push({key:"dev.mockTouchid",value:ae,formatted:Oe(ae),source:ba("VISA_MOCK_TOUCHID",!!re),hint:ui()});let K=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!K,formatted:Oe(!!K),source:ba("VISA_CLI_DEBUG",!!K)})}return{entries:r,statusError:n}}function G_(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 Bd(e,t={}){if(e.length===0)return"";let n=Math.max(...e.map(s=>s.key.length)),r=Math.max(...e.map(s=>s.formatted.length)),o=[];for(let s of e){let i=s.key.padEnd(n+2),a=s.formatted.padEnd(r+2);o.push(`${i}${a}(${G_(s.source)})`),t.verbose&&s.hint&&o.push(` ${"\u21B3".padStart(n)} ${s.hint}`)}return o.join(`
137
+ `)}function Hd(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 qd(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"}]}}}var tn=require("fs"),Gd=require("os"),va=require("path"),W_=(0,va.join)((0,Gd.homedir)(),".visa-mcp"),Kd=(0,va.join)(W_,"mcp-session-budget.json");function ws(){try{(0,tn.existsSync)(Kd)&&(0,tn.unlinkSync)(Kd)}catch{}}var Sa=require("crypto"),ze=E(dr()),Ln=null,Me=0,fr=0,Ie=0,nn=null,xa=null,Ta=null,xs=Promise.resolve();function z_(e){return Number((0,ze.fromCents)(e))}function zd(e){return(0,ze.toCents)((0,ze.micros)(BigInt(e)))}function Wd(e){return(0,ze.toWire)((0,ze.fromCents)(e))}function wa(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Ss(e){return typeof e=="string"&&/^\d+$/.test(e)}var J_=43,Y_=new RegExp(`^[A-Za-z0-9_-]{${J_}}$`);function X_(e){return typeof e=="string"&&Y_.test(e)}function Z_(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||Ln&&e.session_id!==Ln||typeof e.nonce!="string"||e.nonce.length===0||!X_(e.server_signature)||!wa(e.cumulative)||!wa(e.remaining)||!wa(e.delta)||e.cumulative<Me||Ie>0&&e.cumulative>Ie||Ie>0&&e.remaining>Ie||e.cumulative_micros!==void 0&&!Ss(e.cumulative_micros)||e.remaining_micros!==void 0&&!Ss(e.remaining_micros)||e.delta_micros!==void 0&&!Ss(e.delta_micros)||e.reserved_micros!==void 0&&!Ss(e.reserved_micros))}function It(e){Ln=e,Me=0,fr=0,Ie=0,nn=null,xa=null,Ta=null,xs=Promise.resolve()}function oo(e){Ie=Math.max(0,Math.floor(e))}function Ca(){return Ln}function ka(e){if(!Ln)return null;let t=Me+fr;return Ie>0&&t>Ie&&(t=Ie),{session_budget_id:Ln,cumulative_micros:z_(t),nonce:(0,Sa.randomUUID)(),idempotency_key:e||(0,Sa.randomUUID)()}}function so(e){if(!e)return null;let t;try{t=Buffer.from(e,"base64").toString("utf-8")}catch{return null}let n;try{n=JSON.parse(t)}catch{return null}if(!n||typeof n!="object")return null;let r=n;return Z_(r)?(Me=Math.max(Me,r.cumulative),fr=0,nn=r,r):null}function Jd(){return nn}function Ea(e){let t=zd(e.cumulative_micros);Me=Math.max(Me,t),fr=0;let n={status:"accepted",session_id:e.session_budget_id,cumulative:Me,remaining:Math.max(0,Ie-Me),delta:0,cumulative_micros:Wd(Me),remaining_micros:Wd(Math.max(0,Ie-Me)),delta_micros:"0",nonce:e.nonce};return nn=n,n}function io(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,ze.toCents)((0,ze.micros)(n));if(!Number.isFinite(r)||r<0)return;xa=t;let o=e,s=typeof o.session_id=="string"?o.session_id:Ln??"";nn?(typeof o.remaining_micros=="string"&&/^\d+$/.test(o.remaining_micros)&&(nn.remaining_micros=o.remaining_micros),typeof o.charged_micros=="string"&&/^\d+$/.test(o.charged_micros)&&(nn.delta_micros=o.charged_micros)):nn={session_id:s,cumulative:r,remaining:0,delta:0,nonce:typeof o.transaction_id=="string"?o.transaction_id:"",remaining_micros:typeof o.remaining_micros=="string"&&/^\d+$/.test(o.remaining_micros)?o.remaining_micros:void 0,delta_micros:typeof o.charged_micros=="string"&&/^\d+$/.test(o.charged_micros)?o.charged_micros:void 0}}function Yd(e){let t=e.receipt??null;Ta={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:zd(e.voucher.cumulative_micros),estimatedCumulativeCents:Ts(),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 Xd(){return Ta}function Zd(){return Me}function Qd(){return xa}function Ts(){let e=Me+fr;return Ie>0&&e>Ie&&(e=Ie),e}function em(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return xs=xs.then(()=>{fr+=t}),xs}var Q_=10,eb=1,se=null,tm=Promise.resolve();function Aa(e){let t=tm.catch(()=>{}).then(e);return tm=t.then(()=>{},()=>{}),t}var he=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 Ra(e,t,n){return Aa(()=>nm(e,t,n))}async function nm(e,t,n){if(ws(),se&&new Date(se.expiresAt).getTime()>Date.now())return Ca()!==se.budgetId&&(It(se.budgetId),oo(se.totalCents)),f.info("mcp-session:active-hit",{budgetId:se.budgetId,tool:n.toolName,remainingEstimatedCents:se.totalCents-Ts()}),{budgetId:se.budgetId,isFresh:!1,totalCents:se.totalCents,requestedCapCents:se.totalCents,appliedCapCents:se.totalCents,clampedReason:null};se&&(se=null,It(null));let r=await e.getBalance();if(!r.success)throw new Error(`Could not read balance: ${r.error||"unknown error"}`);let o=n.sessionKind??"explicit",s=o==="one_shot"?eb:Q_,i=Math.max(s,Math.ceil(n.minRequiredCents??s));if(r.balanceCents<i)throw new he(r.balanceCents,i);let a=n.capCentsOverride??Ru(),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:o,...u?{attestation:u}:{}});if(!d.success||!d.budget){let m=d.error||"unknown error";throw new Error(`Failed to open credit session: ${m}`)}let p={budgetId:d.budget.id,expiresAt:d.budget.expiresAt,totalCents:d.budget.totalCents,createdAt:d.budget.createdAt};return se=p,It(p.budgetId),oo(p.totalCents),f.info("mcp-session:opened",{budgetId:p.budgetId,capCents:p.totalCents,requestedCapCents:a,clampedReason:l,sessionKind:o,expiresAt:p.expiresAt,tool:n.toolName}),{budgetId:p.budgetId,isFresh:!0,totalCents:p.totalCents,requestedCapCents:a,appliedCapCents:p.totalCents,clampedReason:l}}async function rm(e,t,n){return Aa(async()=>{let o=rn()?await om(e):null,s=await nm(e,t,n);return{budgetId:s.budgetId,totalCents:s.totalCents,closedPrevious:o,requestedCapCents:s.requestedCapCents,appliedCapCents:s.appliedCapCents,clampedReason:s.clampedReason}})}async function om(e){let n=rn()?.budgetId??Ca(),r=!1,o,s;if(n)try{let i=await e.closeSession(n);r=!!i?.success,typeof i?.finalCumulativeCents=="number"&&(o=i.finalCumulativeCents),typeof i?.finalCumulativeMicros=="string"&&(s=i.finalCumulativeMicros)}catch(i){f.warn("mcp-session:close-server-failed",{budgetId:n,error:i?.message||String(i)})}return ws(),se=null,It(null),{closedServerSide:r,budgetId:n,finalCumulativeCents:o,finalCumulativeMicros:s}}async function Cs(e){return Aa(()=>om(e))}function rn(){return ws(),se?new Date(se.expiresAt).getTime()<=Date.now()?(se=null,It(null),null):{budgetId:se.budgetId,totalCents:se.totalCents,lastReceiptCumulative:Zd(),lastReceiptCumulativeMicros:Jd()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:Qd(),estimatedCumulative:Ts(),lastToolSpend:Xd(),expiresAt:se.expiresAt}:null}var im=E(dr()),sm=10000n;function tb(e){return e<=0n?0:Number((e+sm-1n)/sm)}function am(e){return tb((0,im.fromUsd)(e))}var ks=E(dr()),nb=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;function Es(e){if(typeof e!="string"||!nb.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 o=Number(r);return o<=0?{ok:!1,error:"amount must be greater than $0.00"}:{ok:!0,cents:o,displayUsd:(0,ks.toDisplay)((0,ks.fromCents)(o),{symbol:""})}}var As="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.",cm="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.";var lm=Promise.resolve();function rb(e,t){if(e)try{let n=(0,Ns.fromWire)(e),r=n%10000n===0n?2:6;return(0,Ns.toDisplay)(n,{decimals:r})}catch{}return`$${(t/100).toFixed(2)}`}var um=!1,dm=!1,mm=!1;function Us(e){let t=lm.catch(()=>{}).then(e);return lm=t.then(()=>{},()=>{}),t}async function xm(e){let t=await _e(()=>Ra(N,Ve,{toolName:e.toolId,userContext:e.userContext})),n=ka(e.idempotencyKey);if(!n)throw new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await db(),o,s,i=async()=>N.shortcutWithSession(e.toolId,n,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);try{try{({data:o,voucherReceiptHeader:s}=await i())}catch(u){if(u instanceof wt){let d=Math.min(Math.max(u.retryAfterSecs,0),5)*1e3;f.warn("mcp-session:lock-contended-retrying",{tool:e.toolId,retryAfterSecs:u.retryAfterSecs}),await new Promise(p=>setTimeout(p,d)),{data:o,voucherReceiptHeader:s}=await i()}else throw u}}catch(u){if(u instanceof Qn){if(f.warn("mcp-session:server-invalidated-budget",{code:u.code,budgetId:u.budgetId??t.budgetId,tool:e.toolId}),await Cs(N),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 mm||(mm=!0,console.error(`[visa-cli] Your session was closed by another process; reopened automatically as pay-as-you-go.
138
+ To require an explicit session approval instead, set VISA_REQUIRE_EXPLICIT_SESSION=true.`)),f.info("mcp-session:falling-back-to-payg",{code:u.code,tool:e.toolId}),Tm(e)}throw u instanceof wt?(f.warn("mcp-session:lock-contended-give-up",{tool:e.toolId}),new Error("Another paid call is currently in progress on this session. Wait a moment and try again.")):u}let a=so(s)??(n?Ea(n):null);if(io(o?.receipt_v2),await em(e.estimatedAmountCents),Yd({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),Na(o))return ut(o);let c=await Ma();if(e.idempotencyKey&&La(o,c,e.idempotencyKey))return ut(o);let l=c?ao(c):null;return ut(Ua(o,r,l))}function Fe(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function Ps(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(Ps).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${Ps(r)}`).join(",")}}`}function Oa(e,t,n,r){let o=ye.createHash("sha256").update(`${n}:${Ps(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${o}`}function ob(e,t){return`${e}:${t}`}function sb(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 Os(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,o=Je(r),s=o!==null?o.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=sb(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),c=i!=null?String(i):a;return{batch_id:e,item_id:ob(e,t),index:t,...c!==void 0?{transaction_id:c}:{},...a!==void 0?{ledger_id:a}:{},...s?{amountMicros:s,amount_micros:s,cost_micros:s}:{}}}async function Tm(e){return _e(()=>ab(e))}async function Cm(e,t,n){if(Na(e))return ut(e);let r=await Ma();if(n&&La(e,r,n))return ut(e);let o=r?ao(r):null;return ut(Ua(e,t,o))}async function ib(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 Ve("shortcut_call",t,e.toolId,n,e.userContext);f.info("parentless-single-call:attempt",{tool:e.toolId,approvedMaxCents:t,attested:!!r});let o=r?.nonce??(await N.getAttestationChallenge()).nonce,{data:s,voucherReceiptHeader:i}=await N.shortcutParentless(e.toolId,{...r?{attestation:r}:{},nonce:o,approved_max_cents:t,idempotency_key:e.idempotencyKey},e.toolParams,e.timeoutMs,e.userContext,e.metaTool);return so(i),io(s?.receipt_v2),f.info("parentless-single-call:completed",{tool:e.toolId}),Cm(s,e.beforeBalanceMicros,e.idempotencyKey)}async function ab(e){let t=Math.max(1,Math.ceil(e.estimatedAmountCents)),n=await N.getBalance();if(!n.success)throw new Error(`Could not read balance: ${n.error||"unknown error"}`);if(n.balanceCents<t)throw new he(n.balanceCents,t);let r=t,o=ao(n);if(Dd()&&!um){let l=e.idempotencyKey??ye.randomUUID();try{return await ib({toolId:e.toolId,toolParams:e.toolParams,estimatedAmountCents:e.estimatedAmountCents,cap:r,beforeBalanceMicros:o,userContext:e.userContext,metaTool:e.metaTool,timeoutMs:e.timeoutMs,idempotencyKey:l})}catch(u){if(u instanceof ot)um=!0,f.info("parentless-single-call:falling-back-to-session",{tool:e.toolId,status:u.status,serverErrorCode:u.serverErrorCode});else throw u}}let s=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(r/100).toFixed(2)})`,i=await Ve("session_create",r,"Visa CLI Session",s,e.userContext),a=await N.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;It(c),oo(a.budget.totalCents),f.info("on-demand-session:opened",{budgetId:c,capCents:a.budget.totalCents,tool:e.toolId});try{let l=ka(e.idempotencyKey);if(!l)throw new Error(`Internal: mintVoucher returned null after on-demand session-open ${c}`);let{data:u,voucherReceiptHeader:d}=await N.shortcutWithSession(e.toolId,l,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(so(d)||Ea(l),io(u?.receipt_v2),Na(u))return ut(u);let p=await Ma();if(e.idempotencyKey&&La(u,p,e.idempotencyKey))return ut(u);let m=p?ao(p):null;return ut(Ua(u,o,m))}finally{try{await N.closeSession(c)}catch(l){f.warn("on-demand-session:close-failed",{budgetId:c,error:l?.message||String(l)})}It(null),f.info("on-demand-session:closed",{budgetId:c,tool:e.toolId})}}async function sn(e){return Us(async()=>rn()?xm(e):Tm(e))}function Ds(){return $e()}var N=new Pe(()=>B.getSessionToken());function Je(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function ao(e){return Je(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function cb(e){if(e<0n&&(e=0n),e>=1000000n){let r=(e+5000n)/10000n,o=r/100n,s=r%100n;return`$${o.toString()}.${s.toString().padStart(2,"0")}`}let t=e%1000000n;return t===0n?"$0.00":`$0.${t.toString().padStart(6,"0").replace(/0+$/,"")}`}function lb(e){let t=Je(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=Je(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=Je(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function Rs(e,t="INVALID_TOOL_PARAMS",n){return{success:!1,error_code:t,code:t,error:e,message:e,...n??{}}}function ub(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 db(){try{let e=await N.getBalance();return e.success?ao(e):null}catch{return null}}async function Ma(){try{let e=await N.getBalance();return e.success?e:null}catch{return null}}function Na(e){if(!e||e.success===!1)return!1;let t=Je(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=Je(e.amountMicros??e.amount_micros??e.charged_micros),r=t??n;if(r===null||r<=0n)return!1;let o=r.toString();return e.amountMicros??=o,e.amount_micros??=o,e.charged_micros??=o,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),!0}function La(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 o=Je(r.deltaMicros)??BigInt(r.deltaCents)*10000n,s=o<0n?-o:o;if(s<=0n)return!1;let i=s.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(s)/1e6),!0}function Ua(e,t,n){if(!e||e.success===!1||t===null||n===null)return e;let r=t-n;if(r<=0n)return e;let o=r.toString();return e.amountMicros??=o,e.amount_micros??=o,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),e}var mb="3.0.1",GC=["","","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(`
139
+ `);function Xe(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=Nr(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(Eu())return{opened:!1,url:t,blockedReason:"suppressed"};let n=xi();if(n.headless)return f.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let r=ll(t,Ds());if(!r)return f.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let o=dl(r);return o?((0,Sm.execFile)(o.cmd,o.args,s=>{s&&f.warn(`Browser open failed: ${s.message}. URL: ${r}`)}),{opened:!0,url:r}):(f.info(`No browser command for platform "${co.platform()}". URL: ${r}`),{opened:!1,url:r,blockedReason:"unsupported_platform"})}async function _e(e){return pr(N,e,Om)}var km="get_cards",Em="set_default_card";function pb(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 '${km}' to see enrolled cards and '${Em}' to switch, then retry the original request.`}function fb(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 '${km}' to see enrolled cards and '${Em}' to switch. Do not retry automatically.`}function Ze(e,t){let n=e.retryable?pb(e.code,e.retryAfter):fb(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 gb(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 gr=null,hb=3e4;function Am(){gr=null}var on=class extends Error{constructor(n){super(`${Ms()} attestation is required for this action, but it is not available in this MCP process. `+Da());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function js(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. `+Da()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function yb(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:As,agent_guidance:cm}}function Ms(){return process.platform==="darwin"?"Touch ID":"local biometric"}function Da(){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 _b(e){let t=Date.now();if(gr&&gr.expiresAt>t)return{required:gr.required,hasRegisteredKey:gr.hasRegisteredKey};try{let n=await N.getStatus(e),r=n.attestationRequired!==!1,o=dt(n);return gr={required:r,hasRegisteredKey:o,expiresAt:t+hb},{required:r,hasRegisteredKey:o}}catch{return{required:!0,hasRegisteredKey:!0}}}async function Ve(e,t,n,r,o,s){if(!s?.forceRequired){let i=await _b(o);if(!i.required){f.info("attestation:skipped-by-server-policy",{context:e});return}if(!i.hasRegisteredKey){f.info("attestation:skipped-no-registered-key",{context:e});return}}if(!de())throw f.warn("attestation:unavailable",{context:e}),new on(e);f.info("attestation:attempt",{context:e,amount:t,merchant:n});try{let{nonce:i}=await N.getAttestationChallenge(),a=Buffer.from(JSON.stringify({nonce:i,amount:t,merchant:n,context:e})).toString("base64");f.info("touchid:prompt",{context:e,amount:t,merchant:n});let c=await Nn(a,r);return f.info("attestation:success",{context:e,amount:t,merchant:n}),{signature:c,nonce:i,amount:t,merchant:n}}catch(i){throw f.error("attestation:failure",{context:e,amount:t,merchant:n,error:i.message}),i}}var pm="[dry-run] https://placeholder.visa-cli.dev/image.png",bb=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"]),vb=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 wb(e,t){return t==="run_llm"||e.startsWith("or-")?"llm":t==="generate_image"||bb.has(e)?"image":t==="generate_video"||vb.has(e)?"video":Sb(e)?"media":null}function Sb(e){let t=ur(e);return t?!Fa(t):!1}function xb(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function Tb(e){return e==="llm"?"OpenRouter":"fal.ai"}function hr(e,t,n,r){let o={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:Tb(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${xb(n)}`;return{...o,content:i,data:{content:i,model:t,dry_run:!0}}}return{...o,urls:[pm],data:{[e==="video"?"videoUrl":e==="image"?"imageUrl":"url"]:pm,metadata:{dry_run:!0}}}}async function Ia(e){let t=e.mode??"mock",n=t==="preflight"?"/v1/telemetry/preflight":"/v1/telemetry/dry-run",r=t==="preflight"?"preflight":null;try{await N.emitTelemetry([{id:ye.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(o){f.warn("dry_run:telemetry_failed",{tool:e.toolName,error:o?.message||String(o),mode:t})}}var Cb="https://openrouter.ai/api/v1/chat/completions",kb="openrouter/free",Eb=50,Ab=15e3;function Rb(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 Ib(e,t,n){let r=process.env.OPENROUTER_API_KEY;if(!r)return f.warn("preflight:no_openrouter_key_falling_back_to_mock",{tool:e}),{result:hr("llm",e,t,n),degraded:!0,resolvedModel:null};let o=Rb(t),s;try{s=await rt(Cb,{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:kb,messages:[{role:"user",content:o}],max_tokens:Eb}),timeoutMs:Ab})}catch(u){return f.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:hr("llm",e,t,n),degraded:!0,resolvedModel:null}}if(!s.ok){let u=await s.text().catch(()=>"");return f.warn("preflight:openrouter_http_error_falling_back_to_mock",{tool:e,status:s.status,bodyExcerpt:u.slice(0,200)}),{result:hr("llm",e,t,n),degraded:!0,resolvedModel:null}}let i;try{i=await s.json()}catch(u){return f.warn("preflight:openrouter_invalid_json_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:hr("llm",e,t,n),degraded:!0,resolvedModel:null}}let a=typeof i?.choices?.[0]?.message?.content=="string"?i.choices[0].message.content:"",c=typeof i?.model=="string"?i.model:null;return{result:{success:!0,transactionId:`preflight:${n??e}`,amount:0,rail:"preflight",merchantName:"OpenRouter",dry_run:!0,preflight:!0,metadata:{dry_run:!0,preflight:!0,model_used:c},content:a,data:{content:a,model:c??e,dry_run:!0,preflight:!0}},degraded:!1,resolvedModel:c}}async function lo(e,t,n,r){let o=_a();if(!o)return null;let s=wb(e,r);if(!s)return null;let i=Date.now();if(o==="mock"){let l=hr(s,e,t,r);return await Ia({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:l,userContext:n,startedAt:i,mode:"mock"}),f.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:s,mode:o}),l}if(s!=="llm"){f.warn("preflight:not_supported_for_kind_falling_back_to_mock",{tool:e,kind:s});let l=hr(s,e,t,r);return await Ia({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 Ib(e,t,r);return await Ia({toolName:r??e,resolvedModel:c??(r&&r!==e?e:null),toolParams:t,result:a,userContext:n,startedAt:i,mode:"preflight"}),f.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:s,mode:o}),a}async function $t(e,t,n){let r=await N.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 Pt(e){return am(e.amount)}function $b(e,t,n){return n.has(e.resolvedTool)?0:Math.max(1,Pt(t[e.resolvedTool]))}function Pb(){return Ls.join(co.homedir(),".visa-mcp","allium-results")}var WC=16*1024,zC=50*1024*1024;function Ob(){let e=Pb();try{if(!Ye.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=Ye.readdirSync(e),n=0,r=0;for(let o of t)try{let s=Ye.statSync(Ls.join(e,o));s.isFile()&&(n+=s.size,r++)}catch{}return{file_count:r,size_bytes:n,path:e}}catch(t){return f.warn("allium:disk_usage_error",{error:t.message}),{file_count:0,size_bytes:0,path:e}}}var fm=3600*1e3,$a=0;function Mb(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function uo(e){if(!Au()&&!(Date.now()<$a))try{if(!await B.getSessionToken())return;await N.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}}),f.info("feed:submitted",{tool:e.tool,mediaType:e.mediaType,transactionId:e.transactionId})}catch(t){if(Mb(t)){let n=$a===0;$a=Date.now()+fm,n&&f.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:fm});return}f.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function Nb(e,t){let n=(e.state||"").trim().toUpperCase(),r=(e.county||"").trim(),o=(e.start_date||"").trim(),s=(e.end_date||o).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(o))throw new Error('start_date must be YYYY-MM (e.g. "2025-08").');if(s&&!/^\d{4}-\d{2}$/.test(s))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})`;f.info("payment:attempt",{tool:"get_visa_smi",amount:a,merchant:i});try{return await _e(async()=>{let l=await Ve("get_visa_smi",a,i,c),u=await N.getVisaSmi({state:n,county:r,start_date:o,end_date:s,attestation:l,idempotencyKey:ye.randomUUID()},t);return u.success?f.info("payment:success",{tool:"get_visa_smi",merchant:i,charged_cents:u.charged_cents}):f.warn("payment:declined",{tool:"get_visa_smi",merchant:i,message:u.error}),u})}catch(l){if(l instanceof le)return f.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:l.code,retryable:l.retryable}),Ze(l,{amount:a,merchantName:i,description:"Visa SMI data"});throw f.error("payment:failure",{tool:"get_visa_smi",merchant:i,error:l.message}),l}}async function Lb(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await lo("generate_image_card",e,t);if(n)return n;let r=await $t("generate_image_card",void 0,t),o=ye.randomUUID();f.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await _e(async()=>{let s;try{s=await sn({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:Pt(r),userContext:t,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof he)return Fe(i);throw i}return f.info("payment:success",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Xe(i)),uo({prompt:e.prompt,tool:"generate_image_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):f.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof le)return f.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Ze(s,r);throw f.error("payment:failure",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function Ub(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await lo("generate_image_fast_card",e,t);if(n)return n;let r=await $t("generate_image_fast_card",void 0,t),o=ye.randomUUID();f.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await _e(async()=>{let s;try{s=await sn({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:Pt(r),userContext:t,timeoutMs:6e4,idempotencyKey:o})}catch(i){if(i instanceof he)return Fe(i);throw i}return f.info("payment:success",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Xe(i)),uo({prompt:e.prompt,tool:"generate_image_fast_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):f.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof le)return f.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Ze(s,r);throw f.error("payment:failure",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function Db(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await lo("generate_video_tempo_card",e,t);if(n)return n;let r=await $t("generate_video_tempo_card",void 0,t),o=ye.randomUUID();f.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await _e(async()=>{let s;try{s=await sn({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:Pt(r),userContext:t,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof he)return Fe(i);throw i}return f.info("payment:success",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Xe(i)),uo({prompt:e.prompt,tool:"generate_video_tempo_card",mediaUrl:s.urls[0],mediaType:"video",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):f.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof le)return f.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Ze(s,r);throw f.error("payment:failure",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function jb(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 $t("generate_music_tempo_card",void 0,t),r=ye.randomUUID();f.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await _e(async()=>{let o;try{o=await sn({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:Pt(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(s){if(s instanceof he)return Fe(s);throw s}return f.info("payment:success",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),o.urls?.length&&o.status!=="processing"?(o.urls.forEach(s=>Xe(s)),uo({prompt:e.prompt,tool:"generate_music_tempo_card",mediaUrl:o.urls[0],mediaType:"audio",cost:o.amount??n.amount,transactionId:o.transactionId,userContext:t})):o.urls?.length&&o.status==="processing"?(o._preliminary_urls=o.urls,delete o.urls,f.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):f.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof le)return f.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Ze(o,n);throw f.error("payment:failure",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}async function Fb(e,t){let n=await $t("check_music_status_tempo_card",void 0,t),r=ye.randomUUID();f.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await _e(async()=>{let o;try{o=await sn({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:Pt(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof he)return Fe(s);throw s}return f.info("payment:success",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),o.urls?.length&&o.urls.forEach(s=>Xe(s)),o})}catch(o){if(o instanceof le)return f.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Ze(o,n);throw f.error("payment:failure",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}async function Vb(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 $t("query_onchain_prices",void 0,t),r=ye.randomUUID();f.info("payment:attempt",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName});try{return await _e(async()=>{let o;try{o=await sn({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:Pt(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof he)return Fe(s);throw s}if(f.info("payment:success",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,mode:"session"}),Array.isArray(o?.data))o.data=o.data.map(s=>{if("mint"in s&&!("address"in s)){let{mint:i,...a}=s;return{address:i,...a}}return s});else if(o&&"mint"in o&&!("address"in o)){let{mint:s,...i}=o;return{address:s,...i}}return o})}catch(o){if(o instanceof le)return f.warn("payment:declined",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Ze(o,n);throw f.error("payment:failure",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}var Bb=["generate_music_tempo_card"],Is=10,gm=5,hm=new Map;function ym(e){let t=hm.get(e);if(t!==void 0)return t;let r=ur(e)?.isAsync===!0||Bb.includes(e);return hm.set(e,r),r}var Hb=36e4,qb=18e4,Kb=15e3,Gb=12e4,Wb=2e3;function Pa(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}function zb(e,t){return ye.createHash("sha256").update(`${e}:${Ps(t)}`).digest("hex")}function Jb(e){let{results:t,batchId:n,index:r,item:o,itemResult:s,preview:i,isFree:a,catalogName:c}=e;a&&s&&typeof s=="object"&&!Array.isArray(s)&&s.merchantName==null&&(s.merchantName=c??o.resolvedTool),t.push({success:s?.success!==!1,tool:o.resolvedTool,...s,...Os(n,r,s)});let l=0,u=0n;if(s?.success!==!1){let d=Je(s?.amountMicros??s?.amount_micros),p=typeof s?.amount=="number"?s.amount:i?.amount??0;d!==null&&d>0n?u+=d:u+=BigInt(Math.round(p*1e6)),l+=p}return s?.urls&&s.urls.forEach(d=>Xe(d)),{deltaCharged:l,deltaMicros:u}}function Yb(e){let{results:t,resolvedItems:n,uniqueTools:r,isHomogeneous:o,primaryTool:s,merchantNames:i,totalAmount:a,totalCharged:c,totalChargedMicros:l,batchId:u,mode:d}=e,p=t.filter($=>$?.success===!1).length,m=t.length-p,g=t.flatMap($=>Array.isArray($?.urls)?$.urls:[]),h=l>0n?Number(l)/1e6:Math.round((c+Number.EPSILON)*100)/100,w=m===0?"failure":p===0?"success":"partial";return f.info("payment:success",{tool:"batch",batchTool:s,count:n.length,totalAmount:a,totalCharged:h,merchant:i,successCount:m,failedCount:p,outcome:w,mode:d,batchId:u}),{success:m>0,outcome:w,batch_id:u,tool:o?r[0]:s,count:n.length,successCount:m,failedCount:p,totalCharged:h,...l>0n?{totalChargedMicros:l.toString(),amountMicros:l.toString(),amount_micros:l.toString()}:{},merchantName:i,results:t,...g.length?{urls:g}:{}}}async function Xb(e){let{resolvedItems:t,previews:n,freeTools:r,catalogEntries:o,itemCeilingCents:s,batchCeilingCents:i,uniqueTools:a,isHomogeneous:c,primaryTool:l,merchantNames:u,totalAmount:d,timeoutMs:p,batchId:m,userContext:g}=e,h=i,w=await N.getBalance();if(!w.success)throw new Error(`Could not read balance: ${w.error||"unknown error"}`);if(w.balanceCents<h)throw new he(w.balanceCents,h);let $=`batch-${m}`,k=`spend up to $${(h/100).toFixed(2)} across a batch of ${t.length}`,{batchParentId:v}=await _e(async()=>{let _=await Ve("batch_open",h,$,k,g,{forceRequired:!0}),T=_?.nonce??(await N.getAttestationChallenge()).nonce;f.info("parentless-batch:open-attempt",{batchTool:l,count:t.length,approvedTotalCents:h,attested:!!_});let{batch_parent_id:re}=await N.batchOpen({..._?{attestation:_}:{},nonce:T,approved_total_cents:h,batch_id:m});return{batchParentId:re}});f.info("parentless-batch:opened",{batchTool:l,count:t.length,batchParentId:v});let S=[],P=0,M=0n;try{for(let _=0;_<t.length;_+=1){let T=t[_],re=n[T.resolvedTool],ae=r.has(T.resolvedTool);try{let K;if(ae)K=await N.shortcut(T.resolvedTool,T.params,p,g,"batch");else{let{data:ee,voucherReceiptHeader:kr}=await N.shortcutParentlessBatchItem(T.resolvedTool,{batch_parent_id:v,batch_id:m,batch_index:_,batch_request_hash:zb(T.resolvedTool,T.params),item_ceiling_cents:s[_],idempotency_key:Oa(m,_,T.resolvedTool,T.params)},T.params,p,g,"batch");so(kr),io(ee?.receipt_v2),K=await Cm(ee,null,Oa(m,_,T.resolvedTool,T.params))}let{deltaCharged:He,deltaMicros:oe}=Jb({results:S,batchId:m,index:_,item:T,itemResult:K,preview:re,isFree:ae,catalogName:o[T.resolvedTool]?.name});P+=He,M+=oe}catch(K){if(K instanceof he&&S.length===0)return Fe(K);f.warn("payment:batch-item-failed",{tool:T.resolvedTool,index:_,error:K?.message||String(K)}),S.push({success:!1,tool:T.resolvedTool,...Os(m,_),error:K?.message||String(K)})}}return Yb({results:S,resolvedItems:t,uniqueTools:a,isHomogeneous:c,primaryTool:l,merchantNames:u,totalAmount:d,totalCharged:P,totalChargedMicros:M,batchId:m,mode:"parentless"})}catch(_){if(_ instanceof le)return f.warn("payment:declined",{tool:"batch",batchTool:l,count:t.length,totalAmount:d,merchant:u,code:_.code,retryable:_.retryable}),Ze(_,{amount:d,merchantName:u});throw f.error("payment:failure",{tool:"batch",batchTool:l,count:t.length,totalAmount:d,merchant:u,error:_.message}),_}}async function Zb(e,t){let n;if(e.requests?.some(_=>_.tool||_.tool_id)&&e.requests)n=e.requests.map(_=>{let T=_.tool||_.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 re=en(T,_.tier||e.tier,_.prompt??t),{tool:ae,tool_id:K,tier:He,params:oe,...ee}=_,kr=oe&&typeof oe=="object"?{...oe,...ee}:ee;return{resolvedTool:re,params:kr}});else if(e.tool){let _=en(e.tool,e.tier,e.params?.prompt??t);if(e.count!==void 0){if(!Number.isSafeInteger(e.count)||e.count<1)return Pa("BATCH_INVALID_COUNT","Batch count must be a positive integer.");if(e.count>Is)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${Is} items. Please split into smaller batches.`}}n=(e.requests||(e.count!==void 0&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(re=>({resolvedTool:_,params:re}))}else return Pa("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return Pa("BATCH_EMPTY","Batch requires at least one item.");if(n.length>Is)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${Is} items. Please split into smaller batches.`};if([...new Set(n.map(_=>_.resolvedTool))].some(ym)&&n.length>gm)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${gm} items. Please use multiple batches for more.`};let i=[...new Set(n.map(_=>_.resolvedTool))],a=i.length===1,c={};for(let _ of i)c[_]=await Mm(_);let l=new Set(i.filter(_=>c[_]&&Fa(c[_]))),u={};for(let _ of i)l.has(_)||(u[_]=await $t(_,void 0,t));let d=0;for(let _ of n)d+=u[_.resolvedTool]?.amount??0;let p=n.map(_=>$b(_,u,l)),m=p.reduce((_,T)=>_+T,0),g=[...new Set([...Object.values(u).map(_=>_.merchantName),...i.filter(_=>l.has(_)).map(_=>c[_]?.name??_)])].join(", "),h=a?i[0]:"mixed";f.info("payment:attempt",{tool:"batch",batchTool:h,count:n.length,totalAmount:d,merchant:g,heterogeneous:!a});let w=n.some(_=>ym(_.resolvedTool)),$=n.some(_=>_.resolvedTool.startsWith("or-")||_.resolvedTool==="run_llm"||_.resolvedTool==="execute_tool"),k=w?Hb:$?qb+n.length*Kb:Gb+n.length*Wb,v=ye.randomUUID(),S=[],P=0,M=0n;return Us(async()=>{let _=!rn();if(jd()&&!dm&&_&&m>0)try{return await Xb({resolvedItems:n,previews:u,freeTools:l,catalogEntries:c,itemCeilingCents:p,batchCeilingCents:m,uniqueTools:i,isHomogeneous:a,primaryTool:h,merchantNames:g,totalAmount:d,timeoutMs:k,batchId:v,userContext:t})}catch(T){if(T instanceof ot)dm=!0,f.info("parentless-batch:falling-back-to-session",{batchTool:h,count:n.length,status:T.status,serverErrorCode:T.serverErrorCode});else{if(T instanceof he)return Fe(T);throw T}}if(_&&m>0)try{let T=m;await _e(()=>Ra(N,Ve,{toolName:"batch",userContext:t,sessionKind:"one_shot",minRequiredCents:T,capCentsOverride:T}))}catch(T){return T instanceof he?Fe(T):(f.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 oe=0;oe<n.length;oe+=1){let ee=n[oe],kr=u[ee.resolvedTool];try{let te=l.has(ee.resolvedTool)?await N.shortcut(ee.resolvedTool,ee.params,k,t,"batch"):await xm({toolId:ee.resolvedTool,toolParams:ee.params,estimatedAmountCents:p[oe],userContext:t,metaTool:"batch",timeoutMs:k,idempotencyKey:Oa(v,oe,ee.resolvedTool,ee.params)});if(l.has(ee.resolvedTool)&&te&&typeof te=="object"&&!Array.isArray(te)&&te.merchantName==null&&(te.merchantName=c[ee.resolvedTool]?.name??ee.resolvedTool),S.push({success:te?.success!==!1,tool:ee.resolvedTool,...te,...Os(v,oe,te)}),te?.success!==!1){let Er=Je(te?.amountMicros??te?.amount_micros),Uc=typeof te?.amount=="number"?te.amount:kr?.amount??0;Er!==null&&Er>0n?M+=Er:M+=BigInt(Math.round(Uc*1e6)),P+=Uc}te?.urls&&te.urls.forEach(Er=>Xe(Er))}catch(te){if(te instanceof he&&S.length===0)return Fe(te);f.warn("payment:batch-item-failed",{tool:ee.resolvedTool,index:oe,error:te?.message||String(te)}),S.push({success:!1,tool:ee.resolvedTool,...Os(v,oe),error:te?.message||String(te)})}}let T=S.filter(oe=>oe?.success===!1).length,re=S.length-T,ae=S.flatMap(oe=>Array.isArray(oe?.urls)?oe.urls:[]),K=M>0n?Number(M)/1e6:Math.round((P+Number.EPSILON)*100)/100,He=re===0?"failure":T===0?"success":"partial";return f.info("payment:success",{tool:"batch",batchTool:h,count:n.length,totalAmount:d,totalCharged:K,merchant:g,successCount:re,failedCount:T,outcome:He,mode:"session",batchId:v}),{success:re>0,outcome:He,batch_id:v,tool:a?i[0]:h,count:n.length,successCount:re,failedCount:T,totalCharged:K,...M>0n?{totalChargedMicros:M.toString(),amountMicros:M.toString(),amount_micros:M.toString()}:{},merchantName:g,results:S,...ae.length?{urls:ae}:{}}}catch(T){if(T instanceof le)return f.warn("payment:declined",{tool:"batch",batchTool:h,count:n.length,totalAmount:d,merchant:g,code:T.code,retryable:T.retryable}),Ze(T,{amount:d,merchantName:g});throw f.error("payment:failure",{tool:"batch",batchTool:h,count:n.length,totalAmount:d,merchant:g,error:T.message}),T}finally{if(_){let T=await Cs(N);f.info("batch-session:closed",{budgetId:T.budgetId,closedServerSide:T.closedServerSide})}}})}function Qb(){let e=!1,t;try{let r=Ls.join(co.homedir(),".claude","settings.json");if(Ye.existsSync(r)){let o=JSON.parse(Ye.readFileSync(r,"utf-8")),s=typeof o.statusLine=="object"?o.statusLine.command:"";e=Ht(s)}}catch{}let n=Fo();return n||(t="visa-cli config hud enable"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function ev(e){let[t,n]=await Promise.all([N.getStatus(e),N.getBalance().catch(s=>(f.warn("get_status:balance_fetch_failed",{error:s?.message||String(s)}),null))]);typeof t?.dailyRemaining=="number"&&(t.dailyRemaining=Math.round(t.dailyRemaining*100)/100);let r=Ob();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=Qb(),!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=mb,Array.isArray(t.cards)&&(t.cards=t.cards.map(s=>({...s,displayName:ja(s)})),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 o=rn();if(t.sessionMode=!!o,o){let s=Math.max(0,o.totalCents-o.estimatedCumulative);t.activeSession={budgetId:o.budgetId,capCents:o.totalCents,capUsd:o.totalCents/100,lastReceiptCumulativeCents:o.lastReceiptCumulative,estimatedCumulativeCents:o.estimatedCumulative,spentCents:o.estimatedCumulative,spentUsd:o.estimatedCumulative/100,estimatedRemainingCents:s,estimatedRemainingUsd:s/100,...o.lastToolSpend?{lastToolSpend:{toolName:o.lastToolSpend.toolName,resolvedToolId:o.lastToolSpend.resolvedToolId,estimatedAmountCents:o.lastToolSpend.estimatedAmountCents,estimatedAmountUsd:o.lastToolSpend.estimatedAmountCents/100,voucherCumulativeCents:o.lastToolSpend.voucherCumulativeCents,estimatedCumulativeCents:o.lastToolSpend.estimatedCumulativeCents,receiptDeltaCents:o.lastToolSpend.receiptDeltaCents,receiptCumulativeCents:o.lastToolSpend.receiptCumulativeCents,receiptRemainingCents:o.lastToolSpend.receiptRemainingCents,recordedAt:o.lastToolSpend.recordedAt}}:{},expiresAt:o.expiresAt}}return t}function ja(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",o=e.isDefault===!0?" (default)":"";return`${n} ending in ${r}${o}`}async function Rm(e,t){try{let r=((await N.getStatus(t)).cards||[]).find(o=>o?.id===e);if(r)return ja(r)}catch(n){f.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function tv(e){let n=(await N.getStatus(e)).cards||[];return n.length===0?{cards:[],message:"No cards enrolled. Use the add_card tool to add a payment card."}:n.some(o=>!Number.isInteger(o?.id)||o.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(o=>({...o,displayName:ja(o)})),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 nv(e,t){return await N.getTransactions({limit:e.limit,offset:e.offset},t)}async function rv(e,t){return await N.feedback(e.message,e.transaction_id,t)}async function ov(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Un("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=Es(String(e.amount));if(n.ok===!1)return{success:!1,error:n.error};let r=n.cents,o=r/100,s=ye.randomUUID();f.info("buy_credits:attempt",{amountCents:r});try{return await _e(async()=>{let i=await Ve("balance-topup",o,"Visa CLI Balance",`top up balance with $${n.displayUsd}`,t,{forceRequired:!0}),a=await N.topupBalance({amount_cents:r,idempotency_key:s,attestation:i});if(a.success){f.info("buy_credits:success",{amountCents:r,balanceCents:a.balanceCents,balanceMicros:a.balanceMicros});let c=rb(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 f.warn("buy_credits:failed",{amountCents:r,error:a.error}),a})}catch(i){if(i instanceof on)return yb();if(i instanceof st)return f.warn("buy_credits:ambiguous",{amountCents:r,code:i.code,transactionId:i.transactionId}),gb(i);throw f.error("buy_credits:failure",{amountCents:r,error:i.message}),i}}function Un(e,t){return{success:!1,error:t,code:e,message:t}}async function sv(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Un("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 Un("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 Un("INVALID_VALUE","dailyLimit must be at least $1");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return Un("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");f.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await _e(async()=>{let n=await Ve("spending-controls",0,"","update spending controls"),r=await N.updateSpendingControls({maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit,confirm:!0,attestation:n},t);return f.info("spending_controls:success",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit}),r})}catch(n){if(f.error("spending_controls:failure",{error:n.message}),n instanceof on)return js(n,"update_spending_controls");if(String(n?.message||n).includes("Attestation required"))return Un("ATTESTATION_REQUIRED","Changing spending controls requires local attestation, even when payment biometric prompts are disabled.");throw n}}async function iv(e){let t=await ro({api:N,includeDev:!!e.includeDev});return{config:t.entries.map(n=>({key:n.key,value:n.value,source:n.source,hint:n.hint})),statusError:t.statusError}}async function av(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."};f.info("config:set",{key:e.key});try{let t=ns(e.key,e.value);return f.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 St?"UNKNOWN_KEY":t instanceof xt?"SERVER_CONTROLLED":t instanceof qt?"RETIRED_KEY":"INVALID_VALUE";return f.warn("config:set:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(Gt).sort()}}}async function cv(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."};f.info("config:unset",{key:e.key});try{let t=rs(e.key);return f.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 St?"UNKNOWN_KEY":t instanceof xt?"SERVER_CONTROLLED":t instanceof qt?"RETIRED_KEY":"INVALID_VALUE";return f.warn("config:unset:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(Gt).sort()}}}async function lv(e){let t=await N.getStatus(e),n=t.attestationRequired!==!1,r=dt(t),o=de(),s=n?r?o?`${Ms()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${Ms()} is not available in this process. ${Da()}`:"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:o,platform:process.platform,effectiveRequiredOnThisDevice:n&&r&&o,canDisableFromThisDevice:!n||!r||o,message:s}}async function uv(e){f.info("biometric:on");let t=await _s(N,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 N.setBiometricPreference({required:!0},e);return n.success?(Am(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:n.error||"unknown error"}}async function dv(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Un("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.");f.info("biometric:off");try{return await _e(async()=>{let n=await N.getStatus(t),r;if(dt(n)&&(r=await Ve("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${Ms()} confirmation required to disable \u2014 not available on this device.`);let o=await N.setBiometricPreference({required:!1,attestation:r},t);if(!o.success)throw new Error(o.error||"unknown error");return Am(),{success:!0,required:!1,message:"Touch ID is no longer required for payments."}})}catch(n){if(f.error("biometric:off:failure",{error:n.message}),n instanceof on)return js(n,"biometric_off");throw n}}var _m=3e4,mv=3e5;async function Im(e,t,n="login"){let r=ye.randomUUID(),o=`${e}${e.includes("?")?"&":"?"}state=${r}`,s=Xe(o);return!s.opened&&s.blockedReason!=="non_internal_host"&&s.blockedReason!=="invalid_url"?$m(o,s,n):s.opened?{...await Pm(r,t,n),browserUrl:o}:{success:!1,browserUrl:o,message:`Could not open the browser URL safely. Please check the configured auth server and try again. URL: ${o}`}}function $m(e,t,n){let r=n==="enrollment"?"card enrollment":n==="attestation-recovery"?"biometric reset":"login",o=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 ${o}. Open this URL to continue ${r}: ${e}`}}async function Pm(e,t,n="login"){let r=Date.now()+mv;for(;Date.now()<r;)try{let s=await fetch(`${Ds()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:_m,...t&&{user_context:t}}),signal:AbortSignal.timeout(_m+5e3)});if(!s.ok){await Ft(s,a=>{f.warn("auth_status:retry_after_http_error",{status:s.status,delayMs:a})});continue}let i=await s.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 f.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=qd(a);if(n!=="enrollment"&&i.sessionToken){await B.saveSessionToken(i.sessionToken);let u=i.user||"",d=i.last4||"****";return f.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 f.info("auth:card_added",{last4:l,bonusCents:a}),{success:!0,message:`Card ending in ${l} enrolled and ready for payments.`,...c||{}}}}catch{await Ft(void 0,s=>{f.warn("auth_status:retry_after_network_error",{delayMs:s})})}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 Om(e){let t=ye.randomUUID(),n;try{n=await N.startAttestationRecovery(t,e)}catch(s){return{success:!1,message:`Could not start biometric reset: ${s?.message||"unknown error"}`}}if(!n.success||!n.recoveryUrl)return{success:!1,message:n.error||"Could not start biometric reset. Please try again."};let r=Xe(n.recoveryUrl);return!r.opened&&r.blockedReason!=="non_internal_host"&&r.blockedReason!=="invalid_url"?$m(n.recoveryUrl,r,"attestation-recovery"):r.opened?{...await Pm(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 pv(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."};f.info("cards:remove_attempt",{cardId:n});let r=`remove-card:${n}`,o=`remove ${await Rm(n,t)}`;try{return await _e(async()=>{let s=await Ve(r,0,"",o,t,{forceRequired:!0}),i=await N.removeCard(n,{attestation:s},t);return f.info("cards:remove_success",{cardId:n,promotedId:i?.promotedId??null}),i})}catch(s){if(f.error("cards:remove_failure",{cardId:n,error:s.message}),s instanceof on)return js(s,"remove_card");throw s}}async function fv(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."};f.info("cards:set_default_attempt",{cardId:n});let r=`set-default-card:${n}`,o=`set ${await Rm(n,t)} as default`;try{return await _e(async()=>{let s=await Ve(r,0,"",o,t,{forceRequired:!0}),i=await N.setDefaultCard(n,{attestation:s},t);return f.info("cards:set_default_success",{cardId:n}),i})}catch(s){if(f.error("cards:set_default_failure",{cardId:n,error:s.message}),s instanceof on)return js(s,"set_default_card");throw s}}async function gv(e){return f.info("auth:login_attempt"),Im(`${Ds()}/login`,e)}function hv(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 yv(e={},t){let n;try{n=hv(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return Us(async()=>{let r=await _e(()=>rm(N,Ve,{toolName:"start_session",userContext:t,capCentsOverride:n}));f.info("session:started",{budgetId:r.budgetId,totalCents:r.totalCents,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious});let o=(r.appliedCapCents/100).toFixed(2),s=(r.requestedCapCents/100).toFixed(2),i=`Session started with a $${o} 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 $${s} was clamped to your prepaid balance of $${o}. 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 _v(){let e=rn();if(!e)return{success:!0,active:!1,message:"No active explicit approval window. Paid calls use a one-shot session in pay-as-you-go mode; see transaction_history for records."};let t=Math.max(0,e.totalCents-e.estimatedCumulative);return{success:!0,active:!0,budgetId:e.budgetId,totalCents:e.totalCents,estimatedCumulativeCents:e.estimatedCumulative,estimatedRemainingCents:t,expiresAt:e.expiresAt,lastToolSpend:e.lastToolSpend,message:`Active explicit approval window: about $${(t/100).toFixed(2)} remaining of $${(e.totalCents/100).toFixed(2)}.`}}async function bv(){return Us(async()=>{let e=rn();if(!e)return{success:!0,message:"No active explicit approval window to close. Paid calls remain pay-as-you-go.",closed:!1};let t=await Cs(N);f.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=lb(e),r=Je(t.finalCumulativeMicros),o=r??(typeof t.finalCumulativeCents=="number"?BigInt(Math.max(0,t.finalCumulativeCents))*10000n:n.micros),s=Number(o/10000n);return f.info("session:closed:final-spend",{budgetId:t.budgetId,closedServerSide:t.closedServerSide,finalSpendMicros:o.toString(),finalSpendCents:s,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:s,finalEstimatedCumulativeMicros:o.toString(),totalCents:e.totalCents,message:t.closedServerSide?`Explicit approval window closed. Spent ${cb(o)} 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 vv(e){if(f.info("auth:add_card_attempt"),!await B.getSessionToken())return{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."};let{code:n}=await N.createEnrollCode();return Im(`${Ds()}/enroll-card?code=${encodeURIComponent(n)}`,e,"enrollment")}async function bm(){if(await B.clearAll(),de())try{await ys()}catch{}}async function wv(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};if(f.info("reset:attempt"),e.localOnly)return await bm(),f.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 N.getStatus(t);if(r&&dt(r)){let o=await Om(t);if(!o.success)return o;n=!0}}catch(r){let o=r?.message||"unknown error";if(!/not logged in|session.*expired|no local credentials/i.test(o))return{success:!1,message:`Could not check server biometric state: ${o}`};f.warn("reset:server_attestation_status_unavailable",{error:o})}try{await N.logout(void 0,t)}catch{}return await bm(),f.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 Sv(e){let t=e.query?.trim()||void 0,n=e.category?.trim()||void 0,r=!t&&!n;f.info("catalog:discover",{query:t,category:n,browseAll:r});try{let s=(await N.catalogSearch(t,n)).tools||[];if(s.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 s){let u=l.category||"other";(a[u]??=[]).push(l)}let c=Object.keys(a).sort().map(l=>{let u=a[l].map((p,m)=>`${m+1}. **${p.name}** (${p.id})
140
140
  ${p.description}
141
- Provider: ${p.provider} | Price: ${Ed(p)}${Ad(p)}
141
+ Provider: ${p.provider} | Price: ${vm(p)}${wm(p)}
142
142
  Params: ${Object.keys(p.inputSchema?.properties||p.inputSchema||{}).join(", ")||"none"}`).join(`
143
143
 
144
144
  `);return`## ${l.length<=3?l.toUpperCase():l.charAt(0).toUpperCase()+l.slice(1)}
@@ -151,58 +151,58 @@ ${c}
151
151
 
152
152
  Use execute_tool with the tool id and required params to run any of these.`}],_tools:s}}let i=s.map((a,c)=>`${c+1}. **${a.name}** (${a.id})
153
153
  ${a.description}
154
- Provider: ${a.provider} | Category: ${a.category} | Price: ${Ed(a)}${Ad(a)}
154
+ Provider: ${a.provider} | Category: ${a.category} | Price: ${vm(a)}${wm(a)}
155
155
  Params: ${Object.keys(a.inputSchema?.properties||a.inputSchema||{}).join(", ")||"none"}`).join(`
156
156
 
157
157
  `);return f.info("catalog:discovered",{count:s.length}),{content:[{type:"text",text:`Found ${s.length} tool(s):
158
158
 
159
159
  ${i}
160
160
 
161
- Use execute_tool with the tool id and required params to run any of these.`}],_tools:s}}catch(o){throw f.error("catalog:discover:error",{error:o.message}),new Error(`Failed to search tool catalog: ${o.message}`)}}function Ed(e){return e.priceDisplay??`$${(e.priceCents/100).toFixed(2)}`}function Ad(e){let t=e.protocol;return t==="mpp"||t==="x402"?" | Paid from your prepaid balance":""}function J_(e,t){return t==="image"||t==="video"||t==="audio"?t:e?.match(/\.(mp4|webm|mov)/)?"video":"image"}function ms(e,t){return Array.isArray(e.type)?e.type.includes(t):e.type===t}function Y_(e,t,n){let r=e.inputSchema;if(!r||r.type!=="object")return null;let o=r.properties??{},s=n??e.id;for(let a of Object.keys(t))if(!Object.prototype.hasOwnProperty.call(o,a)){let c=Object.keys(o),l=c.length>0?` Expected: ${c.join(", ")}.`:"";return`Unknown parameter "${a}" for ${s}.${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 ${s}.`;for(let a of r.required??[]){if(!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0)return`${a} is required for ${s}.`;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=o[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(ms(l,"integer")){if(typeof c!="number"||!Number.isInteger(c))return`${a} must be an integer.`}else if(ms(l,"number")){if(typeof c!="number"||!Number.isFinite(c))return`${a} must be a number.`}else if(ms(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(ms(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 Vd(e){let t=Xn(e);if(t)return t;try{return await I.catalogTool(e)}catch(n){return f.warn("catalog:resolve:error",{tool:e,error:n?.message||String(n)}),null}}function da(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 X_(e){return e.split(/[-_]/).filter(t=>t.length>0&&!/^[0-9a-f]{8,}$/i.test(t)).join(" ").trim()}async function Z_(e){let t=X_(e);if(!t)return[];try{return((await I.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 f.warn("catalog:suggest:error",{tool:e,error:n?.message||String(n)}),[]}}async function Q_(e,t,n="execute_tool"){let{tool_id:r,params:o,...s}=e,i=o||s;if(!r)return us("tool_id is required. Use discover_tools first to find available tools.","MISSING_TOOL_ID");f.info("catalog:execute",{tool:r,metaTool:n});let a=await Vd(r);if(!a){let m=await Z_(r),g=m.length?` Did you mean: ${m.map(y=>y.tool_id).join(", ")}?`:"";return us(`Unknown tool: '${r}'.${g} Use discover_tools first to find available tools.`,"UNKNOWN_TOOL",m.length?{suggestions:m}:void 0)}if(a.deprecated){let m=a.replacementTool?` Use '${a.replacementTool}' instead.`:"";return us(`Tool '${r}' is deprecated and is no longer available for new paid calls.${m}`,"DEPRECATED_TOOL")}let l=Y_(a,i,n&&n!=="execute_tool"?n:void 0);if(l)return f.info("catalog:execute:validation_failed",{tool:r,metaTool:n,error:l}),us(l);let u=await Gr(r,i,t,n);if(u)return u;if(da(a)){f.info("catalog:execute:free",{tool:r,metaTool:n});let m=await I.shortcut(r,i,6e4,t,n);return m&&typeof m=="object"&&!Array.isArray(m)&&m.merchantName==null&&(m.merchantName=a.name??r),m}let d=await Ct(r,void 0,t),p=pe.randomUUID();f.info("payment:attempt",{tool:r,amount:d.amount,merchant:d.merchantName});try{return await fe(async()=>{let m;try{m=await Xt({toolId:r,toolParams:i,estimatedAmountCents:Tt(d),userContext:t,metaTool:n,timeoutMs:12e4,idempotencyKey:p})}catch(g){if(g instanceof me)return Le(g);throw g}if(f.info("payment:success",{tool:r,amount:d.amount,merchant:d.merchantName,mode:"session"}),m&&typeof m=="object"&&!Array.isArray(m)&&m.merchantName==null&&(m.merchantName=a?.name??r),m.urls?.length){m.urls.forEach(y=>Ge(y));let g=J_(m.urls[0],m.mediaType);Wr({prompt:i.prompt||`${r} execution`,tool:r,mediaUrl:m.urls[0],mediaType:g,cost:m.amount??d.amount,transactionId:m.transactionId,userContext:t})}return m})}catch(m){return m instanceof oe?(f.warn("payment:declined",{tool:r,amount:d.amount,merchant:d.merchantName,code:m.code,retryable:m.retryable}),We(m,d)):(eb(m?.message)?f.warn("payment:ambiguous",{tool:r,amount:d.amount,merchant:d.merchantName,error:m.message,note:"Polling/timeout error on async tool \u2014 call may have succeeded. Verify via `visa-cli transactions list`."}):f.error("payment:failure",{tool:r,amount:d.amount,merchant:d.merchantName,error:m.message}),Ly({toolId:r,surface:n,merchantName:d.merchantName,amount:d.amount,message:m?.message||"Tool execution failed."}))}}function eb(e){return e?/\b(task_id|polling?|timeout|timed out|queue|IN_QUEUE|aborted)\b/i.test(e):!1}var qe=class{static async getStatus(t){return T_(t)}static async getVisaSmi(t,n){return a_(t,n)}static async getCards(t){return E_(t)}static async transactionHistory(t,n){return A_(t||{},n)}static async feedback(t,n){return R_(t,n)}static async updateSpendingControls(t,n){return $_(t,n)}static async configList(t){return P_(t||{})}static async configSet(t){return O_(t||{})}static async configUnset(t){return M_(t||{})}static async biometricStatus(t){return N_(t)}static async biometricOn(t){return L_(t)}static async biometricOff(t,n){return U_(t,n)}static async reset(t,n){return W_(t,n)}static async login(t){return V_(t)}static async closeSession(t){return K_()}static async startSession(t,n){return B_(t||{},n)}static async getSessionStatus(t){return H_()}static async addCard(t){return G_(t)}static async removeCard(t,n){return j_(t,n)}static async setDefaultCard(t,n){return F_(t,n)}static async buyCredits(t,n){return I_(t,n)}static async batch(t,n){return k_(t,n)}static async discoverTools(t){return z_(t)}static async executeTool(t,n,r="execute_tool"){return Q_(t,n,r)}static async shortcut(t,n,r){switch(t){case"generate_image_card":return c_(n,r);case"generate_image_fast_card":return l_(n,r);case"generate_video_tempo_card":return u_(n,r);case"generate_music_tempo_card":return d_(n,r);case"check_music_status_tempo_card":return m_(n,r);case"query_onchain_prices_card":return p_(n,r);default:{let o=await Gr(t,n,r);if(o)return o;let s=await Ct(t,void 0,r);f.info("payment:attempt",{tool:t});try{let i=await Xt({toolId:t,toolParams:n,estimatedAmountCents:Tt(s),userContext:r,timeoutMs:6e4});return f.info("payment:success",{tool:t,mode:"session"}),i.urls?.length&&i.urls.forEach(a=>Ge(a)),i}catch(i){if(i instanceof me)return Le(i);if(i instanceof oe)return f.warn("payment:declined",{tool:t,code:i.code,retryable:i.retryable}),We(i,s);throw f.error("payment:failure",{tool:t,error:i.message}),i}}}}static async submitFeedback(t,n,r){f.info("feedback:submit",{length:t.length,transactionId:n,hasContext:!!r});try{let o=await I.submitFeedback(t,n,r);return f.info("feedback:submitted",{transactionId:n}),o}catch(o){let s=o instanceof Error?o.message:"Unknown error";throw f.error("feedback:error",{error:s,transactionId:n}),o}}static async getFeedback(t,n){f.info("feedback:list",{limit:t||20});try{let r=await I.getFeedback(t,n);return f.info("feedback:listed",{count:r?.feedback?.length||0}),r}catch(r){let o=r instanceof Error?r.message:"Unknown error";throw f.error("feedback:error",{error:o}),r}}};function qd(e,t=process.stderr){if(tt()||!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(`
161
+ Use execute_tool with the tool id and required params to run any of these.`}],_tools:s}}catch(o){throw f.error("catalog:discover:error",{error:o.message}),new Error(`Failed to search tool catalog: ${o.message}`)}}function vm(e){return e.priceDisplay??`$${(e.priceCents/100).toFixed(2)}`}function wm(e){let t=e.protocol;return t==="mpp"||t==="x402"?" | Paid from your prepaid balance":""}function xv(e,t){return t==="image"||t==="video"||t==="audio"?t:e?.match(/\.(mp4|webm|mov)/)?"video":"image"}function $s(e,t){return Array.isArray(e.type)?e.type.includes(t):e.type===t}function Tv(e,t,n){let r=e.inputSchema;if(!r||r.type!=="object")return null;let o=r.properties??{},s=n??e.id;for(let a of Object.keys(t))if(!Object.prototype.hasOwnProperty.call(o,a)){let c=Object.keys(o),l=c.length>0?` Expected: ${c.join(", ")}.`:"";return`Unknown parameter "${a}" for ${s}.${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 ${s}.`;for(let a of r.required??[]){if(!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0)return`${a} is required for ${s}.`;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=o[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($s(l,"integer")){if(typeof c!="number"||!Number.isInteger(c))return`${a} must be an integer.`}else if($s(l,"number")){if(typeof c!="number"||!Number.isFinite(c))return`${a} must be a number.`}else if($s(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($s(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 Mm(e){let t=ur(e);if(t)return t;try{return await N.catalogTool(e)}catch(n){return f.warn("catalog:resolve:error",{tool:e,error:n?.message||String(n)}),null}}function Fa(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 Cv(e){return e.split(/[-_]/).filter(t=>t.length>0&&!/^[0-9a-f]{8,}$/i.test(t)).join(" ").trim()}async function kv(e){let t=Cv(e);if(!t)return[];try{return((await N.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 f.warn("catalog:suggest:error",{tool:e,error:n?.message||String(n)}),[]}}async function Ev(e,t,n="execute_tool"){let{tool_id:r,params:o,...s}=e,i=o||s;if(!r)return Rs("tool_id is required. Use discover_tools first to find available tools.","MISSING_TOOL_ID");f.info("catalog:execute",{tool:r,metaTool:n});let a=await Mm(r);if(!a){let m=await kv(r),g=m.length?` Did you mean: ${m.map(h=>h.tool_id).join(", ")}?`:"";return Rs(`Unknown tool: '${r}'.${g} Use discover_tools first to find available tools.`,"UNKNOWN_TOOL",m.length?{suggestions:m}:void 0)}if(a.deprecated){let m=a.replacementTool?` Use '${a.replacementTool}' instead.`:"";return Rs(`Tool '${r}' is deprecated and is no longer available for new paid calls.${m}`,"DEPRECATED_TOOL")}let l=Tv(a,i,n&&n!=="execute_tool"?n:void 0);if(l)return f.info("catalog:execute:validation_failed",{tool:r,metaTool:n,error:l}),Rs(l);let u=await lo(r,i,t,n);if(u)return u;if(Fa(a)){f.info("catalog:execute:free",{tool:r,metaTool:n});let m=await N.shortcut(r,i,6e4,t,n);return m&&typeof m=="object"&&!Array.isArray(m)&&m.merchantName==null&&(m.merchantName=a.name??r),m}let d=await $t(r,void 0,t),p=ye.randomUUID();f.info("payment:attempt",{tool:r,amount:d.amount,merchant:d.merchantName});try{return await _e(async()=>{let m;try{m=await sn({toolId:r,toolParams:i,estimatedAmountCents:Pt(d),userContext:t,metaTool:n,timeoutMs:12e4,idempotencyKey:p})}catch(g){if(g instanceof he)return Fe(g);throw g}if(f.info("payment:success",{tool:r,amount:d.amount,merchant:d.merchantName,mode:"session"}),m&&typeof m=="object"&&!Array.isArray(m)&&m.merchantName==null&&(m.merchantName=a?.name??r),m.urls?.length){m.urls.forEach(h=>Xe(h));let g=xv(m.urls[0],m.mediaType);uo({prompt:i.prompt||`${r} execution`,tool:r,mediaUrl:m.urls[0],mediaType:g,cost:m.amount??d.amount,transactionId:m.transactionId,userContext:t})}return m})}catch(m){return m instanceof le?(f.warn("payment:declined",{tool:r,amount:d.amount,merchant:d.merchantName,code:m.code,retryable:m.retryable}),Ze(m,d)):(Av(m?.message)?f.warn("payment:ambiguous",{tool:r,amount:d.amount,merchant:d.merchantName,error:m.message,note:"Polling/timeout error on async tool \u2014 call may have succeeded. Verify via `visa-cli transactions list`."}):f.error("payment:failure",{tool:r,amount:d.amount,merchant:d.merchantName,error:m.message}),ub({toolId:r,surface:n,merchantName:d.merchantName,amount:d.amount,message:m?.message||"Tool execution failed."}))}}function Av(e){return e?/\b(task_id|polling?|timeout|timed out|queue|IN_QUEUE|aborted)\b/i.test(e):!1}var We=class{static async getStatus(t){return ev(t)}static async getVisaSmi(t,n){return Nb(t,n)}static async getCards(t){return tv(t)}static async transactionHistory(t,n){return nv(t||{},n)}static async feedback(t,n){return rv(t,n)}static async updateSpendingControls(t,n){return sv(t,n)}static async configList(t){return iv(t||{})}static async configSet(t){return av(t||{})}static async configUnset(t){return cv(t||{})}static async biometricStatus(t){return lv(t)}static async biometricOn(t){return uv(t)}static async biometricOff(t,n){return dv(t,n)}static async reset(t,n){return wv(t,n)}static async login(t){return gv(t)}static async closeSession(t){return bv()}static async startSession(t,n){return yv(t||{},n)}static async getSessionStatus(t){return _v()}static async addCard(t){return vv(t)}static async removeCard(t,n){return pv(t,n)}static async setDefaultCard(t,n){return fv(t,n)}static async buyCredits(t,n){return ov(t,n)}static async batch(t,n){return Zb(t,n)}static async discoverTools(t){return Sv(t)}static async executeTool(t,n,r="execute_tool"){return Ev(t,n,r)}static async shortcut(t,n,r){switch(t){case"generate_image_card":return Lb(n,r);case"generate_image_fast_card":return Ub(n,r);case"generate_video_tempo_card":return Db(n,r);case"generate_music_tempo_card":return jb(n,r);case"check_music_status_tempo_card":return Fb(n,r);case"query_onchain_prices_card":return Vb(n,r);default:{let o=await lo(t,n,r);if(o)return o;let s=await $t(t,void 0,r);f.info("payment:attempt",{tool:t});try{let i=await sn({toolId:t,toolParams:n,estimatedAmountCents:Pt(s),userContext:r,timeoutMs:6e4});return f.info("payment:success",{tool:t,mode:"session"}),i.urls?.length&&i.urls.forEach(a=>Xe(a)),i}catch(i){if(i instanceof he)return Fe(i);if(i instanceof le)return f.warn("payment:declined",{tool:t,code:i.code,retryable:i.retryable}),Ze(i,s);throw f.error("payment:failure",{tool:t,error:i.message}),i}}}}static async submitFeedback(t,n,r){f.info("feedback:submit",{length:t.length,transactionId:n,hasContext:!!r});try{let o=await N.submitFeedback(t,n,r);return f.info("feedback:submitted",{transactionId:n}),o}catch(o){let s=o instanceof Error?o.message:"Unknown error";throw f.error("feedback:error",{error:s,transactionId:n}),o}}static async getFeedback(t,n){f.info("feedback:list",{limit:t||20});try{let r=await N.getFeedback(t,n);return f.info("feedback:listed",{count:r?.feedback?.length||0}),r}catch(r){let o=r instanceof Error?r.message:"Unknown error";throw f.error("feedback:error",{error:o}),r}}};function Nm(e,t=process.stderr){if(it()||!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(`
162
162
  \x1B[33m\u2191 ${r}\x1B[0m
163
- `),!0}function Bd(e){let t=Array.isArray(e.inputSchema?.required)?e.inputSchema.required.filter(o=>typeof o=="string"):[],n=e.inputSchema?.properties&&typeof e.inputSchema.properties=="object"?e.inputSchema.properties:{};if(t.length===0)return{prompt:"a lobster"};let r={};for(let o of t)r[o]=tb(o,n[o]?.description);return r}function tb(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 nb(e){let t=at(e.referralCode,"");if(!t)return[];let n=["Referrals",` Your code ${t}`],r=at(e.referralLink,"");if(r&&n.push(` Your link ${r}`),typeof e.referralCount=="number"&&Number.isFinite(e.referralCount)){let o=Math.max(0,Math.trunc(e.referralCount));n.push(` Joined ${o} ${o===1?"person":"people"} via your link`)}return n}var rb=20;function Kd(e,t,n,r){let o=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=ub(e.spendingControls).dailyLimit,a=Math.max(0,zr(e.dailyCardFundedTopupSpent??e.dailySpent)),c=i>0?Math.min(i,Math.max(0,zr(e.dailyCardFundedTopupRemaining??e.dailyRemaining??i-a))):0,l=i>0?Math.min(1,a/i):0,d=(Array.isArray(t)?t:[]).filter(ib),p=d.slice(0,3),m=ab(d,3),g=(e.cards??[]).slice(0,3),y=r.latestVersion?Rn(r.latestVersion):"",w=r.updateCheckDisabled?"update checks disabled":y?`update ready: v${y}`:"up to date",N=Math.round(l*100),U=at(e.status,e.enrolled?"approved":"not enrolled"),x=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${U} | touch id: ${n?"ready":"unavailable"}`,`Version: v${o} | ${w}`,`Top-up meter: ${Hd(l)} ${String(N).padStart(3," ")}% | remaining ${rr(c)}/day | daily top-up cap ${rr(i)}`,"","Card top-ups",` Remaining ${rr(c)} / ${rr(i)}`,` Usage ${Hd(l)} ${N}%`,` Top-ups today ${rr(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...g.length>0?g.map(O=>` ${lb(O)}`):[" No cards enrolled"],"","Last 3 services",...m.length>0?m.map((O,_)=>` ${_+1}. ${O}`):[" No paid services yet"],"","Recent receipts",...p.length>0?p.map(O=>` ${cb(O)}`):[" No receipts yet"]],$=nb(e);return $.length>0&&x.push("",...$),y&&!r.updateCheckDisabled?(x.push("",`Update: v${y} ready \u2014 run \`visa-cli update\``),r.updateMessage&&x.push(` ${Rn(r.updateMessage)}`)):r.updateMessage&&x.push("",`Update: ${Rn(r.updateMessage)}`),`${x.join(`
163
+ `),!0}function Lm(e){let t=Array.isArray(e.inputSchema?.required)?e.inputSchema.required.filter(o=>typeof o=="string"):[],n=e.inputSchema?.properties&&typeof e.inputSchema.properties=="object"?e.inputSchema.properties:{};if(t.length===0)return{prompt:"a lobster"};let r={};for(let o of t)r[o]=Rv(o,n[o]?.description);return r}function Rv(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 Iv(e){let t=mt(e.referralCode,"");if(!t)return[];let n=["Referrals",` Your code ${t}`],r=mt(e.referralLink,"");if(r&&n.push(` Your link ${r}`),typeof e.referralCount=="number"&&Number.isFinite(e.referralCount)){let o=Math.max(0,Math.trunc(e.referralCount));n.push(` Joined ${o} ${o===1?"person":"people"} via your link`)}return n}var $v=20;function Dm(e,t,n,r){let o=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=Dv(e.spendingControls).dailyLimit,a=Math.max(0,mo(e.dailyCardFundedTopupSpent??e.dailySpent)),c=i>0?Math.min(i,Math.max(0,mo(e.dailyCardFundedTopupRemaining??e.dailyRemaining??i-a))):0,l=i>0?Math.min(1,a/i):0,d=(Array.isArray(t)?t:[]).filter(Mv),p=d.slice(0,3),m=Nv(d,3),g=(e.cards??[]).slice(0,3),h=r.latestVersion?Dn(r.latestVersion):"",w=r.updateCheckDisabled?"update checks disabled":h?`update ready: v${h}`:"up to date",$=Math.round(l*100),k=mt(e.status,e.enrolled?"approved":"not enrolled"),S=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${k} | touch id: ${n?"ready":"unavailable"}`,`Version: v${o} | ${w}`,`Top-up meter: ${Um(l)} ${String($).padStart(3," ")}% | remaining ${yr(c)}/day | daily top-up cap ${yr(i)}`,"","Card top-ups",` Remaining ${yr(c)} / ${yr(i)}`,` Usage ${Um(l)} ${$}%`,` Top-ups today ${yr(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...g.length>0?g.map(M=>` ${Uv(M)}`):[" No cards enrolled"],"","Last 3 services",...m.length>0?m.map((M,_)=>` ${_+1}. ${M}`):[" No paid services yet"],"","Recent receipts",...p.length>0?p.map(M=>` ${Lv(M)}`):[" No receipts yet"]],P=Iv(e);return P.length>0&&S.push("",...P),h&&!r.updateCheckDisabled?(S.push("",`Update: v${h} ready \u2014 run \`visa-cli update\``),r.updateMessage&&S.push(` ${Dn(r.updateMessage)}`)):r.updateMessage&&S.push("",`Update: ${Dn(r.updateMessage)}`),`${S.join(`
164
164
  `)}
165
- `}function ob(e){return e.tool_name!=null}function sb(e){return zr(e.amount)===0&&e.status==="failed"}function ib(e){return ob(e)&&!sb(e)}function ab(e,t=1/0){let n=new Set,r=[];for(let o of e){if(r.length>=t)break;let s=at(o.merchant_name,"Unknown merchant"),i=at(o.tool_name,"unknown_tool"),a=`${s} :: ${i}`;n.has(a)||(n.add(a),r.push(`${s} [${i}]`))}return r}function cb(e){let t=at(e.merchant_name,"Unknown merchant"),n=at(e.tool_name,"unknown_tool"),r=rr(zr(e.amount)),o=at(e.status,"unknown"),s=db(e.created_at);return`${r} ${o.padEnd(9)} ${t} [${n}] ${s}`}function lb(e){let t=at(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function ub(e){return{dailyLimit:zr(e?.daily_limit??e?.dailyLimit??0)}}function zr(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function rr(e){return`$${e.toFixed(2)}`}function Hd(e,t=rb){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function at(e,t){let n=Rn(e??"").trim();return n.length>0?n:t}function db(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?at(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function Rn(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 mb=/^[1-9]\d{0,9}$/;function ma(e){if(!mb.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 Gd(e){let t=Rn(e.brand||"Visa"),n=Rn(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 ct=T(require("fs")),ae=T(require("path")),pb=["npm","pnpm","yarn","bun"],fb=/\s+/,gb=process.platform==="win32"?"visa-cli.cmd":"visa-cli",pa=["node_modules","@visa","cli"];function hb(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(fb)[0]??"",r=n.indexOf("/"),o=r===-1?n:n.slice(0,r);return pb.includes(o)?o:void 0}function fa(e){if(!e)return;let t=e;try{t=ct.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 yb(e=process.argv[1]){return hb()??fa(process.env.npm_execpath)??fa(process.env.npm_node_execpath)??fa(e)}function _b(e=process.env.PATH??""){let t=[];for(let n of e.split(ae.delimiter))n&&t.push(n);return t}function bb(e=process.env.PATH??""){let t=new Set,n=[];for(let r of _b(e))try{let o=ae.join(r,gb);ct.accessSync(o,ct.constants.X_OK);let s=ae.resolve(o);t.has(s)||(t.add(s),n.push(o))}catch{}return n}function Wd(e){try{let t=ct.readFileSync(ae.join(e,"package.json"),"utf-8"),n=JSON.parse(t);if(n.name==="@visa/cli"&&typeof n.version=="string")return n.version}catch{}}function vb(e){let t=ae.resolve(e).split(ae.sep);for(let n=t.length-pa.length;n>=0;n--)if(pa.every((r,o)=>t[n+o]===r)){let r=t.slice(0,n+pa.length).join(ae.sep)||ae.sep;if(Wd(r))return r}}function wb(e){if(!e)return;let t=ae.normalize(e),n=t.split(ae.sep),r=s=>s.every((a,c)=>n[n.length-s.length+c]===a)?n.slice(0,-s.length).join(ae.sep)||ae.parse(t).root:void 0,o=r(["lib","node_modules","@visa","cli"]);if(o)return o;if(process.platform==="win32")return r(["node_modules","@visa","cli"])}function Sb(e,t){let n=ae.resolve(e);try{n=ct.realpathSync(e)}catch{}let r=vb(n);return{binPath:e,realPath:n,packageRoot:r,version:r?Wd(r):void 0,prefix:wb(r),isActive:n===t}}function xb(e,t=process.env.PATH??""){let n=e??process.argv[1],r=n?ae.resolve(n):"";try{n&&(r=ct.realpathSync(n))}catch{}let o=e?[e]:[n,...bb(t)].filter(Boolean),s=new Map;for(let d of o){let p=Sb(d,r),m=s.get(p.realPath);s.set(p.realPath,m?{...p,binPath:m.binPath}:p)}let i=[...s.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 kb(e,t=process.platform){return/^[A-Za-z0-9_./:@+-]+$/.test(e)?e:t==="win32"?`"${e.replace(/"/g,'""')}"`:`'${e.replace(/'/g,"'\\''")}'`}function ga(e,t,n,r={}){let o=t??yb(n)??"npm",s=r.withDiagnostics?xb(n):void 0,a=`@visa/cli@${e??"latest"}`;switch(o){case"npm":if(s?.hasConflictingInstalls&&s.recommendedPrefix){let c=s.recommendedPrefix;return{packageManager:o,command:"npm",args:["install","-g","--prefix",c,a],display:`npm install -g --prefix ${kb(c)} ${a}`,diagnostics:s}}return{packageManager:o,command:"npm",args:["install","-g",a],display:`npm install -g ${a}`,diagnostics:s};case"pnpm":return{packageManager:o,command:"pnpm",args:["add","-g",a],display:`pnpm add -g ${a}`,diagnostics:s};case"yarn":return{packageManager:o,command:"yarn",args:["global","add",a],display:`yarn global add ${a}`,diagnostics:s};case"bun":return{packageManager:o,command:"bun",args:["add","-g",a],display:`bun add -g ${a}`,diagnostics:s}}}function Cb(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 ha(e,t){if(!e.hasConflictingInstalls)return null;let n=["Multiple Visa CLI installs detected.",...e.installs.map(Cb)];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(`
166
- `)}var Es=T(Fr());function Tb(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function zd(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=Tb(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 Jd(){await V.deleteSessionToken()}var lt=T(require("crypto")),$e=T(require("fs")),vs=T(require("os")),or=T(require("path")),Zd=T(require("node:readline")),ya="3.0.0",Eb=process.env.PORTER_API_URL??"https://porter-travel.up.railway.app",Ab=process.env.TAP_REGISTRY_URL??"https://tap-production-eff9.up.railway.app",Jr=or.join(vs.homedir(),".visa-cli","agents");function Rb(){return!!(process.env.VISA_DEV==="1"||ya==="0.0.0"||ya.startsWith("0.0.")||/-rc\.|-beta\./.test(ya))}function Ib(){$e.mkdirSync(Jr,{recursive:!0,mode:448})}function va(e){return or.join(Jr,`${e}.json`)}function _a(){return $e.existsSync(Jr)?$e.readdirSync(Jr).filter(e=>e.endsWith(".json")).map(e=>or.join(Jr,e)):[]}function $b(e){let t=va(e);return $e.existsSync(t)?JSON.parse($e.readFileSync(t,"utf8")):null}function Pb(e){Ib();let t=va(e.agent_id);$e.writeFileSync(t,JSON.stringify(e,null,2),{mode:384})}async function ba(e,t,n,r){let o=`${e.replace(/\/+$/,"")}${n}`,s=await fetch(o,{method:t,headers:{"Content-Type":"application/json"},body:r!==void 0?JSON.stringify(r):void 0}),i=await s.json().catch(()=>({}));if(!s.ok||i.errors?.length){let a=i.errors?.[0];throw new Error(`${t} ${o} failed (${s.status}): ${a?.code??"unknown"} \u2014 ${a?.message??"no message"}`)}if(i.data===void 0)throw new Error(`${t} ${o}: empty response data`);return i.data}var Yd=ba;function Ob(){let{publicKey:e,privateKey:t}=lt.generateKeyPairSync("ed25519"),n=e.export({format:"jwk"}),r=t.export({format:"jwk"});return{publicKeyB64url:n.x,privateJwk:r}}function Qd(e,t){let n=lt.createPrivateKey({key:t,format:"jwk"});return lt.sign(null,Buffer.from(e,"utf8"),n).toString("base64url")}async function Mb(e){let{publicKeyB64url:t,privateJwk:n}=Ob(),r=new Date().toISOString(),o=`tap:register:v1:${e.name}:${r}`,s=Qd(o,n),i=await ba(e.registryUrl,"POST","/api/v1/agents",{name:e.name,public_key:t,signed_at:r,signature:s,visibility:"public",capabilities:["porter:book","visa:authorize_payment"]}),a=await ba(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 Pb(c),c}async function em(e){let t=await Yd(e.porter_url,"GET",`/api/v1/tap/challenge?public_key=${encodeURIComponent(e.public_key_b64url)}`),n=Qd(t.challenge,e.private_key_jwk),r=await Yd(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 Nb(e,t,n){let r=JSON.stringify(t),o=JSON.stringify(n),s=Buffer.from(r).toString("base64url"),i=Buffer.from(o).toString("base64url"),a=`${s}.${i}`,c=lt.createPrivateKey({key:e,format:"jwk"}),l=lt.sign(null,Buffer.from(a,"utf8"),c);return`${a}.${l.toString("base64url")}`}var Lb=["visa_authorize_payment"],Ub={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 Db(e,t){let n=Math.floor(Date.now()/1e3),r=n+300,o=`vpid_${lt.randomBytes(16).toString("hex")}`,s=process.env.VISACLI_ISSUER??e.tap_registry_url??e.porter_url;return{jwt:Nb(e.private_key_jwk,{alg:"EdDSA",typ:"JWT",kid:e.agent_id},{iss:s,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:o}),jti:o,expiresAt:r}}async function jb(e){let t=`${e.porter_url.replace(/\/+$/,"")}/api/mcp`,n=null,r=0;async function o(p=!1){if(!p&&n&&Date.now()<r-6e4)return n;let{token:m,expiresInSeconds:g}=await em(e);return n=m,r=Date.now()+g*1e3,m}function s(p){process.stdout.write(JSON.stringify(p)+`
167
- `)}function i(p,m,g){s({jsonrpc:"2.0",id:p??null,error:{code:m,message:g}})}function a(p,m,g){if(m==="visa_authorize_payment"){let y=g;if(typeof y.merchant!="string"||typeof y.amount!="number"||typeof y.currency!="string"||typeof y.idem_key!="string"){i(p,-32602,"visa_authorize_payment: missing or wrong-typed required fields");return}try{let{jwt:w,jti:N,expiresAt:U}=Db(e,y);s({jsonrpc:"2.0",id:p,result:{content:[{type:"text",text:["\u2713 Payment authorized \u2014 pass this JWT as visa_payment_id at checkout:","",w,"",` agent: ${e.agent_id}`,` merchant: ${y.merchant}`,` amount: ${y.amount} ${y.currency.toUpperCase()}`,` jti: ${N}`,` expires: ${new Date(U*1e3).toISOString()}`].join(`
168
- `)},{type:"text",text:JSON.stringify({visa_payment_id:w,jti:N,agent_id:e.agent_id,amount:y.amount,currency:y.currency.toUpperCase(),merchant:y.merchant,expires_at:U})}]}})}catch(w){i(p,-32603,`failed to sign visa_payment_id: ${w instanceof Error?w.message:String(w)}`)}return}i(p,-32601,`unknown synthetic tool: ${m}`)}async function c(p){if(p.method==="tools/call"){let g=p.params??{};if(typeof g.name=="string"&&Lb.includes(g.name)){a(p.id,g.name,g.arguments??{});return}}let m=0;for(;m<2;){m+=1;let g=await o(m>1),y;try{y=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","X-TAP-Token":g},body:JSON.stringify(p)})}catch(N){i(p.id,-32e3,`network error talking to porter: ${N instanceof Error?N.message:String(N)}`);return}if(y.status===401&&m===1){n=null;continue}if(!y.ok){let N=await y.text().catch(()=>"");i(p.id,-32e3,`porter returned ${y.status}: ${N.slice(0,400)}`);return}if((y.headers.get("content-type")??"").includes("text/event-stream"))await u(y,p);else{let N=await y.text();if(N.trim()){let U=JSON.parse(N);l(p,U),s(U)}}return}}function l(p,m){if(p.method!=="tools/list")return;let g=m.result;!g||!Array.isArray(g.tools)||g.tools.some(y=>y.name==="visa_authorize_payment")||g.tools.push(Ub)}async function u(p,m){let g=p.body?.getReader();if(!g)return;let y=new TextDecoder,w="";for(;;){let{done:N,value:U}=await g.read();if(N)break;w+=y.decode(U,{stream:!0});let v;for(;(v=w.indexOf(`
165
+ `}function Pv(e){return e.tool_name!=null}function Ov(e){return mo(e.amount)===0&&e.status==="failed"}function Mv(e){return Pv(e)&&!Ov(e)}function Nv(e,t=1/0){let n=new Set,r=[];for(let o of e){if(r.length>=t)break;let s=mt(o.merchant_name,"Unknown merchant"),i=mt(o.tool_name,"unknown_tool"),a=`${s} :: ${i}`;n.has(a)||(n.add(a),r.push(`${s} [${i}]`))}return r}function Lv(e){let t=mt(e.merchant_name,"Unknown merchant"),n=mt(e.tool_name,"unknown_tool"),r=yr(mo(e.amount)),o=mt(e.status,"unknown"),s=jv(e.created_at);return`${r} ${o.padEnd(9)} ${t} [${n}] ${s}`}function Uv(e){let t=mt(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function Dv(e){return{dailyLimit:mo(e?.daily_limit??e?.dailyLimit??0)}}function mo(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function yr(e){return`$${e.toFixed(2)}`}function Um(e,t=$v){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function mt(e,t){let n=Dn(e??"").trim();return n.length>0?n:t}function jv(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?mt(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function Dn(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 Fv=/^[1-9]\d{0,9}$/;function Va(e){if(!Fv.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 jm(e){let t=Dn(e.brand||"Visa"),n=Dn(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 pt=E(require("fs")),me=E(require("path")),Vv=["npm","pnpm","yarn","bun"],Bv=/\s+/,Hv=process.platform==="win32"?"visa-cli.cmd":"visa-cli",Ba=["node_modules","@visa","cli"];function qv(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(Bv)[0]??"",r=n.indexOf("/"),o=r===-1?n:n.slice(0,r);return Vv.includes(o)?o:void 0}function Ha(e){if(!e)return;let t=e;try{t=pt.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 Kv(e=process.argv[1]){return qv()??Ha(process.env.npm_execpath)??Ha(process.env.npm_node_execpath)??Ha(e)}function Gv(e=process.env.PATH??""){let t=[];for(let n of e.split(me.delimiter))n&&t.push(n);return t}function Wv(e=process.env.PATH??""){let t=new Set,n=[];for(let r of Gv(e))try{let o=me.join(r,Hv);pt.accessSync(o,pt.constants.X_OK);let s=me.resolve(o);t.has(s)||(t.add(s),n.push(o))}catch{}return n}function Fm(e){try{let t=pt.readFileSync(me.join(e,"package.json"),"utf-8"),n=JSON.parse(t);if(n.name==="@visa/cli"&&typeof n.version=="string")return n.version}catch{}}function zv(e){let t=me.resolve(e).split(me.sep);for(let n=t.length-Ba.length;n>=0;n--)if(Ba.every((r,o)=>t[n+o]===r)){let r=t.slice(0,n+Ba.length).join(me.sep)||me.sep;if(Fm(r))return r}}function Jv(e){if(!e)return;let t=me.normalize(e),n=t.split(me.sep),r=s=>s.every((a,c)=>n[n.length-s.length+c]===a)?n.slice(0,-s.length).join(me.sep)||me.parse(t).root:void 0,o=r(["lib","node_modules","@visa","cli"]);if(o)return o;if(process.platform==="win32")return r(["node_modules","@visa","cli"])}function Yv(e,t){let n=me.resolve(e);try{n=pt.realpathSync(e)}catch{}let r=zv(n);return{binPath:e,realPath:n,packageRoot:r,version:r?Fm(r):void 0,prefix:Jv(r),isActive:n===t}}function Xv(e,t=process.env.PATH??""){let n=e??process.argv[1],r=n?me.resolve(n):"";try{n&&(r=pt.realpathSync(n))}catch{}let o=e?[e]:[n,...Wv(t)].filter(Boolean),s=new Map;for(let d of o){let p=Yv(d,r),m=s.get(p.realPath);s.set(p.realPath,m?{...p,binPath:m.binPath}:p)}let i=[...s.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 Zv(e,t=process.platform){return/^[A-Za-z0-9_./:@+-]+$/.test(e)?e:t==="win32"?`"${e.replace(/"/g,'""')}"`:`'${e.replace(/'/g,"'\\''")}'`}function qa(e,t,n,r={}){let o=t??Kv(n)??"npm",s=r.withDiagnostics?Xv(n):void 0,a=`@visa/cli@${e??"latest"}`;switch(o){case"npm":if(s?.hasConflictingInstalls&&s.recommendedPrefix){let c=s.recommendedPrefix;return{packageManager:o,command:"npm",args:["install","-g","--prefix",c,a],display:`npm install -g --prefix ${Zv(c)} ${a}`,diagnostics:s}}return{packageManager:o,command:"npm",args:["install","-g",a],display:`npm install -g ${a}`,diagnostics:s};case"pnpm":return{packageManager:o,command:"pnpm",args:["add","-g",a],display:`pnpm add -g ${a}`,diagnostics:s};case"yarn":return{packageManager:o,command:"yarn",args:["global","add",a],display:`yarn global add ${a}`,diagnostics:s};case"bun":return{packageManager:o,command:"bun",args:["add","-g",a],display:`bun add -g ${a}`,diagnostics:s}}}function Qv(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 Ka(e,t){if(!e.hasConflictingInstalls)return null;let n=["Multiple Visa CLI installs detected.",...e.installs.map(Qv)];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(`
166
+ `)}var ni=E(dr());function e0(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function Vm(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=e0(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 Bm(){await B.deleteSessionToken()}var Sp=E(require("crypto"));var tp=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:qs,n:Hs,Gx:Hm,Gy:qm,a:Ga,d:Wa,h:t0}=tp,vr=32,n0=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},ve=(e="")=>{let t=new Error(e);throw n0(t,ve),t},r0=e=>typeof e=="bigint",o0=e=>typeof e=="string",s0=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,gt=(e,t,n="")=>{let r=s0(e),o=e?.length,s=t!==void 0;if(!r||s&&o!==t){let i=n&&`"${n}" `,a=s?` of length ${t}`:"",c=r?`length=${o}`:`type=${typeof e}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):new TypeError(l)}return e},Ws=e=>new Uint8Array(e),ec=e=>Uint8Array.from(e),np=(e,t)=>e.toString(16).padStart(t,"0"),tc=e=>Array.from(gt(e)).map(t=>np(t,2)).join(""),Ot={_0:48,_9:57,A:65,F:70,a:97,f:102},Km=e=>{if(e>=Ot._0&&e<=Ot._9)return e-Ot._0;if(e>=Ot.A&&e<=Ot.F)return e-(Ot.A-10);if(e>=Ot.a&&e<=Ot.f)return e-(Ot.a-10)},nc=e=>{let t="hex invalid";if(!o0(e))return ve(t);let n=e.length,r=n/2;if(n%2)return ve(t);let o=Ws(r);for(let s=0,i=0;s<r;s++,i+=2){let a=Km(e.charCodeAt(i)),c=Km(e.charCodeAt(i+1));if(a===void 0||c===void 0)return ve(t);o[s]=a*16+c}return o},rp=()=>globalThis?.crypto,i0=()=>rp()?.subtle??ve("crypto.subtle must be defined, consider polyfill"),wr=(...e)=>{let t=0;for(let o of e)t+=gt(o).length;let n=Ws(t),r=0;return e.forEach(o=>{n.set(o,r),r+=o.length}),n},op=(e=vr)=>rp().getRandomValues(Ws(e)),Ks=BigInt,jn=(e,t,n,r="bad number: out of range")=>{if(!r0(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},Z=(e,t=qs)=>{let n=e%t;return n>=0n?n:t+n},Gm=(1n<<255n)-1n,A=e=>{e<0n&&ve("negative coordinate");let t=(e>>255n)*19n+(e&Gm);return t=(t>>255n)*19n+(t&Gm),t%qs},sp=e=>Z(e,Hs),ip=(e,t)=>{(e===0n||t<=0n)&&ve("no inverse n="+e+" mod="+t);let n=Z(e,t),r=t,o=0n,s=1n,i=1n,a=0n;for(;n!==0n;){let c=r/n,l=r%n,u=o-i*c,d=s-a*c;r=n,n=l,o=i,s=a,i=u,a=d}return r===1n?Z(o,t):ve("no inverse")},ap=e=>{let t=mp[e];return typeof t!="function"&&ve("hashes."+e+" not set"),t},cp=e=>gt(e,64,"digest"),za=e=>e instanceof fo?e:ve("Point expected"),Ya=2n**256n,fo=class Fn{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,o){let s=Ya;this.X=jn(t,0n,s),this.Y=jn(n,0n,s),this.Z=jn(r,1n,s),this.T=jn(o,0n,s),Object.freeze(this)}static CURVE(){return tp}static fromAffine(t){return new Fn(t.x,t.y,1n,A(t.x*t.y))}static fromBytes(t,n=!1){let r=Wa,o=ec(gt(t,vr)),s=t[31];o[31]=s&-129;let i=up(o);jn(i,0n,n?Ya:qs);let c=A(i*i),l=Z(c-1n),u=A(r*c+1n),{isValid:d,value:p}=c0(l,u);d||ve("bad point: y not sqrt");let m=(p&1n)===1n,g=(s&128)!==0;return!n&&p===0n&&g&&ve("bad point: x==0, isLastByteOdd"),g!==m&&(p=Z(-p)),new Fn(p,i,1n,A(p*i))}static fromHex(t,n){return Fn.fromBytes(nc(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Ga,n=Wa,r=this;if(r.is0())return ve("bad point: ZERO");let{X:o,Y:s,Z:i,T:a}=r,c=A(o*o),l=A(s*s),u=A(i*i),d=A(u*u),p=A(c*t),m=A(u*(p+l)),g=Z(d+A(n*A(c*l)));if(m!==g)return ve("bad point: equation left != right (1)");let h=A(o*s),w=A(i*a);return h!==w?ve("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:o}=this,{X:s,Y:i,Z:a}=za(t),c=A(n*a),l=A(s*o),u=A(r*a),d=A(i*o);return c===l&&u===d}is0(){return this.equals(Vn)}negate(){return new Fn(Z(-this.X),this.Y,this.Z,Z(-this.T))}double(){let{X:t,Y:n,Z:r}=this,o=Ga,s=A(t*t),i=A(n*n),a=A(2n*r*r),c=A(o*s),l=Z(t+n),u=Z(A(l*l)-s-i),d=Z(c+i),p=Z(d-a),m=Z(c-i),g=A(u*p),h=A(d*m),w=A(u*m),$=A(p*d);return new Fn(g,h,$,w)}add(t){let{X:n,Y:r,Z:o,T:s}=this,{X:i,Y:a,Z:c,T:l}=za(t),u=Ga,d=Wa,p=A(n*i),m=A(r*a),g=A(A(s*d)*l),h=A(o*c),w=Z(A(Z(n+r)*Z(i+a))-p-m),$=Z(h-g),k=Z(h+g),v=Z(m-A(u*p)),S=A(w*$),P=A(k*v),M=A(w*v),_=A($*k);return new Fn(S,P,_,M)}subtract(t){return this.add(za(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(jn(t,1n,Hs),!n&&this.is0()))return Vn;if(t===1n)return this;if(this.equals(Bn))return b0(t).p;let r=Vn,o=Bn;for(let s=this;t>0n;s=s.double(),t>>=1n)t&1n?r=r.add(s):n&&(o=o.add(s));return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(this.equals(Vn))return{x:0n,y:1n};let o=ip(r,qs);A(r*o)!==1n&&ve("invalid inverse");let s=A(t*o),i=A(n*o);return{x:s,y:i}}toBytes(){let{x:t,y:n}=this.toAffine(),r=lp(n);return r[31]|=t&1n?128:0,r}toHex(){return tc(this.toBytes())}clearCofactor(){return this.multiply(Ks(t0),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Hs/2n,!1).double();return Hs%2n&&(t=t.add(this)),t.is0()}},Bn=new fo(Hm,qm,1n,Z(Hm*qm)),Vn=new fo(0n,1n,1n,0n);fo.BASE=Bn;fo.ZERO=Vn;var lp=e=>nc(np(jn(e,0n,Ya),64)).reverse(),up=e=>Ks("0x"+tc(ec(gt(e)).reverse())),ft=(e,t)=>{let n=e;for(;t-- >0n;)n=A(n*n);return n},a0=e=>{let t=A(e*e),n=A(t*e),r=A(ft(n,2n)*n),o=A(ft(r,1n)*e),s=A(ft(o,5n)*o),i=A(ft(s,10n)*s),a=A(ft(i,20n)*i),c=A(ft(a,40n)*a),l=A(ft(c,80n)*c),u=A(ft(l,80n)*c),d=A(ft(u,10n)*s);return{pow_p_5_8:A(ft(d,2n)*e),b2:n}},Wm=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,c0=(e,t)=>{let n=A(t*A(t*t)),r=A(A(n*n)*t),o=a0(A(e*r)).pow_p_5_8,s=A(e*A(n*o)),i=A(t*A(s*s)),a=s,c=A(s*Wm),l=i===e,u=i===Z(-e),d=i===Z(-e*Wm);return l&&(s=a),(u||d)&&(s=c),(Z(s)&1n)===1n&&(s=Z(-s)),{isValid:l||u,value:s}},Xa=e=>sp(up(e)),l0=(...e)=>Promise.resolve(ap("sha512Async")(wr(...e))).then(cp),rc=(...e)=>cp(ap("sha512")(wr(...e))),dp=e=>{let t=ec(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),o=Xa(n),s=Bn.multiply(o),i=s.toBytes();return{head:n,prefix:r,scalar:o,point:s,pointBytes:i}},u0=e=>l0(gt(e,vr)).then(dp),oc=e=>dp(rc(gt(e,vr))),d0=e=>oc(e).pointBytes;var m0=e=>e.finish(rc(e.hashable)),p0=(e,t,n)=>{let{pointBytes:r,scalar:o}=e,s=Xa(t),i=Bn.multiply(s).toBytes();return{hashable:wr(i,r,n),finish:l=>{let u=sp(s+Xa(l)*o);return gt(wr(i,lp(u)),64)}}};var f0=(e,t)=>{let n=gt(e),r=oc(t),o=rc(r.prefix,n);return m0(p0(r,o,n))};var sc=Object.freeze({bytesToHex:tc,hexToBytes:nc,concatBytes:wr,mod:Z,invert:ip,randomBytes:op}),mp={sha512Async:async e=>{let t=i0(),n=wr(e);return Ws(await t.digest("SHA-512",n.buffer))},sha512:void 0},g0=e=>(e=e===void 0?op(vr):e,gt(e,vr)),h0=Object.freeze({getExtendedPublicKeyAsync:u0,getExtendedPublicKey:oc,randomSecretKey:g0}),Gs=8,y0=256,pp=Math.ceil(y0/Gs)+1,Za=2**(Gs-1),_0=()=>{let e=[],t=Bn,n=t;for(let r=0;r<pp;r++){n=t,e.push(n);for(let o=1;o<Za;o++)n=n.add(t),e.push(n);t=n.double()}return e},zm=void 0,Jm=(e,t)=>{let n=t.negate();return e?n:t},b0=e=>{let t=zm||(zm=_0()),n=Vn,r=Bn,o=2**Gs,s=o,i=Ks(o-1),a=Ks(Gs);for(let c=0;c<pp;c++){let l=Number(e&i);e>>=a,l>Za&&(l-=s,e+=1n);let u=c*Za,d=u,p=u+Math.abs(l)-1,m=c%2!==0,g=l<0;l===0?r=r.add(Jm(m,t[d])):n=n.add(Jm(g,t[p]))}return e!==0n&&ve("invalid wnaf"),{p:n,f:r}};function v0(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function fp(e,t,n=""){let r=v0(e),o=e?.length,s=t!==void 0;if(!r||s&&o!==t){let i=n&&`"${n}" `,a=s?` of length ${t}`:"",c=r?`length=${o}`:`type=${typeof e}`,l=i+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(l):new TypeError(l)}return e}function Ym(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 w0(e,t){fp(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 Qa(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ja(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function S0(e,t={}){let n=(o,s)=>e(s).update(o).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>e(o),Object.assign(n,t),Object.freeze(n)}var x0=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});var T0=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=Ja(this.buffer)}update(e){Ym(this),fp(e);let{view:t,buffer:n,blockLen:r}=this,o=e.length;for(let s=0;s<o;){let i=Math.min(r-this.pos,o-s);if(i===r){let a=Ja(e);for(;r<=o-s;s+=r)this.process(a,s);continue}n.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ym(this),w0(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:o}=this,{pos:s}=this;t[s++]=128,Qa(this.buffer.subarray(s)),this.padOffset>r-s&&(this.process(n,0),s=0);for(let u=s;u<r;u++)t[u]=0;n.setBigUint64(r-8,BigInt(this.length*8),o),this.process(n,0);let i=Ja(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],o)}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:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=r,e.pos=i,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}};var Te=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Fs=BigInt(2**32-1),Xm=BigInt(32);function C0(e,t=!1){return t?{h:Number(e&Fs),l:Number(e>>Xm&Fs)}:{h:Number(e>>Xm&Fs)|0,l:Number(e&Fs)|0}}function k0(e,t=!1){let n=e.length,r=new Uint32Array(n),o=new Uint32Array(n);for(let s=0;s<n;s++){let{h:i,l:a}=C0(e[s],t);[r[s],o[s]]=[i,a]}return[r,o]}var Zm=(e,t,n)=>e>>>n,Qm=(e,t,n)=>e<<32-n|t>>>n,_r=(e,t,n)=>e>>>n|t<<32-n,br=(e,t,n)=>e<<32-n|t>>>n,Vs=(e,t,n)=>e<<64-n|t>>>n-32,Bs=(e,t,n)=>e>>>n-32|t<<64-n;function Mt(e,t,n,r){let o=(t>>>0)+(r>>>0);return{h:e+n+(o/2**32|0)|0,l:o|0}}var E0=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),A0=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,R0=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),I0=(e,t,n,r,o)=>t+n+r+o+(e/2**32|0)|0,$0=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),P0=(e,t,n,r,o,s)=>t+n+r+o+s+(e/2**32|0)|0;var gp=k0(["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))),O0=gp[0],M0=gp[1],an=new Uint32Array(80),cn=new Uint32Array(80),N0=class extends T0{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:o,Cl:s,Dh:i,Dl:a,Eh:c,El:l,Fh:u,Fl:d,Gh:p,Gl:m,Hh:g,Hl:h}=this;return[e,t,n,r,o,s,i,a,c,l,u,d,p,m,g,h]}set(e,t,n,r,o,s,i,a,c,l,u,d,p,m,g,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=o|0,this.Cl=s|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=m|0,this.Hh=g|0,this.Hl=h|0}process(e,t){for(let k=0;k<16;k++,t+=4)an[k]=e.getUint32(t),cn[k]=e.getUint32(t+=4);for(let k=16;k<80;k++){let v=an[k-15]|0,S=cn[k-15]|0,P=_r(v,S,1)^_r(v,S,8)^Zm(v,S,7),M=br(v,S,1)^br(v,S,8)^Qm(v,S,7),_=an[k-2]|0,T=cn[k-2]|0,re=_r(_,T,19)^Vs(_,T,61)^Zm(_,T,6),ae=br(_,T,19)^Bs(_,T,61)^Qm(_,T,6),K=R0(M,ae,cn[k-7],cn[k-16]),He=I0(K,P,re,an[k-7],an[k-16]);an[k]=He|0,cn[k]=K|0}let{Ah:n,Al:r,Bh:o,Bl:s,Ch:i,Cl:a,Dh:c,Dl:l,Eh:u,El:d,Fh:p,Fl:m,Gh:g,Gl:h,Hh:w,Hl:$}=this;for(let k=0;k<80;k++){let v=_r(u,d,14)^_r(u,d,18)^Vs(u,d,41),S=br(u,d,14)^br(u,d,18)^Bs(u,d,41),P=u&p^~u&g,M=d&m^~d&h,_=$0($,S,M,M0[k],cn[k]),T=P0(_,w,v,P,O0[k],an[k]),re=_|0,ae=_r(n,r,28)^Vs(n,r,34)^Vs(n,r,39),K=br(n,r,28)^Bs(n,r,34)^Bs(n,r,39),He=n&o^n&i^o&i,oe=r&s^r&a^s&a;w=g|0,$=h|0,g=p|0,h=m|0,p=u|0,m=d|0,{h:u,l:d}=Mt(c|0,l|0,T|0,re|0),c=i|0,l=a|0,i=o|0,a=s|0,o=n|0,s=r|0;let ee=E0(re,K,oe);n=A0(ee,T,ae,He),r=ee|0}({h:n,l:r}=Mt(this.Ah|0,this.Al|0,n|0,r|0)),{h:o,l:s}=Mt(this.Bh|0,this.Bl|0,o|0,s|0),{h:i,l:a}=Mt(this.Ch|0,this.Cl|0,i|0,a|0),{h:c,l}=Mt(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=Mt(this.Eh|0,this.El|0,u|0,d|0),{h:p,l:m}=Mt(this.Fh|0,this.Fl|0,p|0,m|0),{h:g,l:h}=Mt(this.Gh|0,this.Gl|0,g|0,h|0),{h:w,l:$}=Mt(this.Hh|0,this.Hl|0,w|0,$|0),this.set(n,r,o,s,i,a,c,l,u,d,p,m,g,h,w,$)}roundClean(){Qa(an,cn)}destroy(){this.destroyed=!0,Qa(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},L0=class extends N0{Ah=Te[0]|0;Al=Te[1]|0;Bh=Te[2]|0;Bl=Te[3]|0;Ch=Te[4]|0;Cl=Te[5]|0;Dh=Te[6]|0;Dl=Te[7]|0;Eh=Te[8]|0;El=Te[9]|0;Fh=Te[10]|0;Fl=Te[11]|0;Gh=Te[12]|0;Gl=Te[13]|0;Hh=Te[14]|0;Hl=Te[15]|0;constructor(){super(64)}};var U0=S0(()=>new L0,x0(3)),ep=mp;ep.sha512||(ep.sha512=e=>U0(e));function D0(){return h0.randomSecretKey()}function hp(e){return d0(e)}function yp(){let e=D0();return{secretKey:e,publicKey:hp(e)}}function ic(e,t){return f0(t,e)}var lk=sc.bytesToHex,_p=sc.hexToBytes,uk=sc.concatBytes;function j0(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function F0(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 po(e){return j0(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function V0(e){let t=e.length%4===0?0:4-e.length%4,n=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return F0(n)}var dk=new TextEncoder;function B0(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function bp(e){let t=hp(e);return{kty:"OKP",crv:"Ed25519",x:po(t),d:po(e)}}function ac(e){if(B0(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return V0(e.d)}var mk=_p("302e020100300506032b657004220420"),pk=_p("302a300506032b6570032100");var Ne=E(require("fs")),zs=E(require("os")),Sr=E(require("path")),xp=E(require("node:readline")),cc="3.0.1",H0=process.env.PORTER_API_URL??"https://porter-travel.up.railway.app",q0=process.env.TAP_REGISTRY_URL??"https://tap-production-eff9.up.railway.app",go=Sr.join(zs.homedir(),".visa-cli","agents");function K0(){return!!(process.env.VISA_DEV==="1"||cc==="0.0.0"||cc.startsWith("0.0.")||/-rc\.|-beta\./.test(cc))}function G0(){Ne.mkdirSync(go,{recursive:!0,mode:448})}function dc(e){return Sr.join(go,`${e}.json`)}function lc(){return Ne.existsSync(go)?Ne.readdirSync(go).filter(e=>e.endsWith(".json")).map(e=>Sr.join(go,e)):[]}function W0(e){let t=dc(e);return Ne.existsSync(t)?JSON.parse(Ne.readFileSync(t,"utf8")):null}function z0(e){G0();let t=dc(e.agent_id);Ne.writeFileSync(t,JSON.stringify(e,null,2),{mode:384})}async function uc(e,t,n,r){let o=`${e.replace(/\/+$/,"")}${n}`,s=await fetch(o,{method:t,headers:{"Content-Type":"application/json"},body:r!==void 0?JSON.stringify(r):void 0}),i=await s.json().catch(()=>({}));if(!s.ok||i.errors?.length){let a=i.errors?.[0];throw new Error(`${t} ${o} failed (${s.status}): ${a?.code??"unknown"} \u2014 ${a?.message??"no message"}`)}if(i.data===void 0)throw new Error(`${t} ${o}: empty response data`);return i.data}var vp=uc;function J0(){let{secretKey:e}=yp(),t=bp(e);return{publicKeyB64url:t.x,privateJwk:t}}function Tp(e,t){let n=ac(t);return po(ic(n,new TextEncoder().encode(e)))}async function Y0(e){let{publicKeyB64url:t,privateJwk:n}=J0(),r=new Date().toISOString(),o=`tap:register:v1:${e.name}:${r}`,s=Tp(o,n),i=await uc(e.registryUrl,"POST","/api/v1/agents",{name:e.name,public_key:t,signed_at:r,signature:s,visibility:"public",capabilities:["porter:book","visa:authorize_payment"]}),a=await uc(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 z0(c),c}async function Cp(e){let t=await vp(e.porter_url,"GET",`/api/v1/tap/challenge?public_key=${encodeURIComponent(e.public_key_b64url)}`),n=Tp(t.challenge,e.private_key_jwk),r=await vp(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 X0(e,t,n){let r=JSON.stringify(t),o=JSON.stringify(n),s=Buffer.from(r).toString("base64url"),i=Buffer.from(o).toString("base64url"),a=`${s}.${i}`,c=ac(e),l=ic(c,new TextEncoder().encode(a));return`${a}.${po(l)}`}var Z0=["visa_authorize_payment"],Q0={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 ew(e,t){let n=Math.floor(Date.now()/1e3),r=n+300,o=`vpid_${Sp.randomBytes(16).toString("hex")}`,s=process.env.VISACLI_ISSUER??e.tap_registry_url??e.porter_url;return{jwt:X0(e.private_key_jwk,{alg:"EdDSA",typ:"JWT",kid:e.agent_id},{iss:s,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:o}),jti:o,expiresAt:r}}async function tw(e){let t=`${e.porter_url.replace(/\/+$/,"")}/api/mcp`,n=null,r=0;async function o(p=!1){if(!p&&n&&Date.now()<r-6e4)return n;let{token:m,expiresInSeconds:g}=await Cp(e);return n=m,r=Date.now()+g*1e3,m}function s(p){process.stdout.write(JSON.stringify(p)+`
167
+ `)}function i(p,m,g){s({jsonrpc:"2.0",id:p??null,error:{code:m,message:g}})}function a(p,m,g){if(m==="visa_authorize_payment"){let h=g;if(typeof h.merchant!="string"||typeof h.amount!="number"||typeof h.currency!="string"||typeof h.idem_key!="string"){i(p,-32602,"visa_authorize_payment: missing or wrong-typed required fields");return}try{let{jwt:w,jti:$,expiresAt:k}=ew(e,h);s({jsonrpc:"2.0",id:p,result:{content:[{type:"text",text:["\u2713 Payment authorized \u2014 pass this JWT as visa_payment_id at checkout:","",w,"",` agent: ${e.agent_id}`,` merchant: ${h.merchant}`,` amount: ${h.amount} ${h.currency.toUpperCase()}`,` jti: ${$}`,` expires: ${new Date(k*1e3).toISOString()}`].join(`
168
+ `)},{type:"text",text:JSON.stringify({visa_payment_id:w,jti:$,agent_id:e.agent_id,amount:h.amount,currency:h.currency.toUpperCase(),merchant:h.merchant,expires_at:k})}]}})}catch(w){i(p,-32603,`failed to sign visa_payment_id: ${w instanceof Error?w.message:String(w)}`)}return}i(p,-32601,`unknown synthetic tool: ${m}`)}async function c(p){if(p.method==="tools/call"){let g=p.params??{};if(typeof g.name=="string"&&Z0.includes(g.name)){a(p.id,g.name,g.arguments??{});return}}let m=0;for(;m<2;){m+=1;let g=await o(m>1),h;try{h=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","X-TAP-Token":g},body:JSON.stringify(p)})}catch($){i(p.id,-32e3,`network error talking to porter: ${$ instanceof Error?$.message:String($)}`);return}if(h.status===401&&m===1){n=null;continue}if(!h.ok){let $=await h.text().catch(()=>"");i(p.id,-32e3,`porter returned ${h.status}: ${$.slice(0,400)}`);return}if((h.headers.get("content-type")??"").includes("text/event-stream"))await u(h,p);else{let $=await h.text();if($.trim()){let k=JSON.parse($);l(p,k),s(k)}}return}}function l(p,m){if(p.method!=="tools/list")return;let g=m.result;!g||!Array.isArray(g.tools)||g.tools.some(h=>h.name==="visa_authorize_payment")||g.tools.push(Q0)}async function u(p,m){let g=p.body?.getReader();if(!g)return;let h=new TextDecoder,w="";for(;;){let{done:$,value:k}=await g.read();if($)break;w+=h.decode(k,{stream:!0});let v;for(;(v=w.indexOf(`
169
169
 
170
- `))>=0;){let x=w.slice(0,v);w=w.slice(v+2);for(let $ of x.split(`
171
- `))if($.startsWith("data: ")){let O=$.slice(6).trim();if(!O)continue;try{let _=JSON.parse(O);l(m,_),s(_)}catch{}}}}}await o().catch(()=>{});let d=Zd.createInterface({input:process.stdin,terminal:!1});for await(let p of d){let m=p.trim();if(!m)continue;let g;try{g=JSON.parse(m)}catch{continue}c(g)}}function Xd(e){let t=_a();if(t.length===0)throw new Error("No agents registered. Run `visa-cli agent register` first.");if(e){let n=$b(e);if(!n)throw new Error(`Agent not found: ${e}`);return n}if(t.length>1){let n=t.map(r=>or.basename(r,".json")).map(r=>` - ${r}`).join(`
170
+ `))>=0;){let S=w.slice(0,v);w=w.slice(v+2);for(let P of S.split(`
171
+ `))if(P.startsWith("data: ")){let M=P.slice(6).trim();if(!M)continue;try{let _=JSON.parse(M);l(m,_),s(_)}catch{}}}}}await o().catch(()=>{});let d=xp.createInterface({input:process.stdin,terminal:!1});for await(let p of d){let m=p.trim();if(!m)continue;let g;try{g=JSON.parse(m)}catch{continue}c(g)}}function wp(e){let t=lc();if(t.length===0)throw new Error("No agents registered. Run `visa-cli agent register` first.");if(e){let n=W0(e);if(!n)throw new Error(`Agent not found: ${e}`);return n}if(t.length>1){let n=t.map(r=>Sr.basename(r,".json")).map(r=>` - ${r}`).join(`
172
172
  `);throw new Error(`Multiple agents registered \u2014 pass --agent <id>:
173
- ${n}`)}return JSON.parse($e.readFileSync(t[0],"utf8"))}function tm(e){if(!Rb())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",Eb).option("--registry <url>","TAP registry URL (publishes the JWKS)",Ab).option("--name <name>","Human-readable name for this agent",`${process.env.USER??"user"}@${vs.hostname()}`).action(async n=>{try{let r=await Mb({registryUrl:n.registry,porterUrl:n.porter,name:n.name}),o=_a().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: ${va(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${o}`,"",'Now ask Claude: "search flights from JFK to CDG on 2026-09-15."',""].join(`
173
+ ${n}`)}return JSON.parse(Ne.readFileSync(t[0],"utf8"))}function kp(e){if(!K0())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",H0).option("--registry <url>","TAP registry URL (publishes the JWKS)",q0).option("--name <name>","Human-readable name for this agent",`${process.env.USER??"user"}@${zs.hostname()}`).action(async n=>{try{let r=await Y0({registryUrl:n.registry,porterUrl:n.porter,name:n.name}),o=lc().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: ${dc(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${o}`,"",'Now ask Claude: "search flights from JFK to CDG on 2026-09-15."',""].join(`
174
174
  `))}catch(r){process.stderr.write(`agent register failed: ${r instanceof Error?r.message:String(r)}
175
- `),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=Xd(n.agent),{token:o,expiresInSeconds:s}=await em(r);n.export?process.stdout.write(`export X_TAP_TOKEN='${o}'
175
+ `),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=wp(n.agent),{token:o,expiresInSeconds:s}=await Cp(r);n.export?process.stdout.write(`export X_TAP_TOKEN='${o}'
176
176
  `):process.stdout.write(`${o}
177
177
  `),process.stderr.write(`# expires in ${Math.round(s/3600)}h \xB7 agent ${r.agent_id}
178
178
  `)}catch(r){process.stderr.write(`agent token failed: ${r instanceof Error?r.message:String(r)}
179
- `),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=Xd(n.agent);await jb(r)}catch(r){process.stderr.write(`agent proxy failed: ${r instanceof Error?r.message:String(r)}
180
- `),process.exit(1)}}),t.command("list").description("List registered agents.").action(()=>{let n=_a();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 o=JSON.parse($e.readFileSync(r,"utf8"));process.stdout.write(`${o.agent_id} ${o.porter_url} ${o.name}
181
- `)}})}var Fb=["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 Vb(){let e=new Set;for(let t of Fb)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of Dr)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var ek=Vb();var wa=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 sk=new Set(Dr),ik=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...wa,...Dr]);var q=T(require("fs")),D=T(require("path")),nm=T(require("os")),te=nm.homedir(),qb=["Claude_","Anthropic.ClaudeDesktop_"],sr=class extends Error{constructor(n,r,o){super(Hb(n,r,o));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function rm(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
182
- `)}function Bb(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=rm(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function Hb(e,t,n){let r=t.replace(te,"~"),o=rm(n).split(`
183
- `).find(Boolean),s=o?` (${o})`:"";return e.id==="codex"?`Could not update Codex MCP config at ${r}: filesystem access was denied${s}. 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${s}.`}function Yr(){return process.env.APPDATA||D.join(te,"AppData","Roaming")}function Kb(){return process.env.LOCALAPPDATA||D.join(te,"AppData","Local")}function Sa(e){return process.platform==="win32"?e.win32:e.posix}function om(){if(process.platform!=="win32")return;let e=D.join(Kb(),"Packages");if(q.existsSync(e))try{let t=q.readdirSync(e,"utf-8");for(let n of qb){let r=t.filter(o=>o.startsWith(n)).sort()[0];if(r)return D.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function sm(){if(process.platform==="win32"){let e=om();return e?D.join(e,"claude_desktop_config.json"):D.join(Yr(),"Claude","claude_desktop_config.json")}return D.join(te,"Library","Application Support","Claude","claude_desktop_config.json")}function im(){if(process.platform!=="win32")return[D.join(te,"Library","Application Support","Claude")];let e=[D.join(Yr(),"Claude")],t=om();return t&&e.push(t),e}function ws(e){return e.id==="claude-desktop"?sm():e.globalConfigPath}function Gb(e){return e.id==="claude-desktop"?im():e.detectPaths}var ze=[{id:"claude",displayName:"Claude Code",globalConfigPath:D.join(te,".claude.json"),configKey:"mcpServers",detectPaths:[D.join(te,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:sm(),configKey:"mcpServers",detectPaths:im(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:D.join(te,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[D.join(te,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:D.join(te,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[D.join(te,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:D.join(te,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[D.join(te,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:Sa({win32:D.join(Yr(),"Roo","mcp_settings.json"),posix:D.join(te,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[D.join(te,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:D.join(te,".vscode","mcp.json"),configKey:"servers",detectPaths:[D.join(te,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:Sa({win32:D.join(Yr(),"Zed","settings.json"),posix:D.join(te,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:Sa({win32:[D.join(Yr(),"Zed")],posix:[D.join(te,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:D.join(te,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[D.join(te,".codex")],postInstallHint:"Restart Codex to connect."}];function xa(e){return ze.find(t=>t.id===e)}function Xr(e){return Gb(e).some(t=>{if(t.includes("*")){let n=D.dirname(t),r=D.basename(t).replaceAll("*","");if(!q.existsSync(n))return!1;try{return q.readdirSync(n).some(o=>o.startsWith(r))}catch{return!1}}return q.existsSync(t)})}function am(){return{command:"node",args:[D.resolve(__dirname,"mcp-server/index.js")]}}function ka(e,t){return t==="project"?"json":e.configFormat??"json"}function Wb(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 Ca(e,t){let n=`[mcp_servers.${t}]`,r=e.findIndex(s=>s.trim()===n);if(r===-1)return;let o=r+1;for(;o<e.length&&!e[o].trim().startsWith("[");)o++;return{start:r,end:o}}function Ta(e,t){let n=e.split(`
184
- `),r=Ca(n,t);if(!r)return;let o={};for(let s=r.start+1;s<r.end;s++){let i=n[s].trim().match(/^(\w+)\s*=\s*(.+)$/);i&&(o[i[1]]=Wb(i[2]))}return Object.keys(o).length>0?o:void 0}function zb(e,t,n){let r=`[${n.args.map(c=>`"${c}"`).join(", ")}]`,o=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],s=e.split(`
185
- `),i=Ca(s,t);if(i){s.splice(i.start,i.end-i.start,...o);let c=s.join(`
179
+ `),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=wp(n.agent);await tw(r)}catch(r){process.stderr.write(`agent proxy failed: ${r instanceof Error?r.message:String(r)}
180
+ `),process.exit(1)}}),t.command("list").description("List registered agents.").action(()=>{let n=lc();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 o=JSON.parse(Ne.readFileSync(r,"utf8"));process.stdout.write(`${o.agent_id} ${o.porter_url} ${o.name}
181
+ `)}})}var nw=["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 rw(){let e=new Set;for(let t of nw)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of no)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var kk=rw();var mc=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 $k=new Set(no),Pk=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...mc,...no]);var H=E(require("fs")),j=E(require("path")),Ep=E(require("os")),ie=Ep.homedir(),ow=["Claude_","Anthropic.ClaudeDesktop_"],xr=class extends Error{constructor(n,r,o){super(iw(n,r,o));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function Ap(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
182
+ `)}function sw(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=Ap(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function iw(e,t,n){let r=t.replace(ie,"~"),o=Ap(n).split(`
183
+ `).find(Boolean),s=o?` (${o})`:"";return e.id==="codex"?`Could not update Codex MCP config at ${r}: filesystem access was denied${s}. 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${s}.`}function ho(){return process.env.APPDATA||j.join(ie,"AppData","Roaming")}function aw(){return process.env.LOCALAPPDATA||j.join(ie,"AppData","Local")}function pc(e){return process.platform==="win32"?e.win32:e.posix}function Rp(){if(process.platform!=="win32")return;let e=j.join(aw(),"Packages");if(H.existsSync(e))try{let t=H.readdirSync(e,"utf-8");for(let n of ow){let r=t.filter(o=>o.startsWith(n)).sort()[0];if(r)return j.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function Ip(){if(process.platform==="win32"){let e=Rp();return e?j.join(e,"claude_desktop_config.json"):j.join(ho(),"Claude","claude_desktop_config.json")}return j.join(ie,"Library","Application Support","Claude","claude_desktop_config.json")}function $p(){if(process.platform!=="win32")return[j.join(ie,"Library","Application Support","Claude")];let e=[j.join(ho(),"Claude")],t=Rp();return t&&e.push(t),e}function Js(e){return e.id==="claude-desktop"?Ip():e.globalConfigPath}function cw(e){return e.id==="claude-desktop"?$p():e.detectPaths}var Qe=[{id:"claude",displayName:"Claude Code",globalConfigPath:j.join(ie,".claude.json"),configKey:"mcpServers",detectPaths:[j.join(ie,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:Ip(),configKey:"mcpServers",detectPaths:$p(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:j.join(ie,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[j.join(ie,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:j.join(ie,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[j.join(ie,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:j.join(ie,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[j.join(ie,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:pc({win32:j.join(ho(),"Roo","mcp_settings.json"),posix:j.join(ie,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[j.join(ie,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:j.join(ie,".vscode","mcp.json"),configKey:"servers",detectPaths:[j.join(ie,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:pc({win32:j.join(ho(),"Zed","settings.json"),posix:j.join(ie,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:pc({win32:[j.join(ho(),"Zed")],posix:[j.join(ie,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:j.join(ie,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[j.join(ie,".codex")],postInstallHint:"Restart Codex to connect."}];function fc(e){return Qe.find(t=>t.id===e)}function yo(e){return cw(e).some(t=>{if(t.includes("*")){let n=j.dirname(t),r=j.basename(t).replaceAll("*","");if(!H.existsSync(n))return!1;try{return H.readdirSync(n).some(o=>o.startsWith(r))}catch{return!1}}return H.existsSync(t)})}function Pp(){return{command:"node",args:[j.resolve(__dirname,"mcp-server/index.js")]}}function gc(e,t){return t==="project"?"json":e.configFormat??"json"}function lw(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 hc(e,t){let n=`[mcp_servers.${t}]`,r=e.findIndex(s=>s.trim()===n);if(r===-1)return;let o=r+1;for(;o<e.length&&!e[o].trim().startsWith("[");)o++;return{start:r,end:o}}function yc(e,t){let n=e.split(`
184
+ `),r=hc(n,t);if(!r)return;let o={};for(let s=r.start+1;s<r.end;s++){let i=n[s].trim().match(/^(\w+)\s*=\s*(.+)$/);i&&(o[i[1]]=lw(i[2]))}return Object.keys(o).length>0?o:void 0}function uw(e,t,n){let r=`[${n.args.map(c=>`"${c}"`).join(", ")}]`,o=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],s=e.split(`
185
+ `),i=hc(s,t);if(i){s.splice(i.start,i.end-i.start,...o);let c=s.join(`
186
186
  `);return c.endsWith(`
187
187
  `)?c:c+`
188
188
  `}let a=e.trimEnd();return a+(a.length>0?`
189
189
 
190
190
  `:"")+o.join(`
191
191
  `)+`
192
- `}function Jb(e,t){let n=e.split(`
193
- `),r=Ca(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
192
+ `}function dw(e,t){let n=e.split(`
193
+ `),r=hc(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
194
194
  `).replace(/\n{3,}/g,`
195
195
 
196
- `)):e}function Zr(e,t="global"){let n=t==="project"?D.join(process.cwd(),".mcp.json"):ws(e);try{let r=D.dirname(n);q.existsSync(r)||q.mkdirSync(r,{recursive:!0});let o=ka(e,t),s=am();if(o==="toml"){let i=q.existsSync(n)?q.readFileSync(n,"utf-8"):"",a=zb(i,"visa-cli",s);q.writeFileSync(n,a)}else{let i={};if(q.existsSync(n))try{i=JSON.parse(q.readFileSync(n,"utf-8"))}catch{i={}}i[e.configKey]=i[e.configKey]||{},i[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(s):s,q.writeFileSync(n,JSON.stringify(i,null,2)+`
197
- `)}}catch(r){throw Bb(r)?new sr(e,n,r):r}return{installed:!0,configPath:n,message:e.postInstallHint}}function Ea(e,t="global"){let n=t==="project"?D.join(process.cwd(),".mcp.json"):ws(e);if(!q.existsSync(n))return{removed:!1,configPath:n};if(ka(e,t)==="toml"){let i=q.readFileSync(n,"utf-8");return Ta(i,"visa-cli")?(q.writeFileSync(n,Jb(i,"visa-cli")),{removed:!0,configPath:n}):{removed:!1,configPath:n}}let o;try{o=JSON.parse(q.readFileSync(n,"utf-8"))}catch{return{removed:!1,configPath:n}}let s=o[e.configKey];return!s||!s["visa-cli"]?{removed:!1,configPath:n}:(delete s["visa-cli"],q.writeFileSync(n,JSON.stringify(o,null,2)+`
198
- `),{removed:!0,configPath:n})}function cm(e,t="global"){let n=t==="project"?D.join(process.cwd(),".mcp.json"):ws(e);if(!q.existsSync(n))return!1;if(ka(e,t)==="toml")try{let o=q.readFileSync(n,"utf-8");return!!Ta(o,"visa-cli")}catch{return!1}try{return!!JSON.parse(q.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function Yb(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 Xb(e,t){if(e===t)return!0;let n=D.resolve(e),r=D.resolve(t);if(n===r)return!0;try{let o=q.realpathSync(n),s=q.realpathSync(r);return o===s}catch{return!1}}function Qr(){let e=am(),t=e.args[e.args.length-1],n=[];for(let r of ze){let o=ws(r);if(!q.existsSync(o))continue;let s=r.configFormat??"json",i;if(s==="toml")try{let l=q.readFileSync(o,"utf-8");i=Ta(l,"visa-cli")}catch{continue}else{let l;try{l=JSON.parse(q.readFileSync(o,"utf-8"))}catch{continue}i=l?.[r.configKey]?.["visa-cli"]}if(!i)continue;let a=Yb(i);if(!a||Xb(a,t))continue;let c=q.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:o,currentPath:a,expectedPath:t,staleReason:c})}return n}function Aa(e){return{configPath:Zr(e.client,"global").configPath}}var Pa=(0,_m.promisify)(ym.execFile);function Ra(){let e=pt();setImmediate(()=>{si(e,{getCommand:()=>Eo(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 nv(e){let t=J.homedir(),n=o=>o.replace(t,"~"),r=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
199
- ${r}: ${n(e.currentPath)}`}function bm(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(nv(n))}function lm(e){console.log(` ! ${e.client.displayName} skipped: ${e.message}`)}function Je(){this.help({error:!1})}var G=new hm.Command,rv=new Set(["pay",...wa]),ks=null,eo=!1;function ce(){return ks=new Ae(()=>V.getSessionToken()),ks}function um(e){if(e instanceof an)return!0;let t=e instanceof Error?e.message:"";return/attestation required|invalid signature|rotate biometric key|biometric key/i.test(t)}var dm=0,mm="",ov="attestation-key-rotation",sv="api-keys-create",pm=0,fm="",iv=12e3;async function av(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:dm,merchant:mm,context:ov})).toString("base64");return{signature:await Tn(n,"verify Visa CLI Touch ID setup"),nonce:t,amount:dm,merchant:mm}}async function cv(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:pm,merchant:fm,context:sv})).toString("base64");return{signature:await Tn(n,"create a Visa Key",{timeoutMs:iv}),nonce:t,amount:pm,merchant:fm}}async function lv(e){let t=await e.getStatus();return t.attestationRequired!==!1||it(t)}async function uv(e){let t=await qu(),n=await av(e);await e.registerAttestationKey(t,n)}async function vm(e,t,n=!1){let r=await Yo();console.log(" Attestation key generated."),await e.registerAttestationKey(r),console.log(" Attestation key registered with server."),t&&(await e.setBiometricPreference({required:!0}),n&&f.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 Ia(e){if(!await Ua(e))throw new Error("Could not clear stale server biometric state. Run `visa-cli config reset`, then `visa-cli setup`.");await vm(e,!0,!0)}function La(e){return async()=>{let t=await Ua(e);return{success:t,...t?{}:{message:"Biometric recovery was not completed."}}}}async function dv(e){let r=Date.now()+3e5;for(;Date.now()<r;)try{let o=await globalThis.fetch(`${Ee()}/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(!o.ok){await Pt(o,i=>{f.warn("auth_status:retry_after_http_error",{status:o.status,delayMs:i})});continue}let s=await o.json();if(s.status==="pending")continue;if(s.status==="complete"&&s.attestationCleared)return;if(s.status==="expired")throw new Error("Biometric reset session expired. Please run visa-cli config reset again.");if(s.status==="error")throw new Error(s.error||"Biometric reset failed. Please try again.")}catch(o){if(o?.message&&!/fetch failed|network|abort/i.test(o.message))throw o;await Pt(void 0,s=>{f.warn("auth_status:retry_after_network_error",{delayMs:s})})}throw new Error("Biometric reset timed out after 5 minutes. Please run visa-cli config reset again.")}async function Ua(e){let t;try{t=await e.getStatus()}catch(o){let s=o?.message||"";if(/not logged in|session.*expired|no local credentials/i.test(s))return!1;throw new Error(`Could not check server biometric state: ${s||"unknown error"}`)}if(!it(t))return!1;let n=Ts.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 Js(r.recoveryUrl),await dv(n),console.log(" Server biometric state cleared."),!0}function to(e){return`$${(e/100).toFixed(2)}`}function mv(e){return typeof e=="number"?to(e):"no cap"}function Oa(e,t,n=!1){if(!e){let i=to(t);return n&&t>=0?`+${i}`:i}let r=(0,Es.fromWire)(e),o=r%10000n===0n?2:6,s=(0,Es.toDisplay)(r,{decimals:o});return n&&r>=0n?`+${s}`:s}function pv(e){return Oa(e,0)}function fv(e){let t=`visa-cli-${J.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 gv(e){if(!e)return;let t=e.split(",").map(s=>s.trim()).filter(Boolean),n=Array.from(new Set(t)),r=n.find(s=>s.length>64);if(r)throw new Error(`Tool id is too long: ${r}`);let o=n.find(s=>rv.has(s));if(o)throw new Error(`Tool id "${o}" is retired for direct API-key access. Use category meta-tools or discover/execute instead.`);return n}var Ma=!1;async function wm(e){let t=(0,Na.createInterface)({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function hv(e,t=!1){let n=Sl(e,{json:t,isTTY:process.stdin.isTTY===!0});if(n!==void 0)return n;if(await ui("Use recommended Visa Key caps ($5/day and $25 total)? Without caps, leaked keys can spend from prepaid balance until revoked.",!0))return Ma=!0,500;let o=await wm("Daily cap USD (1-100): ");if(!o)throw new Error("--daily-cap is required when declining the recommended daily cap.");return mi(o)}async function yv(e,t=!1){let n=xl(e,{json:t,isTTY:process.stdin.isTTY===!0,recommendedCapsAccepted:Ma});if(n!==void 0)return Ma=!1,n;let r=await wm("Cumulative cap USD (1-10000, default 25): ");return pi(r||"25")}function _v(e){return e&&e.length>0?e.join(", "):"all tools"}function Sm(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 As(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=Mn(c);if(d){let p=typeof e?.merchantName=="string"?e.merchantName:"media",m=typeof e?.transactionId=="string"?`${p}-${e.transactionId}`:p,g=mr(d,{tag:m}),y=Hs(i,e);y.success&&(y.filePath=g.filePath,y.mime=g.mime,y.bytes=g.bytes,u&&u.startsWith("data:")&&(y.urls=void 0)),hr(y,a);return}}catch(d){hr(pr(i,`Failed to save inline media: ${d instanceof Error?d.message:String(d)}`),a),process.exitCode=km;return}hr(Hs(i,e),a);return}if(e?.content?.[0]?.text&&typeof e.content[0].text=="string"){try{let i=Mn(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=mr(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 o=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}`),o.length>0){console.log(`
196
+ `)):e}function _o(e,t="global"){let n=t==="project"?j.join(process.cwd(),".mcp.json"):Js(e);try{let r=j.dirname(n);H.existsSync(r)||H.mkdirSync(r,{recursive:!0});let o=gc(e,t),s=Pp();if(o==="toml"){let i=H.existsSync(n)?H.readFileSync(n,"utf-8"):"",a=uw(i,"visa-cli",s);H.writeFileSync(n,a)}else{let i={};if(H.existsSync(n))try{i=JSON.parse(H.readFileSync(n,"utf-8"))}catch{i={}}i[e.configKey]=i[e.configKey]||{},i[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(s):s,H.writeFileSync(n,JSON.stringify(i,null,2)+`
197
+ `)}}catch(r){throw sw(r)?new xr(e,n,r):r}return{installed:!0,configPath:n,message:e.postInstallHint}}function _c(e,t="global"){let n=t==="project"?j.join(process.cwd(),".mcp.json"):Js(e);if(!H.existsSync(n))return{removed:!1,configPath:n};if(gc(e,t)==="toml"){let i=H.readFileSync(n,"utf-8");return yc(i,"visa-cli")?(H.writeFileSync(n,dw(i,"visa-cli")),{removed:!0,configPath:n}):{removed:!1,configPath:n}}let o;try{o=JSON.parse(H.readFileSync(n,"utf-8"))}catch{return{removed:!1,configPath:n}}let s=o[e.configKey];return!s||!s["visa-cli"]?{removed:!1,configPath:n}:(delete s["visa-cli"],H.writeFileSync(n,JSON.stringify(o,null,2)+`
198
+ `),{removed:!0,configPath:n})}function Op(e,t="global"){let n=t==="project"?j.join(process.cwd(),".mcp.json"):Js(e);if(!H.existsSync(n))return!1;if(gc(e,t)==="toml")try{let o=H.readFileSync(n,"utf-8");return!!yc(o,"visa-cli")}catch{return!1}try{return!!JSON.parse(H.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function mw(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 pw(e,t){if(e===t)return!0;let n=j.resolve(e),r=j.resolve(t);if(n===r)return!0;try{let o=H.realpathSync(n),s=H.realpathSync(r);return o===s}catch{return!1}}function bo(){let e=Pp(),t=e.args[e.args.length-1],n=[];for(let r of Qe){let o=Js(r);if(!H.existsSync(o))continue;let s=r.configFormat??"json",i;if(s==="toml")try{let l=H.readFileSync(o,"utf-8");i=yc(l,"visa-cli")}catch{continue}else{let l;try{l=JSON.parse(H.readFileSync(o,"utf-8"))}catch{continue}i=l?.[r.configKey]?.["visa-cli"]}if(!i)continue;let a=mw(i);if(!a||pw(a,t))continue;let c=H.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:o,currentPath:a,expectedPath:t,staleReason:c})}return n}function bc(e){return{configPath:_o(e.client,"global").configPath}}var xc=(0,Hp.promisify)(Bp.execFile);function vc(){let e=bt();setImmediate(()=>{Mi(e,{getCommand:()=>Go(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 _w(e){let t=X.homedir(),n=o=>o.replace(t,"~"),r=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
199
+ ${r}: ${n(e.currentPath)}`}function qp(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(_w(n))}function Mp(e){console.log(` ! ${e.client.displayName} skipped: ${e.message}`)}function et(){this.help({error:!1})}var z=new Vp.Command,bw=new Set(["pay",...mc]),Zs=null,vo=!1;function pe(){return Zs=new Pe(()=>B.getSessionToken()),Zs}function Np(e){if(e instanceof hn)return!0;let t=e instanceof Error?e.message:"";return/attestation required|invalid signature|rotate biometric key|biometric key/i.test(t)}var Lp=0,Up="",vw="attestation-key-rotation",ww="api-keys-create",Dp=0,jp="",Sw=12e3;async function xw(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:Lp,merchant:Up,context:vw})).toString("base64");return{signature:await Nn(n,"verify Visa CLI Touch ID setup"),nonce:t,amount:Lp,merchant:Up}}async function Tw(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:Dp,merchant:jp,context:ww})).toString("base64");return{signature:await Nn(n,"create a Visa Key",{timeoutMs:Sw}),nonce:t,amount:Dp,merchant:jp}}async function Cw(e){let t=await e.getStatus();return t.attestationRequired!==!1||dt(t)}async function kw(e){let t=await Od(),n=await xw(e);await e.registerAttestationKey(t,n)}async function Kp(e,t,n=!1){let r=await gs();console.log(" Attestation key generated."),await e.registerAttestationKey(r),console.log(" Attestation key registered with server."),t&&(await e.setBiometricPreference({required:!0}),n&&f.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 wc(e){if(!await Ec(e))throw new Error("Could not clear stale server biometric state. Run `visa-cli config reset`, then `visa-cli setup`.");await Kp(e,!0,!0)}function kc(e){return async()=>{let t=await Ec(e);return{success:t,...t?{}:{message:"Biometric recovery was not completed."}}}}async function Ew(e){let r=Date.now()+3e5;for(;Date.now()<r;)try{let o=await globalThis.fetch(`${$e()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:3e4}),signal:AbortSignal.timeout(35e3)});if(!o.ok){await Ft(o,i=>{f.warn("auth_status:retry_after_http_error",{status:o.status,delayMs:i})});continue}let s=await o.json();if(s.status==="pending")continue;if(s.status==="complete"&&s.attestationCleared)return;if(s.status==="expired")throw new Error("Biometric reset session expired. Please run visa-cli config reset again.");if(s.status==="error")throw new Error(s.error||"Biometric reset failed. Please try again.")}catch(o){if(o?.message&&!/fetch failed|network|abort/i.test(o.message))throw o;await Ft(void 0,s=>{f.warn("auth_status:retry_after_network_error",{delayMs:s})})}throw new Error("Biometric reset timed out after 5 minutes. Please run visa-cli config reset again.")}async function Ec(e){let t;try{t=await e.getStatus()}catch(o){let s=o?.message||"";if(/not logged in|session.*expired|no local credentials/i.test(s))return!1;throw new Error(`Could not check server biometric state: ${s||"unknown error"}`)}if(!dt(t))return!1;let n=ti.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 Ti(r.recoveryUrl),await Ew(n),console.log(" Server biometric state cleared."),!0}function wo(e){return`$${(e/100).toFixed(2)}`}function Aw(e){return typeof e=="number"?wo(e):"no cap"}function Qs(e,t,n=!1){if(!e){let i=wo(t);return n&&t>=0?`+${i}`:i}let r=(0,ni.fromWire)(e),o=r%10000n===0n?2:6,s=(0,ni.toDisplay)(r,{decimals:o});return n&&r>=0n?`+${s}`:s}function Rw(e){return Qs(e,0)}function Iw(e){let t=`visa-cli-${X.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 $w(e){if(!e)return;let t=e.split(",").map(s=>s.trim()).filter(Boolean),n=Array.from(new Set(t)),r=n.find(s=>s.length>64);if(r)throw new Error(`Tool id is too long: ${r}`);let o=n.find(s=>bw.has(s));if(o)throw new Error(`Tool id "${o}" is retired for direct API-key access. Use category meta-tools or discover/execute instead.`);return n}var Tc=!1;async function Gp(e){let t=(0,Cc.createInterface)({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function Pw(e,t=!1){let n=mu(e,{json:t,isTTY:process.stdin.isTTY===!0});if(n!==void 0)return n;if(await ji("Use recommended Visa Key caps ($5/day and $25 total)? Without caps, leaked keys can spend from prepaid balance until revoked.",!0))return Tc=!0,500;let o=await Gp("Daily cap USD (1-100): ");if(!o)throw new Error("--daily-cap is required when declining the recommended daily cap.");return Vi(o)}async function Ow(e,t=!1){let n=pu(e,{json:t,isTTY:process.stdin.isTTY===!0,recommendedCapsAccepted:Tc});if(n!==void 0)return Tc=!1,n;let r=await Gp("Cumulative cap USD (1-10000, default 25): ");return Bi(r||"25")}function Mw(e){return e&&e.length>0?e.join(", "):"all tools"}function Wp(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 ri(e,t={}){let n=t.format&&Mo(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=Wn(c);if(d){let p=typeof e?.merchantName=="string"?e.merchantName:"media",m=typeof e?.transactionId=="string"?`${p}-${e.transactionId}`:p,g=Ir(d,{tag:m}),h=bi(i,e);h.success&&(h.filePath=g.filePath,h.mime=g.mime,h.bytes=g.bytes,u&&u.startsWith("data:")&&(h.urls=void 0)),Mr(h,a);return}}catch(d){Mr($r(i,`Failed to save inline media: ${d instanceof Error?d.message:String(d)}`),a),process.exitCode=Jp;return}Mr(bi(i,e),a);return}if(e?.content?.[0]?.text&&typeof e.content[0].text=="string"){try{let i=Wn(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=Ir(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 o=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}`),o.length>0){console.log(`
200
200
  Result URLs:`);for(let i of o)console.log(` ${i}`);return}let s=JSON.stringify(e,null,2);s&&s!=="{}"&&(console.log(`
201
- Result:`),console.log(s))}var bv=new Set(["INVALID_TOOL_PARAMS","MISSING_TOOL_ID","UNKNOWN_TOOL"]),xm=0,km=1,vv=2;function wv(e){if(e?.success!==!1)return xm;let n=(typeof e?.error_code=="string"?e.error_code:typeof e?.code=="string"?e.code:"").toUpperCase();return bv.has(n)?vv:km}function Rs(e){let t=wv(e);t!==xm&&(process.exitCode=t)}function ir(e,t,n={}){let r=typeof n=="boolean"?{json:n}:n,o=t instanceof Error?t.message:String(t),s=r.format&&go(r.format)?r.format:void 0;if(r.json||s!==void 0){let i=s??"json";hr(pr(e,o),i)}else console.error("Error:",o);process.exit(1)}async function Sv(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 Da=100,ja=200;function Cs(e){let t=Number.parseInt(e,10);return Number.isNaN(t)?Number.NaN:t}function xv(e){let t=typeof e.limit=="number"&&Number.isInteger(e.limit)?Math.max(1,Math.min(e.limit,ja)):Da,n=typeof e.offset=="number"&&Number.isInteger(e.offset)?Math.max(0,e.offset):0;return{limit:t,offset:n}}function kv(e){let t=`
201
+ Result:`),console.log(s))}var Nw=new Set(["INVALID_TOOL_PARAMS","MISSING_TOOL_ID","UNKNOWN_TOOL"]),zp=0,Jp=1,Lw=2;function Uw(e){if(e?.success!==!1)return zp;let n=(typeof e?.error_code=="string"?e.error_code:typeof e?.code=="string"?e.code:"").toUpperCase();return Nw.has(n)?Lw:Jp}function oi(e){let t=Uw(e);t!==zp&&(process.exitCode=t)}function Tr(e,t,n={}){let r=typeof n=="boolean"?{json:n}:n,o=t instanceof Error?t.message:String(t),s=r.format&&Mo(r.format)?r.format:void 0;if(r.json||s!==void 0){let i=s??"json";Mr($r(e,o),i)}else console.error("Error:",o);process.exit(1)}async function Dw(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 Ac=100,Rc=200;function ei(e){let t=Number.parseInt(e,10);return Number.isNaN(t)?Number.NaN:t}function jw(e){let t=typeof e.limit=="number"&&Number.isInteger(e.limit)?Math.max(1,Math.min(e.limit,Rc)):Ac,n=typeof e.offset=="number"&&Number.isInteger(e.offset)?Math.max(0,e.offset):0;return{limit:t,offset:n}}function Fw(e){let t=`
202
202
  Options:
203
203
  `,n=`
204
204
  Commands:
205
- `,r=e.indexOf(t),o=e.indexOf(n);if(r===-1||o===-1||r>o)return e;let s=p=>{let g=e.slice(p+1).search(/\n[A-Z][A-Za-z ]+:\n/);return g===-1?e.length:p+1+g},i=s(r),a=s(o),c=e.slice(0,r),l=e.slice(r,i),u=e.slice(o,a),d=e.slice(a);return`${c}${u}${l}${d}`}function Cv(e){if(!e.startsWith("Usage: "))return e;let t=e.indexOf(`
205
+ `,r=e.indexOf(t),o=e.indexOf(n);if(r===-1||o===-1||r>o)return e;let s=p=>{let g=e.slice(p+1).search(/\n[A-Z][A-Za-z ]+:\n/);return g===-1?e.length:p+1+g},i=s(r),a=s(o),c=e.slice(0,r),l=e.slice(r,i),u=e.slice(o,a),d=e.slice(a);return`${c}${u}${l}${d}`}function Vw(e){if(!e.startsWith("Usage: "))return e;let t=e.indexOf(`
206
206
 
207
207
  `);if(t===-1)return e;let n=e.slice(0,t),r=e.slice(t+2),o=r.indexOf(`
208
208
 
@@ -210,18 +210,18 @@ Commands:
210
210
 
211
211
  ${n}
212
212
 
213
- ${i}`:e}function Tv(e){return e.replace(/(^|\n)(Commands:\n)([\s\S]*?)(?=\n[A-Z][A-Za-z ]+:\n|$)/g,(t,n,r,o)=>{let s=o.split(`
214
- `).map(Ev).join(`
215
- `);return`${n}${r}${s}`})}function Ev(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 o=-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){o=l;break}}if(o===-1)return e;let s=e.slice(n,r),i=e.slice(o),a=Math.max(2,o-2-s.length);return` ${s}${" ".repeat(a)}${i}`}function Av(e){return e.replace(/^(Usage: .+?) \[options\](?= |$)/gm,"$1")}function Rv(e){return e.replace(/^Options:$/gm,"Flags:")}function Cm(e){let t=e.helpInformation.bind(e);e.helpInformation=()=>Rv(Av(Tv(kv(Cv(t())))));for(let n of e.commands)Cm(n)}function Iv(e){let t=new Map(e.map((r,o)=>[r,o]));G.commands.sort((r,o)=>{let s=t.get(r.name())??Number.MAX_SAFE_INTEGER,i=t.get(o.name())??Number.MAX_SAFE_INTEGER;return s-i})}G.name("visa-cli").description("Visa CLI - set up MCP payments, manage credentials, and monitor AI spend").version(dr().version).addHelpCommand(!1).action(Je);G.hook("preAction",async()=>{await lc()});G.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(`
213
+ ${i}`:e}function Bw(e){return e.replace(/(^|\n)(Commands:\n)([\s\S]*?)(?=\n[A-Z][A-Za-z ]+:\n|$)/g,(t,n,r,o)=>{let s=o.split(`
214
+ `).map(Hw).join(`
215
+ `);return`${n}${r}${s}`})}function Hw(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 o=-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){o=l;break}}if(o===-1)return e;let s=e.slice(n,r),i=e.slice(o),a=Math.max(2,o-2-s.length);return` ${s}${" ".repeat(a)}${i}`}function qw(e){return e.replace(/^(Usage: .+?) \[options\](?= |$)/gm,"$1")}function Kw(e){return e.replace(/^Options:$/gm,"Flags:")}function Yp(e){let t=e.helpInformation.bind(e);e.helpInformation=()=>Kw(qw(Bw(Fw(Vw(t())))));for(let n of e.commands)Yp(n)}function Gw(e){let t=new Map(e.map((r,o)=>[r,o]));z.commands.sort((r,o)=>{let s=t.get(r.name())??Number.MAX_SAFE_INTEGER,i=t.get(o.name())??Number.MAX_SAFE_INTEGER;return s-i})}z.name("visa-cli").description("Visa CLI - set up MCP payments, manage credentials, and monitor AI spend").version(Rr().version).addHelpCommand(!1).action(et);z.hook("preAction",async()=>{await Qc()});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(`
216
216
 
217
- 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=Qr();bm(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 o=Qr(),s=new Map(o.map(v=>[v.client.id,v])),i=new Set,a=new Set,c=new Set;for(let v of ze)if(Xr(v)){let x;try{x=Zr(v)}catch(_){if(_ instanceof sr){lm(_),a.add(v.displayName),c.add(v.id);continue}throw _}let $=s.get(v.id),O=$?` \u2014 repaired stale ${$.staleReason} entry`:"";console.log(` \u2713 ${v.displayName} (${x.configPath.replace(J.homedir(),"~")})${O}`),$&&i.add(v.id)}let l=o.filter(v=>!i.has(v.client.id)&&!c.has(v.client.id)),u=0;for(let v of l){try{Aa(v)}catch(x){if(x instanceof sr){lm(x),a.add(v.client.displayName),c.add(v.client.id);continue}throw x}console.log(` \u2713 ${v.client.displayName} (${v.configPath.replace(J.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(`
218
- Step 2: Checking authentication...`);let p=await V.getSessionToken();if(p)try{await new Ae(()=>Promise.resolve(p)).getStatus(),console.log(" Already authenticated.")}catch(v){let x=v instanceof Error?v.message:"";x.includes("session has expired")||x.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await Jd(),p=null):console.log(` Couldn't verify session (${x||"unknown error"}) \u2014 continuing with existing token.`)}if(!p){let v=null;try{let{stdout:x}=await Pa("gh",["auth","token"],{timeout:5e3});v=x.trim()}catch{}if(v||(v=process.env.GITHUB_TOKEN||null),v)try{console.log(" Found GitHub token \u2014 attempting headless login...");let x=await globalThis.fetch(`${Ee()}/v1/auth/token-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({github_token:v}),signal:AbortSignal.timeout(1e4)});if(x.ok){let $=await x.json();if($.success&&$.sessionToken){let O=$.sessionToken;p=O,await V.saveSessionToken(O),console.log(` Signed in as ${$.user} (headless).`)}}else(await x.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,x)=>{let $=Ts.randomUUID(),O=`${Ee()}/login?state=${$}`;await Js(O);let _=3e4,C=300*1e3,he=Date.now()+C;for(;Date.now()<he;)try{let ye=await globalThis.fetch(`${Ee()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:$,timeout:_}),signal:AbortSignal.timeout(_+5e3)});if(!ye.ok){await Pt(ye,Qt=>{f.warn("auth_status:retry_after_http_error",{status:ye.status,delayMs:Qt})});continue}let Y=await ye.json();if(Y.status==="pending")continue;if(Y.status==="expired"){x(new Error("Session expired. Please run setup again."));return}if(Y.status==="complete"&&Y.sessionToken){console.log(` Signed in as ${Y.user}.`),v(Y.sessionToken);return}}catch{await Pt(void 0,ye=>{f.warn("auth_status:retry_after_network_error",{delayMs:ye})})}x(new Error("Login timed out after 5 minutes. Please run setup again."))}),await V.saveSessionToken(p),console.log(" Session token saved.")),console.log(`
219
- Step 3: Setting up authentication...`),ie()){try{await Pa("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=ce();try{let x=await v.getStatus(),$=!0;if(it(x))if(await Xo())try{await uv(v),console.log(" Attestation key already registered with server."),console.log(" Existing local Touch ID key verified and preserved."),$=!1}catch(O){if(!um(O))throw O;console.log(" Existing local Touch ID key does not match server biometric state."),await Ia(v),$=!1}else console.log(" Server already has a biometric key, but this device has no local key."),await Ia(v),$=!1;$&&await vm(v,x.attestationRequired===!1)}catch(x){let $=x?.message||"unknown error";if(um(x)){console.log(" Server already has a biometric key for this account, but this device cannot prove access to it.");let O=!1;try{await Ia(v),O=!0}catch(_){console.error(` Biometric recovery failed: ${_?.message||"unknown error"}`)}if(!O){let _=x instanceof an&&x.hint?x.hint:"Run `visa-cli config reset` to clear server-side biometric state through GitHub, then run `visa-cli setup` again.";console.error(` ${_}`),process.exit(1)}}else console.error(` Biometric setup failed: ${$}`),process.exit(1)}}else{let v=ce(),x;try{x=await v.getStatus()}catch(O){console.error(" Biometric attestation (Touch ID or Windows Hello) is unavailable in this process."),console.error(` Could not verify server biometric policy: ${O?.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 $=zd(x);$.canContinue||(console.error(` ${$.message}`),$.hint&&console.error(` ${$.hint}`),process.exit(1)),console.log(` ${$.message}`)}let m=pt(),g=X.existsSync(De.join(J.homedir(),".claude.json")),y=e.hud===!0;if(e.hud===void 0&&g&&!e.yes&&process.stdin.isTTY&&(console.log(`
220
- Step 4: Visa HUD`),console.log(" Pin balance, card, spend, model, and session activity below the Claude Code input."),console.log(gl()),y=await ui(" Install the Visa HUD now?",!1)),y)if(!g)console.log(`
217
+ 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=bo();qp(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 o=bo(),s=new Map(o.map(v=>[v.client.id,v])),i=new Set,a=new Set,c=new Set;for(let v of Qe)if(yo(v)){let S;try{S=_o(v)}catch(_){if(_ instanceof xr){Mp(_),a.add(v.displayName),c.add(v.id);continue}throw _}let P=s.get(v.id),M=P?` \u2014 repaired stale ${P.staleReason} entry`:"";console.log(` \u2713 ${v.displayName} (${S.configPath.replace(X.homedir(),"~")})${M}`),P&&i.add(v.id)}let l=o.filter(v=>!i.has(v.client.id)&&!c.has(v.client.id)),u=0;for(let v of l){try{bc(v)}catch(S){if(S instanceof xr){Mp(S),a.add(v.client.displayName),c.add(v.client.id);continue}throw S}console.log(` \u2713 ${v.client.displayName} (${v.configPath.replace(X.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(`
218
+ Step 2: Checking authentication...`);let p=await B.getSessionToken();if(p)try{await new Pe(()=>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 Bm(),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 xc("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(`${$e()}/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 P=await S.json();if(P.success&&P.sessionToken){let M=P.sessionToken;p=M,await B.saveSessionToken(M),console.log(` Signed in as ${P.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 P=ti.randomUUID(),M=`${$e()}/login?state=${P}`;await Ti(M);let _=3e4,T=300*1e3,re=Date.now()+T;for(;Date.now()<re;)try{let ae=await globalThis.fetch(`${$e()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:P,timeout:_}),signal:AbortSignal.timeout(_+5e3)});if(!ae.ok){await Ft(ae,He=>{f.warn("auth_status:retry_after_http_error",{status:ae.status,delayMs:He})});continue}let K=await ae.json();if(K.status==="pending")continue;if(K.status==="expired"){S(new Error("Session expired. Please run setup again."));return}if(K.status==="complete"&&K.sessionToken){console.log(` Signed in as ${K.user}.`),v(K.sessionToken);return}}catch{await Ft(void 0,ae=>{f.warn("auth_status:retry_after_network_error",{delayMs:ae})})}S(new Error("Login timed out after 5 minutes. Please run setup again."))}),await B.saveSessionToken(p),console.log(" Session token saved.")),console.log(`
219
+ Step 3: Setting up authentication...`),de()){try{await xc("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(),P=!0;if(dt(S))if(await hs())try{await kw(v),console.log(" Attestation key already registered with server."),console.log(" Existing local Touch ID key verified and preserved."),P=!1}catch(M){if(!Np(M))throw M;console.log(" Existing local Touch ID key does not match server biometric state."),await wc(v),P=!1}else console.log(" Server already has a biometric key, but this device has no local key."),await wc(v),P=!1;P&&await Kp(v,S.attestationRequired===!1)}catch(S){let P=S?.message||"unknown error";if(Np(S)){console.log(" Server already has a biometric key for this account, but this device cannot prove access to it.");let M=!1;try{await wc(v),M=!0}catch(_){console.error(` Biometric recovery failed: ${_?.message||"unknown error"}`)}if(!M){let _=S instanceof hn&&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(` ${_}`),process.exit(1)}}else console.error(` Biometric setup failed: ${P}`),process.exit(1)}}else{let v=pe(),S;try{S=await v.getStatus()}catch(M){console.error(" Biometric attestation (Touch ID or Windows Hello) is unavailable in this process."),console.error(` Could not verify server biometric policy: ${M?.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 P=Vm(S);P.canContinue||(console.error(` ${P.message}`),P.hint&&console.error(` ${P.hint}`),process.exit(1)),console.log(` ${P.message}`)}let m=bt(),g=Q.existsSync(Be.join(X.homedir(),".claude.json")),h=e.hud===!0;if(e.hud===void 0&&g&&!e.yes&&process.stdin.isTTY&&(console.log(`
220
+ Step 4: Visa HUD`),console.log(" Pin balance, card, spend, model, and session activity below the Claude Code input."),console.log(su()),h=await ji(" Install the Visa HUD now?",!1)),h)if(!g)console.log(`
221
221
  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(`
222
- Step 4: Enabling the Visa spend HUD...`);let v=xr(m),x=v.installed==="new"||v.installed==="already-visa"||v.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${x}${v.message}`);try{let $=ce(),O=await $.getStatus(),_={currentVersion:$.getClientVersion(),latestVersion:$.lastSignals?.updateAvailable?.latestVersion,updateCheckDisabled:tt()},C=ei(O,_);ti(C,O),console.log(` Preview: ${C.split(`
222
+ Step 4: Enabling the Visa spend HUD...`);let v=Vr(m),S=v.installed==="new"||v.installed==="already-visa"||v.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${S}${v.message}`);try{let P=pe(),M=await P.getStatus(),_={currentVersion:P.getClientVersion(),latestVersion:P.lastSignals?.updateAvailable?.latestVersion,updateCheckDisabled:it()},T=Ri(M,_);Ii(T,M),console.log(` Preview: ${T.split(`
223
223
  `)[0]}`)}catch{}}else e.hud!==!1&&(console.log(`
224
- Step 4: Visa HUD not installed.`),console.log(" Enable later with: visa-cli config hud enable"));let w="\x1B[1m",N="\x1B[2m",U="\x1B[0m";console.log(`
224
+ Step 4: Visa HUD not installed.`),console.log(" Enable later with: visa-cli config hud enable"));let w="\x1B[1m",$="\x1B[2m",k="\x1B[0m";console.log(`
225
225
  \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
226
226
  \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
227
227
  \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
@@ -229,87 +229,92 @@ Step 4: Visa HUD not installed.`),console.log(" Enable later with: visa-cli co
229
229
  \u255A\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551
230
230
  \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u2588 CLI
231
231
 
232
- ${w}Setup complete.${U} Restart Claude Code or run /mcp to connect.
232
+ ${w}Setup complete.${k} Restart Claude Code or run /mcp to connect.
233
233
 
234
- ${w}Try it out:${U}
234
+ ${w}Try it out:${k}
235
235
  \u2022 Ask Claude: "Generate an image of a neon cityscape"
236
236
  \u2022 Ask Claude: "What's the price of ETH on Base?"
237
237
  \u2022 Check balance: visa-cli balance show
238
238
 
239
239
  \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510
240
- \u2502 ${w}Recommended: enable the spend HUD${U} \u2502
240
+ \u2502 ${w}Recommended: enable the spend HUD${k} \u2502
241
241
  \u2502 \u2502
242
242
  \u2502 Keep an eye on what your agents are spending. \u2502
243
243
  \u2502 Shows your balance, active card, and recent tool usage \u2502
244
244
  \u2502 on every prompt. \u2502
245
245
  \u2502 \u2502
246
- \u2502 ${N}$${U} visa-cli config hud enable \u2502
246
+ \u2502 ${$}$${k} visa-cli config hud enable \u2502
247
247
  \u2502 \u2502
248
248
  \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
249
249
 
250
- ${w}Verify:${U} visa-cli status
251
- ${w}Docs:${U} https://visacli.sh
252
- `),r()}catch(o){console.error("Error:",o.message),r(),process.exit(1)}});G.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 s=Qr();bm(s,"MCP config check:"),s.length>0&&process.exit(1);return}if(t.repair){let s=Qr();if(s.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of s)Aa(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(J.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
250
+ ${w}Verify:${k} visa-cli status
251
+ ${w}Docs:${k} https://visacli.sh
252
+ `),r()}catch(o){console.error("Error:",o.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 s=bo();qp(s,"MCP config check:"),s.length>0&&process.exit(1);return}if(t.repair){let s=bo();if(s.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of s)bc(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(X.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
253
253
  Repaired ${s.length} stale MCP config ${s.length===1?"entry":"entries"}.`);return}if(t.list){console.log(`
254
254
  \x1B[1mSupported MCP Clients\x1B[0m
255
- `),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 ze){let c=Xr(a),l=cm(a),u=c?"Yes":"No",d=l?"Yes":"No",p=a.globalConfigPath.replace(J.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 s=[],i=[];for(let a of ze){if(!Xr(a)){i.push(a.displayName);continue}Zr(a,n),s.push(a.displayName)}s.length>0&&console.log(`Installed for: ${s.join(", ")}.`),i.length>0&&console.log(`Skipped: ${i.map(a=>`${a} (not detected)`).join(", ")}.`),s.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(`
256
- Supported clients: ${ze.map(s=>s.id).join(", ")}`),process.exit(1));let r=xa(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${ze.map(s=>s.id).join(", ")}`),process.exit(1)),n==="global"&&!Xr(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let o=Zr(r,n);console.log(`Registered visa-cli MCP server in ${o.configPath}`),console.log(o.message)}catch(n){console.error("Error:",n.message),process.exit(1)}});G.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{eo=!1;try{let e=ce(),[t,n]=await Promise.all([e.getStatus(),e.getTransactions().catch(o=>{if(process.env.VISA_CLI_DEBUG){let s=o instanceof Error?o.message:String(o);process.stderr.write(`[visa-cli] getTransactions failed (HUD will omit): ${s}
257
- `)}return{transactions:[]}})]),r={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:tt()};process.stdout.write(Kd(t,Array.isArray(n?.transactions)?n.transactions:[],ie(),r)),eo=!0}catch(e){eo=!1,console.error("Error:",e.message),process.exit(1)}});function $v(e){let t=e.map(Gd),n=Math.max(2,...t.map(i=>i.id.length)),r=Math.max(5,...t.map(i=>i.brand.length)),o=Math.max(4,...t.map(i=>i.card.length)),s=7;console.log(`
255
+ `),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 Qe){let c=yo(a),l=Op(a),u=c?"Yes":"No",d=l?"Yes":"No",p=a.globalConfigPath.replace(X.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 s=[],i=[];for(let a of Qe){if(!yo(a)){i.push(a.displayName);continue}_o(a,n),s.push(a.displayName)}s.length>0&&console.log(`Installed for: ${s.join(", ")}.`),i.length>0&&console.log(`Skipped: ${i.map(a=>`${a} (not detected)`).join(", ")}.`),s.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(`
256
+ Supported clients: ${Qe.map(s=>s.id).join(", ")}`),process.exit(1));let r=fc(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${Qe.map(s=>s.id).join(", ")}`),process.exit(1)),n==="global"&&!yo(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let o=_o(r,n);console.log(`Registered visa-cli MCP server in ${o.configPath}`),console.log(o.message)}catch(n){console.error("Error:",n.message),process.exit(1)}});z.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{vo=!1;try{let e=pe(),[t,n]=await Promise.all([e.getStatus(),e.getTransactions().catch(o=>{if(process.env.VISA_CLI_DEBUG){let s=o instanceof Error?o.message:String(o);process.stderr.write(`[visa-cli] getTransactions failed (HUD will omit): ${s}
257
+ `)}return{transactions:[]}})]),r={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:it()};process.stdout.write(Dm(t,Array.isArray(n?.transactions)?n.transactions:[],de(),r)),vo=!0}catch(e){vo=!1,console.error("Error:",e.message),process.exit(1)}});function Ww(e){let t=e.map(jm),n=Math.max(2,...t.map(i=>i.id.length)),r=Math.max(5,...t.map(i=>i.brand.length)),o=Math.max(4,...t.map(i=>i.card.length)),s=7;console.log(`
258
258
  Cards
259
259
  `),console.log(` ${"ID".padEnd(n)} ${"Brand".padEnd(r)} ${"Card".padEnd(o)} Default`),console.log(` ${"\u2500".repeat(n)} ${"\u2500".repeat(r)} ${"\u2500".repeat(o)} ${"\u2500".repeat(s)}`);for(let i of t)console.log(` ${i.id.padEnd(n)} ${i.brand.padEnd(r)} ${i.card.padEnd(o)} ${i.default}`);console.log(`
260
260
  Use:`),console.log(" visa-cli cards default <id>"),console.log(` visa-cli cards remove <id>
261
- `)}async function Tm(e,t){if(t.yes)return"confirmed";if(!process.stdin.isTTY)return"refused-non-tty";let n=(0,Na.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 Is=G.command("cards").description("Manage enrolled payment cards").addHelpCommand(!1).action(Je);Is.command("list").alias("ls").description("List enrolled payment cards").action(async()=>{try{let e=await qe.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}$v(t)}catch(e){console.error("Error:",e.message),process.exit(1)}});Is.command("add").description("Add a new Visa card").action(async()=>{try{let e=await qe.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)}});Is.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=ma(e),r=await Tm(`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 o=await qe.removeCard({cardId:n,confirm:!0},"visa-cli cards remove");o?.success===!1&&(console.error(o.error||o.message||"Failed to remove card."),process.exit(1)),console.log(o?.message||`Removed card ${n}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});Is.command("default <card-id>").alias("set-default").description("Set the default payment card").action(async e=>{try{let t=ma(e),n=await qe.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 Pv(e){return/timed out waiting for touch id\/device approval|attestation[_\s-]?required/i.test(e)}function Fa(e){let t=e instanceof Error?e.message:String(e);console.error("Error:",t),Pv(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 Ov(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 Va(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 qa=G.command("keys").description("Create and manage Visa Keys for apps and agents").addHelpCommand(!1).action(Je);qa.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 hv(t.dailyCap,t.json),r=await yv(t.totalCap,t.json),o=await Va(async()=>{let s=ce(),i={label:fv(e),allowed_tools:gv(t.tools),daily_cap_cents:n,total_cap_cents:r};return await lv(s)?await Qn(s,async()=>{let a=await cv(s);return s.createAppApiKey({...i,attestation:a})},La(s)):await s.createAppApiKey(i)});if(t.json){console.log(JSON.stringify(o,null,2));return}process.stdout.write(vl(o,{authUrl:Ee()}))}catch(n){Fa(n)}});qa.command("list").description("List Visa Keys for the authenticated user").option("--json","Output raw JSON").action(async e=>{try{let t=await Va(async()=>await ce().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: ${_v(r.allowed_tools)}`),console.log(` Daily cap: ${to(r.daily_cap_cents)}/day`),console.log(` Total cap: ${mv(r.total_cap_cents)}`),console.log(` Last used: ${r.last_used_at||"never"}`)}catch(t){Fa(t)}});qa.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 Va(async()=>await ce().revokeAppApiKey(t));console.log(`Revoked Visa Key ${n.revoked}.`)}catch(t){Fa(t)}});async function Mv(){if(await V.clearAll(),console.log(" Keychain credentials cleared."),ie())try{await Zo(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}}async function Em(e={}){try{if(console.log(`Resetting Visa CLI...
262
- `),e.localOnly)console.log(" Local-only reset: skipping server logout and biometric recovery.");else{let t=ce();await Ua(t);try{await t.logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}}await Mv(),console.log(`
263
- 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)}}G.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(Em);var Ba=G.command("balance").description("Manage prepaid balance").addHelpCommand(!1).action(Je);Ba.command("show").description("Show prepaid balance + recent ledger entries").action(async()=>{try{let t=await new Ae(()=>V.getSessionToken()).getBalance();if(console.log(`
264
- Balance: ${Oa(t.balanceMicros,t.balanceCents)}
261
+ `)}async function Xp(e,t){if(t.yes)return"confirmed";if(!process.stdin.isTTY)return"refused-non-tty";let n=(0,Cc.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 si=z.command("cards").description("Manage enrolled payment cards").addHelpCommand(!1).action(et);si.command("list").alias("ls").description("List enrolled payment cards").action(async()=>{try{let e=await We.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}Ww(t)}catch(e){console.error("Error:",e.message),process.exit(1)}});si.command("add").description("Add a new Visa card").action(async()=>{try{let e=await We.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)}});si.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=Va(e),r=await Xp(`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 o=await We.removeCard({cardId:n,confirm:!0},"visa-cli cards remove");o?.success===!1&&(console.error(o.error||o.message||"Failed to remove card."),process.exit(1)),console.log(o?.message||`Removed card ${n}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});si.command("default <card-id>").alias("set-default").description("Set the default payment card").action(async e=>{try{let t=Va(e),n=await We.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 zw(e){return/timed out waiting for touch id\/device approval|attestation[_\s-]?required/i.test(e)}function Ic(e){let t=e instanceof Error?e.message:String(e);console.error("Error:",t),zw(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 Jw(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 $c(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 Pc=z.command("keys").description("Create and manage Visa Keys for apps and agents").addHelpCommand(!1).action(et);Pc.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 Pw(t.dailyCap,t.json),r=await Ow(t.totalCap,t.json),o=await $c(async()=>{let s=pe(),i={label:Iw(e),allowed_tools:$w(t.tools),daily_cap_cents:n,total_cap_cents:r};return await Cw(s)?await pr(s,async()=>{let a=await Tw(s);return s.createAppApiKey({...i,attestation:a})},kc(s)):await s.createAppApiKey(i)});if(t.json){console.log(JSON.stringify(o,null,2));return}process.stdout.write(uu(o,{authUrl:$e()}))}catch(n){Ic(n)}});Pc.command("list").description("List Visa Keys for the authenticated user").option("--json","Output raw JSON").action(async e=>{try{let t=await $c(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: ${Mw(r.allowed_tools)}`),console.log(` Daily cap: ${wo(r.daily_cap_cents)}/day`),console.log(` Total cap: ${Aw(r.total_cap_cents)}`),console.log(` Last used: ${r.last_used_at||"never"}`)}catch(t){Ic(t)}});Pc.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 $c(async()=>await pe().revokeAppApiKey(t));console.log(`Revoked Visa Key ${n.revoked}.`)}catch(t){Ic(t)}});async function Yw(){if(await B.clearAll(),console.log(" Keychain credentials cleared."),de())try{await ys(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}}async function Zp(e={}){try{if(console.log(`Resetting Visa CLI...
262
+ `),e.localOnly)console.log(" Local-only reset: skipping server logout and biometric recovery.");else{let t=pe();await Ec(t);try{await t.logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}}await Yw(),console.log(`
263
+ 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(Zp);var Oc=z.command("balance").description("Manage prepaid balance").addHelpCommand(!1).action(et);Oc.command("show").description("Show prepaid balance + recent ledger entries").action(async()=>{try{let t=await new Pe(()=>B.getSessionToken()).getBalance();if(console.log(`
264
+ Balance: ${Qs(t.balanceMicros,t.balanceCents)}
265
265
  `),t.ledger.length===0){console.log(` (no ledger entries \u2014 top up to begin: visa-cli balance topup --amount 5)
266
- `);return}let n=t.ledger.slice(0,20),r=[],o=t.balanceCents,s=t.balanceMicros?BigInt(t.balanceMicros):null;for(let u of n)r.push(s!=null?s.toString():String(o*1e4)),s!=null&&u.deltaMicros?s-=BigInt(u.deltaMicros):(s=null,o-=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),m=Oa(u.deltaMicros,u.deltaCents,!0),g=pv(r[d]),y=(u.reason??"").slice(0,l),w=u.toolName??"";console.log(` ${p.padEnd(i)} ${m.padStart(a)} ${g.padStart(c)} ${y.padEnd(l)} ${w}`)}),console.log()}catch(e){e instanceof et&&(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)}});Ba.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=cs(e.amount);if(!t.ok)throw new Error(t.error);let n=t.cents,r=n/100,o=new Ae(()=>V.getSessionToken());if(!ie())throw new Error(ls);let s=Ts.randomUUID(),i=await Qn(o,async()=>{let a;if(ie()){let{nonce:c}=await o.getAttestationChallenge(),l=Buffer.from(JSON.stringify({nonce:c,amount:r,merchant:"Visa CLI Balance",context:"balance-topup"})).toString("base64");a={signature:await Tn(l,`top up balance with $${t.displayUsd}`),nonce:c,amount:r,merchant:"Visa CLI Balance"}}return o.topupBalance({amount_cents:n,idempotency_key:s,attestation:a})},La(o));if(i.success)console.log(`Top-up complete: +$${(n/100).toFixed(2)} \u2192 balance now $${((i.balanceCents??0)/100).toFixed(2)}`),i.transactionId&&console.log(`Transaction: ${i.transactionId}`),Dc();else{let a=i.error_code?` [${i.error_code}]`:"";console.error(`Top-up failed${a}: ${i.error||"Unknown error"}`),process.exit(1)}}catch(t){console.error("Error:",t.message),process.exit(1)}});var Am=Ba.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(Je);Am.command("show").description("Show current auto-topup configuration").action(async()=>{try{let t=await new Ae(()=>V.getSessionToken()).getAutoTopup();if(t.targetCents==null||t.targetCents===0){console.log(`
266
+ `);return}let n=t.ledger.slice(0,20),r=[],o=t.balanceCents,s=t.balanceMicros?BigInt(t.balanceMicros):null;for(let u of n)r.push(s!=null?s.toString():String(o*1e4)),s!=null&&u.deltaMicros?s-=BigInt(u.deltaMicros):(s=null,o-=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),m=Qs(u.deltaMicros,u.deltaCents,!0),g=Rw(r[d]),h=(u.reason??"").slice(0,l),w=u.toolName??"";console.log(` ${p.padEnd(i)} ${m.padStart(a)} ${g.padStart(c)} ${h.padEnd(l)} ${w}`)}),console.log()}catch(e){e instanceof st&&(console.error(`Top-up pending reconciliation [${e.code}]: ${e.message}`),e.transactionId&&console.error(`Transaction: ${e.transactionId}`),process.exit(1)),console.error("Error:",e.message),process.exit(1)}});Oc.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=Es(e.amount);if(!t.ok)throw new Error(t.error);let n=t.cents,r=n/100,o=new Pe(()=>B.getSessionToken());if(!de())throw new Error(As);let s=ti.randomUUID(),i=await pr(o,async()=>{let a;if(de()){let{nonce:c}=await o.getAttestationChallenge(),l=Buffer.from(JSON.stringify({nonce:c,amount:r,merchant:"Visa CLI Balance",context:"balance-topup"})).toString("base64");a={signature:await Nn(l,`top up balance with $${t.displayUsd}`),nonce:c,amount:r,merchant:"Visa CLI Balance"}}return o.topupBalance({amount_cents:n,idempotency_key:s,attestation:a})},kc(o));if(i.success)console.log(`Top-up complete: +$${(n/100).toFixed(2)} \u2192 balance now ${Qs(i.balanceMicros,i.balanceCents??0)}`),i.transactionId&&console.log(`Transaction: ${i.transactionId}`),Al();else{let a=i.error_code?` [${i.error_code}]`:"";console.error(`Top-up failed${a}: ${i.error||"Unknown error"}`),process.exit(1)}}catch(t){console.error("Error:",t.message),process.exit(1)}});var Qp=Oc.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(et);Qp.command("show").description("Show current auto-topup configuration").action(async()=>{try{let t=await new Pe(()=>B.getSessionToken()).getAutoTopup();if(t.targetCents==null||t.targetCents===0){console.log(`
267
267
  Auto-topup: disabled
268
- `);return}let n=to(t.targetCents),r=to(t.thresholdCents),o=12,s=13;console.log(),console.log(` ${"STATE".padEnd(o)} enabled`),console.log(` ${"TARGET".padEnd(o)} ${n.padStart(s)} (refill balance to this amount)`),console.log(` ${"THRESHOLD".padEnd(o)} ${r.padStart(s)} (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)}});Am.command("disable").description("Disable auto-topup").action(async()=>{try{let t=await new Ae(()=>V.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 Nv=G.command("session",{hidden:!0}).description("Inspect session budgets");Nv.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 Ae(()=>V.getSessionToken()),[n,r]=await Promise.allSettled([t.getSessionBudget(e),t.getSessionLedger(e)]),o=n.status==="fulfilled"?n.value.budget:void 0,s=r.status==="fulfilled"?r.value:void 0;if(!o&&!s?.ledger?.length&&(console.error(`Session not found: ${e}`),process.exit(1)),console.log(`
268
+ `);return}let n=wo(t.targetCents),r=wo(t.thresholdCents),o=12,s=13;console.log(),console.log(` ${"STATE".padEnd(o)} enabled`),console.log(` ${"TARGET".padEnd(o)} ${n.padStart(s)} (refill balance to this amount)`),console.log(` ${"THRESHOLD".padEnd(o)} ${r.padStart(s)} (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)}});Qp.command("disable").description("Disable auto-topup").action(async()=>{try{let t=await new Pe(()=>B.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 Xw=z.command("session",{hidden:!0}).description("Inspect session budgets");Xw.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 Pe(()=>B.getSessionToken()),[n,r]=await Promise.allSettled([t.getSessionBudget(e),t.getSessionLedger(e)]),o=n.status==="fulfilled"?n.value.budget:void 0,s=r.status==="fulfilled"?r.value:void 0;if(!o&&!s?.ledger?.length&&(console.error(`Session not found: ${e}`),process.exit(1)),console.log(`
269
269
  Session: ${e}`),o){let i=(o.totalCents/100).toFixed(2),a=(o.cumulativeCents/100).toFixed(2),c=(o.remainingCents/100).toFixed(2);console.log(` Status: ${o.status}${o.expired?" (expired)":""}`),console.log(` Budget: $${i} \xB7 spent $${a} \xB7 remaining $${c}`),console.log(` Created: ${o.createdAt}`),console.log(` Expires: ${o.expiresAt}`)}if(s?.ledger?.length){console.log(`
270
270
  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 s.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 o&&console.log(`
271
- (no PSP references yet \u2014 no holds placed)`);console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});async function Rm(e){(!e||e.trim().length===0)&&(console.log('Usage: visa-cli feedback "your message"'),process.exit(1));try{await V.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await ce().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}}G.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action(Rm);G.command("update").description("Update Visa CLI to the latest stable version").action(async()=>{let e=ga(void 0,void 0,void 0,{withDiagnostics:!0}),t=e.diagnostics?ha(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 Pa(e.command,e.args,{timeout:5*6e4,maxBuffer:10*1024*1024});n.trim()&&process.stdout.write(n),r.trim()&&process.stderr.write(r);let o=si(pt(),{force:!0});for(let s of o.messages)console.log(s);console.log("Visa CLI update complete. Restart any running MCP clients to use the new version.")}catch(n){console.error(`Update failed while running: ${e.display}`),console.error(n?.message??String(n)),process.exit(1)}});var ut=G.command("config").description("Manage CLI configuration and local integrations").addHelpCommand(!1).action(Je);function Im(e){return[De.join(e,".zshrc"),De.join(e,".bashrc"),De.join(e,".bash_profile"),De.join(e,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),De.join(e,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),De.join(e,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),De.join(e,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),De.join(e,".config","powershell","Microsoft.PowerShell_profile.ps1")]}function Lv(e){let t=new Map;for(let n of Im(e))try{X.existsSync(n)&&t.set(n,X.readFileSync(n,"utf-8"))}catch{}return t}function Uv(e){let t=[];for(let[n,r]of e)try{(X.existsSync(n)?X.readFileSync(n,"utf-8"):"")!==r&&t.push(n)}catch{}return t}function Dv(e){let t=[];for(let n of Im(e))try{if(!X.existsSync(n))continue;let r=X.readFileSync(n,"utf-8");wr(r)!==r.trimEnd()&&t.push(n)}catch{}return t}ut.command("feedback",{hidden:!0}).description("Deprecated alias for `feedback`").argument("[message]","Your feedback message").action(Rm);ut.command("list").description("Show resolved config values (env vars, server state, defaults) with their source").option("--json","Output as JSON for scripting / agent consumption").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").option("--verbose","Show one-line hints beneath entries that have them").action(async e=>{try{let t=ce(),n=await jr({api:t,includeDev:!!e.dev});if(e.json){console.log(Xu(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(Yu(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});ut.command("get <key>").description("Print the resolved value of a single config key (pipe-friendly)").option("--raw","Print the underlying value as JSON instead of the formatted display string").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").action(async(e,t)=>{try{let n=ce(),o=(await jr({api:n,includeDev:!!t.dev})).entries.find(s=>s.key===e);o||(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(o.value)):console.log(o.formatted)}catch(n){console.error("Error:",n.message),process.exit(1)}});function jv(){return Object.entries(Dt).map(([e,t])=>` ${e.padEnd(22)} (${t.type}) ${t.description}`).join(`
272
- `)}ut.command("set <key> <value>").description("Persist a CLI setting to ~/.visa-mcp/settings.json").addHelpText("after",`
271
+ (no PSP references yet \u2014 no holds placed)`);console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});async function ef(e){(!e||e.trim().length===0)&&(console.log('Usage: visa-cli feedback "your message"'),process.exit(1));try{await B.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(ef);z.command("update").description("Update Visa CLI to the latest stable version").action(async()=>{let e=qa(void 0,void 0,void 0,{withDiagnostics:!0}),t=e.diagnostics?Ka(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 xc(e.command,e.args,{timeout:5*6e4,maxBuffer:10*1024*1024});n.trim()&&process.stdout.write(n),r.trim()&&process.stderr.write(r);let o=Mi(bt(),{force:!0});for(let s of o.messages)console.log(s);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 ht=z.command("config").description("Manage CLI configuration and local integrations").addHelpCommand(!1).action(et);function tf(e){return[Be.join(e,".zshrc"),Be.join(e,".bashrc"),Be.join(e,".bash_profile"),Be.join(e,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),Be.join(e,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),Be.join(e,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),Be.join(e,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),Be.join(e,".config","powershell","Microsoft.PowerShell_profile.ps1")]}function Zw(e){let t=new Map;for(let n of tf(e))try{Q.existsSync(n)&&t.set(n,Q.readFileSync(n,"utf-8"))}catch{}return t}function Qw(e){let t=[];for(let[n,r]of e)try{(Q.existsSync(n)?Q.readFileSync(n,"utf-8"):"")!==r&&t.push(n)}catch{}return t}function eS(e){let t=[];for(let n of tf(e))try{if(!Q.existsSync(n))continue;let r=Q.readFileSync(n,"utf-8");jr(r)!==r.trimEnd()&&t.push(n)}catch{}return t}ht.command("feedback",{hidden:!0}).description("Deprecated alias for `feedback`").argument("[message]","Your feedback message").action(ef);ht.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 ro({api:t,includeDev:!!e.dev});if(e.json){console.log(Hd(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(Bd(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});ht.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(),o=(await ro({api:n,includeDev:!!t.dev})).entries.find(s=>s.key===e);o||(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(o.value)):console.log(o.formatted)}catch(n){console.error("Error:",n.message),process.exit(1)}});function tS(){return Object.entries(Gt).map(([e,t])=>` ${e.padEnd(22)} (${t.type}) ${t.description}`).join(`
272
+ `)}ht.command("set <key> <value>").description("Persist a CLI setting to ~/.visa-mcp/settings.json").addHelpText("after",`
273
273
  Settable keys:
274
- ${jv()}`).action((e,t)=>{try{let n=Uo(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 ht||n instanceof yt||n instanceof Lt?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});ut.command("unset <key>").description("Remove a CLI setting from ~/.visa-mcp/settings.json (falls back to env var or default)").action(e=>{try{let t=Do(e);t.removed?(console.log(`Removed ${t.key} from ${t.path}`),t.requiresRestart&&console.log("Restart Claude Code (or your MCP-enabled client) for the change to take effect.")):console.log(`No-op: ${t.key} was not set in ${t.path}.`)}catch(t){console.error(`Error: ${t.message}`),process.exit(1)}});ut.command("reset").description("Log out and clear all credentials").option("--local-only","Only clear local credentials and the local biometric key; skip server-side biometric recovery").action(Em);var Ha=ut.command("biometric").description("Manage Touch ID / biometric attestation enforcement").addHelpCommand(!1).action(Je);Ha.command("status").description("Show current biometric enforcement state").action(async()=>{try{await V.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let n=await ce().getStatus(),r=n.attestationRequired!==!1,o=!!n.hasAttestationKey,s=ie();console.log(`Server policy: Touch ID ${r?"REQUIRED":"NOT required"}`),console.log(`Attestation key registered: ${o?"yes":"no"}`),console.log(`Touch ID available on this device: ${s?"yes":"no"}`)}catch(e){console.error("Error:",e.message),process.exit(1)}});Ha.command("on").description("Require Touch ID for payments (security upgrade \u2014 no Touch ID needed)").action(async()=>{try{await V.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=ce(),n=await Qo(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)}});Ha.command("off").description("Disable Touch ID requirement (security downgrade \u2014 one Touch ID confirmation required)").action(async()=>{try{await V.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=ce(),n=await t.getStatus();if(n.attestationRequired===!1){console.log("Touch ID is already disabled.");return}n.hasAttestationKey&&!ie()&&(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 Qn(t,async()=>{let o;if(n.hasAttestationKey&&ie())try{let{nonce:s}=await t.getAttestationChallenge(),i=0,a="",c=Buffer.from(JSON.stringify({nonce:s,amount:i,merchant:a,context:"biometric-preference"})).toString("base64");o={signature:await Tn(c,"disable Touch ID requirement"),nonce:s,amount:i,merchant:a}}catch(s){throw new Error(`Touch ID confirmation failed: ${s?.message||"cancelled"}`)}return t.setBiometricPreference({required:!1,attestation:o})},La(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)}});var $n=ut.command("shell-hud").description("Manage the shell prompt HUD (opt-in \u2014 prefer: visa-cli config hud enable)").addHelpCommand(!1).action(Je);function $m(){let e=So();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function Pm(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 Fv(){Pm(li(void 0,{homeDir:J.homedir(),installVisaStatusLine:xr,installShellHud:So}))}function Om(){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"),Fv()}function $s(){let e=mt();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}$n.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action($m);$n.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(Om);$n.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action($s);$n.command("disable").description("Disable the persistent shell HUD").action($s);$n.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${xo()}
275
- `)});$n.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,r=(d,p,m)=>{console.log(` ${p?"\u2713":"\u2717"} ${d}: ${m}`),p||(n=!1)};console.log(`Shell HUD Doctor
276
- `);let o=jn();if(r("Shell detected",!!o,o??"none (zsh, bash, or PowerShell required)"),o){let d=vr(o),p=e(d);if(r("RC file exists",p,d.replace(J.homedir(),"~")),p){let g=t(d,"utf-8").includes("visa-cli shell hud v2");r("HUD block installed",!!g,g?"found in rc file":"missing \u2014 run: visa-cli config hud enable shell")}}let s=Ot(),i=e(s);if(r("Cache file",i,i?s.replace(J.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let d=JSON.parse(t(s,"utf-8")),p=Date.now()-(d.renderedAt??0),m=Math.round(p/1e3),g=m<=30;console.log(` ${g?"\u2713":"\u26A0"} Cache freshness: ${m}s old${g?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{r("Cache readable",!1,"corrupt JSON")}let a=br(),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 V.getSessionToken()}catch{}if(r("Auth token",u,u?"found in keychain":"missing \u2014 run: visa-cli setup"),u)try{await ce().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?`
274
+ ${tS()}`).action((e,t)=>{try{let n=ns(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 St||n instanceof xt||n instanceof qt?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});ht.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=rs(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)}});ht.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(Zp);var Mc=ht.command("biometric").description("Manage Touch ID / biometric attestation enforcement").addHelpCommand(!1).action(et);Mc.command("status").description("Show current biometric enforcement state").action(async()=>{try{await B.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let n=await pe().getStatus(),r=n.attestationRequired!==!1,o=!!n.hasAttestationKey,s=de();console.log(`Server policy: Touch ID ${r?"REQUIRED":"NOT required"}`),console.log(`Attestation key registered: ${o?"yes":"no"}`),console.log(`Touch ID available on this device: ${s?"yes":"no"}`)}catch(e){console.error("Error:",e.message),process.exit(1)}});Mc.command("on").description("Require Touch ID for payments (security upgrade \u2014 no Touch ID needed)").action(async()=>{try{await B.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=pe(),n=await _s(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)}});Mc.command("off").description("Disable Touch ID requirement (security downgrade \u2014 one Touch ID confirmation required)").action(async()=>{try{await B.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 pr(t,async()=>{let o;if(n.hasAttestationKey&&de())try{let{nonce:s}=await t.getAttestationChallenge(),i=0,a="",c=Buffer.from(JSON.stringify({nonce:s,amount:i,merchant:a,context:"biometric-preference"})).toString("base64");o={signature:await Nn(c,"disable Touch ID requirement"),nonce:s,amount:i,merchant:a}}catch(s){throw new Error(`Touch ID confirmation failed: ${s?.message||"cancelled"}`)}return t.setBiometricPreference({required:!1,attestation:o})},kc(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)}});var qn=ht.command("shell-hud").description("Manage the shell prompt HUD (opt-in \u2014 prefer: visa-cli config hud enable)").addHelpCommand(!1).action(et);function nf(){let e=Vo();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function rf(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 nS(){rf(Di(void 0,{homeDir:X.homedir(),installVisaStatusLine:Vr,installShellHud:Vo}))}function of(){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"),nS()}function ii(){let e=_t();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}qn.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(nf);qn.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(of);qn.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(ii);qn.command("disable").description("Disable the persistent shell HUD").action(ii);qn.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${Bo()}
275
+ `)});qn.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,r=(d,p,m)=>{console.log(` ${p?"\u2713":"\u2717"} ${d}: ${m}`),p||(n=!1)};console.log(`Shell HUD Doctor
276
+ `);let o=Zn();if(r("Shell detected",!!o,o??"none (zsh, bash, or PowerShell required)"),o){let d=Dr(o),p=e(d);if(r("RC file exists",p,d.replace(X.homedir(),"~")),p){let g=t(d,"utf-8").includes("visa-cli shell hud v2");r("HUD block installed",!!g,g?"found in rc file":"missing \u2014 run: visa-cli config hud enable shell")}}let s=Vt(),i=e(s);if(r("Cache file",i,i?s.replace(X.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let d=JSON.parse(t(s,"utf-8")),p=Date.now()-(d.renderedAt??0),m=Math.round(p/1e3),g=m<=30;console.log(` ${g?"\u2713":"\u26A0"} Cache freshness: ${m}s old${g?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{r("Cache readable",!1,"corrupt JSON")}let a=Ur(),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 B.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?`
277
277
  All checks passed.`:`
278
- Some checks failed \u2014 see above.`),n||process.exit(1)});async function Mm(e){if(!(!e.force&&Lc()))try{await Ys();let t=ce(),[n,r,o,s]=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?.amountUsd;i.amountUsd=typeof u=="number"?u:a/100}if(r.status==="fulfilled"&&r.value.success&&(i.balanceCents=r.value.balanceCents,i.amountUsd=r.value.amountUsd),o.status==="fulfilled"&&o.value.success?i.apiKeyCount=Array.isArray(o.value.keys)?o.value.keys.length:0:o.status==="rejected"&&Ov(o.reason)&&(i.apiKeyStatus="rollout_locked"),s.status==="fulfilled"){let u=s.value,p=(Array.isArray(u)?u:Array.isArray(u.transactions)?u.transactions:[]).find(m=>m&&typeof m.tool_name=="string"&&m.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:tt()},l=ei(i,c);ti(l,i)}catch(t){let n=t instanceof Error?t.message:"unknown refresh failure";Uc(n)}finally{nn()}}$n.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(Mm);var Pn=G.command("shell-hud",{hidden:!0}).description("Deprecated alias for `config shell-hud`");Pn.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action($m);Pn.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(Om);Pn.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action($s);Pn.command("disable").description("Disable the persistent shell HUD").action($s);Pn.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${xo()}
279
- `)});Pn.command("doctor").description("Show the new shell HUD doctor command").action(()=>{console.log("Run: visa-cli config shell-hud doctor")});Pn.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(Mm);async function Nm(e){try{await Ys();let t=await Zc(),n=xo(),r=n,o=n.split(`
280
- `)[0],s=jc();if(!t&&o.includes("loading")){process.stdout.write(`VISA | HUD not initialized \u2014 run: visa-cli config hud enable
281
- `),Ra();return}if(e.json){let a=await ol(r,t,s);process.stdout.write(`${JSON.stringify(a,null,2)}
282
- `),Ra();return}let i=await tl(r,t,s);process.stdout.write(`${i}
283
- `),Ra()}catch(t){let n=t instanceof Error?t.message:"unknown error";console.error(`Failed to render Visa HUD: ${n}`),process.exit(1)}}ut.command("statusline").description("Output the Visa HUD for agent statusline integrations").option("--json","Output structured JSON for clients that render their own HUD").action(Nm);G.command("statusline",{hidden:!0}).description("Deprecated alias for `config statusline`").option("--json","Output structured JSON for clients that render their own HUD").action(Nm);var ar=ut.command("hud").description("Manage the Visa spend HUD \u2014 one command for all surfaces").addHelpCommand(!1);ar.description("Show which HUD surfaces are currently enabled").action(()=>{let e="\x1B[1m",t="\x1B[2m",n="\x1B[32m",r="\x1B[33m",o="\x1B[0m";console.log(`
278
+ Some checks failed \u2014 see above.`),n||process.exit(1)});async function sf(e){if(!(!e.force&&kl()))try{await Ci();let t=pe(),[n,r,o,s]=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),o.status==="fulfilled"&&o.value.success?i.apiKeyCount=Array.isArray(o.value.keys)?o.value.keys.length:0:o.status==="rejected"&&Jw(o.reason)&&(i.apiKeyStatus="rollout_locked"),s.status==="fulfilled"){let u=s.value,p=(Array.isArray(u)?u:Array.isArray(u.transactions)?u.transactions:[]).find(m=>m&&typeof m.tool_name=="string"&&m.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:it()},l=Ri(i,c);Ii(l,i)}catch(t){let n=t instanceof Error?t.message:"unknown refresh failure";El(n)}finally{mn()}}qn.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(sf);var Kn=z.command("shell-hud",{hidden:!0}).description("Deprecated alias for `config shell-hud`");Kn.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(nf);Kn.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(of);Kn.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(ii);Kn.command("disable").description("Disable the persistent shell HUD").action(ii);Kn.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${Bo()}
279
+ `)});Kn.command("doctor").description("Show the new shell HUD doctor command").action(()=>{console.log("Run: visa-cli config shell-hud doctor")});Kn.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(sf);async function af(e){try{await Ci();let t=await Bl(),n=Bo(),r=n,o=n.split(`
280
+ `)[0],s=Rl();if(!t&&o.includes("loading")){process.stdout.write(`VISA | HUD not initialized \u2014 run: visa-cli config hud enable
281
+ `),vc();return}if(e.json){let a=await zl(r,t,s);process.stdout.write(`${JSON.stringify(a,null,2)}
282
+ `),vc();return}let i=await Kl(r,t,s);process.stdout.write(`${i}
283
+ `),vc()}catch(t){let n=t instanceof Error?t.message:"unknown error";console.error(`Failed to render Visa HUD: ${n}`),process.exit(1)}}ht.command("statusline").description("Output the Visa HUD for agent statusline integrations").option("--json","Output structured JSON for clients that render their own HUD").action(af);z.command("statusline",{hidden:!0}).description("Deprecated alias for `config statusline`").option("--json","Output structured JSON for clients that render their own HUD").action(af);var Cr=ht.command("hud").description("Manage the Visa spend HUD \u2014 one command for all surfaces").addHelpCommand(!1);Cr.description("Show which HUD surfaces are currently enabled").action(()=>{let e="\x1B[1m",t="\x1B[2m",n="\x1B[32m",r="\x1B[33m",o="\x1B[0m";console.log(`
284
284
  ${e}Visa HUD Status${o}
285
- `);let s=pt(),i=!1,a=!1;try{if(X.existsSync(s)){let g=JSON.parse(X.readFileSync(s,"utf-8")),y=typeof g.statusLine=="object"?g.statusLine.command:"";i=Nt(y),a=!!g.statusLine&&!i}}catch{}let c=i?`${n}\u2713${o}`:`${t}\u2717${o}`,l=i?"registered in ~/.claude/settings.json":a?`${r}another HUD is configured${o} \u2014 edit settings.json to switch`:"not enabled";console.log(` ${c} ${e}Claude Code${o} (statusLine) ${l}`);let u=on(J.homedir()),d=u.length>0||wo(),p=d?`${n}\u2713${o}`:`${t}\u2717${o}`,m=d?`installed in shell rc file${u.length>0?` (${u.map(g=>g.replace(J.homedir(),"~")).join(", ")})`:""}`:"not installed (opt-in)";console.log(` ${p} ${e}Shell prompt${o} ${m}`),i&&d&&console.log(` ${r}!${o} ${e}Overlap${o} Claude statusLine and shell prompt HUD are both installed. Remove shell prompt output with: visa-cli config hud disable shell`),console.log(`
286
- ${e}Quick start:${o}`),i||console.log(` visa-cli config hud enable ${t}# Claude Code statusLine (recommended)${o}`),d||console.log(` visa-cli config hud enable shell ${t}# zsh/bash prompt line (opt-in)${o}`),i&&d&&console.log(` ${n}All surfaces enabled.${o}`),(i||d)&&console.log(` visa-cli config hud disable [shell] ${t}# remove a surface${o}`),console.log(` visa-cli config hud doctor ${t}# diagnose connectivity${o}`),console.log()});ar.command("enable").description("Enable the Visa HUD \u2014 claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{Pm(li(e,{homeDir:J.homedir(),installVisaStatusLine:xr,installShellHud:So}))});ar.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 s=mt();s.removed||(console.error(s.message),process.exit(1)),console.log(s.message);return}let n=$o(t);n||(console.error(`Unknown HUD surface: ${t}`),console.error("Supported: claude (default), shell, all"),process.exit(1));let r=!1,o=!1;if(n==="claude"||n==="claude-code"||n==="all"){let s=pt(),i=ii(s);console.log(i.message),i.removed&&(o=!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&&!Ro()&&on(J.homedir()).length>0){let l=mt();l.removed&&l.rcPaths&&l.rcPaths.length>0&&(console.log(`Also cleaned legacy shell-prompt HUD block from ${l.rcPaths.map(u=>u.replace(J.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.`),o=!0,(i.status==="missing-settings"||i.status==="missing-statusline")&&(r=!1))}}if(n==="all"){let s=mt();console.log(s.message),s.removed&&(o=!0),!s.removed&&n!=="all"&&(r=!0)}n==="all"&&!o&&(r=!0),r&&process.exit(1)});ar.command("doctor").description("Diagnose HUD installation and connectivity across all surfaces").option("--fix","Self-heal locally fixable issues (stale cache, legacy placeholder, orphan precmd block)").option("-y, --yes","Allow --fix to remove overlapping shell HUD blocks without an interactive prompt").action(async e=>{let t=!0,n=(m,g,y)=>{console.log(` ${g?"\u2713":"\u2717"} ${m}: ${y}`),g||(t=!1)};console.log(`Visa HUD Doctor
287
- `);let r=[],o=ga(void 0,void 0,void 0,{withDiagnostics:!0}),s=o.diagnostics?ha(o.diagnostics,o.display):null;s&&(console.log(`\u26A0 ${s}`),console.log(""));let i=pt(),a=!1;try{if(X.existsSync(i)){let m=JSON.parse(X.readFileSync(i,"utf-8")),g=typeof m.statusLine=="object"?m.statusLine.command:"";a=Nt(g)}}catch{}n("Claude Code statusLine",a,a?"registered":"not registered \u2014 run: visa-cli config hud enable");let c=Dv(J.homedir()),l=jn();if(n("Shell detected",!!l,l??"none (zsh, bash, or PowerShell required)"),l){let m=vr(l),g=X.existsSync(m);if(n("RC file exists",g,m.replace(J.homedir(),"~")),g){let w=X.readFileSync(m,"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(m=>m.replace(J.homedir(),"~")).join(", ")}`),a&&c.length>0&&e.fix){let m=c.map(y=>y.replace(J.homedir(),"~")).join(", "),g=e.yes===!0;if(!g&&process.stdin.isTTY&&(g=await Tm(`Remove shell prompt HUD block from ${m}?`,{})==="confirmed"),g){let y=Lv(J.homedir());mt();let w=Uv(y);if(w.length>0){let N=w.map(U=>U.replace(J.homedir(),"~")).join(", ");console.log(` \u2713 --fix: cleaned legacy shell-prompt HUD block from ${N}`),r.push(`removed shell precmd block from ${N}`)}}else console.log(` ! --fix: preserving shell prompt HUD block in ${m}; rerun with --yes or remove it explicitly with: visa-cli config hud disable shell`)}else a&&c.length>0&&console.log(" ! Overlap notice: Claude Code statusLine and shell prompt HUD are both installed. If the prompt output is unintended, run: visa-cli config hud disable shell \u2014 or rerun with: visa-cli config hud doctor --fix --yes");let u=Ot(),d=X.existsSync(u);if(n("HUD cache file",d,d?u.replace(J.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),d)try{let m=JSON.parse(X.readFileSync(u,"utf-8")),g=Date.now()-(m.renderedAt??0),y=Math.round(g/1e3),w=y<=30,N=typeof m.line=="string"?m.line:"",U=N.length>0&&ko(N);if(console.log(` ${w?"\u2713":"\u26A0"} Cache freshness: ${y}s old${w?"":" (stale \u2014 will refresh on next prompt)"}`),U&&console.log(' \u26A0 Cache content: legacy placeholder (HUD will display "VISA | HUD not ready" until next successful refresh)'),e.fix&&(!w||U)){let v=!1;try{X.rmSync(u,{force:!0}),v=!0}catch{}try{let x=br();X.existsSync(x)&&(X.rmSync(x,{force:!0}),v=!0)}catch{}if(v){let x=U?"cache held legacy placeholder":`cache was ${y}s stale`;console.log(` \u2713 --fix: cleared HUD cache (${x}); next prompt will trigger a fresh refresh`),r.push("cleared HUD cache");let $=De.join(J.homedir(),".visa-cli","shell-hud.lock");X.existsSync($)&&(nn(),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{X.rmSync(u,{force:!0}),console.log(" \u2713 --fix: removed corrupt cache file; next prompt will trigger a fresh refresh"),r.push("removed corrupt cache");let m=De.join(J.homedir(),".visa-cli","shell-hud.lock");X.existsSync(m)&&(nn(),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 V.getSessionToken()}catch{}if(n("Auth token",p,p?"found in keychain":"missing \u2014 run: visa-cli setup"),p)try{await ce().getStatus(),n("API connectivity",!0,"GET /v1/status OK")}catch(m){let g=m instanceof Error?m.message:"unknown error";n("API connectivity",!1,g)}e.fix&&(r.length===0?console.log(`
285
+ `);let s=bt(),i=!1,a=!1;try{if(Q.existsSync(s)){let g=JSON.parse(Q.readFileSync(s,"utf-8")),h=typeof g.statusLine=="object"?g.statusLine.command:"";i=Ht(h),a=!!g.statusLine&&!i}}catch{}let c=i?`${n}\u2713${o}`:`${t}\u2717${o}`,l=i?"registered in ~/.claude/settings.json":a?`${r}another HUD is configured${o} \u2014 edit settings.json to switch`:"not enabled";console.log(` ${c} ${e}Claude Code${o} (statusLine) ${l}`);let u=fn(X.homedir()),d=u.length>0||Fo(),p=d?`${n}\u2713${o}`:`${t}\u2717${o}`,m=d?`installed in shell rc file${u.length>0?` (${u.map(g=>g.replace(X.homedir(),"~")).join(", ")})`:""}`:"not installed (opt-in)";console.log(` ${p} ${e}Shell prompt${o} ${m}`),i&&d&&console.log(` ${r}!${o} ${e}Overlap${o} Claude statusLine and shell prompt HUD are both installed. Remove shell prompt output with: visa-cli config hud disable shell`),console.log(`
286
+ ${e}Quick start:${o}`),i||console.log(` visa-cli config hud enable ${t}# Claude Code statusLine (recommended)${o}`),d||console.log(` visa-cli config hud enable shell ${t}# zsh/bash prompt line (opt-in)${o}`),i&&d&&console.log(` ${n}All surfaces enabled.${o}`),(i||d)&&console.log(` visa-cli config hud disable [shell] ${t}# remove a surface${o}`),console.log(` visa-cli config hud doctor ${t}# diagnose connectivity${o}`),console.log()});Cr.command("enable").description("Enable the Visa HUD \u2014 claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{rf(Di(e,{homeDir:X.homedir(),installVisaStatusLine:Vr,installShellHud:Vo}))});Cr.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 s=_t();s.removed||(console.error(s.message),process.exit(1)),console.log(s.message);return}let n=Yo(t);n||(console.error(`Unknown HUD surface: ${t}`),console.error("Supported: claude (default), shell, all"),process.exit(1));let r=!1,o=!1;if(n==="claude"||n==="claude-code"||n==="all"){let s=bt(),i=Ni(s);console.log(i.message),i.removed&&(o=!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&&!zo()&&fn(X.homedir()).length>0){let l=_t();l.removed&&l.rcPaths&&l.rcPaths.length>0&&(console.log(`Also cleaned legacy shell-prompt HUD block from ${l.rcPaths.map(u=>u.replace(X.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.`),o=!0,(i.status==="missing-settings"||i.status==="missing-statusline")&&(r=!1))}}if(n==="all"){let s=_t();console.log(s.message),s.removed&&(o=!0),!s.removed&&n!=="all"&&(r=!0)}n==="all"&&!o&&(r=!0),r&&process.exit(1)});Cr.command("doctor").description("Diagnose HUD installation and connectivity across all surfaces").option("--fix","Self-heal locally fixable issues (stale cache, legacy placeholder, orphan precmd block)").option("-y, --yes","Allow --fix to remove overlapping shell HUD blocks without an interactive prompt").action(async e=>{let t=!0,n=(m,g,h)=>{console.log(` ${g?"\u2713":"\u2717"} ${m}: ${h}`),g||(t=!1)};console.log(`Visa HUD Doctor
287
+ `);let r=[],o=qa(void 0,void 0,void 0,{withDiagnostics:!0}),s=o.diagnostics?Ka(o.diagnostics,o.display):null;s&&(console.log(`\u26A0 ${s}`),console.log(""));let i=bt(),a=!1;try{if(Q.existsSync(i)){let m=JSON.parse(Q.readFileSync(i,"utf-8")),g=typeof m.statusLine=="object"?m.statusLine.command:"";a=Ht(g)}}catch{}n("Claude Code statusLine",a,a?"registered":"not registered \u2014 run: visa-cli config hud enable");let c=eS(X.homedir()),l=Zn();if(n("Shell detected",!!l,l??"none (zsh, bash, or PowerShell required)"),l){let m=Dr(l),g=Q.existsSync(m);if(n("RC file exists",g,m.replace(X.homedir(),"~")),g){let w=Q.readFileSync(m,"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(m=>m.replace(X.homedir(),"~")).join(", ")}`),a&&c.length>0&&e.fix){let m=c.map(h=>h.replace(X.homedir(),"~")).join(", "),g=e.yes===!0;if(!g&&process.stdin.isTTY&&(g=await Xp(`Remove shell prompt HUD block from ${m}?`,{})==="confirmed"),g){let h=Zw(X.homedir());_t();let w=Qw(h);if(w.length>0){let $=w.map(k=>k.replace(X.homedir(),"~")).join(", ");console.log(` \u2713 --fix: cleaned legacy shell-prompt HUD block from ${$}`),r.push(`removed shell precmd block from ${$}`)}}else console.log(` ! --fix: preserving shell prompt HUD block in ${m}; rerun with --yes or remove it explicitly with: visa-cli config hud disable shell`)}else a&&c.length>0&&console.log(" ! Overlap notice: Claude Code statusLine and shell prompt HUD are both installed. If the prompt output is unintended, run: visa-cli config hud disable shell \u2014 or rerun with: visa-cli config hud doctor --fix --yes");let u=Vt(),d=Q.existsSync(u);if(n("HUD cache file",d,d?u.replace(X.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),d)try{let m=JSON.parse(Q.readFileSync(u,"utf-8")),g=Date.now()-(m.renderedAt??0),h=Math.round(g/1e3),w=h<=30,$=typeof m.line=="string"?m.line:"",k=$.length>0&&Ho($);if(console.log(` ${w?"\u2713":"\u26A0"} Cache freshness: ${h}s old${w?"":" (stale \u2014 will refresh on next prompt)"}`),k&&console.log(' \u26A0 Cache content: legacy placeholder (HUD will display "VISA | HUD not ready" until next successful refresh)'),e.fix&&(!w||k)){let v=!1;try{Q.rmSync(u,{force:!0}),v=!0}catch{}try{let S=Ur();Q.existsSync(S)&&(Q.rmSync(S,{force:!0}),v=!0)}catch{}if(v){let S=k?"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 P=Be.join(X.homedir(),".visa-cli","shell-hud.lock");Q.existsSync(P)&&(mn(),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{Q.rmSync(u,{force:!0}),console.log(" \u2713 --fix: removed corrupt cache file; next prompt will trigger a fresh refresh"),r.push("removed corrupt cache");let m=Be.join(X.homedir(),".visa-cli","shell-hud.lock");Q.existsSync(m)&&(mn(),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 B.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(m){let g=m instanceof Error?m.message:"unknown error";n("API connectivity",!1,g)}e.fix&&(r.length===0?console.log(`
288
288
  --fix: no locally fixable issues found.`):console.log(`
289
289
  --fix: applied ${r.length} change${r.length===1?"":"s"} \u2014 ${r.join("; ")}.`)),console.log(t?`
290
290
  All checks passed.`:`
291
- Some checks failed \u2014 see above.`),t||process.exit(1)});ar.command("enable-claude").description("Alias for: hud enable claude").action(()=>{let e=pt(),t=xr(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});ar.command("disable-claude").description("Alias for: hud disable claude").action(()=>{let e=pt(),t=ii(e);console.log(t.message),t.removed||process.exit(1)});var In=G.command("merchants").description("Discover and run paid merchant tools").addHelpCommand(!1).action(Je);In.command("list").description("List live platform merchants").option("--json","Print machine-readable JSON").action(async e=>{try{let n=await new Ae(()=>V.getSessionToken()).listPublicMerchants();if(n.length===0){e.json?console.log(JSON.stringify({merchants:[]},null,2)):console.log(`
291
+ Some checks failed \u2014 see above.`),t||process.exit(1)});Cr.command("enable-claude").description("Alias for: hud enable claude").action(()=>{let e=bt(),t=Vr(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});Cr.command("disable-claude").description("Alias for: hud disable claude").action(()=>{let e=bt(),t=Ni(e);console.log(t.message),t.removed||process.exit(1)});var Hn=z.command("merchants").description("Discover and run paid merchant tools").addHelpCommand(!1).action(et);Hn.command("list").description("List live platform merchants").option("--json","Print machine-readable JSON").action(async e=>{try{let n=await new Pe(()=>B.getSessionToken()).listPublicMerchants();if(n.length===0){e.json?console.log(JSON.stringify({merchants:[]},null,2)):console.log(`
292
292
  No live platform merchants on this auth server.
293
293
  `);return}if(e.json){console.log(JSON.stringify({merchants:n},null,2));return}let r="\x1B[1m",o="\x1B[2m",s="\x1B[0m";console.log();for(let i of n)console.log(` ${r}${i.display_name}${s} ${o}\u2014 slug: ${i.slug}${s}`);console.log(`
294
294
  ${o}Run 'visa-cli merchants tools' to browse tools by merchant.${s}
295
- `)}catch(t){console.error("Error:",t.message),process.exit(1)}});var Vv=new Set(["list","tools","describe","run","refresh"]);async function Ka(e){try{let n=await ce().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(`
295
+ `)}catch(t){console.error("Error:",t.message),process.exit(1)}});var rS=new Set(["list","tools","describe","run","refresh"]);async function Nc(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(`
296
296
  ${n.id}
297
297
  `),console.log(n.description),console.log(`
298
- Price`),console.log(` ${Pr(n.priceCents,n.priceDisplay)}`),console.log(`
298
+ Price`),console.log(` ${Yr(n.priceCents,n.priceDisplay)}`),console.log(`
299
299
  Provider`),console.log(` ${n.provider} \xB7 ${n.category}`),console.log(`
300
- Inputs`);let r=n.inputSchema?.properties;if(r&&typeof r=="object"&&!Array.isArray(r)){let s=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=s.has(c)?"required":"optional",d=ml(l),p=d?` ${d.padEnd(8)}`:" ",m=l?.description?` - ${l.description}`:"";console.log(` ${c.padEnd(a)} ${u}${p}${m}`)}}else console.log(" No published schema. Use --json with the request body.");console.log(`
301
- Examples`);let o=Bd(n);console.log(` visa-cli merchants run ${n.id} --json '${JSON.stringify(o)}'`),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 Ga(e){try{let t=ce();if(e.merchant){let s=e.merchant,i=await t.getPublicMerchantDiscover(s);i||(console.error(`Merchant not found: ${s}`),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:s,tools:c},null,2));return}if(c.length===0){console.log(`No tools found for merchant "${s}".`);return}e.verbose?Ci(c):Hl(s,c);return}let{limit:n,offset:r}=xv(e),o=await Sv(t,{query:e.query,category:e.category,limit:n,offset:r});if(e.json){console.log(JSON.stringify({tools:o},null,2));return}if(o.length===0){console.log("No merchant tools found. Try: visa-cli tools --category image");return}e.verbose?Ci(o):Bl(o)}catch(t){console.error("Error:",t.message),process.exit(1)}}In.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 ${Da}, max ${ja})`,Cs).option("--offset <n>","Pagination offset (default 0)",Cs).action(Ga);In.command("describe <tool>").description("Show tool schema, price, and examples").action(async e=>{await Ka(e)});function qv(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 Ps(e,t,n){return qv(e)?qe.shortcut(e,t,n):qe.executeTool({tool_id:e,params:t},n,"execute_tool")}In.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=Sm(t.json,"--json");t.prompt&&(n.prompt=t.prompt),fr({yes:t.yes}),console.log(`Running ${e}`);let r=await Ps(e,n,`visa-cli merchants run ${e}`);As(r),Rs(r)}catch(n){console.error("Error:",n.message),process.exit(1)}});In.command("refresh").description("Hint: restart the MCP server (Claude/Cursor) to refresh discovered tools \u2014 discovery is in-process").action(()=>{console.log(`
300
+ Inputs`);let r=n.inputSchema?.properties;if(r&&typeof r=="object"&&!Array.isArray(r)){let s=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=s.has(c)?"required":"optional",d=nu(l),p=d?` ${d.padEnd(8)}`:" ",m=l?.description?` - ${l.description}`:"";console.log(` ${c.padEnd(a)} ${u}${p}${m}`)}}else console.log(" No published schema. Use --json with the request body.");console.log(`
301
+ Examples`);let o=Lm(n);console.log(` visa-cli merchants run ${n.id} --json '${JSON.stringify(o)}'`),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 Lc(e){try{let t=pe();if(e.merchant){let s=e.merchant,i=await t.getPublicMerchantDiscover(s);i||(console.error(`Merchant not found: ${s}`),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:s,tools:c},null,2));return}if(c.length===0){console.log(`No tools found for merchant "${s}".`);return}e.verbose?ea(c):Mu(s,c);return}let{limit:n,offset:r}=jw(e),o=await Dw(t,{query:e.query,category:e.category,limit:n,offset:r});if(e.json){console.log(JSON.stringify({tools:o},null,2));return}if(o.length===0){console.log("No merchant tools found. Try: visa-cli tools --category image");return}e.verbose?ea(o):Ou(o)}catch(t){console.error("Error:",t.message),process.exit(1)}}Hn.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 ${Ac}, max ${Rc})`,ei).option("--offset <n>","Pagination offset (default 0)",ei).action(Lc);Hn.command("describe <tool>").description("Show tool schema, price, and examples").action(async e=>{await Nc(e)});function oS(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 ai(e,t,n){return oS(e)?We.shortcut(e,t,n):We.executeTool({tool_id:e,params:t},n,"execute_tool")}Hn.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=Wp(t.json,"--json");t.prompt&&(n.prompt=t.prompt),Pr({yes:t.yes}),console.log(`Running ${e}`);let r=await ai(e,n,`visa-cli merchants run ${e}`);ri(r),oi(r)}catch(n){console.error("Error:",n.message),process.exit(1)}});Hn.command("refresh").description("Hint: restart the MCP server (Claude/Cursor) to refresh discovered tools \u2014 discovery is in-process").action(()=>{console.log(`
302
302
  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.
303
- `)});In.on("command:*",async function(e){let t=e[0],n=e[1],r=e.slice(2);if(!t||Vv.has(t)){console.error(`Unknown merchants subcommand: ${t}`),In.help({error:!0});return}if(!n||n==="tools"){let o=r.indexOf("--category"),s=o!==-1?r[o+1]:void 0,i=r.includes("--verbose"),a=r.includes("--json");await Ga({category:s,verbose:i,json:a,merchant:t});return}if(n==="describe"){let o=r[0];o||(console.error(`Usage: visa-cli merchants ${t} describe <tool>`),process.exit(1));try{let s=ce(),i=await s.getPublicMerchantDiscover(t);if(i||(console.error(`Merchant not found: ${t}`),console.error("List merchants with: visa-cli merchants list"),process.exit(1)),!await s.catalogTool(o,"discover_tools")){let c=i.routes.find(l=>l.tool_id===o);c||(console.error(`Tool "${o}" not found for merchant "${t}"`),console.error(`Browse with: visa-cli merchants ${t} tools`),process.exit(1)),console.log(`
303
+ `)});Hn.on("command:*",async function(e){let t=e[0],n=e[1],r=e.slice(2);if(!t||rS.has(t)){console.error(`Unknown merchants subcommand: ${t}`),Hn.help({error:!0});return}if(!n||n==="tools"){let o=r.indexOf("--category"),s=o!==-1?r[o+1]:void 0,i=r.includes("--verbose"),a=r.includes("--json");await Lc({category:s,verbose:i,json:a,merchant:t});return}if(n==="describe"){let o=r[0];o||(console.error(`Usage: visa-cli merchants ${t} describe <tool>`),process.exit(1));try{let s=pe(),i=await s.getPublicMerchantDiscover(t);if(i||(console.error(`Merchant not found: ${t}`),console.error("List merchants with: visa-cli merchants list"),process.exit(1)),!await s.catalogTool(o,"discover_tools")){let c=i.routes.find(l=>l.tool_id===o);c||(console.error(`Tool "${o}" not found for merchant "${t}"`),console.error(`Browse with: visa-cli merchants ${t} tools`),process.exit(1)),console.log(`
304
304
  ${o}
305
305
  `),c.description&&console.log(c.description),console.log(`
306
- Price`),console.log(` ${Pr(c.price_cents)}`),console.log(`
306
+ Price`),console.log(` ${Yr(c.price_cents)}`),console.log(`
307
307
  Examples`),console.log(` visa-cli merchants run ${o} --json '${JSON.stringify(c.request?.body_example??{})}'`),console.log(` visa-cli merchants ${t} run ${o}
308
- `);return}await Ka(o)}catch(s){console.error("Error:",s.message),process.exit(1)}return}if(n==="run"){let o=r[0];o||(console.error(`Usage: visa-cli merchants ${t} run <tool> [--json '{...}']`),process.exit(1));let s=a=>{let c=r.indexOf(a);return c!==-1?r[c+1]:void 0},i=r.includes("--yes");try{let a=s("--json"),c=Sm(a,"--json"),l=s("--prompt");l&&(c.prompt=l),fr({yes:i}),console.log(`Running ${o}`);let u=await Ps(o,c,`visa-cli merchants ${t} run ${o}`);As(u),Rs(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)});G.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 ${Da}, max ${ja})`,Cs).option("--offset <n>","Pagination offset (default 0)",Cs).action(Ga);G.command("describe <tool>").description("Show schema, price, and examples for a tool (alias for: merchants describe)").action(async e=>{await Ka(e)});var no=G.command("generate").description("Generate media with merchant tools").addHelpCommand(!1).action(Je);async function ro(e){fr({yes:e.yes}),e.json||e.format&&go(e.format)||(console.log(`
308
+ `);return}await Nc(o)}catch(s){console.error("Error:",s.message),process.exit(1)}return}if(n==="run"){let o=r[0];o||(console.error(`Usage: visa-cli merchants ${t} run <tool> [--json '{...}']`),process.exit(1));let s=a=>{let c=r.indexOf(a);return c!==-1?r[c+1]:void 0},i=r.includes("--yes");try{let a=s("--json"),c=Wp(a,"--json"),l=s("--prompt");l&&(c.prompt=l),Pr({yes:i}),console.log(`Running ${o}`);let u=await ai(o,c,`visa-cli merchants ${t} run ${o}`);ri(u),oi(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 ${Ac}, max ${Rc})`,ei).option("--offset <n>","Pagination offset (default 0)",ei).action(Lc);z.command("describe <tool>").description("Show schema, price, and examples for a tool (alias for: merchants describe)").action(async e=>{await Nc(e)});var So=z.command("generate").description("Generate media with merchant tools").addHelpCommand(!1).action(et);async function xo(e){Pr({yes:e.yes}),e.json||e.format&&Mo(e.format)||(console.log(`
309
309
  ${e.kind}
310
310
  `),console.log(`Using: ${e.toolId}`),console.log(`Prompt: ${e.prompt}
311
- `));let n=await Ps(e.toolId,e.params,`visa-cli generate ${e.kind.toLowerCase()}: ${e.prompt}`);As(n,{json:e.json,format:e.format,command:e.command??`generate.${e.kind.toLowerCase().replace(/\s+/g,"_")}`}),Rs(n)}var Zt=(e,t)=>n=>(t.includes(n)||G.error(`error: option '${e}' accepts ${t.map(r=>`'${r}'`).join(", ")} (got '${n}')`,{exitCode:2}),n);no.command("image [prompt]").description("Generate an image from a prompt (accepts stdin via `-` or --stdin)").option("--quality <quality>","Image quality: standard or high",Zt("--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)",Zt("--format",$t)).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 en(e,t),r=t.tool??(t.fast||t.quality!=="high"?"fal-flux-pro":"fal-flux-pro-ultra"),o={prompt:n};t.imageRef&&(o.image_url=t.imageRef),await ro({kind:"Image generation",toolId:r,params:o,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.image"})}catch(n){ir("generate.image",n,{json:t.json,format:t.format})}});no.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)",Zt("--format",$t)).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 en(e,t),r={prompt:n};t.aspectRatio&&(r.aspect_ratio=t.aspectRatio),t.duration&&(r.duration=Number(t.duration)),await ro({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){ir("generate.video",n,{json:t.json,format:t.format})}});no.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)",Zt("--format",$t)).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 en(e,t),r={prompt:n};t.instrumental&&(r.instrumental=!0),t.duration&&(r.duration=Number(t.duration)),await ro({kind:"Music generation",toolId:t.tool??Gt("generate_music"),params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.music"})}catch(n){ir("generate.music",n,{json:t.json,format:t.format})}});no.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)",Zt("--format",$t)).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||G.error("error: option '--audio-url <url>' is required for visa-cli generate speech",{exitCode:2});let r=await en(e,t),o={text:r,audio_url:n};await ro({kind:"Speech generation",toolId:t.tool??"fal-metavoice",params:o,prompt:r,json:t.json,format:t.format,yes:t.yes,command:"generate.speech"})}catch(n){ir("generate.speech",n,{json:t.json,format:t.format})}});no.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)",Zt("--format",$t)).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 en(e,t),r={image_url:n};await ro({kind:"3D generation",toolId:t.tool??Gt("generate_3d"),params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.3d"})}catch(n){ir("generate.3d",n,{json:t.json,format:t.format})}});var $a="reasoning",gm=Object.keys(Ur.run_llm.tiers);G.command("run-llm [prompt]").description(`Run a chat-completion against an OpenRouter-backed LLM (default tier: ${$a})`).option("--tier <tier>",`LLM tier: ${gm.join(" | ")} (resolves to a catalog tool id via the run_llm meta-tool)`,Zt("--tier",gm),$a).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)",Zt("--format",$t)).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 Gs(),u=JSON.parse(l),d=pc(u,t.fromStdin);n=n??d}let r=await en(e,{stdin:t.stdin&&!t.fromStdin});fr({yes:t.yes});let o={prompt:r},s=await gc(t.system);s&&(o.system_prompt=s),t.maxTokens&&(o.max_tokens=Number(t.maxTokens)),t.temperature!==void 0&&(o.temperature=Number(t.temperature)),n&&(o.image_url=n);let i=t.tier??$a,a=t.model??Gt("run_llm",i);if(!t.json){console.log(`
311
+ `));let n=await ai(e.toolId,e.params,`visa-cli generate ${e.kind.toLowerCase()}: ${e.prompt}`);ri(n,{json:e.json,format:e.format,command:e.command??`generate.${e.kind.toLowerCase().replace(/\s+/g,"_")}`}),oi(n)}var ln=(e,t)=>n=>(t.includes(n)||z.error(`error: option '${e}' accepts ${t.map(r=>`'${r}'`).join(", ")} (got '${n}')`,{exitCode:2}),n);So.command("image [prompt]").description("Generate an image from a prompt (accepts stdin via `-` or --stdin)").option("--quality <quality>","Image quality: standard or high",ln("--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)",ln("--format",jt)).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 un(e,t),r=t.tool??(t.fast||t.quality!=="high"?"fal-flux-pro":"fal-flux-pro-ultra"),o={prompt:n};t.imageRef&&(o.image_url=t.imageRef),await xo({kind:"Image generation",toolId:r,params:o,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.image"})}catch(n){Tr("generate.image",n,{json:t.json,format:t.format})}});So.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)",ln("--format",jt)).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 un(e,t),r={prompt:n};t.aspectRatio&&(r.aspect_ratio=t.aspectRatio),t.duration&&(r.duration=Number(t.duration)),await xo({kind:"Video generation",toolId:t.tool??"fal-minimax-video",params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.video"})}catch(n){Tr("generate.video",n,{json:t.json,format:t.format})}});So.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)",ln("--format",jt)).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 un(e,t),r={prompt:n};t.instrumental&&(r.instrumental=!0),t.duration&&(r.duration=Number(t.duration)),await xo({kind:"Music generation",toolId:t.tool??en("generate_music"),params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.music"})}catch(n){Tr("generate.music",n,{json:t.json,format:t.format})}});So.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)",ln("--format",jt)).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 un(e,t),o={text:r,audio_url:n};await xo({kind:"Speech generation",toolId:t.tool??"fal-metavoice",params:o,prompt:r,json:t.json,format:t.format,yes:t.yes,command:"generate.speech"})}catch(n){Tr("generate.speech",n,{json:t.json,format:t.format})}});So.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)",ln("--format",jt)).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 un(e,t),r={image_url:n};await xo({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){Tr("generate.3d",n,{json:t.json,format:t.format})}});var Sc="reasoning",Fp=Object.keys(to.run_llm.tiers);z.command("run-llm [prompt]").description(`Run a chat-completion against an OpenRouter-backed LLM (default tier: ${Sc})`).option("--tier <tier>",`LLM tier: ${Fp.join(" | ")} (resolves to a catalog tool id via the run_llm meta-tool)`,ln("--tier",Fp),Sc).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)",ln("--format",jt)).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 wi(),u=JSON.parse(l),d=rl(u,t.fromStdin);n=n??d}let r=await un(e,{stdin:t.stdin&&!t.fromStdin});Pr({yes:t.yes});let o={prompt:r},s=await sl(t.system);s&&(o.system_prompt=s),t.maxTokens&&(o.max_tokens=Number(t.maxTokens)),t.temperature!==void 0&&(o.temperature=Number(t.temperature)),n&&(o.image_url=n);let i=t.tier??Sc,a=t.model??en("run_llm",i);if(!t.json){console.log(`
312
312
  LLM completion
313
313
  `),console.log(`Using: ${a}`);let l=r.length>200?`${r.slice(0,200)}\u2026`:r;console.log(`Prompt: ${l}
314
- `)}let c=await Ps(a,o,"visa-cli run-llm");As(c,{json:t.json,format:t.format,command:"run-llm"}),Rs(c)}catch(n){ir("run-llm",n,{json:t.json,format:t.format})}});G.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 s=[];for(let i of ze)Ea(i,n).removed&&s.push(i.displayName);s.length>0?console.log(`Removed visa-cli from: ${s.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(`
315
- Supported clients: ${ze.map(s=>s.id).join(", ")}`),process.exit(1));let r=xa(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${ze.map(s=>s.id).join(", ")}`),process.exit(1));let o=Ea(r,n);o.removed?console.log(`Removed visa-cli from ${o.configPath}`):console.log(`visa-cli was not installed for ${r.displayName}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});G.hook("postAction",()=>{if(eo){eo=!1;return}ks&&qd(ks.lastSignals)});tm(G);Iv(["setup","install","status","cards","keys","balance","tools","describe","merchants","generate","run-llm","config","feedback","update","uninstall"]);Cm(G);G.parseAsync().catch(async e=>{console.error("Error:",e instanceof Error?e.message:String(e));let{reportFatal:t}=await Promise.resolve().then(()=>(xs(),Ss));await t(e)});process.on("uncaughtException",async e=>{console.error("Uncaught exception:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(xs(),Ss));await t(e)});process.on("unhandledRejection",async e=>{console.error("Unhandled rejection:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(xs(),Ss));await t(e)});0&&(module.exports={printGroupHelpAndExit});
314
+ `)}let c=await ai(a,o,"visa-cli run-llm");ri(c,{json:t.json,format:t.format,command:"run-llm"}),oi(c)}catch(n){Tr("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 s=[];for(let i of Qe)_c(i,n).removed&&s.push(i.displayName);s.length>0?console.log(`Removed visa-cli from: ${s.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(`
315
+ Supported clients: ${Qe.map(s=>s.id).join(", ")}`),process.exit(1));let r=fc(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${Qe.map(s=>s.id).join(", ")}`),process.exit(1));let o=_c(r,n);o.removed?console.log(`Removed visa-cli from ${o.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(vo){vo=!1;return}Zs&&Nm(Zs.lastSignals)});kp(z);Gw(["setup","install","status","cards","keys","balance","tools","describe","merchants","generate","run-llm","config","feedback","update","uninstall"]);Yp(z);z.parseAsync().catch(async e=>{console.error("Error:",e instanceof Error?e.message:String(e));let{reportFatal:t}=await Promise.resolve().then(()=>(Xs(),Ys));await t(e)});process.on("uncaughtException",async e=>{console.error("Uncaught exception:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(Xs(),Ys));await t(e)});process.on("unhandledRejection",async e=>{console.error("Unhandled rejection:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(Xs(),Ys));await t(e)});0&&(module.exports={printGroupHelpAndExit});
316
+ /*! Bundled license information:
317
+
318
+ @noble/ed25519/index.js:
319
+ (*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
320
+ */