@visa/cli 2.0.0-rc.42 → 2.0.0-rc.43

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 $c=Object.create;var Jr=Object.defineProperty;var Rc=Object.getOwnPropertyDescriptor;var Ic=Object.getOwnPropertyNames;var Pc=Object.getPrototypeOf,Mc=Object.prototype.hasOwnProperty;var Oc=(e,t)=>()=>(e&&(t=e(e=0)),t);var Eo=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),$o=(e,t)=>{for(var n in t)Jr(e,n,{get:t[n],enumerable:!0})},Nc=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ic(t))!Mc.call(e,s)&&s!==n&&Jr(e,s,{get:()=>t[s],enumerable:!(r=Rc(t,s))||r.enumerable});return e};var A=(e,t,n)=>(n=e!=null?$c(Pc(e)):{},Nc(t||!e||!e.__esModule?Jr(n,"default",{value:e,enumerable:!0}):n,e));var Gn=Eo((wf,Wc)=>{Wc.exports={name:"@visa/cli",version:"2.0.0-rc.42",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{prebuild:"pnpm --filter @visa/money build && pnpm --filter @visa-cli/tools build",build:"tsc --noEmit && node esbuild.config.js",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.6.0","@typescript-eslint/eslint-plugin":"^8.59.2","@typescript-eslint/parser":"^8.59.1","@types/express":"^5.0.0",esbuild:"^0.27.4",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.3","ts-jest":"^29.2.0",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","native/visa-keychain.m","server.json","README.md","LICENSE"]}});var so=Eo(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.micros=jd;X.fromCents=Vd;X.fromUsdc=qd;X.fromUsd=Fd;X.toCents=Bd;X.toCentsForAcquirer=Hd;X.toUsdc=Kd;X.toWire=Gd;X.fromWire=zd;X.toDisplay=Wd;X.toUsdRounded2dp=Jd;X.add=Yd;X.sub=Zd;X.clampNonNegative=Xd;X.isNonNegative=Qd;X.max=em;X.min=tm;var Je=10000n,Ea=1000000n;function jd(e){return e}function Vd(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*Je}function qd(e){return e}function Fd(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function Bd(e){if(e>=0n)return Number(e/Je);let t=e/Je,n=e%Je;return Number(n===0n?t:t-1n)}function Hd(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/Je)}function Kd(e){return e}function Gd(e){return e.toString()}function zd(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 Wd(e,t={}){let n=t.decimals??2,r=t.symbol??"$",s=e<0n,o=s?-e:e,i=o/Ea,a=o%Ea,l=s?"-":"";if(n===0)return`${l}${r}${i.toString()}`;let c=a.toString().padStart(6,"0").slice(0,n);return`${l}${r}${i.toString()}.${c}`}function Jd(e){let t=e<0n,n=t?-e:e,r=n/Je,o=n%Je*2n,i;o<Je?i=r:o>Je?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function Yd(e,t){return e+t}function Zd(e,t){return e-t}function Xd(e){return e<0n?0n:e}function Qd(e){return e>=0n}function em(e,t){return e>t?e:t}function tm(e,t){return e<t?e:t}});var Br={};$o(Br,{initSentry:()=>Bp,isSentryConfigured:()=>Fp,reportFatal:()=>Hp});function Fp(){return!1}async function Bp(){return null}async function Hp(e,t){process.exit(t?.exitCode??1)}var Hr=Oc(()=>{});var gc=require("commander"),Ln=A(require("crypto")),Ie=A(require("fs")),W=A(require("os")),Ze=A(require("path")),hc=require("child_process"),yc=require("util");var Hn=require("child_process"),Ro=require("util"),et=A(require("fs")),Kn=A(require("os")),Qr=A(require("path"));var je="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";var Pe=(0,Ro.promisify)(Hn.execFile),es=Qr.join(Kn.homedir(),".visa-mcp"),mn=Qr.join(es,"session-token"),ye="visa-cli",Qe="session-token",Fn="rc-access",Uc=5e3,Bn=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function Dc(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
2
- `)}function Io(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=Dc(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function Lc(){try{let{stdout:e}=await Pe("security",["find-generic-password","-s",ye,"-a",Qe,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(Io(e))throw new Bn("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 jc(e){try{try{await Pe("security",["delete-generic-password","-s",ye,"-a",Qe],{timeout:5e3})}catch{}return await Pe("security",["add-generic-password","-s",ye,"-a",Qe,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function Vc(){try{await Pe("security",["delete-generic-password","-s",ye,"-a",Qe],{timeout:5e3})}catch{}}async function qc(){if(!ts())return null;try{let{stdout:e}=await Pe("secret-tool",["lookup","service",ye,"account",Qe],{timeout:5e3});return e.trim()||null}catch{return null}}async function Fc(e){if(!ts())return!1;try{let t=(0,Hn.execFile)("secret-tool",["store","--label",`${ye} ${Qe}`,"service",ye,"account",Qe]);return t.stdin?(t.stdin.write(e),t.stdin.end(),await Promise.race([new Promise((n,r)=>{t.on("exit",s=>s===0?n():r(new Error(`secret-tool exited ${s}`))),t.on("error",r)}),new Promise((n,r)=>setTimeout(()=>{t.kill(),r(new Error("secret-tool timed out"))},Uc))]),!0):!1}catch{return!1}}async function Bc(){if(ts())try{await Pe("secret-tool",["clear","service",ye,"account",Qe],{timeout:5e3})}catch{}}function ts(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function Hc(){try{let{stdout:e}=await Pe("security",["find-generic-password","-s",ye,"-a",Fn,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Kc(e){try{try{await Pe("security",["delete-generic-password","-s",ye,"-a",Fn],{timeout:5e3})}catch{}await Pe("security",["add-generic-password","-s",ye,"-a",Fn,"-w",e],{timeout:5e3})}catch{}}async function Gc(){try{await Pe("security",["delete-generic-password","-s",ye,"-a",Fn],{timeout:5e3})}catch{}}function Zr(){try{return et.readFileSync(mn,"utf-8").trim()||null}catch(e){if(Io(e))throw new Bn(`Unable to read Visa CLI credentials from ${mn}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function Po(e){et.mkdirSync(es,{recursive:!0,mode:448}),et.writeFileSync(mn,e,{mode:384}),process.platform==="win32"&&zc(mn)}function Xr(){try{et.unlinkSync(mn)}catch{}}function zc(e){try{let t=Kn.userInfo().username;(0,Hn.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 Yr(){switch(process.platform){case"darwin":return{get:Lc,store:jc,delete:Vc};case"linux":return{get:qc,store:Fc,delete:Bc};default:return{get:async()=>Zr(),store:async e=>{try{return Po(e),!0}catch{return!1}},delete:async()=>Xr(),storesInSessionFile:!0}}}var D=class{static async getSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return Promise.resolve("mock-session-token-for-testing");let t=Yr(),n=await t.get();if(n)return n;let r=Zr();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;let n=Yr();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||Xr();return}await n.delete()}if(Po(t),Zr()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${es} is writable.`))}static async getRcAccessToken(){return process.env.VISA_MOCK_KEYCHAIN==="true"?je:Hc()}static async saveRcAccessToken(t){process.env.VISA_MOCK_KEYCHAIN!=="true"&&await Kc(t)}static async deleteSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;await Yr().delete(),Xr()}static async clearAll(){await this.deleteSessionToken(),await Gc()}};var zn=A(require("crypto")),Wn=A(require("tty")),Jn=A(require("fs"));function Jc(e){return/-rc\.|-beta\./.test(e)}function ns(e){return zn.createHash("sha256").update(e.trim()).digest("hex")}function Mo(e){return je==="SKIP"?!0:zn.timingSafeEqual(Buffer.from(ns(e)),Buffer.from(je))}function Yc(){try{let e=Jn.openSync("/dev/tty","r+"),t=new Wn.ReadStream(e),n=new Wn.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{Jn.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 Zc(e){return new Promise((t,n)=>{let r;try{r=Yc()}catch(u){n(u);return}let{input:s,output:o,cleanupStreams:i}=r,a=()=>{s.off("data",c);try{s.setRawMode?.(!1)}catch{}i()};o.write(e),s.setRawMode?.(!0),s.resume(),s.setEncoding("utf8");let l="",c=u=>{u==="\r"||u===`
1
+ "use strict";var Mc=Object.create;var Yr=Object.defineProperty;var Oc=Object.getOwnPropertyDescriptor;var Nc=Object.getOwnPropertyNames;var Uc=Object.getPrototypeOf,Dc=Object.prototype.hasOwnProperty;var Lc=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ro=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Io=(e,t)=>{for(var n in t)Yr(e,n,{get:t[n],enumerable:!0})},jc=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Nc(t))!Dc.call(e,s)&&s!==n&&Yr(e,s,{get:()=>t[s],enumerable:!(r=Oc(t,s))||r.enumerable});return e};var T=(e,t,n)=>(n=e!=null?Mc(Uc(e)):{},jc(t||!e||!e.__esModule?Yr(n,"default",{value:e,enumerable:!0}):n,e));var Gn=Ro(($f,Xc)=>{Xc.exports={name:"@visa/cli",version:"2.0.0-rc.43",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{prebuild:"pnpm --filter @visa/money build && pnpm --filter @visa-cli/tools build",build:"tsc --noEmit && node esbuild.config.js",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.6.0","@typescript-eslint/eslint-plugin":"^8.59.2","@typescript-eslint/parser":"^8.59.1","@types/express":"^5.0.0",esbuild:"^0.27.4",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.3","ts-jest":"^29.2.0",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","native/visa-keychain.m","server.json","README.md","LICENSE"]}});var oo=Ro(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.micros=Bd;X.fromCents=Hd;X.fromUsdc=Kd;X.fromUsd=Gd;X.toCents=zd;X.toCentsForAcquirer=Wd;X.toUsdc=Jd;X.toWire=Yd;X.fromWire=Zd;X.toDisplay=Xd;X.toUsdRounded2dp=Qd;X.add=em;X.sub=tm;X.clampNonNegative=nm;X.isNonNegative=rm;X.max=sm;X.min=om;var Ye=10000n,Ra=1000000n;function Bd(e){return e}function Hd(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*Ye}function Kd(e){return e}function Gd(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function zd(e){if(e>=0n)return Number(e/Ye);let t=e/Ye,n=e%Ye;return Number(n===0n?t:t-1n)}function Wd(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/Ye)}function Jd(e){return e}function Yd(e){return e.toString()}function Zd(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 Xd(e,t={}){let n=t.decimals??2,r=t.symbol??"$",s=e<0n,o=s?-e:e,i=o/Ra,a=o%Ra,l=s?"-":"";if(n===0)return`${l}${r}${i.toString()}`;let c=a.toString().padStart(6,"0").slice(0,n);return`${l}${r}${i.toString()}.${c}`}function Qd(e){let t=e<0n,n=t?-e:e,r=n/Ye,o=n%Ye*2n,i;o<Ye?i=r:o>Ye?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function em(e,t){return e+t}function tm(e,t){return e-t}function nm(e){return e<0n?0n:e}function rm(e){return e>=0n}function sm(e,t){return e>t?e:t}function om(e,t){return e<t?e:t}});var Br={};Io(Br,{initSentry:()=>Wp,isSentryConfigured:()=>zp,reportFatal:()=>Jp});function zp(){return!1}async function Wp(){return null}async function Jp(e,t){process.exit(t?.exitCode??1)}var Hr=Lc(()=>{});var _c=require("commander"),Ln=T(require("crypto")),Ie=T(require("fs")),W=T(require("os")),Xe=T(require("path")),vc=require("child_process"),bc=T(require("node:readline/promises")),Sc=require("util");var Hn=require("child_process"),Po=require("util"),tt=T(require("fs")),Kn=T(require("os")),es=T(require("path"));var Ve="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";var Pe=(0,Po.promisify)(Hn.execFile),ts=es.join(Kn.homedir(),".visa-mcp"),pn=es.join(ts,"session-token"),ye="visa-cli",et="session-token",Fn="rc-access",Vc=5e3,Bn=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function qc(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
2
+ `)}function Mo(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=qc(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function Fc(){try{let{stdout:e}=await Pe("security",["find-generic-password","-s",ye,"-a",et,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(Mo(e))throw new Bn("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 Bc(e){try{try{await Pe("security",["delete-generic-password","-s",ye,"-a",et],{timeout:5e3})}catch{}return await Pe("security",["add-generic-password","-s",ye,"-a",et,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function Hc(){try{await Pe("security",["delete-generic-password","-s",ye,"-a",et],{timeout:5e3})}catch{}}async function Kc(){if(!ns())return null;try{let{stdout:e}=await Pe("secret-tool",["lookup","service",ye,"account",et],{timeout:5e3});return e.trim()||null}catch{return null}}async function Gc(e){if(!ns())return!1;try{let t=(0,Hn.execFile)("secret-tool",["store","--label",`${ye} ${et}`,"service",ye,"account",et]);return t.stdin?(t.stdin.write(e),t.stdin.end(),await Promise.race([new Promise((n,r)=>{t.on("exit",s=>s===0?n():r(new Error(`secret-tool exited ${s}`))),t.on("error",r)}),new Promise((n,r)=>setTimeout(()=>{t.kill(),r(new Error("secret-tool timed out"))},Vc))]),!0):!1}catch{return!1}}async function zc(){if(ns())try{await Pe("secret-tool",["clear","service",ye,"account",et],{timeout:5e3})}catch{}}function ns(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function Wc(){try{let{stdout:e}=await Pe("security",["find-generic-password","-s",ye,"-a",Fn,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Jc(e){try{try{await Pe("security",["delete-generic-password","-s",ye,"-a",Fn],{timeout:5e3})}catch{}await Pe("security",["add-generic-password","-s",ye,"-a",Fn,"-w",e],{timeout:5e3})}catch{}}async function Yc(){try{await Pe("security",["delete-generic-password","-s",ye,"-a",Fn],{timeout:5e3})}catch{}}function Xr(){try{return tt.readFileSync(pn,"utf-8").trim()||null}catch(e){if(Mo(e))throw new Bn(`Unable to read Visa CLI credentials from ${pn}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function Oo(e){tt.mkdirSync(ts,{recursive:!0,mode:448}),tt.writeFileSync(pn,e,{mode:384}),process.platform==="win32"&&Zc(pn)}function Qr(){try{tt.unlinkSync(pn)}catch{}}function Zc(e){try{let t=Kn.userInfo().username;(0,Hn.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 Zr(){switch(process.platform){case"darwin":return{get:Fc,store:Bc,delete:Hc};case"linux":return{get:Kc,store:Gc,delete:zc};default:return{get:async()=>Xr(),store:async e=>{try{return Oo(e),!0}catch{return!1}},delete:async()=>Qr(),storesInSessionFile:!0}}}var D=class{static async getSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return Promise.resolve("mock-session-token-for-testing");let t=Zr(),n=await t.get();if(n)return n;let r=Xr();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;let n=Zr();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||Qr();return}await n.delete()}if(Oo(t),Xr()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${ts} is writable.`))}static async getRcAccessToken(){return process.env.VISA_MOCK_KEYCHAIN==="true"?Ve:Wc()}static async saveRcAccessToken(t){process.env.VISA_MOCK_KEYCHAIN!=="true"&&await Jc(t)}static async deleteSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;await Zr().delete(),Qr()}static async clearAll(){await this.deleteSessionToken(),await Yc()}};var zn=T(require("crypto")),Wn=T(require("tty")),Jn=T(require("fs"));function Qc(e){return/-rc\.|-beta\./.test(e)}function rs(e){return zn.createHash("sha256").update(e.trim()).digest("hex")}function No(e){return Ve==="SKIP"?!0:zn.timingSafeEqual(Buffer.from(rs(e)),Buffer.from(Ve))}function el(){try{let e=Jn.openSync("/dev/tty","r+"),t=new Wn.ReadStream(e),n=new Wn.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{Jn.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 tl(e){return new Promise((t,n)=>{let r;try{r=el()}catch(u){n(u);return}let{input:s,output:o,cleanupStreams:i}=r,a=()=>{s.off("data",c);try{s.setRawMode?.(!1)}catch{}i()};o.write(e),s.setRawMode?.(!0),s.resume(),s.setEncoding("utf8");let l="",c=u=>{u==="\r"||u===`
3
3
  `?(o.write(`
4
4
  `),a(),t(l)):u===""?(o.write(`
5
- `),a(),n(new Error("Cancelled"))):u==="\x7F"||u==="\b"?l.length>0&&(l=l.slice(0,-1),o.write("\b \b")):(l+=u,o.write("\u2022"))};s.on("data",c)})}var Xc=`
5
+ `),a(),n(new Error("Cancelled"))):u==="\x7F"||u==="\b"?l.length>0&&(l=l.slice(0,-1),o.write("\b \b")):(l+=u,o.write("\u2022"))};s.on("data",c)})}var nl=`
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,30 +11,30 @@
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 Oo(e={}){let t=e.version??Gn().version;if(!Jc(t))return;let n=process.env.VISA_RC_CODE;if(n&&Mo(n)){await D.saveRcAccessToken(ns(n));return}if(e.isMcp??!1){let i=await D.getRcAccessToken();if(i&&(je==="SKIP"||i===je))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
15
- `),process.exit(1)}let s=await D.getRcAccessToken();if(s&&(je==="SKIP"||s===je))return;console.log(Xc);let o=3;for(let i=1;i<=o;i++){let a;try{a=await Zc(" Enter RC access code: ")}catch{process.exit(1)}if(Mo(a)){await D.saveRcAccessToken(ns(a)),console.log(`
14
+ `;async function Uo(e={}){let t=e.version??Gn().version;if(!Qc(t))return;let n=process.env.VISA_RC_CODE;if(n&&No(n)){await D.saveRcAccessToken(rs(n));return}if(e.isMcp??!1){let i=await D.getRcAccessToken();if(i&&(Ve==="SKIP"||i===Ve))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
15
+ `),process.exit(1)}let s=await D.getRcAccessToken();if(s&&(Ve==="SKIP"||s===Ve))return;console.log(nl);let o=3;for(let i=1;i<=o;i++){let a;try{a=await tl(" Enter RC access code: ")}catch{process.exit(1)}if(No(a)){await D.saveRcAccessToken(rs(a)),console.log(`
16
16
  Access granted. Welcome.
17
17
  `);return}i<o&&console.log(`
18
18
  Invalid code. ${o-i} attempt(s) remaining.
19
19
  `)}console.log(`
20
20
  Invalid code. Contact your team lead.
21
- `),process.exit(1)}var No=require("child_process");function rs(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 Qc(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(`
22
- `)}function ss(e,t=process.platform){return t==="darwin"?{cmd:"open",args:[e]}:t==="win32"?{cmd:"cmd",args:["/c","start","",e]}:t==="linux"?{cmd:"xdg-open",args:[e]}:null}async function os(e,t={}){let n=t.log??(l=>console.log(l)),r=t.env??process.env,s=t.platform??process.platform,o=t.spawn??((l,c,u)=>{(0,No.execFile)(l,c,m=>u(m))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let l of Qc(e).split(`
23
- `))n(` ${l}`);n("");let i=rs(r,s);if(i.headless){n(` (${i.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 a=ss(e,s);if(!a){n(` No known browser-open command for platform "${s}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(l=>{o(a.cmd,a.args,c=>{c?(n(` Could not open browser automatically (${c.message}).`),n(" Open the URL above manually to continue."),n("")):(n(" Opened browser. Waiting for you to sign in..."),n("")),l()})})}function el(e){return new Promise(t=>setTimeout(t,e))}function Uo(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 Do(e){return!Number.isFinite(e)||e===null||e<=0?1e3:Math.min(Math.max(Math.ceil(e),1e3),3e4)}async function tl(e,t=Math.random()*250){let n=s=>Math.min(s+Math.max(0,Math.ceil(t)),3e4);if(!e||e.status!==429)return n(1e3);let r=Uo(e.headers?.get("Retry-After"));if(r!==null)return n(Do(r));if(typeof e.json=="function")try{let s=await e.json();return n(Do(Uo(s?.retryAfter)))}catch{return n(1e3)}return n(1e3)}async function tt(e,t){let n=await tl(e);return t?.(n),await el(n),n}var jo=A(require("crypto")),ue=A(require("fs")),Yn=A(require("path"));function Vo(e,t){ue.mkdirSync(Yn.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${jo.randomBytes(8).toString("hex")}.tmp`;try{ue.writeFileSync(n,JSON.stringify(t,null,2)+`
24
- `),ue.renameSync(n,e)}catch(r){try{ue.unlinkSync(n)}catch{}throw r}}function Lo(e){return`'${e.replace(/'/g,"'\\''")}'`}var qo="# visa-cli-hud-v1";function nl(e,t){let n=e??process.execPath,r=t??process.argv[1]??"",s=r?Yn.resolve(r):"";return`${s?`${Lo(n)} ${Lo(s)} config statusline`:"visa-cli config statusline"} ${qo}`}function _t(e){return typeof e!="string"?!1:e.includes(qo)?!0:e.includes("visa-cli")&&e.includes("statusline")}function Zn(e,t=nl){let n={},r=!1;if(ue.existsSync(e)){r=!0;try{n=JSON.parse(ue.readFileSync(e,"utf-8"))}catch(s){return{installed:"malformed-json",message:`~/.claude/settings.json is not valid JSON (${s.message}). Fix the file manually, then run: visa-cli config hud enable claude`}}}if(n.statusLine){let s=typeof n.statusLine=="object"?n.statusLine.command:"";return _t(s)?{installed:"already-visa",message:"Visa HUD already registered in ~/.claude/settings.json."}:{installed:"other-hud-present",message:"Another HUD is already configured (keeping it). To switch to Visa HUD, edit ~/.claude/settings.json \u2192 statusLine.command"}}try{return n.statusLine={type:"command",command:t()},Vo(e,n),{installed:"new",message:`Visa HUD registered in ~/.claude/settings.json${r?"":" (new file)"}. Restart Claude Code to see it pinned below the input.`}}catch(s){return{installed:"error",message:`Failed to write settings: ${s.message}. Enable manually later with: visa-cli config hud enable claude`}}}function is(e){if(!ue.existsSync(e))return{removed:!1,message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(ue.readFileSync(e,"utf-8"))}catch(r){return{removed:!1,message:`~/.claude/settings.json is not valid JSON: ${r.message}`}}if(!t.statusLine)return{removed:!1,message:"No statusLine configured."};let n=typeof t.statusLine=="object"?t.statusLine.command:"";return _t(n)?(delete t.statusLine,Vo(e,t),{removed:!0,message:"Visa HUD removed from ~/.claude/settings.json. Restart Claude Code to take effect."}):{removed:!1,message:"statusLine is owned by another tool \u2014 leaving it alone."}}var Ve=A(require("fs")),qe=A(require("path")),rl=1,vt={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},sl=["terminal","claude","claude-code","codex","all"];function ms(e){let t=e.toLowerCase();return sl.includes(t)?t:null}var ol=50,il=64*1024,Fo=10,as=80;function al(){let e=(process.env.COLORTERM??"").toLowerCase();if(e==="truecolor"||e==="24bit")return!0;let t=(process.env.TERM??"").toLowerCase();return t.includes("truecolor")||t.includes("24bit")}var cs=al(),C={reset:"\x1B[0m",visaBlue:cs?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:cs?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:cs?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function E(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${C.reset}`}function Bo(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function Wo(e=process.stdin){return e.isTTY?null:new Promise(t=>{let n=[],r=!1,s=()=>{e.removeListener("data",i),e.removeListener("end",a),e.removeListener("error",l),clearTimeout(c)},o=u=>{r||(r=!0,s(),t(u))},i=u=>{n.push(typeof u=="string"?Buffer.from(u):u)},a=()=>{let u=Buffer.concat(n).toString("utf-8").trim();if(!u)return o(null);try{let m=JSON.parse(u);o(m&&typeof m=="object"?m:null)}catch{o(null)}},l=()=>o(null),c=setTimeout(()=>{n.length>0?a():o(null)},ol);e.on("data",i),e.on("end",a),e.on("error",l)})}function Xn(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${E(r||"",C.visaBlueSoft)}${E(s||"",C.dim)}`}function ls(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 Ho(e){if(_l(e))return cl(e);let t=` ${E("\u2502",C.dim)} `,n=us(e)||"claude",r=e.cwd?te(qe.basename(e.cwd)):"",s=ps(e.workspace),o=r||s,i=s&&s!==o?` ${E(`@${s}`,C.visaBlueSoft)}`:"",a=[E(`[${n}]`,C.visaBlueSoft)];o&&a.push(`${E(o,C.visaGold)}${i}`);let l=a.join(t),c=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,m=e.context_window?.current_usage,h=[m?.input_tokens,m?.output_tokens,m?.cache_creation_input_tokens,m?.cache_read_input_tokens].filter(U=>typeof U=="number"&&Number.isFinite(U)),v=h.length>0?h.reduce((U,J)=>U+J,0):null,g=Number(e.context_window?.total_input_tokens??v??m?.input_tokens??0),x=u!==null?Math.max(0,Math.min(1,u/100)):c>0?Math.max(0,Math.min(1,g/c)):0,O=u!==null&&c>0?Math.round(x*c):g,F;if(c>0||u!==null){let U=`${String(Math.round(x*100)).padStart(2," ")}%`,J=c>0?` ${E(`(${ls(O)}/${ls(c)})`,C.dim)}`:"";F=`${E("Context",C.dim)} ${Xn(x)} ${E(U,C.green)}${J}`}else F=`${E("Context",C.dim)} ${E("-",C.dim)}`;let j=ul(e.rate_limits),k=[F];j&&k.push(j);let P=k.join(t);return`${l}
25
- ${P}`}function cl(e){let t=` ${E("\u2502",C.dim)} `,n=ri(e),r=n.model||"codex",s=[E(`[${r}]`,C.visaBlueSoft)];n.project&&s.push(E(n.project,C.visaGold)),n.gitBranch&&s.push(`${E("git",C.dim)} ${E(n.gitBranch,C.visaGold)}`);let o=s.join(t),i=[];if(typeof n.contextUsedPercent=="number"){let l=Math.max(0,Math.min(1,n.contextUsedPercent/100));i.push(`${E("Context",C.dim)} ${Xn(l)} ${E(`${Math.round(n.contextUsedPercent)}%`,C.green)}`)}else if(typeof n.contextRemainingPercent=="number"){let l=100-n.contextRemainingPercent,c=Math.max(0,Math.min(1,l/100));i.push(`${E("Context",C.dim)} ${Xn(c)} ${E(`${Math.round(l)}%`,C.green)}`)}typeof n.usedTokens=="number"&&i.push(`${E("Tokens",C.dim)} ${ls(n.usedTokens)}`),n.status&&i.push(`${E("Status",C.dim)} ${E(n.status,C.visaBlueSoft)}`),n.threadTitle&&i.push(`${E("Thread",C.dim)} ${E(n.threadTitle,C.visaBlueSoft)}`);let a=i.length>0?i.join(t):`${E("Context",C.dim)} ${E("-",C.dim)}`;return`${o}
26
- ${a}`}function ll(e){if(typeof e!="number"||e<=0)return"";let n=(e>1e12?e:e*1e3)-Date.now();if(n<=0||n>=10080*60*1e3)return"";let r=Math.floor(n/6e4),s=Math.floor(r/60),o=r%60;return s>0?`${s}h ${o}m`:`${o}m`}function Ko(e,t){if(!e||typeof e.used_percentage!="number")return null;let n=Math.max(0,Math.min(100,e.used_percentage)),r=n/100,s=Xn(r),o=n>=90?"\x1B[38;5;196m":n>=70?C.visaGold:C.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=ll(e.resets_at),l=a?` ${E(`(${a} / ${t})`,C.dim)}`:` ${E(`(${t})`,C.dim)}`;return`${s} ${E(i,o)}${l}`}function ul(e){if(!e)return null;let t=Ko(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?Ko(e.seven_day,"7d"):null;if(!t&&!r)return null;let s=` ${E("\u2502",C.dim)} `,o=[t,r].filter(Boolean);return`${E("Usage",C.dim)} ${o.join(s)}`}function Jo(e){let t;try{let n=Ve.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let s=Math.min(r,il),o=r-s;t=Ve.openSync(e,"r");let i=Buffer.alloc(s);Ve.readSync(t,i,0,s,o);let a=i.toString("utf-8");if(o>0){let l=Buffer.alloc(1);if(Ve.readSync(t,l,0,1,o-1),l[0]!==10){let c=a.indexOf(`
27
- `);c>=0&&(a=a.slice(c+1))}}return a}catch{return null}finally{if(t!==void 0)try{Ve.closeSync(t)}catch{}}}function dl(e){if(!e||typeof e!="object")return;let t=e,n=["file_path","path","notebook_path","pattern","command","url"];for(let r of n){let s=t[r];if(typeof s=="string"&&s.length>0){if(r.endsWith("_path")||r==="path"){let o=qe.basename(qe.dirname(s)),i=qe.basename(s);return o&&o!=="."&&o!=="/"?`${o}/${i}`:i}return s}}}function ml(e){let t=e.split(`
28
- `),n=[],r=new Set;for(let s=t.length-1;s>=0&&n.length<Fo*3;s-=1){let o=t[s].trim();if(!o)continue;let i;try{i=JSON.parse(o)}catch{continue}if(!i||typeof i!="object")continue;let l=i.message;if(!l||typeof l!="object")continue;let c=l.content;if(Array.isArray(c))for(let u of c){if(!u||typeof u!="object")continue;let m=u;if(m.type==="tool_result"&&typeof m.tool_use_id=="string")r.add(m.tool_use_id);else if(m.type==="tool_use"&&typeof m.name=="string"){let h=typeof m.id=="string"?m.id:"",v=h.length>0?!r.has(h):!1;n.push({name:m.name,target:dl(m.input),running:v})}}}return n.reverse(),n.slice(Math.max(0,n.length-Fo))}function pl(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 fl(e){let t=e.running?E("\u25D0",C.visaGold):E("\u2713",C.green),n=e.running?C.visaGold:C.visaBlueSoft,r=E(te(e.name),n),s=e.target?te(e.target):"",o=s?`${E(":",C.dim)} ${E(s,C.dim)}`:"",i=e.count>1?` ${E(`\xD7${e.count}`,C.dim)}`:"";return o?`${t} ${r}${o}${i}`:`${t} ${r}${i}`}function gl(e){let t=` ${E("\u2502",C.dim)} `,n=Bo(t),r=e.slice();for(;r.length>0;){let l=r.join(t);if(Bo(l)<=as)return l;r=r.slice(1)}if(e.length===0)return"";let s="\u2026",i=e[e.length-1].replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,""),a=i.length>as-n-1?i.slice(0,as-n-1)+s:i;return`${E(s,C.dim)}${t}${a}`}async function Go(e){if(!e||typeof e!="string")return null;let t=Jo(e);if(!t)return null;let n;try{n=ml(t)}catch{return null}if(n.length===0)return null;let s=pl(n).map(fl);return gl(s)||null}async function Yo(e,t,n){return(await Xo(e,t,n)).join(`
29
- `)}function Zo(e,t,n){let r=!!t?.activeSession||e.includes("in session"),s=n?yl(n):!1;return{isActive:r||s,hasSession:r,hasToolActivity:s}}async function Xo(e,t,n){let{isActive:r}=Zo(e,n,t?.transcript_path);if(t&&!r){let o=[],i=Ho(t);if(i&&o.push(...i.split(`
30
- `)),t.transcript_path){let l=await Go(t.transcript_path);l&&o.push(...l.split(`
31
- `))}let a=E(ds(e),C.dim);return o.push(a),o}let s=[e];if(t){let o=Ho(t);if(o&&s.push(...o.split(`
32
- `)),t.transcript_path){let i=await Go(t.transcript_path);i&&s.push(...i.split(`
33
- `))}}return s}var hl=["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 yl(e){let t=Jo(e);if(!t)return!1;let n=t.slice(-16384).toLowerCase();return hl.some(r=>n.includes(`"${r}"`))}async function Qo(e,t,n){let r=await Xo(e,t,n),s=r.join(`
34
- `),{isActive:o}=Zo(e,n,t?.transcript_path);return{schemaVersion:rl,client:t?ni(t):vt.UNKNOWN,rendered:s,lines:r.map(ds),visa:{spendLine:ds(e),balanceCents:n?.balanceCents,balanceUsd:n?.amountUsd,sessionMode:n?.sessionMode,activeSession:n?.activeSession,isVisaActive:o},context:t?ri(t):{}}}function te(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 ps(e){if(typeof e=="string")return te(qe.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 te(t?qe.basename(t):e.name)}function ei(e){return te(e.app_name??e.appName??e.app??e.client)}function us(e){return te(e.model?.display_name??e.model?.id??e.model_name??e.modelName)}function ti(e){return te(e.cwd??e.current_dir??e.project_root)}function zo(e){let t=te(e.project);if(t)return t;let n=ti(e);if(n)return te(qe.basename(n));let r=ps(e.workspace);return r||""}function ke(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function ni(e){let t=ei(e).toLowerCase();return t.includes("codex")?vt.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?vt.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||ke(e.context_used)!==void 0?vt.CODEX:vt.UNKNOWN}function _l(e){return ni(e)===vt.CODEX}function ri(e){let t=ei(e),n=ti(e),r=ps(e.workspace),s=ke(e.context_used)??ke(e.context_window?.used_percentage??void 0),o=ke(e.context_remaining)??ke(e.context_window?.remaining_percentage??void 0);return{...t?{app:t}:{},...us(e)?{model:us(e)}:{},...zo(e)?{project:zo(e)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...te(e.git_branch??e.branch)?{gitBranch:te(e.git_branch??e.branch)}:{},...te(e.status??e.run_state??e.runState)?{status:te(e.status??e.run_state??e.runState)}:{},...te(e.thread_title??e.threadTitle)?{threadTitle:te(e.thread_title??e.threadTitle)}:{},...s!==void 0?{contextUsedPercent:s}:{},...o!==void 0?{contextRemainingPercent:o}:{},...ke(e.used_tokens)!==void 0?{usedTokens:ke(e.used_tokens)}:{},...ke(e.total_input_tokens)!==void 0?{totalInputTokens:ke(e.total_input_tokens)}:{},...ke(e.total_output_tokens)!==void 0?{totalOutputTokens:ke(e.total_output_tokens)}:{}}}function ds(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}async function bt(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,s=setTimeout(()=>r.abort(),n);try{let{timeoutMs:o,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(s)}}var ne=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(t,n,r,s,o,i,a,l){super(t),this.name="CardDeclinedError",this.retryable=n,this.code=r,this.reason=s,this.paymentErrorClass=o,this.correlationId=i,this.transactionId=a,this.retryAfter=l}};var si={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 fs(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&&si[n]?si[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 vl=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function ii(e,t){let n=oi(e),r=oi(t);if(!n||!r)return!1;for(let s=0;s<3;s++)if(n.main[s]!==r.main[s])return n.main[s]>r.main[s];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:bl(n.pre,r.pre)>0}function oi(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(vl);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function bl(e,t){let n=e.split("."),r=t.split("."),s=Math.max(n.length,r.length);for(let o=0;o<s;o++){if(o>=n.length)return-1;if(o>=r.length)return 1;let i=n[o],a=r[o],l=/^\d+$/.test(i),c=/^\d+$/.test(a);if(l&&c){let u=Number(i)-Number(a);if(u!==0)return u}else{if(l)return-1;if(c)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function Me(){return!!(ai(process.env.VISA_CLI_NO_UPDATE_CHECK)||ai(process.env.CI)||process.env.NODE_ENV==="test")}function ai(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var rt=A(require("fs")),ui=A(require("path"));var Qn=A(require("fs")),ci=A(require("path")),li=A(require("os"));var gs=ci.join(li.homedir(),".visa-mcp"),pn=class{static ensureConfigDir(){Qn.existsSync(gs)||Qn.mkdirSync(gs,{recursive:!0,mode:448})}static getConfigDir(){return gs}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}};var Sl="settings.json";function fn(){return ui.join(pn.getConfigDir(),Sl)}var st={"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");let t;try{t=new URL(e)}catch{throw new Error(`auth.serverUrl must be a valid URL (got: ${JSON.stringify(e)})`)}if(t.protocol!=="https:"&&t.protocol!=="http:")throw new Error(`auth.serverUrl must use http or https (got: ${t.protocol})`)}},"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_music, ...). Restart required.",requiresRestart:!0},"tools.discover":{type:"boolean",description:"Show the dynamic-catalog tools (discover_tools, execute_tool). Restart required.",requiresRestart:!0},"merchants.discover":{type:"string",description:'Platform-merchant JIT tool discovery: "all" = every live merchant, "off" = none, comma-separated slugs = exactly those. Equivalent to VISA_MERCHANT_DISCOVER / VISA_MERCHANT_SLUGS env. Restart required.',requiresRestart:!0,validate:e=>{if(typeof e!="string")throw new Error("merchants.discover must be a string");let t=e.trim().toLowerCase();if(t===""||t==="all"||t==="off"||t==="*")return;let n=/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/,r=e.split(",").map(s=>s.trim()).filter(Boolean);for(let s of r)if(!n.test(s))throw new Error(`merchants.discover: "${s}" is not a valid merchant slug`)}},"credit.sessionCapCents":{type:"number",description:"Default cap (in cents) for start_session and pay-as-you-go one-shot approvals. Server clamps to [100, 10000] = $1\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<100||e>1e4)throw new Error("credit.sessionCapCents must be between 100 ($1) and 10000 ($100)")}}},ys=500,er={"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 St(){let e=fn();if(!rt.existsSync(e))return{};try{let t=rt.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?{}:n}catch{return{}}}function hs(e){pn.ensureConfigDir();let t=fn(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
35
- `;rt.writeFileSync(n,r,{mode:384}),rt.renameSync(n,t)}function _s(e){let t=St()[e];return typeof t=="string"?t:void 0}function tr(e){let t=St()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function vs(e){let t=St()[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 Fe=class extends Error{constructor(t){let n=Object.keys(st).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"}},Be=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"}},nt=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+er[t]),this.name="RetiredSettingKeyError"}},di=["biometric.","spending.","account.","cards.","biometric"];function nr(e,t){if(di.some(o=>e.startsWith(o)))throw new Be(e);if(e in er)throw new nt(e);let n=st[e];if(!n)throw new Fe(e);let r;if(n.type==="boolean")if(typeof t=="boolean")r=t;else if(typeof t=="string"){let o=t.toLowerCase();if(o==="true")r=!0;else if(o==="false")r=!1;else throw new Error(`${e} expects true or false (got: ${JSON.stringify(t)})`)}else throw new Error(`${e} expects a boolean (got: ${typeof t})`);else if(n.type==="number")if(typeof t=="number")r=t;else if(typeof t=="string"&&t.trim().length>0){let o=Number(t);if(!Number.isFinite(o))throw new Error(`${e} expects a number (got: ${JSON.stringify(t)})`);r=o}else throw new Error(`${e} expects a number (got: ${typeof t})`);else{if(typeof t!="string"||t.length===0)throw new Error(`${e} expects a non-empty string`);r=t}n.validate&&n.validate(r);let s=St();return s[e]=r,hs(s),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:fn()}}function rr(e){if(di.some(o=>e.startsWith(o)))throw new Be(e);let t=st[e];if(e in er){let o=St(),i=e in o;return i&&(delete o[e],hs(o)),{key:e,removed:i,requiresRestart:!1,path:fn()}}if(!t)throw new Fe(e);let r=St(),s=e in r;return s&&(delete r[e],hs(r)),{key:e,removed:s,requiresRestart:s&&!!t.requiresRestart,path:fn()}}function mi(){let e=St();return Object.entries(er).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}var wl="https://auth.visacli.sh",xl="https://auth-visa-code-preview.up.railway.app";function Cl(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function kl(){try{let e=Gn();return Cl(e.version)}catch{return!1}}function Tl(e){return e.envVar!==void 0&&e.envVar!==""?e.envVar:e.settingValue!==void 0?e.settingValue:e.isPrerelease?xl:wl}function _e(){return Tl({envVar:process.env.VISA_AUTH_URL,settingValue:_s("auth.serverUrl"),isPrerelease:kl()})}function pi(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":tr("ui.suppressBrowser")??!1}function fi(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":tr("ui.suppressFeed")??!1}function sr(){let e=process.env.VISA_CREDIT_SESSION_CAP_CENTS;if(e!==void 0){let n=Number(e);if(Number.isFinite(n)&&n>=100&&n<=1e4)return Math.floor(n)}let t=vs("credit.sessionCapCents");return t!==void 0&&t>=100&&t<=1e4?Math.floor(t):ys}var gn="2.0.0-rc.42",Al=/^vk_[A-Za-z0-9_-]{32,}$/;function gi(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?Al.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 vk_<32+ base64url chars>)."),n.push("Create a new token with: visa-cli tokens 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(`
36
- `)}var ve=class{constructor(t){this.getSessionToken=t;this.baseUrl=_e()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!Me()){let r=t.headers.get("X-Latest-Version");r&&ii(r,gn)&&(this.lastSignals.updateAvailable={currentVersion:gn,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return gn}async request(t,n,r,s,o,i){let a=await this.getSessionToken();if(!a)throw new Error(gi());let l={Authorization:`Bearer ${a}`};o&&(t==="GET"?l["X-User-Context"]=encodeURIComponent(o.replace(/[\r\n\0]/g," ").slice(0,1e3)):r={...r||{},user_context:o}),i&&(l["X-Visa-Meta-Tool"]=i),r&&(l["Content-Type"]="application/json");let c;try{c=await bt(`${this.baseUrl}${n}`,{method:t,headers:{...l,"X-Visa-CLI-Version":gn,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:s})}catch(m){throw new Error(fs(m))}if(this.parseServerSignals(c),c.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(c.status===429){let m=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${m}s. Tip: use the batch tool to combine multiple requests into one.`)}if(c.status===503)throw new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status.");let u;try{u=await c.json()}catch{throw c.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(!c.ok){if(c.status===500)throw new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`);if(u?.declined){let m=Number(u.retryAfter??c.headers.get("Retry-After"));throw new ne(u.error||"Your card was declined.",!!u.retryable,u.code,u.reason,u.payment_error_class,u.correlation_id,u.transactionId,Number.isFinite(m)&&m>0?m:void 0)}if(c.status===402){let m=u?.error||"Gateway returned 402";throw new Error(`${m}. This usually means your daily or per-transaction spending limit has been reached. Check your limits with get_status or run: visa-cli update-spending-controls`)}throw new Error(u?.error||`Request failed (${c.status}). Try again.`)}return u}async pay(t,n){return this.request("POST","/v1/pay",t,void 0,n)}async shortcut(t,n,r,s,o){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,s,o)}async shortcutWithSession(t,n,r,s,o,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,l=await this.getSessionToken();if(!l)throw new Error(gi());let c={Authorization:`Bearer ${l}`,"X-Visa-CLI-Version":gn,"X-Source":"cli","Content-Type":"application/json"};i&&(c["X-Visa-Meta-Tool"]=i);let u={...n,...r};o&&(u.user_context=o.replace(/[\r\n\0]/g," ").slice(0,1e3));let m;try{m=await bt(`${this.baseUrl}${a}`,{method:"POST",headers:c,body:JSON.stringify(u),timeoutMs:s})}catch(g){throw new Error(fs(g))}if(this.parseServerSignals(m),m.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(m.status===429){let g=m.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.`)}if(m.status===503)throw new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status.");let h=m.headers.get("X-Voucher-Receipt"),v;try{v=await m.json()}catch{throw m.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${a}. Try again.`)}if(!m.ok){if(m.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(v?.declined){let g=Number(v.retryAfter??m.headers.get("Retry-After"));throw new ne(v.error||"Your card was declined.",!!v.retryable,v.code,v.reason,v.payment_error_class,v.correlation_id,v.transactionId,Number.isFinite(g)&&g>0?g:void 0)}throw new Error(v?.error||`Request failed (${m.status}). Try again.`)}return{data:v,voucherReceiptHeader:h}}async batch(t,n,r){return this.request("POST","/v1/batch",t,n,r)}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async catalogSearch(t,n,r){let s=r??"discover_tools",o=new URLSearchParams;t&&o.set("q",t),n&&o.set("category",n);let i=o.toString();return this.request("GET",`/v1/catalog${i?`?${i}`:""}`,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 bt(`${this.baseUrl}/v1/platform/merchants/public`,{method:"GET",timeoutMs:8e3});if(!t.ok)return[];let n=await t.json();return Array.isArray(n.merchants)?n.merchants:[]}catch{return[]}}async getPublicMerchantDiscover(t){try{let n=await bt(`${this.baseUrl}/v1/platform/discover/${encodeURIComponent(t)}`,{method:"GET",timeoutMs:8e3});return n.ok?await n.json():null}catch{return null}}async paymentPreview(t,n){return this.request("POST","/v1/payment-preview",t,void 0,n)}async getBalance(){return this.request("GET","/v1/balance")}async topupBalance(t){return this.request("POST","/v1/balance/topup",t)}async createSessionBudget(t){return this.request("POST","/v1/session-budget/create",{...t,mode:"prepaid"})}async closeSession(t){return this.request("POST","/v1/session/close",{session_budget_id:t})}async getSessionBudget(t){return this.request("GET",`/v1/session-budget/${encodeURIComponent(t)}`)}async getSessionLedger(t){return this.request("GET",`/v1/session/${encodeURIComponent(t)}/ledger`)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getVisaSmi(t,n){return this.request("POST","/v1/visa/smi",t,6e4,n)}async getTransactions(t,n){let r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.offset!=null&&r.set("offset",String(t.offset));let s=r.toString(),o=s?`/v1/transactions?${s}`:"/v1/transactions";return this.request("GET",o,void 0,void 0,n)}async updateSpendingControls(t,n){return this.request("POST","/v1/spending-controls",t,void 0,n)}async removeCard(t,n,r){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(t))}`,n,void 0,r)}async setDefaultCard(t,n,r){return this.request("POST",`/v1/cards/${encodeURIComponent(String(t))}/default`,n,void 0,r)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t){return this.request("POST","/v1/attestation-key",{publicKey:t})}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(){return this.request("GET","/v1/api/keys")}async revokeAppApiKey(t){return this.request("DELETE",`/v1/api/keys/${encodeURIComponent(String(t))}`)}async feedSubmit(t){return this.request("POST","/v1/feed",t)}async feedList(t){let n=new URLSearchParams;t?.tab&&n.set("tab",t.tab),t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset));let r=n.toString();return this.request("GET",`/v1/feed${r?"?"+r:""}`)}async feedVote(t,n){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/vote`,{direction:n})}async feedApprove(t){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/approve`)}async feedDelete(t){return this.request("DELETE",`/v1/feed/${encodeURIComponent(t)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async getFeedback(t,n){let r=new URLSearchParams;t&&r.set("limit",String(t));let s=r.toString();return this.request("GET",`/v1/feedback${s?"?"+s:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}};var p={};$o(p,{BRAND:()=>Ql,DIRTY:()=>wt,EMPTY_PATH:()=>Il,INVALID:()=>S,NEVER:()=>Du,OK:()=>ie,ParseStatus:()=>re,Schema:()=>I,ZodAny:()=>at,ZodArray:()=>ze,ZodBigInt:()=>Ct,ZodBoolean:()=>kt,ZodBranded:()=>yn,ZodCatch:()=>Ut,ZodDate:()=>Tt,ZodDefault:()=>Nt,ZodDiscriminatedUnion:()=>ar,ZodEffects:()=>we,ZodEnum:()=>Mt,ZodError:()=>de,ZodFirstPartyTypeKind:()=>w,ZodFunction:()=>lr,ZodIntersection:()=>Rt,ZodIssueCode:()=>f,ZodLazy:()=>It,ZodLiteral:()=>Pt,ZodMap:()=>Gt,ZodNaN:()=>Wt,ZodNativeEnum:()=>Ot,ZodNever:()=>Te,ZodNull:()=>Et,ZodNullable:()=>Ue,ZodNumber:()=>xt,ZodObject:()=>me,ZodOptional:()=>be,ZodParsedType:()=>_,ZodPipeline:()=>_n,ZodPromise:()=>ct,ZodReadonly:()=>Dt,ZodRecord:()=>cr,ZodSchema:()=>I,ZodSet:()=>zt,ZodString:()=>it,ZodSymbol:()=>Ht,ZodTransformer:()=>we,ZodTuple:()=>Ne,ZodType:()=>I,ZodUndefined:()=>At,ZodUnion:()=>$t,ZodUnknown:()=>Ge,ZodVoid:()=>Kt,addIssueToContext:()=>y,any:()=>cu,array:()=>mu,bigint:()=>ru,boolean:()=>Ti,coerce:()=>Uu,custom:()=>xi,date:()=>su,datetimeRegex:()=>Si,defaultErrorMap:()=>He,discriminatedUnion:()=>hu,effect:()=>Eu,enum:()=>ku,function:()=>wu,getErrorMap:()=>qt,getParsedType:()=>Oe,instanceof:()=>tu,intersection:()=>yu,isAborted:()=>or,isAsync:()=>Ft,isDirty:()=>ir,isValid:()=>ot,late:()=>eu,lazy:()=>xu,literal:()=>Cu,makeIssue:()=>hn,map:()=>bu,nan:()=>nu,nativeEnum:()=>Tu,never:()=>uu,null:()=>au,nullable:()=>Ru,number:()=>ki,object:()=>pu,objectUtil:()=>bs,oboolean:()=>Nu,onumber:()=>Ou,optional:()=>$u,ostring:()=>Mu,pipeline:()=>Pu,preprocess:()=>Iu,promise:()=>Au,quotelessJson:()=>El,record:()=>vu,set:()=>Su,setErrorMap:()=>Rl,strictObject:()=>fu,string:()=>Ci,symbol:()=>ou,transformer:()=>Eu,tuple:()=>_u,undefined:()=>iu,union:()=>gu,unknown:()=>lu,util:()=>M,void:()=>du});var M;(function(e){e.assertEqual=s=>{};function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{let o={};for(let i of s)o[i]=i;return o},e.getValidEnumValues=s=>{let o=e.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(let a of o)i[a]=s[a];return e.objectValues(i)},e.objectValues=s=>e.objectKeys(s).map(function(o){return s[o]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},e.find=(s,o)=>{for(let i of s)if(o(i))return i},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}e.joinValues=r,e.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(M||(M={}));var bs;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(bs||(bs={}));var _=M.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Oe=e=>{switch(typeof e){case"undefined":return _.undefined;case"string":return _.string;case"number":return Number.isNaN(e)?_.nan:_.number;case"boolean":return _.boolean;case"function":return _.function;case"bigint":return _.bigint;case"symbol":return _.symbol;case"object":return Array.isArray(e)?_.array:e===null?_.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?_.promise:typeof Map<"u"&&e instanceof Map?_.map:typeof Set<"u"&&e instanceof Set?_.set:typeof Date<"u"&&e instanceof Date?_.date:_.object;default:return _.unknown}};var f=M.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"]),El=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),de=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(o){return o.message},r={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,l=0;for(;l<i.path.length;){let c=i.path[l];l===i.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(i))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return s(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,M.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];n[o]=n[o]||[],n[o].push(t(s))}else r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};de.create=e=>new de(e);var $l=(e,t)=>{let n;switch(e.code){case f.invalid_type:e.received===_.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case f.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,M.jsonStringifyReplacer)}`;break;case f.unrecognized_keys:n=`Unrecognized key(s) in object: ${M.joinValues(e.keys,", ")}`;break;case f.invalid_union:n="Invalid input";break;case f.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${M.joinValues(e.options)}`;break;case f.invalid_enum_value:n=`Invalid enum value. Expected ${M.joinValues(e.options)}, received '${e.received}'`;break;case f.invalid_arguments:n="Invalid function arguments";break;case f.invalid_return_type:n="Invalid function return type";break;case f.invalid_date:n="Invalid date";break;case f.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}"`:M.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case f.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 f.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 f.custom:n="Invalid input";break;case f.invalid_intersection_types:n="Intersection results could not be merged";break;case f.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case f.not_finite:n="Number must be finite";break;default:n=t.defaultError,M.assertNever(e)}return{message:n}},He=$l;var hi=He;function Rl(e){hi=e}function qt(){return hi}var hn=e=>{let{data:t,path:n,errorMaps:r,issueData:s}=e,o=[...n,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)a=c(i,{data:t,defaultError:a}).message;return{...s,path:o,message:a}},Il=[];function y(e,t){let n=qt(),r=hn({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===He?void 0:He].filter(s=>!!s)});e.common.issues.push(r)}var re=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let s of n){if(s.status==="aborted")return S;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let s of n){let o=await s.key,i=await s.value;r.push({key:o,value:i})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let s of n){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return S;o.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(r[o.value]=i.value)}return{status:t.value,value:r}}},S=Object.freeze({status:"aborted"}),wt=e=>({status:"dirty",value:e}),ie=e=>({status:"valid",value:e}),or=e=>e.status==="aborted",ir=e=>e.status==="dirty",ot=e=>e.status==="valid",Ft=e=>typeof Promise<"u"&&e instanceof Promise;var b;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(b||(b={}));var Se=class{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},yi=(e,t)=>{if(ot(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 de(e.common.issues);return this._error=n,this._error}}};function T(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(i,a)=>{let{message:l}=e;return i.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:s}}var I=class{get description(){return this._def.description}_getType(t){return Oe(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Oe(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new re,ctx:{common:t.parent.common,data:t.data,parsedType:Oe(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Ft(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:Oe(t)},s=this._parseSync({data:t,path:r.path,parent:r});return yi(r,s)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Oe(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return ot(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=>ot(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:Oe(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(Ft(s)?s:Promise.resolve(s));return yi(r,o)}refine(t,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{let i=t(s),a=()=>o.addIssue({code:f.custom,...r(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new we({schema:this,typeName:w.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 be.create(this,this._def)}nullable(){return Ue.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ze.create(this)}promise(){return ct.create(this,this._def)}or(t){return $t.create([this,t],this._def)}and(t){return Rt.create(this,t,this._def)}transform(t){return new we({...T(this._def),schema:this,typeName:w.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new Nt({...T(this._def),innerType:this,defaultValue:n,typeName:w.ZodDefault})}brand(){return new yn({typeName:w.ZodBranded,type:this,...T(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new Ut({...T(this._def),innerType:this,catchValue:n,typeName:w.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return _n.create(this,t)}readonly(){return Dt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Pl=/^c[^\s-]{8,}$/i,Ml=/^[0-9a-z]+$/,Ol=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Nl=/^[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,Ul=/^[a-z0-9_-]{21}$/i,Dl=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ll=/^[-+]?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)?)??$/,jl=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Vl="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ss,ql=/^(?:(?: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])$/,Fl=/^(?:(?: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])$/,Bl=/^(([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]))$/,Hl=/^(([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])$/,Kl=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Gl=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,vi="((\\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])))",zl=new RegExp(`^${vi}$`);function bi(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 Wl(e){return new RegExp(`^${bi(e)}$`)}function Si(e){let t=`${vi}T${bi(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 Jl(e,t){return!!((t==="v4"||!t)&&ql.test(e)||(t==="v6"||!t)&&Bl.test(e))}function Yl(e,t){if(!Dl.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||t&&s.alg!==t)}catch{return!1}}function Zl(e,t){return!!((t==="v4"||!t)&&Fl.test(e)||(t==="v6"||!t)&&Hl.test(e))}var it=class e extends I{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==_.string){let o=this._getOrReturnCtx(t);return y(o,{code:f.invalid_type,expected:_.string,received:o.parsedType}),S}let r=new re,s;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(s=this._getOrReturnCtx(t,s),y(s,{code:f.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")t.data.length>o.value&&(s=this._getOrReturnCtx(t,s),y(s,{code:f.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){let i=t.data.length>o.value,a=t.data.length<o.value;(i||a)&&(s=this._getOrReturnCtx(t,s),i?y(s,{code:f.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&y(s,{code:f.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")jl.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"email",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")Ss||(Ss=new RegExp(Vl,"u")),Ss.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"emoji",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")Nl.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"uuid",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")Ul.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"nanoid",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")Pl.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"cuid",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")Ml.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"cuid2",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")Ol.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"ulid",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),y(s,{validation:"url",code:f.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"regex",code:f.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(t,s),y(s,{code:f.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(s=this._getOrReturnCtx(t,s),y(s,{code:f.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(s=this._getOrReturnCtx(t,s),y(s,{code:f.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?Si(o).test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{code:f.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?zl.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{code:f.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?Wl(o).test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{code:f.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?Ll.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"duration",code:f.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?Jl(t.data,o.version)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"ip",code:f.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?Yl(t.data,o.alg)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"jwt",code:f.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?Zl(t.data,o.version)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"cidr",code:f.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?Kl.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"base64",code:f.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?Gl.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"base64url",code:f.invalid_string,message:o.message}),r.dirty()):M.assertNever(o);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:f.invalid_string,...b.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...b.errToObj(t)})}url(t){return this._addCheck({kind:"url",...b.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...b.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...b.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...b.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...b.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...b.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...b.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...b.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...b.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...b.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...b.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...b.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,...b.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,...b.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...b.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...b.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...b.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...b.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...b.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...b.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...b.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...b.errToObj(n)})}nonempty(t){return this.min(1,b.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}};it.create=e=>new it({checks:[],typeName:w.ZodString,coerce:e?.coerce??!1,...T(e)});function Xl(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,o=Number.parseInt(e.toFixed(s).replace(".","")),i=Number.parseInt(t.toFixed(s).replace(".",""));return o%i/10**s}var xt=class e extends I{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)!==_.number){let o=this._getOrReturnCtx(t);return y(o,{code:f.invalid_type,expected:_.number,received:o.parsedType}),S}let r,s=new re;for(let o of this._def.checks)o.kind==="int"?M.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{code:f.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),y(r,{code:f.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),y(r,{code:f.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?Xl(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),y(r,{code:f.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{code:f.not_finite,message:o.message}),s.dirty()):M.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,b.toString(n))}gt(t,n){return this.setLimit("min",t,!1,b.toString(n))}lte(t,n){return this.setLimit("max",t,!0,b.toString(n))}lt(t,n){return this.setLimit("max",t,!1,b.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:b.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:b.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:b.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:b.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:b.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:b.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:b.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:b.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:b.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:b.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"&&M.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)}};xt.create=e=>new xt({checks:[],typeName:w.ZodNumber,coerce:e?.coerce||!1,...T(e)});var Ct=class e extends I{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)!==_.bigint)return this._getInvalidInput(t);let r,s=new re;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),y(r,{code:f.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),y(r,{code:f.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),y(r,{code:f.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):M.assertNever(o);return{status:s.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return y(n,{code:f.invalid_type,expected:_.bigint,received:n.parsedType}),S}gte(t,n){return this.setLimit("min",t,!0,b.toString(n))}gt(t,n){return this.setLimit("min",t,!1,b.toString(n))}lte(t,n){return this.setLimit("max",t,!0,b.toString(n))}lt(t,n){return this.setLimit("max",t,!1,b.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:b.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:b.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:b.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:b.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:b.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:b.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}};Ct.create=e=>new Ct({checks:[],typeName:w.ZodBigInt,coerce:e?.coerce??!1,...T(e)});var kt=class extends I{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==_.boolean){let r=this._getOrReturnCtx(t);return y(r,{code:f.invalid_type,expected:_.boolean,received:r.parsedType}),S}return ie(t.data)}};kt.create=e=>new kt({typeName:w.ZodBoolean,coerce:e?.coerce||!1,...T(e)});var Tt=class e extends I{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==_.date){let o=this._getOrReturnCtx(t);return y(o,{code:f.invalid_type,expected:_.date,received:o.parsedType}),S}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return y(o,{code:f.invalid_date}),S}let r=new re,s;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(s=this._getOrReturnCtx(t,s),y(s,{code:f.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(s=this._getOrReturnCtx(t,s),y(s,{code:f.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):M.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:b.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:b.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}};Tt.create=e=>new Tt({checks:[],coerce:e?.coerce||!1,typeName:w.ZodDate,...T(e)});var Ht=class extends I{_parse(t){if(this._getType(t)!==_.symbol){let r=this._getOrReturnCtx(t);return y(r,{code:f.invalid_type,expected:_.symbol,received:r.parsedType}),S}return ie(t.data)}};Ht.create=e=>new Ht({typeName:w.ZodSymbol,...T(e)});var At=class extends I{_parse(t){if(this._getType(t)!==_.undefined){let r=this._getOrReturnCtx(t);return y(r,{code:f.invalid_type,expected:_.undefined,received:r.parsedType}),S}return ie(t.data)}};At.create=e=>new At({typeName:w.ZodUndefined,...T(e)});var Et=class extends I{_parse(t){if(this._getType(t)!==_.null){let r=this._getOrReturnCtx(t);return y(r,{code:f.invalid_type,expected:_.null,received:r.parsedType}),S}return ie(t.data)}};Et.create=e=>new Et({typeName:w.ZodNull,...T(e)});var at=class extends I{constructor(){super(...arguments),this._any=!0}_parse(t){return ie(t.data)}};at.create=e=>new at({typeName:w.ZodAny,...T(e)});var Ge=class extends I{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ie(t.data)}};Ge.create=e=>new Ge({typeName:w.ZodUnknown,...T(e)});var Te=class extends I{_parse(t){let n=this._getOrReturnCtx(t);return y(n,{code:f.invalid_type,expected:_.never,received:n.parsedType}),S}};Te.create=e=>new Te({typeName:w.ZodNever,...T(e)});var Kt=class extends I{_parse(t){if(this._getType(t)!==_.undefined){let r=this._getOrReturnCtx(t);return y(r,{code:f.invalid_type,expected:_.void,received:r.parsedType}),S}return ie(t.data)}};Kt.create=e=>new Kt({typeName:w.ZodVoid,...T(e)});var ze=class e extends I{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==_.array)return y(n,{code:f.invalid_type,expected:_.array,received:n.parsedType}),S;if(s.exactLength!==null){let i=n.data.length>s.exactLength.value,a=n.data.length<s.exactLength.value;(i||a)&&(y(n,{code:i?f.too_big:f.too_small,minimum:a?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(y(n,{code:f.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(y(n,{code:f.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>s.type._parseAsync(new Se(n,i,n.path,a)))).then(i=>re.mergeArray(r,i));let o=[...n.data].map((i,a)=>s.type._parseSync(new Se(n,i,n.path,a)));return re.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:b.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:b.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:b.toString(n)}})}nonempty(t){return this.min(1,t)}};ze.create=(e,t)=>new ze({type:e,minLength:null,maxLength:null,exactLength:null,typeName:w.ZodArray,...T(t)});function Bt(e){if(e instanceof me){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=be.create(Bt(r))}return new me({...e._def,shape:()=>t})}else return e instanceof ze?new ze({...e._def,type:Bt(e.element)}):e instanceof be?be.create(Bt(e.unwrap())):e instanceof Ue?Ue.create(Bt(e.unwrap())):e instanceof Ne?Ne.create(e.items.map(t=>Bt(t))):e}var me=class e extends I{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=M.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==_.object){let c=this._getOrReturnCtx(t);return y(c,{code:f.invalid_type,expected:_.object,received:c.parsedType}),S}let{status:r,ctx:s}=this._processInputParams(t),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Te&&this._def.unknownKeys==="strip"))for(let c in s.data)i.includes(c)||a.push(c);let l=[];for(let c of i){let u=o[c],m=s.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Se(s,m,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Te){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(c==="strict")a.length>0&&(y(s,{code:f.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let u of a){let m=s.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Se(s,m,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of l){let m=await u.key,h=await u.value;c.push({key:m,value:h,alwaysSet:u.alwaysSet})}return c}).then(c=>re.mergeObjectSync(r,c)):re.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return b.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:b.errToObj(t).message??s}:{message:s}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:w.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 M.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 M.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return Bt(this)}partial(t){let n={};for(let r of M.objectKeys(this.shape)){let s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let r of M.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof be;)o=o._def.innerType;n[r]=o}return new e({...this._def,shape:()=>n})}keyof(){return wi(M.objectKeys(this.shape))}};me.create=(e,t)=>new me({shape:()=>e,unknownKeys:"strip",catchall:Te.create(),typeName:w.ZodObject,...T(t)});me.strictCreate=(e,t)=>new me({shape:()=>e,unknownKeys:"strict",catchall:Te.create(),typeName:w.ZodObject,...T(t)});me.lazycreate=(e,t)=>new me({shape:e,unknownKeys:"strip",catchall:Te.create(),typeName:w.ZodObject,...T(t)});var $t=class extends I{_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new de(a.ctx.common.issues));return y(n,{code:f.invalid_union,unionErrors:i}),S}if(n.common.async)return Promise.all(r.map(async o=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let l of r){let c={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(l=>new de(l));return y(n,{code:f.invalid_union,unionErrors:a}),S}}get options(){return this._def.options}};$t.create=(e,t)=>new $t({options:e,typeName:w.ZodUnion,...T(t)});var Ke=e=>e instanceof It?Ke(e.schema):e instanceof we?Ke(e.innerType()):e instanceof Pt?[e.value]:e instanceof Mt?e.options:e instanceof Ot?M.objectValues(e.enum):e instanceof Nt?Ke(e._def.innerType):e instanceof At?[void 0]:e instanceof Et?[null]:e instanceof be?[void 0,...Ke(e.unwrap())]:e instanceof Ue?[null,...Ke(e.unwrap())]:e instanceof yn||e instanceof Dt?Ke(e.unwrap()):e instanceof Ut?Ke(e._def.innerType):[],ar=class e extends I{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==_.object)return y(n,{code:f.invalid_type,expected:_.object,received:n.parsedType}),S;let r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(y(n,{code:f.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),S)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let s=new Map;for(let o of n){let i=Ke(o.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of i){if(s.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);s.set(a,o)}}return new e({typeName:w.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...T(r)})}};function ws(e,t){let n=Oe(e),r=Oe(t);if(e===t)return{valid:!0,data:e};if(n===_.object&&r===_.object){let s=M.objectKeys(t),o=M.objectKeys(e).filter(a=>s.indexOf(a)!==-1),i={...e,...t};for(let a of o){let l=ws(e[a],t[a]);if(!l.valid)return{valid:!1};i[a]=l.data}return{valid:!0,data:i}}else if(n===_.array&&r===_.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let o=0;o<e.length;o++){let i=e[o],a=t[o],l=ws(i,a);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return n===_.date&&r===_.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Rt=class extends I{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=(o,i)=>{if(or(o)||or(i))return S;let a=ws(o.value,i.value);return a.valid?((ir(o)||ir(i))&&n.dirty(),{status:n.value,value:a.data}):(y(r,{code:f.invalid_intersection_types}),S)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Rt.create=(e,t,n)=>new Rt({left:e,right:t,typeName:w.ZodIntersection,...T(n)});var Ne=class e extends I{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==_.array)return y(r,{code:f.invalid_type,expected:_.array,received:r.parsedType}),S;if(r.data.length<this._def.items.length)return y(r,{code:f.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S;!this._def.rest&&r.data.length>this._def.items.length&&(y(r,{code:f.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...r.data].map((i,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Se(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>re.mergeArray(n,i)):re.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ne.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ne({items:e,typeName:w.ZodTuple,rest:null,...T(t)})};var cr=class e extends I{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!==_.object)return y(r,{code:f.invalid_type,expected:_.object,received:r.parsedType}),S;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in r.data)s.push({key:o._parse(new Se(r,a,r.path,a)),value:i._parse(new Se(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?re.mergeObjectAsync(n,s):re.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof I?new e({keyType:t,valueType:n,typeName:w.ZodRecord,...T(r)}):new e({keyType:it.create(),valueType:t,typeName:w.ZodRecord,...T(n)})}},Gt=class extends I{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!==_.map)return y(r,{code:f.invalid_type,expected:_.map,received:r.parsedType}),S;let s=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([a,l],c)=>({key:s._parse(new Se(r,a,r.path,[c,"key"])),value:o._parse(new Se(r,l,r.path,[c,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of i){let c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return S;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let l of i){let c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return S;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}}}};Gt.create=(e,t,n)=>new Gt({valueType:t,keyType:e,typeName:w.ZodMap,...T(n)});var zt=class e extends I{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==_.set)return y(r,{code:f.invalid_type,expected:_.set,received:r.parsedType}),S;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(y(r,{code:f.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(y(r,{code:f.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let o=this._def.valueType;function i(l){let c=new Set;for(let u of l){if(u.status==="aborted")return S;u.status==="dirty"&&n.dirty(),c.add(u.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((l,c)=>o._parse(new Se(r,l,r.path,c)));return r.common.async?Promise.all(a).then(l=>i(l)):i(a)}min(t,n){return new e({...this._def,minSize:{value:t,message:b.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:b.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};zt.create=(e,t)=>new zt({valueType:e,minSize:null,maxSize:null,typeName:w.ZodSet,...T(t)});var lr=class e extends I{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==_.function)return y(n,{code:f.invalid_type,expected:_.function,received:n.parsedType}),S;function r(a,l){return hn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,qt(),He].filter(c=>!!c),issueData:{code:f.invalid_arguments,argumentsError:l}})}function s(a,l){return hn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,qt(),He].filter(c=>!!c),issueData:{code:f.invalid_return_type,returnTypeError:l}})}let o={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof ct){let a=this;return ie(async function(...l){let c=new de([]),u=await a._def.args.parseAsync(l,o).catch(v=>{throw c.addIssue(r(l,v)),c}),m=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(m,o).catch(v=>{throw c.addIssue(s(m,v)),c})})}else{let a=this;return ie(function(...l){let c=a._def.args.safeParse(l,o);if(!c.success)throw new de([r(l,c.error)]);let u=Reflect.apply(i,this,c.data),m=a._def.returns.safeParse(u,o);if(!m.success)throw new de([s(u,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Ne.create(t).rest(Ge.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||Ne.create([]).rest(Ge.create()),returns:n||Ge.create(),typeName:w.ZodFunction,...T(r)})}},It=class extends I{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})}};It.create=(e,t)=>new It({getter:e,typeName:w.ZodLazy,...T(t)});var Pt=class extends I{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return y(n,{received:n.data,code:f.invalid_literal,expected:this._def.value}),S}return{status:"valid",value:t.data}}get value(){return this._def.value}};Pt.create=(e,t)=>new Pt({value:e,typeName:w.ZodLiteral,...T(t)});function wi(e,t){return new Mt({values:e,typeName:w.ZodEnum,...T(t)})}var Mt=class e extends I{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return y(n,{expected:M.joinValues(r),received:n.parsedType,code:f.invalid_type}),S}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 y(n,{received:n.data,code:f.invalid_enum_value,options:r}),S}return ie(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};Mt.create=wi;var Ot=class extends I{_parse(t){let n=M.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==_.string&&r.parsedType!==_.number){let s=M.objectValues(n);return y(r,{expected:M.joinValues(s),received:r.parsedType,code:f.invalid_type}),S}if(this._cache||(this._cache=new Set(M.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let s=M.objectValues(n);return y(r,{received:r.data,code:f.invalid_enum_value,options:s}),S}return ie(t.data)}get enum(){return this._def.values}};Ot.create=(e,t)=>new Ot({values:e,typeName:w.ZodNativeEnum,...T(t)});var ct=class extends I{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==_.promise&&n.common.async===!1)return y(n,{code:f.invalid_type,expected:_.promise,received:n.parsedType}),S;let r=n.parsedType===_.promise?n.data:Promise.resolve(n.data);return ie(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};ct.create=(e,t)=>new ct({type:e,typeName:w.ZodPromise,...T(t)});var we=class extends I{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===w.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,o={addIssue:i=>{y(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(r.data,o);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return S;let l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?S:l.status==="dirty"?wt(l.value):n.value==="dirty"?wt(l.value):l});{if(n.value==="aborted")return S;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?S:a.status==="dirty"?wt(a.value):n.value==="dirty"?wt(a.value):a}}if(s.type==="refinement"){let i=a=>{let l=s.refinement(a,o);if(r.common.async)return Promise.resolve(l);if(l 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"?S:(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"?S:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(s.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ot(i))return S;let a=s.transform(i.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>ot(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:n.value,value:a})):S);M.assertNever(s)}};we.create=(e,t,n)=>new we({schema:e,typeName:w.ZodEffects,effect:t,...T(n)});we.createWithPreprocess=(e,t,n)=>new we({schema:t,effect:{type:"preprocess",transform:e},typeName:w.ZodEffects,...T(n)});var be=class extends I{_parse(t){return this._getType(t)===_.undefined?ie(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};be.create=(e,t)=>new be({innerType:e,typeName:w.ZodOptional,...T(t)});var Ue=class extends I{_parse(t){return this._getType(t)===_.null?ie(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ue.create=(e,t)=>new Ue({innerType:e,typeName:w.ZodNullable,...T(t)});var Nt=class extends I{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===_.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Nt.create=(e,t)=>new Nt({innerType:e,typeName:w.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...T(t)});var Ut=class extends I{_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Ft(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new de(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new de(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Ut.create=(e,t)=>new Ut({innerType:e,typeName:w.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...T(t)});var Wt=class extends I{_parse(t){if(this._getType(t)!==_.nan){let r=this._getOrReturnCtx(t);return y(r,{code:f.invalid_type,expected:_.nan,received:r.parsedType}),S}return{status:"valid",value:t.data}}};Wt.create=e=>new Wt({typeName:w.ZodNaN,...T(e)});var Ql=Symbol("zod_brand"),yn=class extends I{_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}},_n=class e extends I{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?S:o.status==="dirty"?(n.dirty(),wt(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?S:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:w.ZodPipeline})}},Dt=class extends I{_parse(t){let n=this._def.innerType._parse(t),r=s=>(ot(s)&&(s.value=Object.freeze(s.value)),s);return Ft(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Dt.create=(e,t)=>new Dt({innerType:e,typeName:w.ZodReadonly,...T(t)});function _i(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function xi(e,t={},n){return e?at.create().superRefine((r,s)=>{let o=e(r);if(o instanceof Promise)return o.then(i=>{if(!i){let a=_i(t,r),l=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:l})}});if(!o){let i=_i(t,r),a=i.fatal??n??!0;s.addIssue({code:"custom",...i,fatal:a})}}):at.create()}var eu={object:me.lazycreate},w;(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"})(w||(w={}));var tu=(e,t={message:`Input not instance of ${e.name}`})=>xi(n=>n instanceof e,t),Ci=it.create,ki=xt.create,nu=Wt.create,ru=Ct.create,Ti=kt.create,su=Tt.create,ou=Ht.create,iu=At.create,au=Et.create,cu=at.create,lu=Ge.create,uu=Te.create,du=Kt.create,mu=ze.create,pu=me.create,fu=me.strictCreate,gu=$t.create,hu=ar.create,yu=Rt.create,_u=Ne.create,vu=cr.create,bu=Gt.create,Su=zt.create,wu=lr.create,xu=It.create,Cu=Pt.create,ku=Mt.create,Tu=Ot.create,Au=ct.create,Eu=we.create,$u=be.create,Ru=Ue.create,Iu=we.createWithPreprocess,Pu=_n.create,Mu=()=>Ci().optional(),Ou=()=>ki().optional(),Nu=()=>Ti().optional(),Uu={string:(e=>it.create({...e,coerce:!0})),number:(e=>xt.create({...e,coerce:!0})),boolean:(e=>kt.create({...e,coerce:!0})),bigint:(e=>Ct.create({...e,coerce:!0})),date:(e=>Tt.create({...e,coerce:!0}))};var Du=S;var Ai=["tempo","mpp_self","merchant_self"];var xs=p.object({inputPerMillion:p.number().positive(),outputPerMillion:p.number().positive(),contextWindow:p.number().int().positive().optional(),maxOutput:p.number().int().positive().optional()}),Lu=p.object({strategy:p.enum(["flat","token","band"]).optional(),pricingModel:p.enum(["per-call","per-token","band"]).optional(),priceCents:p.number().nonnegative().optional(),currency:p.string().optional(),display:p.string().optional(),estimate:p.boolean().optional(),source:p.string().optional(),priceBand:p.record(p.unknown()).optional(),tokenPricing:xs.optional()}).passthrough(),Cs=p.discriminatedUnion("type",[p.object({type:p.literal("shortcut"),routedPath:p.string().min(1).startsWith("/")}),p.object({type:p.literal("custom"),merchantSlug:p.string().min(1),subPath:p.string().optional()}),p.object({type:p.literal("local"),fn:p.string().min(1)}),p.object({type:p.literal("read")})]),ks=p.object({amount:p.number().nonnegative(),currency:p.string().length(3).optional(),display:p.string().optional(),free:p.boolean().optional(),batchDiscount:p.number().min(0).max(100).optional()}),Ei=p.object({attestation:p.boolean().optional(),rateLimitMs:p.number().positive().optional()}),$i=p.object({displayName:p.string().optional(),feedbackEligible:p.boolean().optional(),suggestionEligible:p.boolean().optional(),batchable:p.boolean().optional()}),ju=p.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),Ts={id:p.string().min(1),name:p.string().min(1),description:p.string().min(1),provider:p.string().min(1),model:p.string().min(1),category:ju,priceCents:p.number().nonnegative(),inputSchema:p.record(p.unknown()),gatewayUrl:p.string().min(1),merchantName:p.string().min(1),isAsync:p.boolean().optional(),pollUrl:p.string().optional(),pollInterval:p.number().positive().optional(),pollTimeout:p.number().positive().optional(),tags:p.array(p.string()).optional(),tokenPricing:xs.optional(),priceDisplay:p.string().optional(),pricingModel:p.enum(["per-call","per-token","band"]).optional(),pricingInfo:Lu.optional(),status:p.enum(["available","unavailable"]).optional(),handler:Cs.optional(),pricing:ks.optional(),security:Ei.optional(),engagement:$i.optional(),enabled:p.boolean().optional(),beta:p.boolean().optional(),deprecated:p.boolean().optional(),replacementTool:p.string().optional(),minCliVersion:p.string().optional(),sunsetAt:p.string().optional(),rail:p.enum(Ai).optional(),pricingStrategy:p.enum(["flat","token","band"]).optional()},Ri=p.object({...Ts,dispatch:p.literal("routed"),routedPath:p.string().min(1).startsWith("/")}).strict(),Ii=p.object({...Ts,dispatch:p.literal("enveloped")}).strict(),Pi=p.object({...Ts,handler:Cs,pricing:ks}).strict(),Mi=p.union([p.discriminatedUnion("dispatch",[Ri,Ii]),Pi]);var As=/^[a-z0-9][a-z0-9_-]*$/;var Ui="https://fal.run",qu="https://openrouter.mpp.tempo.xyz";function Fu(e){let{attestation:t,tool_id:n,...r}=e;return r}var Oi={"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 ur(e){let{attestation:t,tool_id:n,aspect_ratio:r,image_size:s,...o}=e,i={...o};return typeof s=="string"&&s.length>0?(i.image_size=s,i):(typeof r=="string"&&Oi[r]&&(i.image_size=Oi[r]),i)}function G(e,t,n,r,s,o,i,a){return{dispatch:"routed",id:e,name:t,description:n,provider:"fal",model:r,category:s,priceCents:o,inputSchema:i,routedPath:`/api/v1/fal/${r}`,gatewayUrl:`${Ui}/${r}`,merchantName:"fal.ai",buildBody:Fu,tags:[],...a}}function Bu(e){return t=>{let{attestation:n,tool_id:r,prompt:s,system_prompt:o,max_tokens:i,temperature:a,...l}=t;return{model:e,messages:[...o?[{role:"system",content:o}]:[],{role:"user",content:s}],max_tokens:i??1024,temperature:a??.7,...l}}}function ae(e,t,n,r,s,o,i){let a=5e-4*s*100,l=500/1e6*o*100,c=Math.max(1,Math.ceil(a+l));return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"llm",priceCents:c,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: 1024)",minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${qu}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:Bu(r),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:s,outputPerMillion:o},...i}}var Es=[G("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"]}),G("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:ur}),G("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:ur}),G("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:ur}),G("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"]}),G("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"]}),G("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"]}),G("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"]}),G("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"]}),G("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"]}),G("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"]}),G("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"]}),G("fal-stable-audio","Stable Audio","Generate music and sound effects 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","music","sound-effects"]}),G("suno-music","Suno Music","AI music generation. Create full songs with vocals or instrumentals.","suno/v4","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"]},{tags:["music","song","vocals","instrumental"],merchantName:"Suno AI",isAsync:!0,pollUrl:`${Ui}/suno/v4/requests/{requestId}/status`}),G("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"]}),G("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"]}),G("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"]}),G("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("or-perplexity-sonar","Perplexity Sonar","Search-augmented LLM. Answers with real-time web sources and citations.","perplexity/sonar",1,1,{tags:["llm","perplexity","search","web","citations","real-time"]}),{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",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",buildBody:e=>ur({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",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",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",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"]},G("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"]}),G("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"]}),{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",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",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",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",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"]},{dispatch:"enveloped",id:"check_fal_status_card",name:"Check fal Async Job Status",description:"Poll an async fal.ai queue job for completion.",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",buildUrl:e=>`https://fal.mpp.tempo.xyz/queue/${e.model_path}/requests/${e.request_id}`,buildBody:()=>({}),tags:["status","fal","async","legacy"]},{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",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},tags:["tts","speech","f5-tts","legacy"]},{dispatch:"enveloped",id:"generate_music_tempo_card",name:"Generate Music (Suno)",description:"Generate a music track using Suno (async, ~$0.50).",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,tags:["music","audio","suno","async","legacy"]},{dispatch:"enveloped",id:"check_music_status_tempo_card",name:"Check Music Status",description:"Poll a Suno music generation task for completion.",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}),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",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:e=>{let t={chain:e.chain,token_address:e.token_address};if(e.start_timestamp){let n=e.end_timestamp||new Date().toISOString(),r=e.time_granularity;if(!r){let s=new Date(e.start_timestamp).getTime();(new Date(n).getTime()-s)/(1e3*60*60*24)<=2?r="1h":r="1d"}return{addresses:[t],start_timestamp:e.start_timestamp,end_timestamp:n,time_granularity:r}}return[t]},tags:["onchain","prices","allium","crypto","legacy"]}];function dr(e){return Es.find(t=>t.id===e)}var Di=1,Li=["pick_one","fan_out"],ji=["concat","dedupe_by_url","top_k_by_score"],Ku=8,Gu=p.object({type:p.string().min(1),description:p.string().min(1),enum:p.array(p.string()).optional(),default:p.unknown().optional(),minimum:p.number().optional(),maximum:p.number().optional()}),zu=p.object({toolId:p.string().min(1),notes:p.string().min(1)}),Wu=p.object({providers:p.array(p.string().min(1)).min(1).max(Ku),merge:p.enum(ji),maxResults:p.number().int().positive().optional()}),Vi=p.object({mode:p.enum(Li).default("pick_one"),intro:p.string().min(1),defaultTier:p.string().min(1),tiers:p.record(p.string(),zu).refine(e=>Object.keys(e).length>0,{message:"must have at least one tier"}),fanOut:Wu.optional(),guidance:p.string().min(1),inputProperties:p.record(p.string(),Gu),required:p.array(p.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"]}),Ju=p.object({version:p.literal(Di),generatedAt:p.string().datetime(),tools:p.record(p.string().regex(As,"tool name must match MCP naming rules"),Vi).refine(e=>Object.keys(e).length>0,{message:"manifest must have at least one tool"})});var Ms=require("child_process"),Gi=require("util"),zi=A(require("crypto")),ce=A(require("fs")),Wi=A(require("os")),De=A(require("path"));var pe=A(require("fs")),Is=A(require("path")),qi=A(require("os")),Rs=Is.join(qi.homedir(),".visa-mcp"),vn=Is.join(Rs,"mcp-server.log"),Xu=5*1024*1024,$s=null;function Qu(){pe.existsSync(Rs)||pe.mkdirSync(Rs,{recursive:!0,mode:448})}function ed(){if(!$s){if(Qu(),pe.existsSync(vn)&&pe.statSync(vn).size>Xu){let t=vn+".1";pe.existsSync(t)&&pe.unlinkSync(t),pe.renameSync(vn,t)}$s=pe.createWriteStream(vn,{flags:"a"})}return $s}function td(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function mr(e,...t){let n=new Date().toISOString(),r=t.map(o=>typeof o=="string"?o:JSON.stringify(o,null,2)).join(" "),s=`[${n}] [${e}] ${r}
37
- `;td(e)&&process.stderr.write(s),ed().write(s)}var d={debug:(...e)=>mr("DEBUG",...e),info:(...e)=>mr("INFO",...e),warn:(...e)=>mr("WARN",...e),error:(...e)=>mr("ERROR",...e)};var Jt=(0,Gi.promisify)(Ms.execFile),gr=De.join(Wi.homedir(),".visa-mcp","bin"),Lt=De.join(gr,"Visa CLI"),nd=De.join(__dirname,"..","native"),Fi="5",Bi=De.join(gr,"visa-keychain.version"),Hi=De.join(gr,"visa-keychain.sha256");function Ki(e){let t=ce.readFileSync(e);return zi.createHash("sha256").update(t).digest("hex")}async function Ji(){try{if(ce.readFileSync(Bi,"utf-8").trim()===Fi&&ce.existsSync(Lt)){let r=ce.readFileSync(Hi,"utf-8").trim();if(Ki(Lt)!==r)d.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),ce.unlinkSync(Lt);else return Lt}}catch{}let e=De.join(nd,"visa-keychain.m");if(ce.existsSync(e)||(e=De.resolve(__dirname,"..","..","native","visa-keychain.m")),ce.existsSync(e)||(e=De.resolve(__dirname,"..","native","visa-keychain.m")),!ce.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");ce.mkdirSync(gr,{recursive:!0,mode:448});try{await Jt("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",Lt,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=Ki(Lt);return ce.writeFileSync(Hi,t,{mode:384}),ce.writeFileSync(Bi,Fi,{mode:384}),Lt}async function Yi(e){let t=await Ji(),n;try{n=(await Jt(t,e,{timeout:6e4})).stdout}catch(o){n=o.stdout||"";let i=n.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(o.stderr?.trim()||o.message||"Unknown error")}let r=n.trim();if(r.startsWith("OK:"))return r.slice(3);if(r==="OK")return;let s=r.startsWith("ERROR:")?r.slice(6):"Unknown error";throw new Error(s)}var Ps=null;function z(){return process.env.VISA_MOCK_TOUCHID==="true"?!0:process.platform!=="darwin"?!1:Ps!==null?Ps:(Ps=!0,!0)}var pr="visa-cli",fr="attestation-key";async function rd(e){try{await Jt("security",["delete-generic-password","-s",pr,"-a",fr],{timeout:5e3})}catch{}await Jt("security",["add-generic-password","-s",pr,"-a",fr,"-w",e],{timeout:5e3})}async function sd(){try{let{stdout:e}=await Jt("security",["find-generic-password","-s",pr,"-a",fr,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function hr(){let e=await Yi(["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 rd(n),r}async function Yt(e,t){if(process.env.VISA_MOCK_TOUCHID==="true")return Promise.resolve("mock-ecdsa-signature-for-testing");let n=await sd();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await Ji(),s=["sign",e];return t&&s.push(t),new Promise((o,i)=>{let a=(0,Ms.execFile)(r,s,{timeout:6e4},(l,c)=>{let u=(c||"").trim();if(l){u.startsWith("ERROR:")?i(new Error(u.slice(6))):i(new Error(l.stderr?.trim()||l.message||"Unknown error"));return}u.startsWith("OK:")?o(u.slice(3)):i(new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error"))});a.stdin.write(n),a.stdin.end()})}async function yr(){try{await Jt("security",["delete-generic-password","-s",pr,"-a",fr],{timeout:5e3})}catch{}try{await Yi(["delete-key"])}catch{}}var od=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],id=[...od.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 Ns(e,t=id){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=Os(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(Os(r.match.provider)))&&r.match.keywords.every(s=>n.includes(Os(s))))return r.targetToolId;return null}function Os(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}var Zi={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; check_fal_status_card resolves 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. Call check_fal_status_card with those values to poll for completion. 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 ~60\u201390s music track from a prompt (Suno V4 \u2014 vocals, lyrics, full arrangement). ~$0.10. Use for jingles, soundtracks, ad music, viral original songs, or any "make me a song about \u2026" / "compose music for \u2026" request.',tiers:{suno:{toolId:"suno-music",notes:"Suno v4 \u2014 songs with vocals, lyrics, full arrangement"}},guidance:"Takes ~60-90s. Returns an audio URL the user can play.",inputProperties:{prompt:{type:"string",description:"Musical style / mood / lyrics hint."},instrumental:{type:"boolean",description:"True for instrumental (no vocals), false for vocal track.",default:!1}},required:["prompt"]},generate_audio:{intro:"Generate speech (TTS, voice-cloned) or sound effects from a prompt. $0.03\u2013$0.04. Use for: voiceover (tts tier \u2014 pass text + audio_url of the voice sample), SFX/ambient/background sound (sfx tier \u2014 pass prompt describing the sound).",tiers:{tts:{toolId:"fal-metavoice",notes:"MetaVoice \u2014 voice cloning TTS (requires a voice sample URL)"},sfx:{toolId:"fal-stable-audio",notes:"Stable Audio \u2014 sound effects and ambient from a prompt"}},guidance:"For tts: provide text + audio_url (voice sample to clone). For sfx: provide prompt describing the sound.",inputProperties:{prompt:{type:"string",description:"Description of sound to generate (sfx tier)."},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 MetaVoice)."}},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`."},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), 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 Us(e,t,n){if(!Qi(e))return ld(e,n);let r=Xi[e];if(!r)return e;let s=Object.keys(r.tiers),o=t||s[0],i=ud(e,o,n);return i||dd(e,r,o,s)}function ld(e,t){return Ns({requestedTool:e,intentText:t})??e}function ud(e,t,n){return Ns({requestedTool:e,metaTool:e,tier:t,intentText:n})}function dd(e,t,n,r){let s=t.tiers[n];if(!s)throw new Error(`Unknown tier '${n}' for ${e}. Valid tiers: ${r.join(", ")}`);return s.toolId}var Xi=Zi;function Qi(e){return e in Xi}var bn=Object.keys(Zi);function Ds(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function ea(e=process.env){return Ds(e)!==null}var se=A(require("crypto")),qa=require("child_process"),Ae=A(require("fs")),En=A(require("os")),Dr=A(require("path"));var L=A(require("fs")),Sr=A(require("os")),V=A(require("path")),sa=require("child_process");var ta=A(require("fs")),md=["npm","pnpm","yarn","bun"],pd=/\s+/;function fd(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(pd)[0]??"",r=n.indexOf("/"),s=r===-1?n:n.slice(0,r);return md.includes(s)?s:void 0}function Ls(e){if(!e)return;let t=e;try{t=ta.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 gd(e=process.argv[1]){return fd()??Ls(process.env.npm_execpath)??Ls(process.env.npm_node_execpath)??Ls(e)}function js(e,t,n){let r=t??gd(n)??"npm",o=`@visa/cli@${e??"latest"}`;switch(r){case"npm":return{packageManager:r,command:"npm",args:["install","-g",o],display:`npm install -g ${o}`};case"pnpm":return{packageManager:r,command:"pnpm",args:["add","-g",o],display:`pnpm add -g ${o}`};case"yarn":return{packageManager:r,command:"yarn",args:["global","add",o],display:`yarn global add ${o}`};case"bun":return{packageManager:r,command:"bun",args:["add","-g",o],display:`bun add -g ${o}`}}}function Xt(e,t,n){return js(e,t,n).display}var hd=2,Sn="# >>> visa-cli shell hud v2 >>>",vr="# <<< visa-cli shell hud v2 <<<",oa="# >>> visa-cli shell hud >>>",yd="# <<< visa-cli shell hud <<<",ia=3e4,_d="VISA | HUD not ready \u2014 run: visa-cli config hud doctor",vd={currentVersion:"0.0.0"},bd=3e4;function Fs(){try{return V.join(Gs(),".visa-cli")}catch{return V.join(Sr.tmpdir(),".visa-cli")}}function en(){return V.join(Fs(),"shell-hud.json")}function wr(){return V.join(Fs(),"shell-hud.line")}function aa(){return V.join(Fs(),"shell-hud.lock")}function nn(e){let t=e??process.env.SHELL;if(!t)return null;let n=V.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 xn(e){let t=Gs();if(e==="zsh")return V.join(t,".zshrc");if(e==="bash")return V.join(t,".bashrc");let n=(process.platform==="win32","PowerShell");return V.join(t,"Documents",n,"Microsoft.PowerShell_profile.ps1")}function Sd(e){let t=Gs(),n=[{shell:"zsh",rcPath:V.join(t,".zshrc")},{shell:"bash",rcPath:V.join(t,".bashrc")},{shell:"bash",rcPath:V.join(t,".bash_profile")},{shell:"powershell",rcPath:V.join(t,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1")}];if(!e)return n;let r=n.filter(o=>o.shell===e),s=n.filter(o=>o.shell!==e);return[...r,...s]}function wd(e){let t="$HOME/.visa-cli/shell-hud.line",n=Pd(e),r=Md(e);if(e==="zsh")return`${Sn}
21
+ `),process.exit(1)}var Do=require("child_process");function ss(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 rl(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(`
22
+ `)}function os(e,t=process.platform){return t==="darwin"?{cmd:"open",args:[e]}:t==="win32"?{cmd:"cmd",args:["/c","start","",e]}:t==="linux"?{cmd:"xdg-open",args:[e]}:null}async function is(e,t={}){let n=t.log??(l=>console.log(l)),r=t.env??process.env,s=t.platform??process.platform,o=t.spawn??((l,c,u)=>{(0,Do.execFile)(l,c,m=>u(m))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let l of rl(e).split(`
23
+ `))n(` ${l}`);n("");let i=ss(r,s);if(i.headless){n(` (${i.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 a=os(e,s);if(!a){n(` No known browser-open command for platform "${s}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(l=>{o(a.cmd,a.args,c=>{c?(n(` Could not open browser automatically (${c.message}).`),n(" Open the URL above manually to continue."),n("")):(n(" Opened browser. Waiting for you to sign in..."),n("")),l()})})}function sl(e){return new Promise(t=>setTimeout(t,e))}function Lo(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 jo(e){return!Number.isFinite(e)||e===null||e<=0?1e3:Math.min(Math.max(Math.ceil(e),1e3),3e4)}async function ol(e,t=Math.random()*250){let n=s=>Math.min(s+Math.max(0,Math.ceil(t)),3e4);if(!e||e.status!==429)return n(1e3);let r=Lo(e.headers?.get("Retry-After"));if(r!==null)return n(jo(r));if(typeof e.json=="function")try{let s=await e.json();return n(jo(Lo(s?.retryAfter)))}catch{return n(1e3)}return n(1e3)}async function nt(e,t){let n=await ol(e);return t?.(n),await sl(n),n}var qo=T(require("crypto")),ue=T(require("fs")),Yn=T(require("path"));function Fo(e,t){ue.mkdirSync(Yn.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${qo.randomBytes(8).toString("hex")}.tmp`;try{ue.writeFileSync(n,JSON.stringify(t,null,2)+`
24
+ `),ue.renameSync(n,e)}catch(r){try{ue.unlinkSync(n)}catch{}throw r}}function Vo(e){return`'${e.replace(/'/g,"'\\''")}'`}var Bo="# visa-cli-hud-v1";function il(e,t){let n=e??process.execPath,r=t??process.argv[1]??"",s=r?Yn.resolve(r):"";return`${s?`${Vo(n)} ${Vo(s)} config statusline`:"visa-cli config statusline"} ${Bo}`}function bt(e){return typeof e!="string"?!1:e.includes(Bo)?!0:e.includes("visa-cli")&&e.includes("statusline")}function Zn(e,t=il){let n={},r=!1;if(ue.existsSync(e)){r=!0;try{n=JSON.parse(ue.readFileSync(e,"utf-8"))}catch(s){return{installed:"malformed-json",message:`~/.claude/settings.json is not valid JSON (${s.message}). Fix the file manually, then run: visa-cli config hud enable claude`}}}if(n.statusLine){let s=typeof n.statusLine=="object"?n.statusLine.command:"";return bt(s)?{installed:"already-visa",message:"Visa HUD already registered in ~/.claude/settings.json."}:{installed:"other-hud-present",message:"Another HUD is already configured (keeping it). To switch to Visa HUD, edit ~/.claude/settings.json \u2192 statusLine.command"}}try{return n.statusLine={type:"command",command:t()},Fo(e,n),{installed:"new",message:`Visa HUD registered in ~/.claude/settings.json${r?"":" (new file)"}. Restart Claude Code to see it pinned below the input.`}}catch(s){return{installed:"error",message:`Failed to write settings: ${s.message}. Enable manually later with: visa-cli config hud enable claude`}}}function as(e){if(!ue.existsSync(e))return{removed:!1,message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(ue.readFileSync(e,"utf-8"))}catch(r){return{removed:!1,message:`~/.claude/settings.json is not valid JSON: ${r.message}`}}if(!t.statusLine)return{removed:!1,message:"No statusLine configured."};let n=typeof t.statusLine=="object"?t.statusLine.command:"";return bt(n)?(delete t.statusLine,Fo(e,t),{removed:!0,message:"Visa HUD removed from ~/.claude/settings.json. Restart Claude Code to take effect."}):{removed:!1,message:"statusLine is owned by another tool \u2014 leaving it alone."}}var qe=T(require("fs")),Fe=T(require("path")),al=1,St={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},cl=["terminal","claude","claude-code","codex","all"];function ps(e){let t=e.toLowerCase();return cl.includes(t)?t:null}var ll=50,ul=64*1024,Ho=10,cs=80;function dl(){let e=(process.env.COLORTERM??"").toLowerCase();if(e==="truecolor"||e==="24bit")return!0;let t=(process.env.TERM??"").toLowerCase();return t.includes("truecolor")||t.includes("24bit")}var ls=dl(),C={reset:"\x1B[0m",visaBlue:ls?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:ls?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:ls?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function E(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${C.reset}`}function Ko(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function Yo(e=process.stdin){return e.isTTY?null:new Promise(t=>{let n=[],r=!1,s=()=>{e.removeListener("data",i),e.removeListener("end",a),e.removeListener("error",l),clearTimeout(c)},o=u=>{r||(r=!0,s(),t(u))},i=u=>{n.push(typeof u=="string"?Buffer.from(u):u)},a=()=>{let u=Buffer.concat(n).toString("utf-8").trim();if(!u)return o(null);try{let m=JSON.parse(u);o(m&&typeof m=="object"?m:null)}catch{o(null)}},l=()=>o(null),c=setTimeout(()=>{n.length>0?a():o(null)},ll);e.on("data",i),e.on("end",a),e.on("error",l)})}function Xn(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${E(r||"",C.visaBlueSoft)}${E(s||"",C.dim)}`}function us(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 Go(e){if(wl(e))return ml(e);let t=` ${E("\u2502",C.dim)} `,n=ds(e)||"claude",r=e.cwd?te(Fe.basename(e.cwd)):"",s=fs(e.workspace),o=r||s,i=s&&s!==o?` ${E(`@${s}`,C.visaBlueSoft)}`:"",a=[E(`[${n}]`,C.visaBlueSoft)];o&&a.push(`${E(o,C.visaGold)}${i}`);let l=a.join(t),c=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,m=e.context_window?.current_usage,h=[m?.input_tokens,m?.output_tokens,m?.cache_creation_input_tokens,m?.cache_read_input_tokens].filter(U=>typeof U=="number"&&Number.isFinite(U)),v=h.length>0?h.reduce((U,J)=>U+J,0):null,g=Number(e.context_window?.total_input_tokens??v??m?.input_tokens??0),x=u!==null?Math.max(0,Math.min(1,u/100)):c>0?Math.max(0,Math.min(1,g/c)):0,O=u!==null&&c>0?Math.round(x*c):g,F;if(c>0||u!==null){let U=`${String(Math.round(x*100)).padStart(2," ")}%`,J=c>0?` ${E(`(${us(O)}/${us(c)})`,C.dim)}`:"";F=`${E("Context",C.dim)} ${Xn(x)} ${E(U,C.green)}${J}`}else F=`${E("Context",C.dim)} ${E("-",C.dim)}`;let j=fl(e.rate_limits),k=[F];j&&k.push(j);let P=k.join(t);return`${l}
25
+ ${P}`}function ml(e){let t=` ${E("\u2502",C.dim)} `,n=oi(e),r=n.model||"codex",s=[E(`[${r}]`,C.visaBlueSoft)];n.project&&s.push(E(n.project,C.visaGold)),n.gitBranch&&s.push(`${E("git",C.dim)} ${E(n.gitBranch,C.visaGold)}`);let o=s.join(t),i=[];if(typeof n.contextUsedPercent=="number"){let l=Math.max(0,Math.min(1,n.contextUsedPercent/100));i.push(`${E("Context",C.dim)} ${Xn(l)} ${E(`${Math.round(n.contextUsedPercent)}%`,C.green)}`)}else if(typeof n.contextRemainingPercent=="number"){let l=100-n.contextRemainingPercent,c=Math.max(0,Math.min(1,l/100));i.push(`${E("Context",C.dim)} ${Xn(c)} ${E(`${Math.round(l)}%`,C.green)}`)}typeof n.usedTokens=="number"&&i.push(`${E("Tokens",C.dim)} ${us(n.usedTokens)}`),n.status&&i.push(`${E("Status",C.dim)} ${E(n.status,C.visaBlueSoft)}`),n.threadTitle&&i.push(`${E("Thread",C.dim)} ${E(n.threadTitle,C.visaBlueSoft)}`);let a=i.length>0?i.join(t):`${E("Context",C.dim)} ${E("-",C.dim)}`;return`${o}
26
+ ${a}`}function pl(e){if(typeof e!="number"||e<=0)return"";let n=(e>1e12?e:e*1e3)-Date.now();if(n<=0||n>=10080*60*1e3)return"";let r=Math.floor(n/6e4),s=Math.floor(r/60),o=r%60;return s>0?`${s}h ${o}m`:`${o}m`}function zo(e,t){if(!e||typeof e.used_percentage!="number")return null;let n=Math.max(0,Math.min(100,e.used_percentage)),r=n/100,s=Xn(r),o=n>=90?"\x1B[38;5;196m":n>=70?C.visaGold:C.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=pl(e.resets_at),l=a?` ${E(`(${a} / ${t})`,C.dim)}`:` ${E(`(${t})`,C.dim)}`;return`${s} ${E(i,o)}${l}`}function fl(e){if(!e)return null;let t=zo(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?zo(e.seven_day,"7d"):null;if(!t&&!r)return null;let s=` ${E("\u2502",C.dim)} `,o=[t,r].filter(Boolean);return`${E("Usage",C.dim)} ${o.join(s)}`}function Zo(e){let t;try{let n=qe.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let s=Math.min(r,ul),o=r-s;t=qe.openSync(e,"r");let i=Buffer.alloc(s);qe.readSync(t,i,0,s,o);let a=i.toString("utf-8");if(o>0){let l=Buffer.alloc(1);if(qe.readSync(t,l,0,1,o-1),l[0]!==10){let c=a.indexOf(`
27
+ `);c>=0&&(a=a.slice(c+1))}}return a}catch{return null}finally{if(t!==void 0)try{qe.closeSync(t)}catch{}}}function gl(e){if(!e||typeof e!="object")return;let t=e,n=["file_path","path","notebook_path","pattern","command","url"];for(let r of n){let s=t[r];if(typeof s=="string"&&s.length>0){if(r.endsWith("_path")||r==="path"){let o=Fe.basename(Fe.dirname(s)),i=Fe.basename(s);return o&&o!=="."&&o!=="/"?`${o}/${i}`:i}return s}}}function hl(e){let t=e.split(`
28
+ `),n=[],r=new Set;for(let s=t.length-1;s>=0&&n.length<Ho*3;s-=1){let o=t[s].trim();if(!o)continue;let i;try{i=JSON.parse(o)}catch{continue}if(!i||typeof i!="object")continue;let l=i.message;if(!l||typeof l!="object")continue;let c=l.content;if(Array.isArray(c))for(let u of c){if(!u||typeof u!="object")continue;let m=u;if(m.type==="tool_result"&&typeof m.tool_use_id=="string")r.add(m.tool_use_id);else if(m.type==="tool_use"&&typeof m.name=="string"){let h=typeof m.id=="string"?m.id:"",v=h.length>0?!r.has(h):!1;n.push({name:m.name,target:gl(m.input),running:v})}}}return n.reverse(),n.slice(Math.max(0,n.length-Ho))}function yl(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 _l(e){let t=e.running?E("\u25D0",C.visaGold):E("\u2713",C.green),n=e.running?C.visaGold:C.visaBlueSoft,r=E(te(e.name),n),s=e.target?te(e.target):"",o=s?`${E(":",C.dim)} ${E(s,C.dim)}`:"",i=e.count>1?` ${E(`\xD7${e.count}`,C.dim)}`:"";return o?`${t} ${r}${o}${i}`:`${t} ${r}${i}`}function vl(e){let t=` ${E("\u2502",C.dim)} `,n=Ko(t),r=e.slice();for(;r.length>0;){let l=r.join(t);if(Ko(l)<=cs)return l;r=r.slice(1)}if(e.length===0)return"";let s="\u2026",i=e[e.length-1].replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,""),a=i.length>cs-n-1?i.slice(0,cs-n-1)+s:i;return`${E(s,C.dim)}${t}${a}`}async function Wo(e){if(!e||typeof e!="string")return null;let t=Zo(e);if(!t)return null;let n;try{n=hl(t)}catch{return null}if(n.length===0)return null;let s=yl(n).map(_l);return vl(s)||null}async function Xo(e,t,n){return(await ei(e,t,n)).join(`
29
+ `)}function Qo(e,t,n){let r=!!t?.activeSession||e.includes("in session"),s=n?Sl(n):!1;return{isActive:r||s,hasSession:r,hasToolActivity:s}}async function ei(e,t,n){let{isActive:r}=Qo(e,n,t?.transcript_path);if(t&&!r){let o=[],i=Go(t);if(i&&o.push(...i.split(`
30
+ `)),t.transcript_path){let l=await Wo(t.transcript_path);l&&o.push(...l.split(`
31
+ `))}let a=E(ms(e),C.dim);return o.push(a),o}let s=[e];if(t){let o=Go(t);if(o&&s.push(...o.split(`
32
+ `)),t.transcript_path){let i=await Wo(t.transcript_path);i&&s.push(...i.split(`
33
+ `))}}return s}var bl=["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 Sl(e){let t=Zo(e);if(!t)return!1;let n=t.slice(-16384).toLowerCase();return bl.some(r=>n.includes(`"${r}"`))}async function ti(e,t,n){let r=await ei(e,t,n),s=r.join(`
34
+ `),{isActive:o}=Qo(e,n,t?.transcript_path);return{schemaVersion:al,client:t?si(t):St.UNKNOWN,rendered:s,lines:r.map(ms),visa:{spendLine:ms(e),balanceCents:n?.balanceCents,balanceUsd:n?.amountUsd,sessionMode:n?.sessionMode,activeSession:n?.activeSession,isVisaActive:o},context:t?oi(t):{}}}function te(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 fs(e){if(typeof e=="string")return te(Fe.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 te(t?Fe.basename(t):e.name)}function ni(e){return te(e.app_name??e.appName??e.app??e.client)}function ds(e){return te(e.model?.display_name??e.model?.id??e.model_name??e.modelName)}function ri(e){return te(e.cwd??e.current_dir??e.project_root)}function Jo(e){let t=te(e.project);if(t)return t;let n=ri(e);if(n)return te(Fe.basename(n));let r=fs(e.workspace);return r||""}function ke(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function si(e){let t=ni(e).toLowerCase();return t.includes("codex")?St.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?St.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||ke(e.context_used)!==void 0?St.CODEX:St.UNKNOWN}function wl(e){return si(e)===St.CODEX}function oi(e){let t=ni(e),n=ri(e),r=fs(e.workspace),s=ke(e.context_used)??ke(e.context_window?.used_percentage??void 0),o=ke(e.context_remaining)??ke(e.context_window?.remaining_percentage??void 0);return{...t?{app:t}:{},...ds(e)?{model:ds(e)}:{},...Jo(e)?{project:Jo(e)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...te(e.git_branch??e.branch)?{gitBranch:te(e.git_branch??e.branch)}:{},...te(e.status??e.run_state??e.runState)?{status:te(e.status??e.run_state??e.runState)}:{},...te(e.thread_title??e.threadTitle)?{threadTitle:te(e.thread_title??e.threadTitle)}:{},...s!==void 0?{contextUsedPercent:s}:{},...o!==void 0?{contextRemainingPercent:o}:{},...ke(e.used_tokens)!==void 0?{usedTokens:ke(e.used_tokens)}:{},...ke(e.total_input_tokens)!==void 0?{totalInputTokens:ke(e.total_input_tokens)}:{},...ke(e.total_output_tokens)!==void 0?{totalOutputTokens:ke(e.total_output_tokens)}:{}}}function ms(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}async function wt(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,s=setTimeout(()=>r.abort(),n);try{let{timeoutMs:o,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(s)}}var ne=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(t,n,r,s,o,i,a,l){super(t),this.name="CardDeclinedError",this.retryable=n,this.code=r,this.reason=s,this.paymentErrorClass=o,this.correlationId=i,this.transactionId=a,this.retryAfter=l}};var ii={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 gs(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&&ii[n]?ii[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 xl=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function ci(e,t){let n=ai(e),r=ai(t);if(!n||!r)return!1;for(let s=0;s<3;s++)if(n.main[s]!==r.main[s])return n.main[s]>r.main[s];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:Cl(n.pre,r.pre)>0}function ai(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(xl);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function Cl(e,t){let n=e.split("."),r=t.split("."),s=Math.max(n.length,r.length);for(let o=0;o<s;o++){if(o>=n.length)return-1;if(o>=r.length)return 1;let i=n[o],a=r[o],l=/^\d+$/.test(i),c=/^\d+$/.test(a);if(l&&c){let u=Number(i)-Number(a);if(u!==0)return u}else{if(l)return-1;if(c)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function Me(){return!!(li(process.env.VISA_CLI_NO_UPDATE_CHECK)||li(process.env.CI)||process.env.NODE_ENV==="test")}function li(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var st=T(require("fs")),mi=T(require("path"));var Qn=T(require("fs")),ui=T(require("path")),di=T(require("os"));var hs=ui.join(di.homedir(),".visa-mcp"),fn=class{static ensureConfigDir(){Qn.existsSync(hs)||Qn.mkdirSync(hs,{recursive:!0,mode:448})}static getConfigDir(){return hs}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}};var kl="settings.json";function gn(){return mi.join(fn.getConfigDir(),kl)}var ot={"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");let t;try{t=new URL(e)}catch{throw new Error(`auth.serverUrl must be a valid URL (got: ${JSON.stringify(e)})`)}if(t.protocol!=="https:"&&t.protocol!=="http:")throw new Error(`auth.serverUrl must use http or https (got: ${t.protocol})`)}},"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_music, ...). Restart required.",requiresRestart:!0},"tools.discover":{type:"boolean",description:"Show the dynamic-catalog tools (discover_tools, execute_tool). Restart required.",requiresRestart:!0},"merchants.discover":{type:"string",description:'Platform-merchant JIT tool discovery: "all" = every live merchant, "off" = none, comma-separated slugs = exactly those. Equivalent to VISA_MERCHANT_DISCOVER / VISA_MERCHANT_SLUGS env. Restart required.',requiresRestart:!0,validate:e=>{if(typeof e!="string")throw new Error("merchants.discover must be a string");let t=e.trim().toLowerCase();if(t===""||t==="all"||t==="off"||t==="*")return;let n=/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/,r=e.split(",").map(s=>s.trim()).filter(Boolean);for(let s of r)if(!n.test(s))throw new Error(`merchants.discover: "${s}" is not a valid merchant slug`)}},"credit.sessionCapCents":{type:"number",description:"Default cap (in cents) for start_session and pay-as-you-go one-shot approvals. Server clamps to [100, 10000] = $1\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<100||e>1e4)throw new Error("credit.sessionCapCents must be between 100 ($1) and 10000 ($100)")}}},_s=500,er={"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 xt(){let e=gn();if(!st.existsSync(e))return{};try{let t=st.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?{}:n}catch{return{}}}function ys(e){fn.ensureConfigDir();let t=gn(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
35
+ `;st.writeFileSync(n,r,{mode:384}),st.renameSync(n,t)}function vs(e){let t=xt()[e];return typeof t=="string"?t:void 0}function tr(e){let t=xt()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function bs(e){let t=xt()[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 Be=class extends Error{constructor(t){let n=Object.keys(ot).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"}},He=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"}},rt=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+er[t]),this.name="RetiredSettingKeyError"}},pi=["biometric.","spending.","account.","cards.","biometric"];function nr(e,t){if(pi.some(o=>e.startsWith(o)))throw new He(e);if(e in er)throw new rt(e);let n=ot[e];if(!n)throw new Be(e);let r;if(n.type==="boolean")if(typeof t=="boolean")r=t;else if(typeof t=="string"){let o=t.toLowerCase();if(o==="true")r=!0;else if(o==="false")r=!1;else throw new Error(`${e} expects true or false (got: ${JSON.stringify(t)})`)}else throw new Error(`${e} expects a boolean (got: ${typeof t})`);else if(n.type==="number")if(typeof t=="number")r=t;else if(typeof t=="string"&&t.trim().length>0){let o=Number(t);if(!Number.isFinite(o))throw new Error(`${e} expects a number (got: ${JSON.stringify(t)})`);r=o}else throw new Error(`${e} expects a number (got: ${typeof t})`);else{if(typeof t!="string"||t.length===0)throw new Error(`${e} expects a non-empty string`);r=t}n.validate&&n.validate(r);let s=xt();return s[e]=r,ys(s),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:gn()}}function rr(e){if(pi.some(o=>e.startsWith(o)))throw new He(e);let t=ot[e];if(e in er){let o=xt(),i=e in o;return i&&(delete o[e],ys(o)),{key:e,removed:i,requiresRestart:!1,path:gn()}}if(!t)throw new Be(e);let r=xt(),s=e in r;return s&&(delete r[e],ys(r)),{key:e,removed:s,requiresRestart:s&&!!t.requiresRestart,path:gn()}}function fi(){let e=xt();return Object.entries(er).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}var Tl="https://auth.visacli.sh",Al="https://auth-visa-code-preview.up.railway.app";function El(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function $l(){try{let e=Gn();return El(e.version)}catch{return!1}}function Rl(e){return e.envVar!==void 0&&e.envVar!==""?e.envVar:e.settingValue!==void 0?e.settingValue:e.isPrerelease?Al:Tl}function _e(){return Rl({envVar:process.env.VISA_AUTH_URL,settingValue:vs("auth.serverUrl"),isPrerelease:$l()})}function gi(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":tr("ui.suppressBrowser")??!1}function hi(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":tr("ui.suppressFeed")??!1}function sr(){let e=process.env.VISA_CREDIT_SESSION_CAP_CENTS;if(e!==void 0){let n=Number(e);if(Number.isFinite(n)&&n>=100&&n<=1e4)return Math.floor(n)}let t=bs("credit.sessionCapCents");return t!==void 0&&t>=100&&t<=1e4?Math.floor(t):_s}var hn="2.0.0-rc.43",Il=/^vk_[A-Za-z0-9_-]{32,}$/;function yi(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?Il.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 vk_<32+ base64url chars>)."),n.push("Create a new token with: visa-cli tokens 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(`
36
+ `)}var ve=class{constructor(t){this.getSessionToken=t;this.baseUrl=_e()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!Me()){let r=t.headers.get("X-Latest-Version");r&&ci(r,hn)&&(this.lastSignals.updateAvailable={currentVersion:hn,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return hn}async request(t,n,r,s,o,i){let a=await this.getSessionToken();if(!a)throw new Error(yi());let l={Authorization:`Bearer ${a}`};o&&(t==="GET"?l["X-User-Context"]=encodeURIComponent(o.replace(/[\r\n\0]/g," ").slice(0,1e3)):r={...r||{},user_context:o}),i&&(l["X-Visa-Meta-Tool"]=i),r&&(l["Content-Type"]="application/json");let c;try{c=await wt(`${this.baseUrl}${n}`,{method:t,headers:{...l,"X-Visa-CLI-Version":hn,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:s})}catch(m){throw new Error(gs(m))}if(this.parseServerSignals(c),c.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(c.status===429){let m=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${m}s. Tip: use the batch tool to combine multiple requests into one.`)}if(c.status===503)throw new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status.");let u;try{u=await c.json()}catch{throw c.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(!c.ok){if(c.status===500)throw new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`);if(u?.declined){let m=Number(u.retryAfter??c.headers.get("Retry-After"));throw new ne(u.error||"Your card was declined.",!!u.retryable,u.code,u.reason,u.payment_error_class,u.correlation_id,u.transactionId,Number.isFinite(m)&&m>0?m:void 0)}if(c.status===402){let m=u?.error||"Gateway returned 402";throw new Error(`${m}. This usually means your daily or per-transaction spending limit has been reached. Check your limits with get_status or run: visa-cli update-spending-controls`)}throw new Error(u?.error||`Request failed (${c.status}). Try again.`)}return u}async pay(t,n){return this.request("POST","/v1/pay",t,void 0,n)}async shortcut(t,n,r,s,o){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,s,o)}async shortcutWithSession(t,n,r,s,o,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,l=await this.getSessionToken();if(!l)throw new Error(yi());let c={Authorization:`Bearer ${l}`,"X-Visa-CLI-Version":hn,"X-Source":"cli","Content-Type":"application/json"};i&&(c["X-Visa-Meta-Tool"]=i);let u={...n,...r};o&&(u.user_context=o.replace(/[\r\n\0]/g," ").slice(0,1e3));let m;try{m=await wt(`${this.baseUrl}${a}`,{method:"POST",headers:c,body:JSON.stringify(u),timeoutMs:s})}catch(g){throw new Error(gs(g))}if(this.parseServerSignals(m),m.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(m.status===429){let g=m.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.`)}if(m.status===503)throw new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status.");let h=m.headers.get("X-Voucher-Receipt"),v;try{v=await m.json()}catch{throw m.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${a}. Try again.`)}if(!m.ok){if(m.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(v?.declined){let g=Number(v.retryAfter??m.headers.get("Retry-After"));throw new ne(v.error||"Your card was declined.",!!v.retryable,v.code,v.reason,v.payment_error_class,v.correlation_id,v.transactionId,Number.isFinite(g)&&g>0?g:void 0)}throw new Error(v?.error||`Request failed (${m.status}). Try again.`)}return{data:v,voucherReceiptHeader:h}}async batch(t,n,r){return this.request("POST","/v1/batch",t,n,r)}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async catalogSearch(t,n,r){let s=r??"discover_tools",o=new URLSearchParams;t&&o.set("q",t),n&&o.set("category",n);let i=o.toString();return this.request("GET",`/v1/catalog${i?`?${i}`:""}`,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 wt(`${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 wt(`${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 createSessionBudget(t){return this.request("POST","/v1/session-budget/create",{...t,mode:"prepaid"})}async closeSession(t){return this.request("POST","/v1/session/close",{session_budget_id:t})}async getSessionBudget(t){return this.request("GET",`/v1/session-budget/${encodeURIComponent(t)}`)}async getSessionLedger(t){return this.request("GET",`/v1/session/${encodeURIComponent(t)}/ledger`)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getVisaSmi(t,n){return this.request("POST","/v1/visa/smi",t,6e4,n)}async getTransactions(t,n){let r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.offset!=null&&r.set("offset",String(t.offset));let s=r.toString(),o=s?`/v1/transactions?${s}`:"/v1/transactions";return this.request("GET",o,void 0,void 0,n)}async updateSpendingControls(t,n){return this.request("POST","/v1/spending-controls",t,void 0,n)}async removeCard(t,n,r){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(t))}`,n,void 0,r)}async setDefaultCard(t,n,r){return this.request("POST",`/v1/cards/${encodeURIComponent(String(t))}/default`,n,void 0,r)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t){return this.request("POST","/v1/attestation-key",{publicKey:t})}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(){return this.request("GET","/v1/api/keys")}async revokeAppApiKey(t){return this.request("DELETE",`/v1/api/keys/${encodeURIComponent(String(t))}`)}async feedSubmit(t){return this.request("POST","/v1/feed",t)}async feedList(t){let n=new URLSearchParams;t?.tab&&n.set("tab",t.tab),t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset));let r=n.toString();return this.request("GET",`/v1/feed${r?"?"+r:""}`)}async feedVote(t,n){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/vote`,{direction:n})}async feedApprove(t){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/approve`)}async feedDelete(t){return this.request("DELETE",`/v1/feed/${encodeURIComponent(t)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async getFeedback(t,n){let r=new URLSearchParams;t&&r.set("limit",String(t));let s=r.toString();return this.request("GET",`/v1/feedback${s?"?"+s:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}};var p={};Io(p,{BRAND:()=>ru,DIRTY:()=>Ct,EMPTY_PATH:()=>Nl,INVALID:()=>S,NEVER:()=>qu,OK:()=>ie,ParseStatus:()=>re,Schema:()=>I,ZodAny:()=>ct,ZodArray:()=>We,ZodBigInt:()=>Tt,ZodBoolean:()=>At,ZodBranded:()=>_n,ZodCatch:()=>Lt,ZodDate:()=>Et,ZodDefault:()=>Dt,ZodDiscriminatedUnion:()=>ar,ZodEffects:()=>we,ZodEnum:()=>Nt,ZodError:()=>de,ZodFirstPartyTypeKind:()=>w,ZodFunction:()=>lr,ZodIntersection:()=>Pt,ZodIssueCode:()=>f,ZodLazy:()=>Mt,ZodLiteral:()=>Ot,ZodMap:()=>Wt,ZodNaN:()=>Yt,ZodNativeEnum:()=>Ut,ZodNever:()=>Te,ZodNull:()=>Rt,ZodNullable:()=>Ue,ZodNumber:()=>kt,ZodObject:()=>me,ZodOptional:()=>be,ZodParsedType:()=>_,ZodPipeline:()=>vn,ZodPromise:()=>lt,ZodReadonly:()=>jt,ZodRecord:()=>cr,ZodSchema:()=>I,ZodSet:()=>Jt,ZodString:()=>at,ZodSymbol:()=>Gt,ZodTransformer:()=>we,ZodTuple:()=>Ne,ZodType:()=>I,ZodUndefined:()=>$t,ZodUnion:()=>It,ZodUnknown:()=>ze,ZodVoid:()=>zt,addIssueToContext:()=>y,any:()=>mu,array:()=>hu,bigint:()=>au,boolean:()=>Ei,coerce:()=>Vu,custom:()=>ki,date:()=>cu,datetimeRegex:()=>xi,defaultErrorMap:()=>Ke,discriminatedUnion:()=>bu,effect:()=>Pu,enum:()=>$u,function:()=>Tu,getErrorMap:()=>Bt,getParsedType:()=>Oe,instanceof:()=>ou,intersection:()=>Su,isAborted:()=>or,isAsync:()=>Ht,isDirty:()=>ir,isValid:()=>it,late:()=>su,lazy:()=>Au,literal:()=>Eu,makeIssue:()=>yn,map:()=>Cu,nan:()=>iu,nativeEnum:()=>Ru,never:()=>fu,null:()=>du,nullable:()=>Ou,number:()=>Ai,object:()=>yu,objectUtil:()=>Ss,oboolean:()=>ju,onumber:()=>Lu,optional:()=>Mu,ostring:()=>Du,pipeline:()=>Uu,preprocess:()=>Nu,promise:()=>Iu,quotelessJson:()=>Pl,record:()=>xu,set:()=>ku,setErrorMap:()=>Ol,strictObject:()=>_u,string:()=>Ti,symbol:()=>lu,transformer:()=>Pu,tuple:()=>wu,undefined:()=>uu,union:()=>vu,unknown:()=>pu,util:()=>M,void:()=>gu});var M;(function(e){e.assertEqual=s=>{};function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{let o={};for(let i of s)o[i]=i;return o},e.getValidEnumValues=s=>{let o=e.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(let a of o)i[a]=s[a];return e.objectValues(i)},e.objectValues=s=>e.objectKeys(s).map(function(o){return s[o]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},e.find=(s,o)=>{for(let i of s)if(o(i))return i},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}e.joinValues=r,e.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(M||(M={}));var Ss;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Ss||(Ss={}));var _=M.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Oe=e=>{switch(typeof e){case"undefined":return _.undefined;case"string":return _.string;case"number":return Number.isNaN(e)?_.nan:_.number;case"boolean":return _.boolean;case"function":return _.function;case"bigint":return _.bigint;case"symbol":return _.symbol;case"object":return Array.isArray(e)?_.array:e===null?_.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?_.promise:typeof Map<"u"&&e instanceof Map?_.map:typeof Set<"u"&&e instanceof Set?_.set:typeof Date<"u"&&e instanceof Date?_.date:_.object;default:return _.unknown}};var f=M.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"]),Pl=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),de=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(o){return o.message},r={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,l=0;for(;l<i.path.length;){let c=i.path[l];l===i.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(i))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return s(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,M.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];n[o]=n[o]||[],n[o].push(t(s))}else r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};de.create=e=>new de(e);var Ml=(e,t)=>{let n;switch(e.code){case f.invalid_type:e.received===_.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case f.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,M.jsonStringifyReplacer)}`;break;case f.unrecognized_keys:n=`Unrecognized key(s) in object: ${M.joinValues(e.keys,", ")}`;break;case f.invalid_union:n="Invalid input";break;case f.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${M.joinValues(e.options)}`;break;case f.invalid_enum_value:n=`Invalid enum value. Expected ${M.joinValues(e.options)}, received '${e.received}'`;break;case f.invalid_arguments:n="Invalid function arguments";break;case f.invalid_return_type:n="Invalid function return type";break;case f.invalid_date:n="Invalid date";break;case f.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}"`:M.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case f.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 f.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 f.custom:n="Invalid input";break;case f.invalid_intersection_types:n="Intersection results could not be merged";break;case f.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case f.not_finite:n="Number must be finite";break;default:n=t.defaultError,M.assertNever(e)}return{message:n}},Ke=Ml;var _i=Ke;function Ol(e){_i=e}function Bt(){return _i}var yn=e=>{let{data:t,path:n,errorMaps:r,issueData:s}=e,o=[...n,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)a=c(i,{data:t,defaultError:a}).message;return{...s,path:o,message:a}},Nl=[];function y(e,t){let n=Bt(),r=yn({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Ke?void 0:Ke].filter(s=>!!s)});e.common.issues.push(r)}var re=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let s of n){if(s.status==="aborted")return S;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let s of n){let o=await s.key,i=await s.value;r.push({key:o,value:i})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let s of n){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return S;o.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(r[o.value]=i.value)}return{status:t.value,value:r}}},S=Object.freeze({status:"aborted"}),Ct=e=>({status:"dirty",value:e}),ie=e=>({status:"valid",value:e}),or=e=>e.status==="aborted",ir=e=>e.status==="dirty",it=e=>e.status==="valid",Ht=e=>typeof Promise<"u"&&e instanceof Promise;var b;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(b||(b={}));var Se=class{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},vi=(e,t)=>{if(it(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 de(e.common.issues);return this._error=n,this._error}}};function A(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(i,a)=>{let{message:l}=e;return i.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:s}}var I=class{get description(){return this._def.description}_getType(t){return Oe(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Oe(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new re,ctx:{common:t.parent.common,data:t.data,parsedType:Oe(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Ht(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:Oe(t)},s=this._parseSync({data:t,path:r.path,parent:r});return vi(r,s)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Oe(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return it(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=>it(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:Oe(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(Ht(s)?s:Promise.resolve(s));return vi(r,o)}refine(t,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{let i=t(s),a=()=>o.addIssue({code:f.custom,...r(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new we({schema:this,typeName:w.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 be.create(this,this._def)}nullable(){return Ue.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return We.create(this)}promise(){return lt.create(this,this._def)}or(t){return It.create([this,t],this._def)}and(t){return Pt.create(this,t,this._def)}transform(t){return new we({...A(this._def),schema:this,typeName:w.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new Dt({...A(this._def),innerType:this,defaultValue:n,typeName:w.ZodDefault})}brand(){return new _n({typeName:w.ZodBranded,type:this,...A(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new Lt({...A(this._def),innerType:this,catchValue:n,typeName:w.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return vn.create(this,t)}readonly(){return jt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Ul=/^c[^\s-]{8,}$/i,Dl=/^[0-9a-z]+$/,Ll=/^[0-9A-HJKMNP-TV-Z]{26}$/i,jl=/^[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,Vl=/^[a-z0-9_-]{21}$/i,ql=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Fl=/^[-+]?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)?)??$/,Bl=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Hl="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ws,Kl=/^(?:(?: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])$/,Gl=/^(?:(?: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])$/,zl=/^(([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]))$/,Wl=/^(([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])$/,Jl=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Yl=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Si="((\\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])))",Zl=new RegExp(`^${Si}$`);function wi(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 Xl(e){return new RegExp(`^${wi(e)}$`)}function xi(e){let t=`${Si}T${wi(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 Ql(e,t){return!!((t==="v4"||!t)&&Kl.test(e)||(t==="v6"||!t)&&zl.test(e))}function eu(e,t){if(!ql.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||t&&s.alg!==t)}catch{return!1}}function tu(e,t){return!!((t==="v4"||!t)&&Gl.test(e)||(t==="v6"||!t)&&Wl.test(e))}var at=class e extends I{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==_.string){let o=this._getOrReturnCtx(t);return y(o,{code:f.invalid_type,expected:_.string,received:o.parsedType}),S}let r=new re,s;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(s=this._getOrReturnCtx(t,s),y(s,{code:f.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")t.data.length>o.value&&(s=this._getOrReturnCtx(t,s),y(s,{code:f.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){let i=t.data.length>o.value,a=t.data.length<o.value;(i||a)&&(s=this._getOrReturnCtx(t,s),i?y(s,{code:f.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&y(s,{code:f.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")Bl.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"email",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")ws||(ws=new RegExp(Hl,"u")),ws.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"emoji",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")jl.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"uuid",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")Vl.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"nanoid",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")Ul.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"cuid",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")Dl.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"cuid2",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")Ll.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"ulid",code:f.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),y(s,{validation:"url",code:f.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"regex",code:f.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(t,s),y(s,{code:f.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(s=this._getOrReturnCtx(t,s),y(s,{code:f.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(s=this._getOrReturnCtx(t,s),y(s,{code:f.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?xi(o).test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{code:f.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?Zl.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{code:f.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?Xl(o).test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{code:f.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?Fl.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"duration",code:f.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?Ql(t.data,o.version)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"ip",code:f.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?eu(t.data,o.alg)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"jwt",code:f.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?tu(t.data,o.version)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"cidr",code:f.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?Jl.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"base64",code:f.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?Yl.test(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{validation:"base64url",code:f.invalid_string,message:o.message}),r.dirty()):M.assertNever(o);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:f.invalid_string,...b.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...b.errToObj(t)})}url(t){return this._addCheck({kind:"url",...b.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...b.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...b.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...b.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...b.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...b.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...b.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...b.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...b.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...b.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...b.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...b.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,...b.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,...b.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...b.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...b.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...b.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...b.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...b.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...b.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...b.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...b.errToObj(n)})}nonempty(t){return this.min(1,b.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}};at.create=e=>new at({checks:[],typeName:w.ZodString,coerce:e?.coerce??!1,...A(e)});function nu(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,o=Number.parseInt(e.toFixed(s).replace(".","")),i=Number.parseInt(t.toFixed(s).replace(".",""));return o%i/10**s}var kt=class e extends I{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)!==_.number){let o=this._getOrReturnCtx(t);return y(o,{code:f.invalid_type,expected:_.number,received:o.parsedType}),S}let r,s=new re;for(let o of this._def.checks)o.kind==="int"?M.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{code:f.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),y(r,{code:f.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),y(r,{code:f.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?nu(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),y(r,{code:f.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{code:f.not_finite,message:o.message}),s.dirty()):M.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,b.toString(n))}gt(t,n){return this.setLimit("min",t,!1,b.toString(n))}lte(t,n){return this.setLimit("max",t,!0,b.toString(n))}lt(t,n){return this.setLimit("max",t,!1,b.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:b.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:b.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:b.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:b.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:b.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:b.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:b.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:b.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:b.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:b.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"&&M.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)}};kt.create=e=>new kt({checks:[],typeName:w.ZodNumber,coerce:e?.coerce||!1,...A(e)});var Tt=class e extends I{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)!==_.bigint)return this._getInvalidInput(t);let r,s=new re;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),y(r,{code:f.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),y(r,{code:f.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),y(r,{code:f.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):M.assertNever(o);return{status:s.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return y(n,{code:f.invalid_type,expected:_.bigint,received:n.parsedType}),S}gte(t,n){return this.setLimit("min",t,!0,b.toString(n))}gt(t,n){return this.setLimit("min",t,!1,b.toString(n))}lte(t,n){return this.setLimit("max",t,!0,b.toString(n))}lt(t,n){return this.setLimit("max",t,!1,b.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:b.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:b.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:b.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:b.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:b.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:b.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}};Tt.create=e=>new Tt({checks:[],typeName:w.ZodBigInt,coerce:e?.coerce??!1,...A(e)});var At=class extends I{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==_.boolean){let r=this._getOrReturnCtx(t);return y(r,{code:f.invalid_type,expected:_.boolean,received:r.parsedType}),S}return ie(t.data)}};At.create=e=>new At({typeName:w.ZodBoolean,coerce:e?.coerce||!1,...A(e)});var Et=class e extends I{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==_.date){let o=this._getOrReturnCtx(t);return y(o,{code:f.invalid_type,expected:_.date,received:o.parsedType}),S}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return y(o,{code:f.invalid_date}),S}let r=new re,s;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(s=this._getOrReturnCtx(t,s),y(s,{code:f.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(s=this._getOrReturnCtx(t,s),y(s,{code:f.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):M.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:b.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:b.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}};Et.create=e=>new Et({checks:[],coerce:e?.coerce||!1,typeName:w.ZodDate,...A(e)});var Gt=class extends I{_parse(t){if(this._getType(t)!==_.symbol){let r=this._getOrReturnCtx(t);return y(r,{code:f.invalid_type,expected:_.symbol,received:r.parsedType}),S}return ie(t.data)}};Gt.create=e=>new Gt({typeName:w.ZodSymbol,...A(e)});var $t=class extends I{_parse(t){if(this._getType(t)!==_.undefined){let r=this._getOrReturnCtx(t);return y(r,{code:f.invalid_type,expected:_.undefined,received:r.parsedType}),S}return ie(t.data)}};$t.create=e=>new $t({typeName:w.ZodUndefined,...A(e)});var Rt=class extends I{_parse(t){if(this._getType(t)!==_.null){let r=this._getOrReturnCtx(t);return y(r,{code:f.invalid_type,expected:_.null,received:r.parsedType}),S}return ie(t.data)}};Rt.create=e=>new Rt({typeName:w.ZodNull,...A(e)});var ct=class extends I{constructor(){super(...arguments),this._any=!0}_parse(t){return ie(t.data)}};ct.create=e=>new ct({typeName:w.ZodAny,...A(e)});var ze=class extends I{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ie(t.data)}};ze.create=e=>new ze({typeName:w.ZodUnknown,...A(e)});var Te=class extends I{_parse(t){let n=this._getOrReturnCtx(t);return y(n,{code:f.invalid_type,expected:_.never,received:n.parsedType}),S}};Te.create=e=>new Te({typeName:w.ZodNever,...A(e)});var zt=class extends I{_parse(t){if(this._getType(t)!==_.undefined){let r=this._getOrReturnCtx(t);return y(r,{code:f.invalid_type,expected:_.void,received:r.parsedType}),S}return ie(t.data)}};zt.create=e=>new zt({typeName:w.ZodVoid,...A(e)});var We=class e extends I{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==_.array)return y(n,{code:f.invalid_type,expected:_.array,received:n.parsedType}),S;if(s.exactLength!==null){let i=n.data.length>s.exactLength.value,a=n.data.length<s.exactLength.value;(i||a)&&(y(n,{code:i?f.too_big:f.too_small,minimum:a?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(y(n,{code:f.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(y(n,{code:f.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>s.type._parseAsync(new Se(n,i,n.path,a)))).then(i=>re.mergeArray(r,i));let o=[...n.data].map((i,a)=>s.type._parseSync(new Se(n,i,n.path,a)));return re.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:b.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:b.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:b.toString(n)}})}nonempty(t){return this.min(1,t)}};We.create=(e,t)=>new We({type:e,minLength:null,maxLength:null,exactLength:null,typeName:w.ZodArray,...A(t)});function Kt(e){if(e instanceof me){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=be.create(Kt(r))}return new me({...e._def,shape:()=>t})}else return e instanceof We?new We({...e._def,type:Kt(e.element)}):e instanceof be?be.create(Kt(e.unwrap())):e instanceof Ue?Ue.create(Kt(e.unwrap())):e instanceof Ne?Ne.create(e.items.map(t=>Kt(t))):e}var me=class e extends I{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=M.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==_.object){let c=this._getOrReturnCtx(t);return y(c,{code:f.invalid_type,expected:_.object,received:c.parsedType}),S}let{status:r,ctx:s}=this._processInputParams(t),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Te&&this._def.unknownKeys==="strip"))for(let c in s.data)i.includes(c)||a.push(c);let l=[];for(let c of i){let u=o[c],m=s.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Se(s,m,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Te){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(c==="strict")a.length>0&&(y(s,{code:f.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let u of a){let m=s.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Se(s,m,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of l){let m=await u.key,h=await u.value;c.push({key:m,value:h,alwaysSet:u.alwaysSet})}return c}).then(c=>re.mergeObjectSync(r,c)):re.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return b.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:b.errToObj(t).message??s}:{message:s}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:w.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 M.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 M.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return Kt(this)}partial(t){let n={};for(let r of M.objectKeys(this.shape)){let s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let r of M.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof be;)o=o._def.innerType;n[r]=o}return new e({...this._def,shape:()=>n})}keyof(){return Ci(M.objectKeys(this.shape))}};me.create=(e,t)=>new me({shape:()=>e,unknownKeys:"strip",catchall:Te.create(),typeName:w.ZodObject,...A(t)});me.strictCreate=(e,t)=>new me({shape:()=>e,unknownKeys:"strict",catchall:Te.create(),typeName:w.ZodObject,...A(t)});me.lazycreate=(e,t)=>new me({shape:e,unknownKeys:"strip",catchall:Te.create(),typeName:w.ZodObject,...A(t)});var It=class extends I{_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new de(a.ctx.common.issues));return y(n,{code:f.invalid_union,unionErrors:i}),S}if(n.common.async)return Promise.all(r.map(async o=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let l of r){let c={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(l=>new de(l));return y(n,{code:f.invalid_union,unionErrors:a}),S}}get options(){return this._def.options}};It.create=(e,t)=>new It({options:e,typeName:w.ZodUnion,...A(t)});var Ge=e=>e instanceof Mt?Ge(e.schema):e instanceof we?Ge(e.innerType()):e instanceof Ot?[e.value]:e instanceof Nt?e.options:e instanceof Ut?M.objectValues(e.enum):e instanceof Dt?Ge(e._def.innerType):e instanceof $t?[void 0]:e instanceof Rt?[null]:e instanceof be?[void 0,...Ge(e.unwrap())]:e instanceof Ue?[null,...Ge(e.unwrap())]:e instanceof _n||e instanceof jt?Ge(e.unwrap()):e instanceof Lt?Ge(e._def.innerType):[],ar=class e extends I{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==_.object)return y(n,{code:f.invalid_type,expected:_.object,received:n.parsedType}),S;let r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(y(n,{code:f.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),S)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let s=new Map;for(let o of n){let i=Ge(o.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of i){if(s.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);s.set(a,o)}}return new e({typeName:w.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...A(r)})}};function xs(e,t){let n=Oe(e),r=Oe(t);if(e===t)return{valid:!0,data:e};if(n===_.object&&r===_.object){let s=M.objectKeys(t),o=M.objectKeys(e).filter(a=>s.indexOf(a)!==-1),i={...e,...t};for(let a of o){let l=xs(e[a],t[a]);if(!l.valid)return{valid:!1};i[a]=l.data}return{valid:!0,data:i}}else if(n===_.array&&r===_.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let o=0;o<e.length;o++){let i=e[o],a=t[o],l=xs(i,a);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return n===_.date&&r===_.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Pt=class extends I{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=(o,i)=>{if(or(o)||or(i))return S;let a=xs(o.value,i.value);return a.valid?((ir(o)||ir(i))&&n.dirty(),{status:n.value,value:a.data}):(y(r,{code:f.invalid_intersection_types}),S)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Pt.create=(e,t,n)=>new Pt({left:e,right:t,typeName:w.ZodIntersection,...A(n)});var Ne=class e extends I{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==_.array)return y(r,{code:f.invalid_type,expected:_.array,received:r.parsedType}),S;if(r.data.length<this._def.items.length)return y(r,{code:f.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S;!this._def.rest&&r.data.length>this._def.items.length&&(y(r,{code:f.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...r.data].map((i,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Se(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>re.mergeArray(n,i)):re.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ne.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ne({items:e,typeName:w.ZodTuple,rest:null,...A(t)})};var cr=class e extends I{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!==_.object)return y(r,{code:f.invalid_type,expected:_.object,received:r.parsedType}),S;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in r.data)s.push({key:o._parse(new Se(r,a,r.path,a)),value:i._parse(new Se(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?re.mergeObjectAsync(n,s):re.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof I?new e({keyType:t,valueType:n,typeName:w.ZodRecord,...A(r)}):new e({keyType:at.create(),valueType:t,typeName:w.ZodRecord,...A(n)})}},Wt=class extends I{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!==_.map)return y(r,{code:f.invalid_type,expected:_.map,received:r.parsedType}),S;let s=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([a,l],c)=>({key:s._parse(new Se(r,a,r.path,[c,"key"])),value:o._parse(new Se(r,l,r.path,[c,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of i){let c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return S;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let l of i){let c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return S;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}}}};Wt.create=(e,t,n)=>new Wt({valueType:t,keyType:e,typeName:w.ZodMap,...A(n)});var Jt=class e extends I{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==_.set)return y(r,{code:f.invalid_type,expected:_.set,received:r.parsedType}),S;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(y(r,{code:f.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(y(r,{code:f.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let o=this._def.valueType;function i(l){let c=new Set;for(let u of l){if(u.status==="aborted")return S;u.status==="dirty"&&n.dirty(),c.add(u.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((l,c)=>o._parse(new Se(r,l,r.path,c)));return r.common.async?Promise.all(a).then(l=>i(l)):i(a)}min(t,n){return new e({...this._def,minSize:{value:t,message:b.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:b.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};Jt.create=(e,t)=>new Jt({valueType:e,minSize:null,maxSize:null,typeName:w.ZodSet,...A(t)});var lr=class e extends I{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==_.function)return y(n,{code:f.invalid_type,expected:_.function,received:n.parsedType}),S;function r(a,l){return yn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Bt(),Ke].filter(c=>!!c),issueData:{code:f.invalid_arguments,argumentsError:l}})}function s(a,l){return yn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Bt(),Ke].filter(c=>!!c),issueData:{code:f.invalid_return_type,returnTypeError:l}})}let o={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof lt){let a=this;return ie(async function(...l){let c=new de([]),u=await a._def.args.parseAsync(l,o).catch(v=>{throw c.addIssue(r(l,v)),c}),m=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(m,o).catch(v=>{throw c.addIssue(s(m,v)),c})})}else{let a=this;return ie(function(...l){let c=a._def.args.safeParse(l,o);if(!c.success)throw new de([r(l,c.error)]);let u=Reflect.apply(i,this,c.data),m=a._def.returns.safeParse(u,o);if(!m.success)throw new de([s(u,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Ne.create(t).rest(ze.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||Ne.create([]).rest(ze.create()),returns:n||ze.create(),typeName:w.ZodFunction,...A(r)})}},Mt=class extends I{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})}};Mt.create=(e,t)=>new Mt({getter:e,typeName:w.ZodLazy,...A(t)});var Ot=class extends I{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return y(n,{received:n.data,code:f.invalid_literal,expected:this._def.value}),S}return{status:"valid",value:t.data}}get value(){return this._def.value}};Ot.create=(e,t)=>new Ot({value:e,typeName:w.ZodLiteral,...A(t)});function Ci(e,t){return new Nt({values:e,typeName:w.ZodEnum,...A(t)})}var Nt=class e extends I{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return y(n,{expected:M.joinValues(r),received:n.parsedType,code:f.invalid_type}),S}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 y(n,{received:n.data,code:f.invalid_enum_value,options:r}),S}return ie(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};Nt.create=Ci;var Ut=class extends I{_parse(t){let n=M.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==_.string&&r.parsedType!==_.number){let s=M.objectValues(n);return y(r,{expected:M.joinValues(s),received:r.parsedType,code:f.invalid_type}),S}if(this._cache||(this._cache=new Set(M.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let s=M.objectValues(n);return y(r,{received:r.data,code:f.invalid_enum_value,options:s}),S}return ie(t.data)}get enum(){return this._def.values}};Ut.create=(e,t)=>new Ut({values:e,typeName:w.ZodNativeEnum,...A(t)});var lt=class extends I{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==_.promise&&n.common.async===!1)return y(n,{code:f.invalid_type,expected:_.promise,received:n.parsedType}),S;let r=n.parsedType===_.promise?n.data:Promise.resolve(n.data);return ie(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};lt.create=(e,t)=>new lt({type:e,typeName:w.ZodPromise,...A(t)});var we=class extends I{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===w.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,o={addIssue:i=>{y(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(r.data,o);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return S;let l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?S:l.status==="dirty"?Ct(l.value):n.value==="dirty"?Ct(l.value):l});{if(n.value==="aborted")return S;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?S:a.status==="dirty"?Ct(a.value):n.value==="dirty"?Ct(a.value):a}}if(s.type==="refinement"){let i=a=>{let l=s.refinement(a,o);if(r.common.async)return Promise.resolve(l);if(l 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"?S:(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"?S:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(s.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!it(i))return S;let a=s.transform(i.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>it(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:n.value,value:a})):S);M.assertNever(s)}};we.create=(e,t,n)=>new we({schema:e,typeName:w.ZodEffects,effect:t,...A(n)});we.createWithPreprocess=(e,t,n)=>new we({schema:t,effect:{type:"preprocess",transform:e},typeName:w.ZodEffects,...A(n)});var be=class extends I{_parse(t){return this._getType(t)===_.undefined?ie(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};be.create=(e,t)=>new be({innerType:e,typeName:w.ZodOptional,...A(t)});var Ue=class extends I{_parse(t){return this._getType(t)===_.null?ie(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ue.create=(e,t)=>new Ue({innerType:e,typeName:w.ZodNullable,...A(t)});var Dt=class extends I{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===_.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Dt.create=(e,t)=>new Dt({innerType:e,typeName:w.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...A(t)});var Lt=class extends I{_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Ht(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new de(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new de(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Lt.create=(e,t)=>new Lt({innerType:e,typeName:w.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...A(t)});var Yt=class extends I{_parse(t){if(this._getType(t)!==_.nan){let r=this._getOrReturnCtx(t);return y(r,{code:f.invalid_type,expected:_.nan,received:r.parsedType}),S}return{status:"valid",value:t.data}}};Yt.create=e=>new Yt({typeName:w.ZodNaN,...A(e)});var ru=Symbol("zod_brand"),_n=class extends I{_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}},vn=class e extends I{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?S:o.status==="dirty"?(n.dirty(),Ct(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?S:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:w.ZodPipeline})}},jt=class extends I{_parse(t){let n=this._def.innerType._parse(t),r=s=>(it(s)&&(s.value=Object.freeze(s.value)),s);return Ht(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};jt.create=(e,t)=>new jt({innerType:e,typeName:w.ZodReadonly,...A(t)});function bi(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function ki(e,t={},n){return e?ct.create().superRefine((r,s)=>{let o=e(r);if(o instanceof Promise)return o.then(i=>{if(!i){let a=bi(t,r),l=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:l})}});if(!o){let i=bi(t,r),a=i.fatal??n??!0;s.addIssue({code:"custom",...i,fatal:a})}}):ct.create()}var su={object:me.lazycreate},w;(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"})(w||(w={}));var ou=(e,t={message:`Input not instance of ${e.name}`})=>ki(n=>n instanceof e,t),Ti=at.create,Ai=kt.create,iu=Yt.create,au=Tt.create,Ei=At.create,cu=Et.create,lu=Gt.create,uu=$t.create,du=Rt.create,mu=ct.create,pu=ze.create,fu=Te.create,gu=zt.create,hu=We.create,yu=me.create,_u=me.strictCreate,vu=It.create,bu=ar.create,Su=Pt.create,wu=Ne.create,xu=cr.create,Cu=Wt.create,ku=Jt.create,Tu=lr.create,Au=Mt.create,Eu=Ot.create,$u=Nt.create,Ru=Ut.create,Iu=lt.create,Pu=we.create,Mu=be.create,Ou=Ue.create,Nu=we.createWithPreprocess,Uu=vn.create,Du=()=>Ti().optional(),Lu=()=>Ai().optional(),ju=()=>Ei().optional(),Vu={string:(e=>at.create({...e,coerce:!0})),number:(e=>kt.create({...e,coerce:!0})),boolean:(e=>At.create({...e,coerce:!0})),bigint:(e=>Tt.create({...e,coerce:!0})),date:(e=>Et.create({...e,coerce:!0}))};var qu=S;var $i=["tempo","mpp_self","merchant_self"];var Cs=p.object({inputPerMillion:p.number().positive(),outputPerMillion:p.number().positive(),contextWindow:p.number().int().positive().optional(),maxOutput:p.number().int().positive().optional()}),Fu=p.object({strategy:p.enum(["flat","token","band"]).optional(),pricingModel:p.enum(["per-call","per-token","band"]).optional(),priceCents:p.number().nonnegative().optional(),currency:p.string().optional(),display:p.string().optional(),estimate:p.boolean().optional(),source:p.string().optional(),priceBand:p.record(p.unknown()).optional(),tokenPricing:Cs.optional()}).passthrough(),ks=p.discriminatedUnion("type",[p.object({type:p.literal("shortcut"),routedPath:p.string().min(1).startsWith("/")}),p.object({type:p.literal("custom"),merchantSlug:p.string().min(1),subPath:p.string().optional()}),p.object({type:p.literal("local"),fn:p.string().min(1)}),p.object({type:p.literal("read")})]),Ts=p.object({amount:p.number().nonnegative(),currency:p.string().length(3).optional(),display:p.string().optional(),free:p.boolean().optional(),batchDiscount:p.number().min(0).max(100).optional()}),Ri=p.object({attestation:p.boolean().optional(),rateLimitMs:p.number().positive().optional()}),Ii=p.object({displayName:p.string().optional(),feedbackEligible:p.boolean().optional(),suggestionEligible:p.boolean().optional(),batchable:p.boolean().optional()}),Bu=p.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),As={id:p.string().min(1),name:p.string().min(1),description:p.string().min(1),provider:p.string().min(1),model:p.string().min(1),category:Bu,priceCents:p.number().nonnegative(),inputSchema:p.record(p.unknown()),gatewayUrl:p.string().min(1),merchantName:p.string().min(1),isAsync:p.boolean().optional(),pollUrl:p.string().optional(),pollInterval:p.number().positive().optional(),pollTimeout:p.number().positive().optional(),tags:p.array(p.string()).optional(),tokenPricing:Cs.optional(),priceDisplay:p.string().optional(),pricingModel:p.enum(["per-call","per-token","band"]).optional(),pricingInfo:Fu.optional(),status:p.enum(["available","unavailable"]).optional(),handler:ks.optional(),pricing:Ts.optional(),security:Ri.optional(),engagement:Ii.optional(),enabled:p.boolean().optional(),beta:p.boolean().optional(),deprecated:p.boolean().optional(),replacementTool:p.string().optional(),minCliVersion:p.string().optional(),sunsetAt:p.string().optional(),rail:p.enum($i).optional(),pricingStrategy:p.enum(["flat","token","band"]).optional()},Pi=p.object({...As,dispatch:p.literal("routed"),routedPath:p.string().min(1).startsWith("/")}).strict(),Mi=p.object({...As,dispatch:p.literal("enveloped")}).strict(),Oi=p.object({...As,handler:ks,pricing:Ts}).strict(),Ni=p.union([p.discriminatedUnion("dispatch",[Pi,Mi]),Oi]);var Es=/^[a-z0-9][a-z0-9_-]*$/;var Li="https://fal.run",Ku="https://openrouter.mpp.tempo.xyz";function Gu(e){let{attestation:t,tool_id:n,...r}=e;return r}var Ui={"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 ur(e){let{attestation:t,tool_id:n,aspect_ratio:r,image_size:s,...o}=e,i={...o};return typeof s=="string"&&s.length>0?(i.image_size=s,i):(typeof r=="string"&&Ui[r]&&(i.image_size=Ui[r]),i)}function G(e,t,n,r,s,o,i,a){return{dispatch:"routed",id:e,name:t,description:n,provider:"fal",model:r,category:s,priceCents:o,inputSchema:i,routedPath:`/api/v1/fal/${r}`,gatewayUrl:`${Li}/${r}`,merchantName:"fal.ai",buildBody:Gu,tags:[],...a}}function zu(e){return t=>{let{attestation:n,tool_id:r,prompt:s,system_prompt:o,max_tokens:i,temperature:a,...l}=t;return{model:e,messages:[...o?[{role:"system",content:o}]:[],{role:"user",content:s}],max_tokens:i??1024,temperature:a??.7,...l}}}function ae(e,t,n,r,s,o,i){let a=5e-4*s*100,l=500/1e6*o*100,c=Math.max(1,Math.ceil(a+l));return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"llm",priceCents:c,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: 1024)",minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${Ku}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:zu(r),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:s,outputPerMillion:o},...i}}var $s=[G("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"]}),G("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:ur}),G("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:ur}),G("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:ur}),G("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"]}),G("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"]}),G("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"]}),G("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"]}),G("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"]}),G("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"]}),G("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"]}),G("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"]}),G("fal-stable-audio","Stable Audio","Generate music and sound effects 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","music","sound-effects"]}),G("suno-music","Suno Music","AI music generation. Create full songs with vocals or instrumentals.","suno/v4","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"]},{tags:["music","song","vocals","instrumental"],merchantName:"Suno AI",isAsync:!0,pollUrl:`${Li}/suno/v4/requests/{requestId}/status`}),G("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"]}),G("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"]}),G("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"]}),G("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("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"]}),ae("or-perplexity-sonar","Perplexity Sonar","Search-augmented LLM. Answers with real-time web sources and citations.","perplexity/sonar",1,1,{tags:["llm","perplexity","search","web","citations","real-time"]}),{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",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",buildBody:e=>ur({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",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",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",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"]},G("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"]}),G("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"]}),{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",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",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",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",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"]},{dispatch:"enveloped",id:"check_fal_status_card",name:"Check fal Async Job Status",description:"Poll an async fal.ai queue job for completion.",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",buildUrl:e=>`https://fal.mpp.tempo.xyz/queue/${e.model_path}/requests/${e.request_id}`,buildBody:()=>({}),tags:["status","fal","async","legacy"]},{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",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},tags:["tts","speech","f5-tts","legacy"]},{dispatch:"enveloped",id:"generate_music_tempo_card",name:"Generate Music (Suno)",description:"Generate a music track using Suno (async, ~$0.50).",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,tags:["music","audio","suno","async","legacy"]},{dispatch:"enveloped",id:"check_music_status_tempo_card",name:"Check Music Status",description:"Poll a Suno music generation task for completion.",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}),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",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:e=>{let t={chain:e.chain,token_address:e.token_address};if(e.start_timestamp){let n=e.end_timestamp||new Date().toISOString(),r=e.time_granularity;if(!r){let s=new Date(e.start_timestamp).getTime();(new Date(n).getTime()-s)/(1e3*60*60*24)<=2?r="1h":r="1d"}return{addresses:[t],start_timestamp:e.start_timestamp,end_timestamp:n,time_granularity:r}}return[t]},tags:["onchain","prices","allium","crypto","legacy"]}];function dr(e){return $s.find(t=>t.id===e)}var ji=1,Vi=["pick_one","fan_out"],qi=["concat","dedupe_by_url","top_k_by_score"],Ju=8,Yu=p.object({type:p.string().min(1),description:p.string().min(1),enum:p.array(p.string()).optional(),default:p.unknown().optional(),minimum:p.number().optional(),maximum:p.number().optional()}),Zu=p.object({toolId:p.string().min(1),notes:p.string().min(1)}),Xu=p.object({providers:p.array(p.string().min(1)).min(1).max(Ju),merge:p.enum(qi),maxResults:p.number().int().positive().optional()}),Fi=p.object({mode:p.enum(Vi).default("pick_one"),intro:p.string().min(1),defaultTier:p.string().min(1),tiers:p.record(p.string(),Zu).refine(e=>Object.keys(e).length>0,{message:"must have at least one tier"}),fanOut:Xu.optional(),guidance:p.string().min(1),inputProperties:p.record(p.string(),Yu),required:p.array(p.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"]}),Qu=p.object({version:p.literal(ji),generatedAt:p.string().datetime(),tools:p.record(p.string().regex(Es,"tool name must match MCP naming rules"),Fi).refine(e=>Object.keys(e).length>0,{message:"manifest must have at least one tool"})});var Os=require("child_process"),Wi=require("util"),Ji=T(require("crypto")),ce=T(require("fs")),Yi=T(require("os")),De=T(require("path"));var pe=T(require("fs")),Ps=T(require("path")),Bi=T(require("os")),Is=Ps.join(Bi.homedir(),".visa-mcp"),bn=Ps.join(Is,"mcp-server.log"),nd=5*1024*1024,Rs=null;function rd(){pe.existsSync(Is)||pe.mkdirSync(Is,{recursive:!0,mode:448})}function sd(){if(!Rs){if(rd(),pe.existsSync(bn)&&pe.statSync(bn).size>nd){let t=bn+".1";pe.existsSync(t)&&pe.unlinkSync(t),pe.renameSync(bn,t)}Rs=pe.createWriteStream(bn,{flags:"a"})}return Rs}function od(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function mr(e,...t){let n=new Date().toISOString(),r=t.map(o=>typeof o=="string"?o:JSON.stringify(o,null,2)).join(" "),s=`[${n}] [${e}] ${r}
37
+ `;od(e)&&process.stderr.write(s),sd().write(s)}var d={debug:(...e)=>mr("DEBUG",...e),info:(...e)=>mr("INFO",...e),warn:(...e)=>mr("WARN",...e),error:(...e)=>mr("ERROR",...e)};var Zt=(0,Wi.promisify)(Os.execFile),gr=De.join(Yi.homedir(),".visa-mcp","bin"),Vt=De.join(gr,"Visa CLI"),id=De.join(__dirname,"..","native"),Hi="5",Ki=De.join(gr,"visa-keychain.version"),Gi=De.join(gr,"visa-keychain.sha256");function zi(e){let t=ce.readFileSync(e);return Ji.createHash("sha256").update(t).digest("hex")}async function Zi(){try{if(ce.readFileSync(Ki,"utf-8").trim()===Hi&&ce.existsSync(Vt)){let r=ce.readFileSync(Gi,"utf-8").trim();if(zi(Vt)!==r)d.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),ce.unlinkSync(Vt);else return Vt}}catch{}let e=De.join(id,"visa-keychain.m");if(ce.existsSync(e)||(e=De.resolve(__dirname,"..","..","native","visa-keychain.m")),ce.existsSync(e)||(e=De.resolve(__dirname,"..","native","visa-keychain.m")),!ce.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");ce.mkdirSync(gr,{recursive:!0,mode:448});try{await Zt("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",Vt,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=zi(Vt);return ce.writeFileSync(Gi,t,{mode:384}),ce.writeFileSync(Ki,Hi,{mode:384}),Vt}async function Xi(e){let t=await Zi(),n;try{n=(await Zt(t,e,{timeout:6e4})).stdout}catch(o){n=o.stdout||"";let i=n.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(o.stderr?.trim()||o.message||"Unknown error")}let r=n.trim();if(r.startsWith("OK:"))return r.slice(3);if(r==="OK")return;let s=r.startsWith("ERROR:")?r.slice(6):"Unknown error";throw new Error(s)}var Ms=null;function z(){return process.env.VISA_MOCK_TOUCHID==="true"?!0:process.platform!=="darwin"?!1:Ms!==null?Ms:(Ms=!0,!0)}var pr="visa-cli",fr="attestation-key";async function ad(e){try{await Zt("security",["delete-generic-password","-s",pr,"-a",fr],{timeout:5e3})}catch{}await Zt("security",["add-generic-password","-s",pr,"-a",fr,"-w",e],{timeout:5e3})}async function cd(){try{let{stdout:e}=await Zt("security",["find-generic-password","-s",pr,"-a",fr,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function hr(){let e=await Xi(["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 ad(n),r}async function Xt(e,t){if(process.env.VISA_MOCK_TOUCHID==="true")return Promise.resolve("mock-ecdsa-signature-for-testing");let n=await cd();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await Zi(),s=["sign",e];return t&&s.push(t),new Promise((o,i)=>{let a=(0,Os.execFile)(r,s,{timeout:6e4},(l,c)=>{let u=(c||"").trim();if(l){u.startsWith("ERROR:")?i(new Error(u.slice(6))):i(new Error(l.stderr?.trim()||l.message||"Unknown error"));return}u.startsWith("OK:")?o(u.slice(3)):i(new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error"))});a.stdin.write(n),a.stdin.end()})}async function yr(){try{await Zt("security",["delete-generic-password","-s",pr,"-a",fr],{timeout:5e3})}catch{}try{await Xi(["delete-key"])}catch{}}var ld=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],ud=[...ld.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 Us(e,t=ud){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=Ns(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(Ns(r.match.provider)))&&r.match.keywords.every(s=>n.includes(Ns(s))))return r.targetToolId;return null}function Ns(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}var Qi={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; check_fal_status_card resolves 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. Call check_fal_status_card with those values to poll for completion. 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 ~60\u201390s music track from a prompt (Suno V4 \u2014 vocals, lyrics, full arrangement). ~$0.10. Use for jingles, soundtracks, ad music, viral original songs, or any "make me a song about \u2026" / "compose music for \u2026" request.',tiers:{suno:{toolId:"suno-music",notes:"Suno v4 \u2014 songs with vocals, lyrics, full arrangement"}},guidance:"Takes ~60-90s. Returns an audio URL the user can play.",inputProperties:{prompt:{type:"string",description:"Musical style / mood / lyrics hint."},instrumental:{type:"boolean",description:"True for instrumental (no vocals), false for vocal track.",default:!1}},required:["prompt"]},generate_audio:{intro:"Generate speech (TTS, voice-cloned) or sound effects from a prompt. $0.03\u2013$0.04. Use for: voiceover (tts tier \u2014 pass text + audio_url of the voice sample), SFX/ambient/background sound (sfx tier \u2014 pass prompt describing the sound).",tiers:{tts:{toolId:"fal-metavoice",notes:"MetaVoice \u2014 voice cloning TTS (requires a voice sample URL)"},sfx:{toolId:"fal-stable-audio",notes:"Stable Audio \u2014 sound effects and ambient from a prompt"}},guidance:"For tts: provide text + audio_url (voice sample to clone). For sfx: provide prompt describing the sound.",inputProperties:{prompt:{type:"string",description:"Description of sound to generate (sfx tier)."},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 MetaVoice)."}},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`."},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), 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 Ds(e,t,n){if(!ta(e))return pd(e,n);let r=ea[e];if(!r)return e;let s=Object.keys(r.tiers),o=t||s[0],i=fd(e,o,n);return i||gd(e,r,o,s)}function pd(e,t){return Us({requestedTool:e,intentText:t})??e}function fd(e,t,n){return Us({requestedTool:e,metaTool:e,tier:t,intentText:n})}function gd(e,t,n,r){let s=t.tiers[n];if(!s)throw new Error(`Unknown tier '${n}' for ${e}. Valid tiers: ${r.join(", ")}`);return s.toolId}var ea=Qi;function ta(e){return e in ea}var Sn=Object.keys(Qi);function Ls(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function na(e=process.env){return Ls(e)!==null}var se=T(require("crypto")),Ba=require("child_process"),Ae=T(require("fs")),$n=T(require("os")),Dr=T(require("path"));var L=T(require("fs")),Sr=T(require("os")),V=T(require("path")),ia=require("child_process");var ra=T(require("fs")),hd=["npm","pnpm","yarn","bun"],yd=/\s+/;function _d(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(yd)[0]??"",r=n.indexOf("/"),s=r===-1?n:n.slice(0,r);return hd.includes(s)?s:void 0}function js(e){if(!e)return;let t=e;try{t=ra.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 vd(e=process.argv[1]){return _d()??js(process.env.npm_execpath)??js(process.env.npm_node_execpath)??js(e)}function Vs(e,t,n){let r=t??vd(n)??"npm",o=`@visa/cli@${e??"latest"}`;switch(r){case"npm":return{packageManager:r,command:"npm",args:["install","-g",o],display:`npm install -g ${o}`};case"pnpm":return{packageManager:r,command:"pnpm",args:["add","-g",o],display:`pnpm add -g ${o}`};case"yarn":return{packageManager:r,command:"yarn",args:["global","add",o],display:`yarn global add ${o}`};case"bun":return{packageManager:r,command:"bun",args:["add","-g",o],display:`bun add -g ${o}`}}}function Qt(e,t,n){return Vs(e,t,n).display}var bd=2,wn="# >>> visa-cli shell hud v2 >>>",vr="# <<< visa-cli shell hud v2 <<<",aa="# >>> visa-cli shell hud >>>",Sd="# <<< visa-cli shell hud <<<",ca=3e4,wd="VISA | HUD not ready \u2014 run: visa-cli config hud doctor",xd={currentVersion:"0.0.0"},Cd=3e4;function Bs(){try{return V.join(zs(),".visa-cli")}catch{return V.join(Sr.tmpdir(),".visa-cli")}}function tn(){return V.join(Bs(),"shell-hud.json")}function wr(){return V.join(Bs(),"shell-hud.line")}function la(){return V.join(Bs(),"shell-hud.lock")}function rn(e){let t=e??process.env.SHELL;if(!t)return null;let n=V.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 Cn(e){let t=zs();if(e==="zsh")return V.join(t,".zshrc");if(e==="bash")return V.join(t,".bashrc");let n=(process.platform==="win32","PowerShell");return V.join(t,"Documents",n,"Microsoft.PowerShell_profile.ps1")}function kd(e){let t=zs(),n=[{shell:"zsh",rcPath:V.join(t,".zshrc")},{shell:"bash",rcPath:V.join(t,".bashrc")},{shell:"bash",rcPath:V.join(t,".bash_profile")},{shell:"powershell",rcPath:V.join(t,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1")}];if(!e)return n;let r=n.filter(o=>o.shell===e),s=n.filter(o=>o.shell!==e);return[...r,...s]}function Td(e){let t="$HOME/.visa-cli/shell-hud.line",n=Ud(e),r=Dd(e);if(e==="zsh")return`${wn}
38
38
  _visa_cli_shell_hud_precmd() {
39
39
  setopt localoptions no_bg_nice
40
40
  if [[ -f "${t}" ]]; then
@@ -51,7 +51,7 @@ autoload -Uz add-zsh-hook
51
51
  if [[ -z "\${precmd_functions[(r)_visa_cli_shell_hud_precmd]}" ]]; then
52
52
  add-zsh-hook precmd _visa_cli_shell_hud_precmd
53
53
  fi
54
- ${vr}`;if(e==="powershell"){let s="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${Sn}
54
+ ${vr}`;if(e==="powershell"){let s="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${wn}
55
55
  if (-not (Test-Path Function:\\global:__visa_cli_original_prompt)) {
56
56
  $function:global:__visa_cli_original_prompt = if (Test-Path Function:\\prompt) { $function:prompt } else { { '' } }
57
57
  }
@@ -70,7 +70,7 @@ function global:prompt {
70
70
  }
71
71
  & $function:global:__visa_cli_original_prompt
72
72
  }
73
- ${vr}`}return`${Sn}
73
+ ${vr}`}return`${wn}
74
74
  __visa_cli_shell_hud_precmd() {
75
75
  if [ -f "${t}" ]; then
76
76
  cat "${t}"
@@ -87,18 +87,18 @@ case ";$PROMPT_COMMAND;" in
87
87
  *";__visa_cli_shell_hud_precmd;"*) ;;
88
88
  *) PROMPT_COMMAND="__visa_cli_shell_hud_precmd\${PROMPT_COMMAND:+;$PROMPT_COMMAND}" ;;
89
89
  esac
90
- ${vr}`}function ca(e){let t=e;for(let[n,r]of[[Sn,vr],[oa,yd]])t=t.replace(new RegExp(`\\n?${ra(n)}[\\s\\S]*?${ra(r)}\\n?`,"g"),"");return t.trimEnd()}function xd(e,t){let n=ca(e).trimEnd(),r=wd(t);return n.length>0?`${n}
90
+ ${vr}`}function ua(e){let t=e;for(let[n,r]of[[wn,vr],[aa,Sd]])t=t.replace(new RegExp(`\\n?${oa(n)}[\\s\\S]*?${oa(r)}\\n?`,"g"),"");return t.trimEnd()}function Ad(e,t){let n=ua(e).trimEnd(),r=Td(t);return n.length>0?`${n}
91
91
 
92
92
  ${r}
93
93
  `:`${r}
94
- `}function xr(e=nn()){if(!e)return!1;try{let t=xn(e),n=L.readFileSync(t,"utf-8");return n.includes(Sn)||n.includes(oa)}catch{return!1}}function Cr(e=nn()){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=xn(e);let n=L.existsSync(t)?L.readFileSync(t,"utf-8"):"",r=xd(n,e),s=r!==n;return s&&br(t,r),{installed:!0,changed:s,shell:e,rcPath:t,message:s?`Persistent shell HUD installed in ${t}. Open a new terminal to start seeing it. Disable it any time with: visa-cli config shell-hud disable`:`Persistent shell HUD already installed in ${t}. Disable it any time with: visa-cli config shell-hud disable`}}catch(n){return{installed:!1,changed:!1,shell:e,rcPath:t,message:`Failed to install persistent shell HUD in ${t}: ${qs(n)}`}}}function kr(e=nn()){let t=[],n=[],r=[];try{for(let s of Sd(e))if(n.push(s.rcPath),!!L.existsSync(s.rcPath))try{let o=L.readFileSync(s.rcPath,"utf-8"),i=ca(o);if(i===o.trimEnd())continue;br(s.rcPath,i.length>0?`${i}
95
- `:""),t.push(s.rcPath)}catch(o){r.push(`${s.rcPath}: ${qs(o)}`)}return t.length>0?{removed:!0,shell:e,rcPath:t[0],rcPaths:t,message:r.length>0?`Removed persistent shell HUD from ${t.join(", ")}. Some rc files could not be updated: ${r.join("; ")}.`:`Removed persistent shell HUD from ${t.join(", ")}.`}:r.length>0?{removed:!1,shell:e,rcPath:n[0],rcPaths:n,message:`Failed to remove persistent shell HUD: ${r.join("; ")}`}:{removed:!0,shell:e,rcPath:n[0],rcPaths:n,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: ${qs(s)}`}}}function Bs(e,t){let n=t??vd,r=n.currentVersion==="0.0.0"&&e.version?e.version:n.currentVersion,s=tn(r),o=` ${Q("\u2502",Z.dim)} `,i=la(n),a=Td(n,i),l=a||n.updateCheckDisabled?"":i,c=kd(s,l);if(!e.enrolled)return[c,Q("setup needed",Z.visaGold),a].filter(Boolean).join(o);let u=Rd(e),m=Cd(e);return[c,Q(u,Z.visaGold),m,a].filter(Boolean).join(o)}function Cd(e){let t=typeof e.balanceCents=="number"?e.balanceCents:null,n=e.activeSession;if(t===null)return Q("balance unknown",Z.dim);let r=t/100;if(n){let o=Math.max(0,n.capCents),i=Math.max(0,n.estimatedRemainingCents),a=Math.max(0,o-i),l=o>0?Math.max(0,Math.min(1,a/o)):0;return`${$d(l)} ${Q(`${Qt(i/100)} in session`,Z.green)} ${Q(`(${Qt(a/100)}/${Qt(o/100)} cap)`,Z.dim)} ${Q("\xB7",Z.dim)} ${Q(`${Qt(r)} balance`,Z.dim)}`}return t>=100?Q(`${Qt(r)} balance`,Z.green):Q(`${Qt(r)} balance \u2014 top up via buy_credits`,Z.visaGold)}function na(e){let t=/^([0-9]+\.[0-9]+\.[0-9]+)-(rc|beta|alpha|next)\.[0-9]+$/.exec(e);return t?`${t[1]} ${t[2].toUpperCase()}`:e}function kd(e,t){let n=na(e),r=`${Q("VISA CLI",Z.visaBlue)} ${Q(`v${n}`,Z.visaBlueSoft)}`;if(!t)return r;let s=na(t);return`${r} ${Q("\u2B06 update",Z.visaGold)} ${Q(`v${s}`,Z.visaGold)}`}function Td(e,t){if(t&&!e.updateCheckDisabled){let n=tn(Xt(t));return Q(`run: ${n}`,Z.visaGold)}return t?null:Ad(e)}function la(e){return e.latestVersion?tn(e.latestVersion):""}function Ad(e){let t=la(e);return t?Q(`update ready v${t}`,Z.visaGold):null}function ua(){let e=Ks();return!(!e||Date.now()-e.renderedAt>ia||e.cwd&&e.cwd!==process.cwd())}function Tr(){let e=Ks();if(e&&Date.now()-e.renderedAt<=ia||(Ed(),e?.line))return e.line;try{let t=wr();if(L.existsSync(t))return L.readFileSync(t,"utf-8").trimEnd()}catch{}return _d}function Hs(e,t){try{let n=V.dirname(en());L.mkdirSync(n,{recursive:!0});let r=tn(e),s={hudVersion:hd,renderedAt:Date.now(),line:r,cwd:process.cwd(),status:t};br(en(),JSON.stringify(s)+`
94
+ `}function xr(e=rn()){if(!e)return!1;try{let t=Cn(e),n=L.readFileSync(t,"utf-8");return n.includes(wn)||n.includes(aa)}catch{return!1}}function Cr(e=rn()){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=Cn(e);let n=L.existsSync(t)?L.readFileSync(t,"utf-8"):"",r=Ad(n,e),s=r!==n;return s&&br(t,r),{installed:!0,changed:s,shell:e,rcPath:t,message:s?`Persistent shell HUD installed in ${t}. Open a new terminal to start seeing it. Disable it any time with: visa-cli config shell-hud disable`:`Persistent shell HUD already installed in ${t}. Disable it any time with: visa-cli config shell-hud disable`}}catch(n){return{installed:!1,changed:!1,shell:e,rcPath:t,message:`Failed to install persistent shell HUD in ${t}: ${Fs(n)}`}}}function kr(e=rn()){let t=[],n=[],r=[];try{for(let s of kd(e))if(n.push(s.rcPath),!!L.existsSync(s.rcPath))try{let o=L.readFileSync(s.rcPath,"utf-8"),i=ua(o);if(i===o.trimEnd())continue;br(s.rcPath,i.length>0?`${i}
95
+ `:""),t.push(s.rcPath)}catch(o){r.push(`${s.rcPath}: ${Fs(o)}`)}return t.length>0?{removed:!0,shell:e,rcPath:t[0],rcPaths:t,message:r.length>0?`Removed persistent shell HUD from ${t.join(", ")}. Some rc files could not be updated: ${r.join("; ")}.`:`Removed persistent shell HUD from ${t.join(", ")}.`}:r.length>0?{removed:!1,shell:e,rcPath:n[0],rcPaths:n,message:`Failed to remove persistent shell HUD: ${r.join("; ")}`}:{removed:!0,shell:e,rcPath:n[0],rcPaths:n,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: ${Fs(s)}`}}}function Hs(e,t){let n=t??xd,r=n.currentVersion==="0.0.0"&&e.version?e.version:n.currentVersion,s=nn(r),o=` ${Q("\u2502",Z.dim)} `,i=da(n),a=Rd(n,i),l=a||n.updateCheckDisabled?"":i,c=$d(s,l);if(!e.enrolled)return[c,Q("setup needed",Z.visaGold),a].filter(Boolean).join(o);let u=Od(e),m=Ed(e);return[c,Q(u,Z.visaGold),m,a].filter(Boolean).join(o)}function Ed(e){let t=typeof e.balanceCents=="number"?e.balanceCents:null,n=e.activeSession;if(t===null)return Q("balance unknown",Z.dim);let r=t/100;if(n){let o=Math.max(0,n.capCents),i=Math.max(0,n.estimatedRemainingCents),a=Math.max(0,o-i),l=o>0?Math.max(0,Math.min(1,a/o)):0;return`${Md(l)} ${Q(`${en(i/100)} in session`,Z.green)} ${Q(`(${en(a/100)}/${en(o/100)} cap)`,Z.dim)} ${Q("\xB7",Z.dim)} ${Q(`${en(r)} balance`,Z.dim)}`}return t>=100?Q(`${en(r)} balance`,Z.green):Q(`${en(r)} balance \u2014 top up via buy_credits`,Z.visaGold)}function sa(e){let t=/^([0-9]+\.[0-9]+\.[0-9]+)-(rc|beta|alpha|next)\.[0-9]+$/.exec(e);return t?`${t[1]} ${t[2].toUpperCase()}`:e}function $d(e,t){let n=sa(e),r=`${Q("VISA CLI",Z.visaBlue)} ${Q(`v${n}`,Z.visaBlueSoft)}`;if(!t)return r;let s=sa(t);return`${r} ${Q("\u2B06 update",Z.visaGold)} ${Q(`v${s}`,Z.visaGold)}`}function Rd(e,t){if(t&&!e.updateCheckDisabled){let n=nn(Qt(t));return Q(`run: ${n}`,Z.visaGold)}return t?null:Id(e)}function da(e){return e.latestVersion?nn(e.latestVersion):""}function Id(e){let t=da(e);return t?Q(`update ready v${t}`,Z.visaGold):null}function ma(){let e=Gs();return!(!e||Date.now()-e.renderedAt>ca||e.cwd&&e.cwd!==process.cwd())}function Tr(){let e=Gs();if(e&&Date.now()-e.renderedAt<=ca||(Pd(),e?.line))return e.line;try{let t=wr();if(L.existsSync(t))return L.readFileSync(t,"utf-8").trimEnd()}catch{}return wd}function Ks(e,t){try{let n=V.dirname(tn());L.mkdirSync(n,{recursive:!0});let r=nn(e),s={hudVersion:bd,renderedAt:Date.now(),line:r,cwd:process.cwd(),status:t};br(tn(),JSON.stringify(s)+`
96
96
  `),br(wr(),r+`
97
- `)}catch{}}function wn(){try{L.unlinkSync(aa())}catch{}}function Ks(){let e=en();if(!L.existsSync(e))return null;try{return JSON.parse(L.readFileSync(e,"utf-8"))}catch{return null}}function da(){return Ks()?.status??null}function Ed(){if(process.env.JEST_WORKER_ID)return;let e=aa();try{if(L.mkdirSync(V.dirname(e),{recursive:!0}),!Od(e))return;let t=process.argv[1]?V.resolve(process.argv[1]):"";if(!t){wn();return}let n=(0,sa.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});n.once("error",wn),n.unref()}catch{wn()}}function tn(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()}function $d(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${Q(r||"",Z.green)}${Q(s||"",Z.dim)}`}function Qt(e){return`$${e.toFixed(2)}`}function Rd(e){let t=e.cards?.find(a=>a.isDefault)??e.cards?.[0];if(!t)return"card none";let n=typeof t.brand=="string"?t.brand:"card",r=typeof t.last4=="string"?t.last4:"????",s=tn(n.toUpperCase()),o=tn(r);return`${t.isDefault?"default":"active"} ${s} ****${o}`}function Id(){let e=(process.env.COLORTERM??"").toLowerCase();if(e==="truecolor"||e==="24bit")return!0;let t=(process.env.TERM??"").toLowerCase();return t.includes("truecolor")||t.includes("24bit")}var Vs=Id(),Z={reset:"\x1B[0m",visaBlue:Vs?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:Vs?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:Vs?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function Q(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${Z.reset}`}function ra(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Gs(){let e=Sr.homedir();if(!e||!V.isAbsolute(e))throw new Error("unable to determine a valid home directory");return V.resolve(e)}function Pd(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function Md(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function Od(e){for(let t=0;t<2;t+=1){let n;try{return n=L.openSync(e,"wx"),L.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=L.statSync(e);if(Date.now()-s.mtimeMs<=bd)return!1;L.unlinkSync(e)}catch{}}finally{n!==void 0&&L.closeSync(n)}}return!1}function qs(e){return e instanceof Error?e.message:"unknown file system error"}function br(e,t){L.mkdirSync(V.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;L.writeFileSync(n,t),L.renameSync(n,e)}async function rn(e,t){try{return await t()}catch(n){if(n.message==="Invalid signature"&&z()){d.warn("attestation:key-mismatch",{action:"reregistering"});try{let r=await hr();await e.registerAttestationKey(r),d.info("attestation:key-reregistered")}catch(r){throw d.error("attestation:reregister-failure",{error:r.message}),n}return await t()}throw n}}var ma="2.0.0-rc.42";function zs(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function Ar(e,t,n){let r=process.env[e];if(r!==void 0)return{value:n==="opt-in"?r==="true":r!=="false",source:{kind:"env",var:e}};let s=tr(t);return s!==void 0?{value:s,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function he(e){return e==null?"\u2014":e?"yes":"no"}function Er(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function Nd(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function Ud(){let e=process.env.VISA_CREDIT_SESSION_CAP_CENTS;if(e!==void 0){let n=Number(e);if(Number.isFinite(n)&&n>=100&&n<=1e4)return{value:Math.floor(n),source:{kind:"env",var:"VISA_CREDIT_SESSION_CAP_CENTS"}}}let t=vs("credit.sessionCapCents");return t!==void 0&&t>=100&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:ys,source:{kind:"default"}}}async function $r(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(Y){n=Y?.message||"unknown error"}let r=[],s=process.env.VISA_AUTH_URL,o=_s("auth.serverUrl"),i=_e(),a=s!==void 0&&s!==""?{kind:"env",var:"VISA_AUTH_URL"}:o!==void 0?{kind:"settings"}:{kind:"default"};r.push({key:"auth.serverUrl",value:i,formatted:i,source:a,hint:a.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),r.push({key:"account.enrolled",value:t?.enrolled??null,formatted:he(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"}});let l=t?t.attestationRequired!==!1:void 0;r.push({key:"biometric.required",value:l,formatted:he(l),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"},hint:l===!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:he(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:z(),formatted:he(z()),source:{kind:"device"}});let c=t?.spendingControls,u=c?c.max_transaction_amount??c.maxTransactionAmount??null:null,m=c?c.daily_limit??c.dailyLimit??null:null;r.push({key:"spending.maxPerTxn",value:u,formatted:Er(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:m,formatted:Er(m),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:Er(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:Er(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 h=t?.cards?.find(Y=>Y.isDefault)??t?.cards?.[0];h&&r.push({key:"cards.default",value:{brand:h.brand??null,last4:h.last4},formatted:`${h.brand||"card"} \u2022\u2022\u2022\u2022 ${h.last4}`,source:{kind:"server"}});let v=Ud();r.push({key:"credit.sessionCapCents",value:v.value,formatted:Nd(v.value),source:v.source});let g=mi();g.length>0&&r.push({key:"settings.retired",value:g.map(Y=>Y.key),formatted:g.map(Y=>Y.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${g.map(Y=>`visa-cli config unset ${Y.key}`).join(" && ")}`});let x=Ar("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:x.value,formatted:he(x.value),source:x.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let O=Ar("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:O.value,formatted:he(O.value),source:O.source});let F=Me(),j;process.env.VISA_CLI_NO_UPDATE_CHECK?j={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?j={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?j={kind:"env",var:"NODE_ENV"}:j={kind:"default"},r.push({key:"ui.updateCheck",value:!F,formatted:he(!F),source:j});let k=Ar("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:k.value,formatted:he(k.value),source:k.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let P=Ar("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:P.value,formatted:he(P.value),source:P.source});let U=process.env.VISA_DRY_RUN,J=ea();if(r.push({key:"tools.dryRun",value:J,formatted:he(J),source:U===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:ma,formatted:ma,source:{kind:"default"}}),e.includeDev){let Y=process.env.VISA_MOCK_KEYCHAIN;r.push({key:"dev.mockKeychain",value:Y==="true",formatted:he(Y==="true"),source:zs("VISA_MOCK_KEYCHAIN",!!Y)});let yt=process.env.VISA_MOCK_TOUCHID;r.push({key:"dev.mockTouchid",value:yt==="true",formatted:he(yt==="true"),source:zs("VISA_MOCK_TOUCHID",!!yt)});let K=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!K,formatted:he(!!K),source:zs("VISA_CLI_DEBUG",!!K)})}return{entries:r,statusError:n}}function Dd(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 pa(e,t={}){if(e.length===0)return"";let n=Math.max(...e.map(o=>o.key.length)),r=Math.max(...e.map(o=>o.formatted.length)),s=[];for(let o of e){let i=o.key.padEnd(n+2),a=o.formatted.padEnd(r+2);s.push(`${i}${a}(${Dd(o.source)})`),t.verbose&&o.hint&&s.push(` ${"\u21B3".padStart(n)} ${o.hint}`)}return s.join(`
98
- `)}function fa(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 ga(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.10",what:"an AI song"}]}}}var lt=require("fs"),ya=require("os"),Ws=require("path"),Ld=(0,Ws.join)((0,ya.homedir)(),".visa-mcp"),ha=(0,Ws.join)(Ld,"mcp-session-budget.json");function Rr(){try{(0,lt.existsSync)(ha)&&(0,lt.unlinkSync)(ha)}catch{}}var Js=require("crypto"),Pr=null,Cn=0,kn=0,ut=0,Ys=null,Zs=null,Ir=Promise.resolve();function We(e){Pr=e,Cn=0,kn=0,ut=0,Ys=null,Zs=null,Ir=Promise.resolve()}function Tn(e){ut=Math.max(0,Math.floor(e))}function Xs(){return Pr}function Qs(e){if(!Pr)return null;let t=Cn+kn;return ut>0&&t>ut&&(t=ut),{session_budget_id:Pr,cumulative_micros:t*1e4,nonce:(0,Js.randomUUID)(),idempotency_key:e||(0,Js.randomUUID)()}}function eo(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 typeof r.cumulative=="number"&&Number.isFinite(r.cumulative)&&(Cn=r.cumulative,kn=0),Ys=r,r}function _a(){return Ys}function va(e){let t=e.receipt??null;Zs={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:Math.floor(e.voucher.cumulative_micros/1e4),estimatedCumulativeCents:Mr(),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 ba(){return Zs}function Sa(){return Cn}function Mr(){let e=Cn+kn;return ut>0&&e>ut&&(e=ut),e}function wa(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return Ir=Ir.then(()=>{kn+=t}),Ir}var xa=100,B=null,Ca=Promise.resolve();function to(e){let t=Ca.catch(()=>{}).then(e);return Ca=t.then(()=>{},()=>{}),t}var le=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 (or enable auto-topup with update_spending_controls).`),this.name="InsufficientBalanceError"}};async function no(e,t,n){return to(()=>ka(e,t,n))}async function ka(e,t,n){if(Rr(),B&&new Date(B.expiresAt).getTime()>Date.now())return Xs()!==B.budgetId&&(We(B.budgetId),Tn(B.totalCents)),d.info("mcp-session:active-hit",{budgetId:B.budgetId,tool:n.toolName,remainingEstimatedCents:B.totalCents-Mr()}),{budgetId:B.budgetId,isFresh:!1,totalCents:B.totalCents,requestedCapCents:B.totalCents,appliedCapCents:B.totalCents,clampedReason:null};B&&(B=null,We(null));let r=await e.getBalance();if(!r.success)throw new Error(`Could not read balance: ${r.error||"unknown error"}`);if(r.balanceCents<xa)throw new le(r.balanceCents,xa);let s=n.capCentsOverride??sr(),o=Math.min(s,r.balanceCents),i=o<s?"balance":null,a=await t("session_create",o,"Visa CLI Session",`open credit-model session with $${(o/100).toFixed(2)} cap`,n.userContext),l=await e.createSessionBudget({total_cents:o,...a?{attestation:a}:{}});if(!l.success||!l.budget){let u=l.error||"unknown error";throw new Error(`Failed to open credit session: ${u}`)}let c={budgetId:l.budget.id,expiresAt:l.budget.expiresAt,totalCents:l.budget.totalCents,createdAt:l.budget.createdAt};return B=c,We(c.budgetId),Tn(c.totalCents),d.info("mcp-session:opened",{budgetId:c.budgetId,capCents:c.totalCents,requestedCapCents:s,clampedReason:i,expiresAt:c.expiresAt,tool:n.toolName}),{budgetId:c.budgetId,isFresh:!0,totalCents:c.totalCents,requestedCapCents:s,appliedCapCents:c.totalCents,clampedReason:i}}async function Ta(e,t,n){return to(async()=>{let s=dt()?await Aa(e):null,o=await ka(e,t,n);return{budgetId:o.budgetId,totalCents:o.totalCents,closedPrevious:s,requestedCapCents:o.requestedCapCents,appliedCapCents:o.appliedCapCents,clampedReason:o.clampedReason}})}async function Aa(e){let n=dt()?.budgetId??Xs(),r=!1;if(n)try{r=!!(await e.closeSession(n))?.success}catch(s){d.warn("mcp-session:close-server-failed",{budgetId:n,error:s?.message||String(s)})}return Rr(),B=null,We(null),{closedServerSide:r,budgetId:n}}async function ro(e){return to(()=>Aa(e))}function dt(){return Rr(),B?new Date(B.expiresAt).getTime()<=Date.now()?(B=null,We(null),null):{budgetId:B.budgetId,totalCents:B.totalCents,lastReceiptCumulative:Sa(),lastReceiptCumulativeMicros:_a()?.cumulative_micros??null,estimatedCumulative:Mr(),lastToolSpend:ba(),expiresAt:B.expiresAt}:null}var Ra=A(so()),$a=10000n;function nm(e){return e<=0n?0:Number((e+$a-1n)/$a)}function Ia(e){return nm((0,Ra.fromUsd)(e))}var Pa=Promise.resolve();function Lr(e){let t=Pa.catch(()=>{}).then(e);return Pa=t.then(()=>{},()=>{}),t}async function Fa(e){let t=await no($,$e,{toolName:e.toolId,userContext:e.userContext}),n=Qs(e.idempotencyKey);if(!n)throw new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await lm(),{data:s,voucherReceiptHeader:o}=await $.shortcutWithSession(e.toolId,n,e.toolParams,e.timeoutMs,e.userContext,e.metaTool),i=eo(o);if(await wa(e.estimatedAmountCents),va({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:i}),Ha(s))return s;let a=await Ba();if(e.idempotencyKey&&Ka(s,a,e.idempotencyKey))return s;let l=a?Nr(a):null;return Ga(s,r,l)}function Le(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function ao(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(ao).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${ao(r)}`).join(",")}}`}function rm(e,t,n,r){let s=se.createHash("sha256").update(`${n}:${ao(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${s}`}function sm(e,t){return`${e}:${t}`}function om(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 Ma(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,s=mt(r),o=s!==null?s.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=om(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),l=i!=null?String(i):a;return{batch_id:e,item_id:sm(e,t),index:t,...l!==void 0?{transaction_id:l}:{},...a!==void 0?{ledger_id:a}:{},...o?{amountMicros:o,amount_micros:o,cost_micros:o}:{}}}async function im(e){let n=await $.getBalance();if(!n.success)throw new Error(`Could not read balance: ${n.error||"unknown error"}`);if(n.balanceCents<100)throw new le(n.balanceCents,100);let r=sr(),s=Math.min(r,n.balanceCents),o=Nr(n),i=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(s/100).toFixed(2)})`,a=await $e("session_create",s,"Visa CLI Session",i,e.userContext),l=await $.createSessionBudget({total_cents:s,...a?{attestation:a}:{}});if(!l.success||!l.budget)throw new Error(`Failed to open on-demand session: ${l.error||"unknown error"}`);let c=l.budget.id;We(c),Tn(l.budget.totalCents),d.info("on-demand-session:opened",{budgetId:c,capCents:l.budget.totalCents,tool:e.toolId});try{let u=Qs(e.idempotencyKey);if(!u)throw new Error(`Internal: mintVoucher returned null after on-demand session-open ${c}`);let{data:m,voucherReceiptHeader:h}=await $.shortcutWithSession(e.toolId,u,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(eo(h),Ha(m))return m;let v=await Ba();if(e.idempotencyKey&&Ka(m,v,e.idempotencyKey))return m;let g=v?Nr(v):null;return Ga(m,o,g)}finally{try{await $.closeSession(c)}catch(u){d.warn("on-demand-session:close-failed",{budgetId:c,error:u?.message||String(u)})}We(null),d.info("on-demand-session:closed",{budgetId:c,tool:e.toolId})}}async function ft(e){return Lr(async()=>dt()?Fa(e):im(e))}function jr(){return _e()}var $=new ve(()=>D.getSessionToken());function mt(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function Nr(e){return mt(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function am(e){if(e<0n&&(e=0n),e>=1000000n){let r=(e+5000n)/10000n,s=r/100n,o=r%100n;return`$${s.toString()}.${o.toString().padStart(2,"0")}`}let t=e%1000000n;return t===0n?"$0.00":`$0.${t.toString().padStart(6,"0").replace(/0+$/,"")}`}function cm(e){let t=mt(e.lastReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"lastReceiptCumulativeMicros"};let n=mt(e.lastToolSpend?.receiptCumulativeMicros);return n!==null?{micros:n,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function oo(e,t="INVALID_TOOL_PARAMS"){return{success:!1,error_code:t,code:t,error:e,message:e}}async function lm(){try{let e=await $.getBalance();return e.success?Nr(e):null}catch{return null}}async function Ba(){try{let e=await $.getBalance();return e.success?e:null}catch{return null}}function Ha(e){if(!e||e.success===!1)return!1;let t=mt(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=mt(e.amountMicros??e.amount_micros??e.charged_micros),r=t??n;if(r===null||r<=0n)return!1;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,e.charged_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),!0}function Ka(e,t,n){if(!e||e.success===!1||!t||!Array.isArray(t.ledger))return!1;let r=t.ledger.find(a=>a.idempotencyKey===n);if(!r)return!1;let s=mt(r.deltaMicros)??BigInt(r.deltaCents)*10000n,o=s<0n?-s:s;if(o<=0n)return!1;let i=o.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(o)/1e6),!0}function Ga(e,t,n){if(!e||e.success===!1||t===null||n===null)return e;let r=t-n;if(r<=0n)return e;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),e}var um="2.0.0-rc.42",Qh=["","","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 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(`
99
- `);function xe(e){if(!e||typeof e!="string"||pi())return;let t;try{t=new URL(e)}catch{return}if(t.protocol!=="https:"&&t.protocol!=="http:")return;let n=t.toString(),r=rs();if(r.headless){d.info(`Browser auto-open skipped (${r.reason}). URL: ${n}`);return}let s=ss(n);if(!s){d.info(`No browser command for platform "${En.platform()}". URL: ${n}`);return}(0,qa.execFile)(s.cmd,s.args,o=>{o&&d.warn(`Browser open failed: ${o.message}. URL: ${n}`)})}async function fe(e){return rn($,e)}var za="get_cards",Wa="set_default_card";function dm(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 '${za}' to see enrolled cards and '${Wa}' to switch, then retry the original request.`}function mm(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 '${za}' to see enrolled cards and '${Wa}' to switch. Do not retry automatically.`}function Ee(e,t){let n=e.retryable?dm(e.code,e.retryAfter):mm(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}}var sn=null,pm=3e4;function Ja(){sn=null}var pt=class extends Error{constructor(n){super(`${Ur()} attestation is required for this action, but it is not available in this MCP process. `+co());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function $n(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. `+co()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function Ur(){return process.platform==="darwin"?"Touch ID":"local biometric"}function co(){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."}function Vr(e){return typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0}async function fm(e){let t=Date.now();if(sn&&sn.expiresAt>t)return{required:sn.required,hasRegisteredKey:sn.hasRegisteredKey};try{let n=await $.getStatus(e),r=n.attestationRequired!==!1,s=Vr(n);return sn={required:r,hasRegisteredKey:s,expiresAt:t+pm},{required:r,hasRegisteredKey:s}}catch{return{required:!0,hasRegisteredKey:!0}}}async function $e(e,t,n,r,s){let o=await fm(s);if(!o.required){d.info("attestation:skipped-by-server-policy",{context:e});return}if(!o.hasRegisteredKey){d.info("attestation:skipped-no-registered-key",{context:e});return}if(!z())throw d.warn("attestation:unavailable",{context:e}),new pt(e);d.info("attestation:attempt",{context:e,amount:t,merchant:n});try{let{nonce:i}=await $.getAttestationChallenge(),a=Buffer.from(JSON.stringify({nonce:i,amount:t,merchant:n,context:e})).toString("base64");d.info("touchid:prompt",{context:e,amount:t,merchant:n});let l=await Yt(a,r);return d.info("attestation:success",{context:e,amount:t,merchant:n}),{signature:l,nonce:i,amount:t,merchant:n}}catch(i){throw d.error("attestation:failure",{context:e,amount:t,merchant:n,error:i.message}),i}}var Oa="[dry-run] https://placeholder.visa-cli.dev/image.png",gm=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"]),hm=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 ym(e,t){return t==="run_llm"||e.startsWith("or-")?"llm":t==="generate_image"||gm.has(e)?"image":t==="generate_video"||hm.has(e)?"video":null}function _m(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function vm(e){return e==="llm"?"OpenRouter":"fal.ai"}function on(e,t,n,r){let s={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:vm(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${_m(n)}`;return{...s,content:i,data:{content:i,model:t,dry_run:!0}}}return{...s,urls:[Oa],data:{[e==="video"?"videoUrl":"imageUrl"]:Oa,metadata:{dry_run:!0}}}}async function io(e){let t=e.mode??"mock",n=t==="preflight"?"/v1/telemetry/preflight":"/v1/telemetry/dry-run",r=t==="preflight"?"preflight":null;try{await $.emitTelemetry([{id:se.randomUUID(),timestamp:new Date().toISOString(),tool_name:e.toolName,user_prompt:e.userContext??"",tool_params:JSON.stringify(e.toolParams),result_success:!0,result_error:null,result_json:JSON.stringify(e.result),payment_rail:r,payment_amount:0,payment_currency:"USD",merchant_name:e.result.merchantName,transaction_id:e.result.transactionId,tx_hash:null,protocol:null,http_status:200,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",event_kind:"mcp_tool",endpoint:n,resolved_model:e.resolvedModel,session_budget_id:null}])}catch(s){d.warn("dry_run:telemetry_failed",{tool:e.toolName,error:s?.message||String(s),mode:t})}}var bm="https://openrouter.ai/api/v1/chat/completions",Sm="openrouter/free",wm=50,xm=15e3;function Cm(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 km(e,t,n){let r=process.env.OPENROUTER_API_KEY;if(!r)return d.warn("preflight:no_openrouter_key_falling_back_to_mock",{tool:e}),{result:on("llm",e,t,n),degraded:!0,resolvedModel:null};let s=Cm(t),o;try{o=await bt(bm,{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:Sm,messages:[{role:"user",content:s}],max_tokens:wm}),timeoutMs:xm})}catch(u){return d.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:on("llm",e,t,n),degraded:!0,resolvedModel:null}}if(!o.ok){let u=await o.text().catch(()=>"");return d.warn("preflight:openrouter_http_error_falling_back_to_mock",{tool:e,status:o.status,bodyExcerpt:u.slice(0,200)}),{result:on("llm",e,t,n),degraded:!0,resolvedModel:null}}let i;try{i=await o.json()}catch(u){return d.warn("preflight:openrouter_invalid_json_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:on("llm",e,t,n),degraded:!0,resolvedModel:null}}let a=typeof i?.choices?.[0]?.message?.content=="string"?i.choices[0].message.content:"",l=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:l},content:a,data:{content:a,model:l??e,dry_run:!0,preflight:!0}},degraded:!1,resolvedModel:l}}async function qr(e,t,n,r){let s=Ds();if(!s)return null;let o=ym(e,r);if(!o)return null;let i=Date.now();if(s==="mock"){let c=on(o,e,t,r);return await io({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:c,userContext:n,startedAt:i,mode:"mock"}),d.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:o,mode:s}),c}if(o!=="llm"){d.warn("preflight:not_supported_for_kind_falling_back_to_mock",{tool:e,kind:o});let c=on(o,e,t,r);return await io({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:c,userContext:n,startedAt:i,mode:"preflight"}),c}let{result:a,resolvedModel:l}=await km(e,t,r);return await io({toolName:r??e,resolvedModel:l??(r&&r!==e?e:null),toolParams:t,result:a,userContext:n,startedAt:i,mode:"preflight"}),d.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:o,mode:s}),a}async function Ye(e,t,n){let r=await $.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 gt(e){return Ia(e.amount)}function Tm(e){if(e.pricingMode==="max-cap"){let t=typeof e.estimatedAmount=="number"&&e.estimatedAmount>0?` (estimated $${e.estimatedAmount.toFixed(2)})`:"";return`pay up to $${e.amount.toFixed(2)} to ${e.merchantName}${t}`}return`pay $${e.amount.toFixed(2)} to ${e.merchantName}`}function Am(){return Dr.join(En.homedir(),".visa-mcp","allium-results")}var ey=16*1024,ty=50*1024*1024;function Em(){let e=Am();try{if(!Ae.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=Ae.readdirSync(e),n=0,r=0;for(let s of t)try{let o=Ae.statSync(Dr.join(e,s));o.isFile()&&(n+=o.size,r++)}catch{}return{file_count:r,size_bytes:n,path:e}}catch(t){return d.warn("allium:disk_usage_error",{error:t.message}),{file_count:0,size_bytes:0,path:e}}}async function Rn(e){if(!fi())try{let t=await D.getSessionToken();if(!t)return;await fetch(`${jr()}/v1/feed`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({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}}),signal:AbortSignal.timeout(5e3)}),d.info("feed:submitted",{tool:e.tool,mediaType:e.mediaType})}catch{}}async function $m(e,t){if(!e.url||!e.url.trim())throw new Error("A URL is required for payments. Provide the merchant payment endpoint.");let n=await Ye(void 0,e.url,t);d.info("payment:attempt",{tool:"pay",amount:n.amount,merchant:n.merchantName,url:e.url});try{return await fe(async()=>{let r=await $e(e.url||"pay",n.amount,n.merchantName,Tm(n)),s=await $.pay({url:e.url||"",merchantName:e.merchantName||"Unknown",description:e.description||"",method:e.method,body:e.body,attestation:r,idempotencyKey:se.randomUUID()},t);return s.success?(d.info("payment:success",{tool:"pay",amount:n.amount,merchant:n.merchantName,rail:s.receipt?.rail}),s.receipt&&gp(s.receipt)):d.warn("payment:declined",{tool:"pay",amount:n.amount,merchant:n.merchantName,message:s.message}),s})}catch(r){if(r instanceof ne)return d.warn("payment:declined",{tool:"pay",amount:n.amount,merchant:n.merchantName,code:r.code,retryable:r.retryable}),Ee(r,n);throw d.error("payment:failure",{tool:"pay",amount:n.amount,merchant:n.merchantName,error:r.message}),r}}async function Rm(e,t){let n=(e.state||"").trim().toUpperCase(),r=(e.county||"").trim(),s=(e.start_date||"").trim(),o=(e.end_date||s).trim();if(!/^[A-Z]{2}$/.test(n))throw new Error('state must be a 2-letter US state code (e.g. "VA").');if(!r)throw new Error("county is required.");if(!/^\d{4}-\d{2}$/.test(s))throw new Error('start_date must be YYYY-MM (e.g. "2025-08").');if(o&&!/^\d{4}-\d{2}$/.test(o))throw new Error("end_date must be YYYY-MM.");let i="Visa SMI",a=.1,l=`Pay $0.10 to ${i} for SMI data (${n} / ${r})`;d.info("payment:attempt",{tool:"get_visa_smi",amount:a,merchant:i});try{return await fe(async()=>{let c=await $e("get_visa_smi",a,i,l),u=await $.getVisaSmi({state:n,county:r,start_date:s,end_date:o,attestation:c,idempotencyKey:se.randomUUID()},t);return u.success?d.info("payment:success",{tool:"get_visa_smi",merchant:i,charged_cents:u.charged_cents}):d.warn("payment:declined",{tool:"get_visa_smi",merchant:i,message:u.error}),u})}catch(c){if(c instanceof ne)return d.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:c.code,retryable:c.retryable}),Ee(c,{amount:a,merchantName:i,description:"Visa SMI data"});throw d.error("payment:failure",{tool:"get_visa_smi",merchant:i,error:c.message}),c}}async function Im(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 qr("generate_image_card",e,t);if(n)return n;let r=await Ye("generate_image_card",void 0,t),s=se.randomUUID();d.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await fe(async()=>{let o;try{o=await ft({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:gt(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof le)return Le(i);throw i}return d.info("payment:success",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>xe(i)),Rn({prompt:e.prompt,tool:"generate_image_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):d.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof ne)return d.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),Ee(o,r);throw d.error("payment:failure",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,error:o.message}),o}}async function Pm(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 qr("generate_image_fast_card",e,t);if(n)return n;let r=await Ye("generate_image_fast_card",void 0,t),s=se.randomUUID();d.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await fe(async()=>{let o;try{o=await ft({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:gt(r),userContext:t,timeoutMs:6e4,idempotencyKey:s})}catch(i){if(i instanceof le)return Le(i);throw i}return d.info("payment:success",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>xe(i)),Rn({prompt:e.prompt,tool:"generate_image_fast_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):d.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof ne)return d.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),Ee(o,r);throw d.error("payment:failure",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,error:o.message}),o}}async function Mm(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 qr("generate_video_tempo_card",e,t);if(n)return n;let r=await Ye("generate_video_tempo_card",void 0,t),s=se.randomUUID();d.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await fe(async()=>{let o;try{o=await ft({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:gt(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof le)return Le(i);throw i}return d.info("payment:success",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>xe(i)),Rn({prompt:e.prompt,tool:"generate_video_tempo_card",mediaUrl:o.urls[0],mediaType:"video",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):d.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof ne)return d.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),Ee(o,r);throw d.error("payment:failure",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,error:o.message}),o}}async function Om(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 Ye("generate_music_tempo_card",void 0,t),r=se.randomUUID();d.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await fe(async()=>{let s;try{s=await ft({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:gt(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(o){if(o instanceof le)return Le(o);throw o}return d.info("payment:success",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),s.urls?.length&&s.status!=="processing"?(s.urls.forEach(o=>xe(o)),Rn({prompt:e.prompt,tool:"generate_music_tempo_card",mediaUrl:s.urls[0],mediaType:"audio",cost:s.amount??n.amount,transactionId:s.transactionId,userContext:t})):s.urls?.length&&s.status==="processing"?(s._preliminary_urls=s.urls,delete s.urls,d.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):d.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof ne)return d.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),Ee(s,n);throw d.error("payment:failure",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,error:s.message}),s}}async function Nm(e,t){let n=await Ye("check_music_status_tempo_card",void 0,t),r=se.randomUUID();d.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await fe(async()=>{let s;try{s=await ft({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:gt(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof le)return Le(o);throw o}return d.info("payment:success",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),s.urls?.length&&s.urls.forEach(o=>xe(o)),s})}catch(s){if(s instanceof ne)return d.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),Ee(s,n);throw d.error("payment:failure",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,error:s.message}),s}}async function Um(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 Ye("query_onchain_prices_card",void 0,t),r=se.randomUUID();d.info("payment:attempt",{tool:"query_onchain_prices_card",amount:n.amount,merchant:n.merchantName});try{return await fe(async()=>{let s;try{s=await ft({toolId:"query_onchain_prices_card",toolParams:e,estimatedAmountCents:gt(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof le)return Le(o);throw o}if(d.info("payment:success",{tool:"query_onchain_prices_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),Array.isArray(s?.data))s.data=s.data.map(o=>{if("mint"in o&&!("address"in o)){let{mint:i,...a}=o;return{address:i,...a}}return o});else if(s&&"mint"in s&&!("address"in s)){let{mint:o,...i}=s;return{address:o,...i}}return s})}catch(s){if(s instanceof ne)return d.warn("payment:declined",{tool:"query_onchain_prices_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),Ee(s,n);throw d.error("payment:failure",{tool:"query_onchain_prices_card",amount:n.amount,merchant:n.merchantName,error:s.message}),s}}var Dm=["generate_music_tempo_card"],Na=50,Ua=5,Da=new Map;function La(e){let t=Da.get(e);if(t!==void 0)return t;let r=dr(e)?.isAsync===!0||Dm.includes(e);return Da.set(e,r),r}var Lm=36e4,jm=18e4,Vm=15e3,qm=12e4,Fm=2e3;async function Bm(e,t){let n;if(e.requests?.some(k=>k.tool||k.tool_id)&&e.requests)n=e.requests.map(k=>{let P=k.tool||k.tool_id||e.tool;if(!P)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let U=Us(P,k.tier||e.tier,k.prompt??t),{tool:J,tool_id:Y,tier:yt,params:K,...Ce}=k,qn=K&&typeof K=="object"?{...K,...Ce}:Ce;return{resolvedTool:U,params:qn}});else if(e.tool){let k=Us(e.tool,e.tier,e.params?.prompt??t);n=(e.requests||(e.count&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(U=>({resolvedTool:k,params:U}))}else throw new Error("Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)throw new Error("Batch requires at least one item.");if(n.length>Na)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${Na} items. Please split into smaller batches.`};if([...new Set(n.map(k=>k.resolvedTool))].some(La)&&n.length>Ua)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${Ua} items. Please use multiple batches for more.`};let i=[...new Set(n.map(k=>k.resolvedTool))],a=i.length===1,l={};for(let k of i)l[k]=await Ye(k,void 0,t);let c=0;for(let k of n)c+=l[k.resolvedTool].amount;let u=[...new Set(Object.values(l).map(k=>k.merchantName))].join(", "),m=a?i[0]:"mixed";d.info("payment:attempt",{tool:"batch",batchTool:m,count:n.length,totalAmount:c,merchant:u,heterogeneous:!a});let h=n.some(k=>La(k.resolvedTool)),v=n.some(k=>k.resolvedTool.startsWith("or-")||k.resolvedTool==="run_llm"||k.resolvedTool==="execute_tool"),g=h?Lm:v?jm+n.length*Vm:qm+n.length*Fm,x=se.randomUUID(),O=[],F=0,j=0n;return Lr(async()=>{let k=!dt();if(k)try{await no($,$e,{toolName:"batch",userContext:t})}catch(P){return P instanceof le?Le(P):(d.warn("payment:batch-prewarm-failed",{batchTool:m,count:n.length,error:P?.message||String(P)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:P?.message||"Failed to authenticate batch session",tool:m,count:n.length,failedCount:n.length,results:[]})}try{for(let K=0;K<n.length;K+=1){let Ce=n[K],qn=l[Ce.resolvedTool];try{let ee=await Fa({toolId:Ce.resolvedTool,toolParams:Ce.params,estimatedAmountCents:gt(qn),userContext:t,metaTool:"batch",timeoutMs:g,idempotencyKey:rm(x,K,Ce.resolvedTool,Ce.params)});if(O.push({success:ee?.success!==!1,tool:Ce.resolvedTool,...ee,...Ma(x,K,ee)}),ee?.success!==!1){let dn=mt(ee?.amountMicros??ee?.amount_micros),Ao=typeof ee?.amount=="number"?ee.amount:qn.amount;dn!==null&&dn>0n?j+=dn:j+=BigInt(Math.round(Ao*1e6)),F+=Ao}ee?.urls&&ee.urls.forEach(dn=>xe(dn))}catch(ee){if(ee instanceof le&&O.length===0)return Le(ee);d.warn("payment:batch-item-failed",{tool:Ce.resolvedTool,index:K,error:ee?.message||String(ee)}),O.push({success:!1,tool:Ce.resolvedTool,...Ma(x,K),error:ee?.message||String(ee)})}}let P=O.filter(K=>K?.success===!1).length,U=O.length-P,J=O.flatMap(K=>Array.isArray(K?.urls)?K.urls:[]),Y=j>0n?Number(j)/1e6:Math.round((F+Number.EPSILON)*100)/100,yt=U===0?"failure":P===0?"success":"partial";return d.info("payment:success",{tool:"batch",batchTool:m,count:n.length,totalAmount:c,totalCharged:Y,merchant:u,successCount:U,failedCount:P,outcome:yt,mode:"session",batchId:x}),{success:U>0,outcome:yt,batch_id:x,tool:a?i[0]:m,count:n.length,successCount:U,failedCount:P,totalCharged:Y,...j>0n?{totalChargedMicros:j.toString(),amountMicros:j.toString(),amount_micros:j.toString()}:{},merchantName:u,results:O,...J.length?{urls:J}:{}}}catch(P){if(P instanceof ne)return d.warn("payment:declined",{tool:"batch",batchTool:m,count:n.length,totalAmount:c,merchant:u,code:P.code,retryable:P.retryable}),Ee(P,{amount:c,merchantName:u});throw d.error("payment:failure",{tool:"batch",batchTool:m,count:n.length,totalAmount:c,merchant:u,error:P.message}),P}finally{if(k){let P=await ro($);d.info("batch-session:closed",{budgetId:P.budgetId,closedServerSide:P.closedServerSide})}}})}function Hm(){let e=!1,t;try{let r=Dr.join(En.homedir(),".claude","settings.json");if(Ae.existsSync(r)){let s=JSON.parse(Ae.readFileSync(r,"utf-8")),o=typeof s.statusLine=="object"?s.statusLine.command:"";e=_t(o)}}catch{}let n=xr();return n||(t="visa-cli config shell-hud install"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function Km(e){let[t,n]=await Promise.all([$.getStatus(e),$.getBalance().catch(o=>(d.warn("get_status:balance_fetch_failed",{error:o?.message||String(o)}),null))]);typeof t?.dailyRemaining=="number"&&(t.dailyRemaining=Math.round(t.dailyRemaining*100)/100);let r=Em();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=Hm(),t.version=um,Array.isArray(t.cards)&&(t.cards=t.cards.map(o=>({...o,displayName:lo(o)})),t.cardIdGuidance="cardId values are opaque tool parameters only; refer to cards by brand and last four digits."),n&&n.success&&(t.balanceCents=n.balanceCents,t.amountUsd=n.amountUsd);let s=dt();if(t.sessionMode=!!s,s){let o=Math.max(0,s.totalCents-s.estimatedCumulative);t.activeSession={budgetId:s.budgetId,capCents:s.totalCents,capUsd:s.totalCents/100,lastReceiptCumulativeCents:s.lastReceiptCumulative,estimatedCumulativeCents:s.estimatedCumulative,spentCents:s.estimatedCumulative,spentUsd:s.estimatedCumulative/100,estimatedRemainingCents:o,estimatedRemainingUsd:o/100,...s.lastToolSpend?{lastToolSpend:{toolName:s.lastToolSpend.toolName,resolvedToolId:s.lastToolSpend.resolvedToolId,estimatedAmountCents:s.lastToolSpend.estimatedAmountCents,estimatedAmountUsd:s.lastToolSpend.estimatedAmountCents/100,voucherCumulativeCents:s.lastToolSpend.voucherCumulativeCents,estimatedCumulativeCents:s.lastToolSpend.estimatedCumulativeCents,receiptDeltaCents:s.lastToolSpend.receiptDeltaCents,receiptCumulativeCents:s.lastToolSpend.receiptCumulativeCents,receiptRemainingCents:s.lastToolSpend.receiptRemainingCents,recordedAt:s.lastToolSpend.recordedAt}}:{},expiresAt:s.expiresAt}}return t}function lo(e){let t=typeof e.brand=="string"&&e.brand.trim().length>0?e.brand.trim():"card",n=t.charAt(0).toUpperCase()+t.slice(1).toLowerCase(),r=typeof e.last4=="string"&&e.last4.trim().length>0?e.last4.trim():"unknown",s=e.isDefault===!0?" (default)":"";return`${n} ending in ${r}${s}`}async function Ya(e,t){try{let r=((await $.getStatus(t)).cards||[]).find(s=>s?.id===e);if(r)return lo(r)}catch(n){d.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function Gm(e){let n=(await $.getStatus(e)).cards||[];return n.length===0?{cards:[],message:"No cards enrolled. Use the add_card tool to add a payment card."}:n.some(s=>!Number.isInteger(s?.id)||s.id<=0)?{success:!1,cards:[],message:"Card action handles are unavailable right now, so remove_card and set_default_card are temporarily disabled."}:{cards:n.map(s=>({...s,displayName:lo(s)})),message:"Use cardId only as an opaque tool parameter. When speaking to the user, refer to cards by brand and last four digits, not by card id."}}async function zm(e,t){let n=await $.getTransactions({limit:e.limit,offset:e.offset},t);return Array.isArray(n?.transactions)&&(n.transactions=n.transactions.filter(r=>!(r.tool_name==null||r.amount===0&&r.status==="failed"))),n}async function Wm(e,t){return await $.feedback(e.message,e.transaction_id,t)}var Jm=100;async function Ym(e,t){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=Math.round(e.amount*100);if(n<Jm)return{success:!1,error:"Minimum top-up is $1.00"};let r=se.randomUUID();d.info("buy_credits:attempt",{amountCents:n});try{return await fe(async()=>{let s=await $e("balance-topup",e.amount,"Visa CLI Balance",`top up balance with $${e.amount.toFixed(2)}`),o=await $.topupBalance({amount_cents:n,idempotency_key:r,attestation:s});if(o.success){d.info("buy_credits:success",{amountCents:n,balanceCents:o.balanceCents});let i=((o.balanceCents??0)/100).toFixed(2),a=(n/100).toFixed(2);return{...o,amount:n/100,amountMicros:String(n*1e4),merchantName:"Visa CLI Balance",message:`Added $${a} \u2014 balance is now $${i}`}}return d.warn("buy_credits:failed",{amountCents:n,error:o.error}),o})}catch(s){if(s instanceof pt)return $n(s,"buy_credits");throw d.error("buy_credits:failure",{amountCents:n,error:s.message}),s}}function An(e,t){return{success:!1,error:t,code:e,message:t}}async function Zm(e,t){if(!e.confirm)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||e.maxTransactionAmount>1e4))return An("INVALID_VALUE","maxTransactionAmount must be between $0.01 and $10,000");if(e.dailyLimit!==void 0&&(typeof e.dailyLimit!="number"||!Number.isFinite(e.dailyLimit)||e.dailyLimit<1||e.dailyLimit>1e4))return An("INVALID_VALUE","dailyLimit must be between $1 and $10,000");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return An("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");d.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await fe(async()=>{let n=await $e("spending-controls",0,"","update spending controls"),r=await $.updateSpendingControls({maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit,confirm:!0,attestation:n},t);return d.info("spending_controls:success",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit}),r})}catch(n){if(d.error("spending_controls:failure",{error:n.message}),n instanceof pt)return $n(n,"update_spending_controls");throw n}}async function Xm(e){let t=await $r({api:$,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 Qm(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."};d.info("config:set",{key:e.key});try{let t=nr(e.key,e.value);return d.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 Fe?"UNKNOWN_KEY":t instanceof Be?"SERVER_CONTROLLED":t instanceof nt?"RETIRED_KEY":"INVALID_VALUE";return d.warn("config:set:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(st).sort()}}}async function ep(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."};d.info("config:unset",{key:e.key});try{let t=rr(e.key);return d.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 Fe?"UNKNOWN_KEY":t instanceof Be?"SERVER_CONTROLLED":t instanceof nt?"RETIRED_KEY":"INVALID_VALUE";return d.warn("config:unset:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(st).sort()}}}async function tp(e){let t=await $.getStatus(e),n=t.attestationRequired!==!1,r=Vr(t),s=z(),o=n?r?s?`${Ur()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${Ur()} is not available in this process. ${co()}`:"Biometric attestation is enabled on the account, but no attestation key is registered. Payments on this device proceed without a biometric signature; processor declines such as INVALID_OR_MISSING_CONFIG are card/account configuration issues, not something biometric setup fixes.":"Biometric attestation is NOT required for payments. Payments will proceed without biometric confirmation.";return{required:n,hasAttestationKey:!!t.hasAttestationKey,hasTelegramAttestationKey:!!t.hasTelegramAttestationKey,hasAnyAttestationKey:r,touchIdAvailable:s,platform:process.platform,effectiveRequiredOnThisDevice:n&&r&&s,canDisableFromThisDevice:!n||!r||s,message:o}}async function np(e){d.info("biometric:on");let t=await $.setBiometricPreference({required:!0},e);return t.success?(Ja(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:t.error||"unknown error"}}async function rp(e,t){if(!e.confirm)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.");d.info("biometric:off");try{return await fe(async()=>{let n=await $.getStatus(t),r;if(Vr(n)&&(r=await $e("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${Ur()} confirmation required to disable \u2014 not available on this device.`);let s=await $.setBiometricPreference({required:!1,attestation:r},t);if(!s.success)throw new Error(s.error||"unknown error");return Ja(),{success:!0,required:!1,message:"Touch ID is no longer required for payments."}})}catch(n){if(d.error("biometric:off:failure",{error:n.message}),n instanceof pt)return $n(n,"biometric_off");throw n}}var ja=3e4,sp=3e5;async function Za(e,t,n="login"){let r=se.randomUUID(),s=`${e}${e.includes("?")?"&":"?"}state=${r}`;return xe(s),Xa(r,t,n)}async function Xa(e,t,n="login"){let r=Date.now()+sp;for(;Date.now()<r;)try{let o=await fetch(`${jr()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:ja,...t&&{user_context:t}}),signal:AbortSignal.timeout(ja+5e3)});if(!o.ok){await tt(o,a=>{d.warn("auth_status:retry_after_http_error",{status:o.status,delayMs:a})});continue}let i=await o.json();if(i.status==="pending")continue;if(i.status==="expired")return{success:!1,message:"Session expired. Please try again."};if(i.status==="error")return{success:!1,message:i.error||"Authentication failed. Please try again."};if(i.status==="complete"){if(n==="attestation-recovery"||i.attestationCleared)return d.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,l=ga(a);if(i.sessionToken){await D.saveSessionToken(i.sessionToken);let u=i.user||"",m=i.last4||"****";return d.info("auth:login_complete",{user:u,last4:m,bonusCents:a}),{success:!0,message:`Signed in as ${u}. Card ending in ${m} enrolled and ready for payments.`,...l||{}}}let c=i.last4||"****";return d.info("auth:card_added",{last4:c,bonusCents:a}),{success:!0,message:`Card ending in ${c} enrolled and ready for payments.`,...l||{}}}}catch{await tt(void 0,o=>{d.warn("auth_status:retry_after_network_error",{delayMs:o})})}return{success:!1,message:n==="enrollment"?"Card enrollment timed out. Please try again.":n==="attestation-recovery"?"Biometric reset timed out. Please try reset again.":"Login timed out. Please try again."}}async function op(e){let t=se.randomUUID(),n;try{n=await $.startAttestationRecovery(t,e)}catch(r){return{success:!1,message:`Could not start biometric reset: ${r?.message||"unknown error"}`}}return!n.success||!n.recoveryUrl?{success:!1,message:n.error||"Could not start biometric reset. Please try again."}:(xe(n.recoveryUrl),Xa(t,e,"attestation-recovery"))}async function ip(e,t){if(!e.confirm)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."};d.info("cards:remove_attempt",{cardId:n});let r=`remove-card:${n}`,s=`remove ${await Ya(n,t)}`;try{return await fe(async()=>{let o=await $e(r,0,"",s),i=await $.removeCard(n,{attestation:o},t);return d.info("cards:remove_success",{cardId:n,promotedId:i?.promotedId??null}),i})}catch(o){if(d.error("cards:remove_failure",{cardId:n,error:o.message}),o instanceof pt)return $n(o,"remove_card");throw o}}async function ap(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."};d.info("cards:set_default_attempt",{cardId:n});let r=`set-default-card:${n}`,s=`set ${await Ya(n,t)} as default`;try{return await fe(async()=>{let o=await $e(r,0,"",s),i=await $.setDefaultCard(n,{attestation:o},t);return d.info("cards:set_default_success",{cardId:n}),i})}catch(o){if(d.error("cards:set_default_failure",{cardId:n,error:o.message}),o instanceof pt)return $n(o,"set_default_card");throw o}}async function cp(e){return d.info("auth:login_attempt"),Za(`${jr()}/login`,e)}function lp(e){if(e.capCents!==void 0){let t=Number(e.capCents);if(!Number.isFinite(t)||t<100||t>1e4)throw new Error("capCents must be between 100 ($1) 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 1 and 100");return Math.floor(t*100)}}async function up(e={},t){let n;try{n=lp(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return Lr(async()=>{let r=await Ta($,$e,{toolName:"start_session",userContext:t,capCentsOverride:n});d.info("session:started",{budgetId:r.budgetId,totalCents:r.totalCents,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious});let s=(r.appliedCapCents/100).toFixed(2),o=(r.requestedCapCents/100).toFixed(2),i=`Session started with a $${s} cap. Paid calls will use this approval window until you close it, it expires, or this MCP process restarts.`,a=r.clampedReason==="balance"?`${i} Note: requested cap of $${o} was clamped to your prepaid balance of $${s}. Run buy_credits to top up if you need a larger session.`:i;return{success:!0,budgetId:r.budgetId,totalCents:r.totalCents,amountUsd:r.totalCents/100,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious,message:a}})}async function dp(){let e=dt();if(!e)return{success:!0,active:!1,message:"No active session. Paid calls are pay-as-you-go and will request approval per call."};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 session: about $${(t/100).toFixed(2)} remaining of $${(e.totalCents/100).toFixed(2)}.`}}async function mp(){return Lr(async()=>{let e=dt();if(!e)return{success:!0,message:"No active session to close.",closed:!1};let t=await ro($);d.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=cm(e),r=n.micros,s=Number(r/10000n);return d.info("session:closed:final-spend",{budgetId:t.budgetId,closedServerSide:t.closedServerSide,finalSpendMicros:r.toString(),finalSpendCents:s,finalSpendSource:n.source,totalCents:e.totalCents}),{success:!0,closed:!0,closedServerSide:t.closedServerSide,budgetId:t.budgetId,finalEstimatedCumulativeCents:s,finalEstimatedCumulativeMicros:r.toString(),totalCents:e.totalCents,message:t.closedServerSide?`Session closed. Spent ${am(r)} of $${(e.totalCents/100).toFixed(2)} cap.`:"Session cleared locally; server-side close call did not succeed (likely already closed). Paid calls will use pay-as-you-go until you start a new session."}})}async function pp(e){return d.info("auth:add_card_attempt"),await D.getSessionToken()?Za(`${jr()}/enroll`,e,"enrollment"):{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."}}async function fp(e,t){if(!e.confirm)return{success:!1,message:"Please confirm by setting confirm: true to reset"};d.info("reset:attempt");let n=!1;try{let r=await $.getStatus(t);if(r&&Vr(r)){let s=await op(t);if(!s.success)return s;n=!0}}catch(r){let s=r?.message||"unknown error";if(!/not logged in|session.*expired|no local credentials/i.test(s))return{success:!1,message:`Could not check server biometric state: ${s}`};d.warn("reset:server_attestation_status_unavailable",{error:s})}try{await $.logout(void 0,t)}catch{}if(await D.clearAll(),z())try{await yr()}catch{}return d.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."}}function gp(e){let t=["url","resultUrl","imageUrl","audioUrl","trackUrl"];for(let n of t){let r=e[n];r&&typeof r=="string"&&r.startsWith("http")&&xe(r)}Array.isArray(e.urls)&&e.urls.forEach(n=>{n&&typeof n=="string"&&n.startsWith("http")&&xe(n)})}async function hp(e){let t=e.query?.trim()||void 0,n=e.category?.trim()||void 0,r=!t&&!n;d.info("catalog:discover",{query:t,category:n,browseAll:r});try{let o=(await $.catalogSearch(t,n)).tools||[];if(o.length===0)return{content:[{type:"text",text:r?"The tool catalog is currently empty.":`No tools found for "${t||n}". Try a different search term.`}]};if(r){let a={};for(let c of o){let u=c.category||"other";(a[u]??=[]).push(c)}let l=Object.keys(a).sort().map(c=>{let u=a[c].map((h,v)=>`${v+1}. **${h.name}** (${h.id})
97
+ `)}catch{}}function xn(){try{L.unlinkSync(la())}catch{}}function Gs(){let e=tn();if(!L.existsSync(e))return null;try{return JSON.parse(L.readFileSync(e,"utf-8"))}catch{return null}}function pa(){return Gs()?.status??null}function Pd(){if(process.env.JEST_WORKER_ID)return;let e=la();try{if(L.mkdirSync(V.dirname(e),{recursive:!0}),!Ld(e))return;let t=process.argv[1]?V.resolve(process.argv[1]):"";if(!t){xn();return}let n=(0,ia.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});n.once("error",xn),n.unref()}catch{xn()}}function nn(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()}function Md(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${Q(r||"",Z.green)}${Q(s||"",Z.dim)}`}function en(e){return`$${e.toFixed(2)}`}function Od(e){let t=e.cards?.find(a=>a.isDefault)??e.cards?.[0];if(!t)return"card none";let n=typeof t.brand=="string"?t.brand:"card",r=typeof t.last4=="string"?t.last4:"????",s=nn(n.toUpperCase()),o=nn(r);return`${t.isDefault?"default":"active"} ${s} ****${o}`}function Nd(){let e=(process.env.COLORTERM??"").toLowerCase();if(e==="truecolor"||e==="24bit")return!0;let t=(process.env.TERM??"").toLowerCase();return t.includes("truecolor")||t.includes("24bit")}var qs=Nd(),Z={reset:"\x1B[0m",visaBlue:qs?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:qs?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:qs?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function Q(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${Z.reset}`}function oa(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function zs(){let e=Sr.homedir();if(!e||!V.isAbsolute(e))throw new Error("unable to determine a valid home directory");return V.resolve(e)}function Ud(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function Dd(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function Ld(e){for(let t=0;t<2;t+=1){let n;try{return n=L.openSync(e,"wx"),L.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=L.statSync(e);if(Date.now()-s.mtimeMs<=Cd)return!1;L.unlinkSync(e)}catch{}}finally{n!==void 0&&L.closeSync(n)}}return!1}function Fs(e){return e instanceof Error?e.message:"unknown file system error"}function br(e,t){L.mkdirSync(V.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;L.writeFileSync(n,t),L.renameSync(n,e)}async function sn(e,t){try{return await t()}catch(n){if(n.message==="Invalid signature"&&z()){d.warn("attestation:key-mismatch",{action:"reregistering"});try{let r=await hr();await e.registerAttestationKey(r),d.info("attestation:key-reregistered")}catch(r){throw d.error("attestation:reregister-failure",{error:r.message}),n}return await t()}throw n}}var fa="2.0.0-rc.43";function Ws(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function Ar(e,t,n){let r=process.env[e];if(r!==void 0)return{value:n==="opt-in"?r==="true":r!=="false",source:{kind:"env",var:e}};let s=tr(t);return s!==void 0?{value:s,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function he(e){return e==null?"\u2014":e?"yes":"no"}function Er(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function jd(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function Vd(){let e=process.env.VISA_CREDIT_SESSION_CAP_CENTS;if(e!==void 0){let n=Number(e);if(Number.isFinite(n)&&n>=100&&n<=1e4)return{value:Math.floor(n),source:{kind:"env",var:"VISA_CREDIT_SESSION_CAP_CENTS"}}}let t=bs("credit.sessionCapCents");return t!==void 0&&t>=100&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:_s,source:{kind:"default"}}}async function $r(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(Y){n=Y?.message||"unknown error"}let r=[],s=process.env.VISA_AUTH_URL,o=vs("auth.serverUrl"),i=_e(),a=s!==void 0&&s!==""?{kind:"env",var:"VISA_AUTH_URL"}:o!==void 0?{kind:"settings"}:{kind:"default"};r.push({key:"auth.serverUrl",value:i,formatted:i,source:a,hint:a.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),r.push({key:"account.enrolled",value:t?.enrolled??null,formatted:he(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"}});let l=t?t.attestationRequired!==!1:void 0;r.push({key:"biometric.required",value:l,formatted:he(l),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"},hint:l===!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:he(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:z(),formatted:he(z()),source:{kind:"device"}});let c=t?.spendingControls,u=c?c.max_transaction_amount??c.maxTransactionAmount??null:null,m=c?c.daily_limit??c.dailyLimit??null:null;r.push({key:"spending.maxPerTxn",value:u,formatted:Er(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:m,formatted:Er(m),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:Er(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:Er(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 h=t?.cards?.find(Y=>Y.isDefault)??t?.cards?.[0];h&&r.push({key:"cards.default",value:{brand:h.brand??null,last4:h.last4},formatted:`${h.brand||"card"} \u2022\u2022\u2022\u2022 ${h.last4}`,source:{kind:"server"}});let v=Vd();r.push({key:"credit.sessionCapCents",value:v.value,formatted:jd(v.value),source:v.source});let g=fi();g.length>0&&r.push({key:"settings.retired",value:g.map(Y=>Y.key),formatted:g.map(Y=>Y.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${g.map(Y=>`visa-cli config unset ${Y.key}`).join(" && ")}`});let x=Ar("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:x.value,formatted:he(x.value),source:x.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let O=Ar("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:O.value,formatted:he(O.value),source:O.source});let F=Me(),j;process.env.VISA_CLI_NO_UPDATE_CHECK?j={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?j={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?j={kind:"env",var:"NODE_ENV"}:j={kind:"default"},r.push({key:"ui.updateCheck",value:!F,formatted:he(!F),source:j});let k=Ar("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:k.value,formatted:he(k.value),source:k.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let P=Ar("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:P.value,formatted:he(P.value),source:P.source});let U=process.env.VISA_DRY_RUN,J=na();if(r.push({key:"tools.dryRun",value:J,formatted:he(J),source:U===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:fa,formatted:fa,source:{kind:"default"}}),e.includeDev){let Y=process.env.VISA_MOCK_KEYCHAIN;r.push({key:"dev.mockKeychain",value:Y==="true",formatted:he(Y==="true"),source:Ws("VISA_MOCK_KEYCHAIN",!!Y)});let vt=process.env.VISA_MOCK_TOUCHID;r.push({key:"dev.mockTouchid",value:vt==="true",formatted:he(vt==="true"),source:Ws("VISA_MOCK_TOUCHID",!!vt)});let K=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!K,formatted:he(!!K),source:Ws("VISA_CLI_DEBUG",!!K)})}return{entries:r,statusError:n}}function qd(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 ga(e,t={}){if(e.length===0)return"";let n=Math.max(...e.map(o=>o.key.length)),r=Math.max(...e.map(o=>o.formatted.length)),s=[];for(let o of e){let i=o.key.padEnd(n+2),a=o.formatted.padEnd(r+2);s.push(`${i}${a}(${qd(o.source)})`),t.verbose&&o.hint&&s.push(` ${"\u21B3".padStart(n)} ${o.hint}`)}return s.join(`
98
+ `)}function ha(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 ya(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.10",what:"an AI song"}]}}}var ut=require("fs"),va=require("os"),Js=require("path"),Fd=(0,Js.join)((0,va.homedir)(),".visa-mcp"),_a=(0,Js.join)(Fd,"mcp-session-budget.json");function Rr(){try{(0,ut.existsSync)(_a)&&(0,ut.unlinkSync)(_a)}catch{}}var Ys=require("crypto"),Pr=null,kn=0,Tn=0,dt=0,Zs=null,Xs=null,Ir=Promise.resolve();function Je(e){Pr=e,kn=0,Tn=0,dt=0,Zs=null,Xs=null,Ir=Promise.resolve()}function An(e){dt=Math.max(0,Math.floor(e))}function Qs(){return Pr}function eo(e){if(!Pr)return null;let t=kn+Tn;return dt>0&&t>dt&&(t=dt),{session_budget_id:Pr,cumulative_micros:t*1e4,nonce:(0,Ys.randomUUID)(),idempotency_key:e||(0,Ys.randomUUID)()}}function to(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 typeof r.cumulative=="number"&&Number.isFinite(r.cumulative)&&(kn=r.cumulative,Tn=0),Zs=r,r}function ba(){return Zs}function Sa(e){let t=e.receipt??null;Xs={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:Math.floor(e.voucher.cumulative_micros/1e4),estimatedCumulativeCents:Mr(),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 wa(){return Xs}function xa(){return kn}function Mr(){let e=kn+Tn;return dt>0&&e>dt&&(e=dt),e}function Ca(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return Ir=Ir.then(()=>{Tn+=t}),Ir}var ka=100,B=null,Ta=Promise.resolve();function no(e){let t=Ta.catch(()=>{}).then(e);return Ta=t.then(()=>{},()=>{}),t}var le=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 (or enable auto-topup with update_spending_controls).`),this.name="InsufficientBalanceError"}};async function ro(e,t,n){return no(()=>Aa(e,t,n))}async function Aa(e,t,n){if(Rr(),B&&new Date(B.expiresAt).getTime()>Date.now())return Qs()!==B.budgetId&&(Je(B.budgetId),An(B.totalCents)),d.info("mcp-session:active-hit",{budgetId:B.budgetId,tool:n.toolName,remainingEstimatedCents:B.totalCents-Mr()}),{budgetId:B.budgetId,isFresh:!1,totalCents:B.totalCents,requestedCapCents:B.totalCents,appliedCapCents:B.totalCents,clampedReason:null};B&&(B=null,Je(null));let r=await e.getBalance();if(!r.success)throw new Error(`Could not read balance: ${r.error||"unknown error"}`);if(r.balanceCents<ka)throw new le(r.balanceCents,ka);let s=n.capCentsOverride??sr(),o=Math.min(s,r.balanceCents),i=o<s?"balance":null,a=await t("session_create",o,"Visa CLI Session",`open credit-model session with $${(o/100).toFixed(2)} cap`,n.userContext),l=await e.createSessionBudget({total_cents:o,...a?{attestation:a}:{}});if(!l.success||!l.budget){let u=l.error||"unknown error";throw new Error(`Failed to open credit session: ${u}`)}let c={budgetId:l.budget.id,expiresAt:l.budget.expiresAt,totalCents:l.budget.totalCents,createdAt:l.budget.createdAt};return B=c,Je(c.budgetId),An(c.totalCents),d.info("mcp-session:opened",{budgetId:c.budgetId,capCents:c.totalCents,requestedCapCents:s,clampedReason:i,expiresAt:c.expiresAt,tool:n.toolName}),{budgetId:c.budgetId,isFresh:!0,totalCents:c.totalCents,requestedCapCents:s,appliedCapCents:c.totalCents,clampedReason:i}}async function Ea(e,t,n){return no(async()=>{let s=mt()?await $a(e):null,o=await Aa(e,t,n);return{budgetId:o.budgetId,totalCents:o.totalCents,closedPrevious:s,requestedCapCents:o.requestedCapCents,appliedCapCents:o.appliedCapCents,clampedReason:o.clampedReason}})}async function $a(e){let n=mt()?.budgetId??Qs(),r=!1;if(n)try{r=!!(await e.closeSession(n))?.success}catch(s){d.warn("mcp-session:close-server-failed",{budgetId:n,error:s?.message||String(s)})}return Rr(),B=null,Je(null),{closedServerSide:r,budgetId:n}}async function so(e){return no(()=>$a(e))}function mt(){return Rr(),B?new Date(B.expiresAt).getTime()<=Date.now()?(B=null,Je(null),null):{budgetId:B.budgetId,totalCents:B.totalCents,lastReceiptCumulative:xa(),lastReceiptCumulativeMicros:ba()?.cumulative_micros??null,estimatedCumulative:Mr(),lastToolSpend:wa(),expiresAt:B.expiresAt}:null}var Pa=T(oo()),Ia=10000n;function im(e){return e<=0n?0:Number((e+Ia-1n)/Ia)}function Ma(e){return im((0,Pa.fromUsd)(e))}var Oa=Promise.resolve();function Lr(e){let t=Oa.catch(()=>{}).then(e);return Oa=t.then(()=>{},()=>{}),t}async function Ha(e){let t=await ro($,$e,{toolName:e.toolId,userContext:e.userContext}),n=eo(e.idempotencyKey);if(!n)throw new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await pm(),{data:s,voucherReceiptHeader:o}=await $.shortcutWithSession(e.toolId,n,e.toolParams,e.timeoutMs,e.userContext,e.metaTool),i=to(o);if(await Ca(e.estimatedAmountCents),Sa({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:i}),Ga(s))return s;let a=await Ka();if(e.idempotencyKey&&za(s,a,e.idempotencyKey))return s;let l=a?Nr(a):null;return Wa(s,r,l)}function je(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function co(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(co).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${co(r)}`).join(",")}}`}function am(e,t,n,r){let s=se.createHash("sha256").update(`${n}:${co(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${s}`}function cm(e,t){return`${e}:${t}`}function lm(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 Na(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,s=pt(r),o=s!==null?s.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=lm(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),l=i!=null?String(i):a;return{batch_id:e,item_id:cm(e,t),index:t,...l!==void 0?{transaction_id:l}:{},...a!==void 0?{ledger_id:a}:{},...o?{amountMicros:o,amount_micros:o,cost_micros:o}:{}}}async function um(e){let n=await $.getBalance();if(!n.success)throw new Error(`Could not read balance: ${n.error||"unknown error"}`);if(n.balanceCents<100)throw new le(n.balanceCents,100);let r=sr(),s=Math.min(r,n.balanceCents),o=Nr(n),i=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(s/100).toFixed(2)})`,a=await $e("session_create",s,"Visa CLI Session",i,e.userContext),l=await $.createSessionBudget({total_cents:s,...a?{attestation:a}:{}});if(!l.success||!l.budget)throw new Error(`Failed to open on-demand session: ${l.error||"unknown error"}`);let c=l.budget.id;Je(c),An(l.budget.totalCents),d.info("on-demand-session:opened",{budgetId:c,capCents:l.budget.totalCents,tool:e.toolId});try{let u=eo(e.idempotencyKey);if(!u)throw new Error(`Internal: mintVoucher returned null after on-demand session-open ${c}`);let{data:m,voucherReceiptHeader:h}=await $.shortcutWithSession(e.toolId,u,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(to(h),Ga(m))return m;let v=await Ka();if(e.idempotencyKey&&za(m,v,e.idempotencyKey))return m;let g=v?Nr(v):null;return Wa(m,o,g)}finally{try{await $.closeSession(c)}catch(u){d.warn("on-demand-session:close-failed",{budgetId:c,error:u?.message||String(u)})}Je(null),d.info("on-demand-session:closed",{budgetId:c,tool:e.toolId})}}async function gt(e){return Lr(async()=>mt()?Ha(e):um(e))}function jr(){return _e()}var $=new ve(()=>D.getSessionToken());function pt(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function Nr(e){return pt(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function dm(e){if(e<0n&&(e=0n),e>=1000000n){let r=(e+5000n)/10000n,s=r/100n,o=r%100n;return`$${s.toString()}.${o.toString().padStart(2,"0")}`}let t=e%1000000n;return t===0n?"$0.00":`$0.${t.toString().padStart(6,"0").replace(/0+$/,"")}`}function mm(e){let t=pt(e.lastReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"lastReceiptCumulativeMicros"};let n=pt(e.lastToolSpend?.receiptCumulativeMicros);return n!==null?{micros:n,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function io(e,t="INVALID_TOOL_PARAMS"){return{success:!1,error_code:t,code:t,error:e,message:e}}async function pm(){try{let e=await $.getBalance();return e.success?Nr(e):null}catch{return null}}async function Ka(){try{let e=await $.getBalance();return e.success?e:null}catch{return null}}function Ga(e){if(!e||e.success===!1)return!1;let t=pt(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=pt(e.amountMicros??e.amount_micros??e.charged_micros),r=t??n;if(r===null||r<=0n)return!1;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,e.charged_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),!0}function za(e,t,n){if(!e||e.success===!1||!t||!Array.isArray(t.ledger))return!1;let r=t.ledger.find(a=>a.idempotencyKey===n);if(!r)return!1;let s=pt(r.deltaMicros)??BigInt(r.deltaCents)*10000n,o=s<0n?-s:s;if(o<=0n)return!1;let i=o.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(o)/1e6),!0}function Wa(e,t,n){if(!e||e.success===!1||t===null||n===null)return e;let r=t-n;if(r<=0n)return e;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),e}var fm="2.0.0-rc.43",iy=["","","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 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(`
99
+ `);function xe(e){if(!e||typeof e!="string"||gi())return;let t;try{t=new URL(e)}catch{return}if(t.protocol!=="https:"&&t.protocol!=="http:")return;let n=t.toString(),r=ss();if(r.headless){d.info(`Browser auto-open skipped (${r.reason}). URL: ${n}`);return}let s=os(n);if(!s){d.info(`No browser command for platform "${$n.platform()}". URL: ${n}`);return}(0,Ba.execFile)(s.cmd,s.args,o=>{o&&d.warn(`Browser open failed: ${o.message}. URL: ${n}`)})}async function fe(e){return sn($,e)}var Ja="get_cards",Ya="set_default_card";function gm(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 '${Ja}' to see enrolled cards and '${Ya}' to switch, then retry the original request.`}function hm(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 '${Ja}' to see enrolled cards and '${Ya}' to switch. Do not retry automatically.`}function Ee(e,t){let n=e.retryable?gm(e.code,e.retryAfter):hm(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}}var on=null,ym=3e4;function Za(){on=null}var ft=class extends Error{constructor(n){super(`${Ur()} attestation is required for this action, but it is not available in this MCP process. `+lo());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function Rn(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. `+lo()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function Ur(){return process.platform==="darwin"?"Touch ID":"local biometric"}function lo(){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."}function Vr(e){return typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0}async function _m(e){let t=Date.now();if(on&&on.expiresAt>t)return{required:on.required,hasRegisteredKey:on.hasRegisteredKey};try{let n=await $.getStatus(e),r=n.attestationRequired!==!1,s=Vr(n);return on={required:r,hasRegisteredKey:s,expiresAt:t+ym},{required:r,hasRegisteredKey:s}}catch{return{required:!0,hasRegisteredKey:!0}}}async function $e(e,t,n,r,s){let o=await _m(s);if(!o.required){d.info("attestation:skipped-by-server-policy",{context:e});return}if(!o.hasRegisteredKey){d.info("attestation:skipped-no-registered-key",{context:e});return}if(!z())throw d.warn("attestation:unavailable",{context:e}),new ft(e);d.info("attestation:attempt",{context:e,amount:t,merchant:n});try{let{nonce:i}=await $.getAttestationChallenge(),a=Buffer.from(JSON.stringify({nonce:i,amount:t,merchant:n,context:e})).toString("base64");d.info("touchid:prompt",{context:e,amount:t,merchant:n});let l=await Xt(a,r);return d.info("attestation:success",{context:e,amount:t,merchant:n}),{signature:l,nonce:i,amount:t,merchant:n}}catch(i){throw d.error("attestation:failure",{context:e,amount:t,merchant:n,error:i.message}),i}}var Ua="[dry-run] https://placeholder.visa-cli.dev/image.png",vm=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"]),bm=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 Sm(e,t){return t==="run_llm"||e.startsWith("or-")?"llm":t==="generate_image"||vm.has(e)?"image":t==="generate_video"||bm.has(e)?"video":null}function wm(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function xm(e){return e==="llm"?"OpenRouter":"fal.ai"}function an(e,t,n,r){let s={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:xm(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${wm(n)}`;return{...s,content:i,data:{content:i,model:t,dry_run:!0}}}return{...s,urls:[Ua],data:{[e==="video"?"videoUrl":"imageUrl"]:Ua,metadata:{dry_run:!0}}}}async function ao(e){let t=e.mode??"mock",n=t==="preflight"?"/v1/telemetry/preflight":"/v1/telemetry/dry-run",r=t==="preflight"?"preflight":null;try{await $.emitTelemetry([{id:se.randomUUID(),timestamp:new Date().toISOString(),tool_name:e.toolName,user_prompt:e.userContext??"",tool_params:JSON.stringify(e.toolParams),result_success:!0,result_error:null,result_json:JSON.stringify(e.result),payment_rail:r,payment_amount:0,payment_currency:"USD",merchant_name:e.result.merchantName,transaction_id:e.result.transactionId,tx_hash:null,protocol:null,http_status:200,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",event_kind:"mcp_tool",endpoint:n,resolved_model:e.resolvedModel,session_budget_id:null}])}catch(s){d.warn("dry_run:telemetry_failed",{tool:e.toolName,error:s?.message||String(s),mode:t})}}var Cm="https://openrouter.ai/api/v1/chat/completions",km="openrouter/free",Tm=50,Am=15e3;function Em(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 $m(e,t,n){let r=process.env.OPENROUTER_API_KEY;if(!r)return d.warn("preflight:no_openrouter_key_falling_back_to_mock",{tool:e}),{result:an("llm",e,t,n),degraded:!0,resolvedModel:null};let s=Em(t),o;try{o=await wt(Cm,{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:km,messages:[{role:"user",content:s}],max_tokens:Tm}),timeoutMs:Am})}catch(u){return d.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:an("llm",e,t,n),degraded:!0,resolvedModel:null}}if(!o.ok){let u=await o.text().catch(()=>"");return d.warn("preflight:openrouter_http_error_falling_back_to_mock",{tool:e,status:o.status,bodyExcerpt:u.slice(0,200)}),{result:an("llm",e,t,n),degraded:!0,resolvedModel:null}}let i;try{i=await o.json()}catch(u){return d.warn("preflight:openrouter_invalid_json_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:an("llm",e,t,n),degraded:!0,resolvedModel:null}}let a=typeof i?.choices?.[0]?.message?.content=="string"?i.choices[0].message.content:"",l=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:l},content:a,data:{content:a,model:l??e,dry_run:!0,preflight:!0}},degraded:!1,resolvedModel:l}}async function qr(e,t,n,r){let s=Ls();if(!s)return null;let o=Sm(e,r);if(!o)return null;let i=Date.now();if(s==="mock"){let c=an(o,e,t,r);return await ao({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:c,userContext:n,startedAt:i,mode:"mock"}),d.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:o,mode:s}),c}if(o!=="llm"){d.warn("preflight:not_supported_for_kind_falling_back_to_mock",{tool:e,kind:o});let c=an(o,e,t,r);return await ao({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:c,userContext:n,startedAt:i,mode:"preflight"}),c}let{result:a,resolvedModel:l}=await $m(e,t,r);return await ao({toolName:r??e,resolvedModel:l??(r&&r!==e?e:null),toolParams:t,result:a,userContext:n,startedAt:i,mode:"preflight"}),d.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:o,mode:s}),a}async function Ze(e,t,n){let r=await $.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 ht(e){return Ma(e.amount)}function Rm(e){if(e.pricingMode==="max-cap"){let t=typeof e.estimatedAmount=="number"&&e.estimatedAmount>0?` (estimated $${e.estimatedAmount.toFixed(2)})`:"";return`pay up to $${e.amount.toFixed(2)} to ${e.merchantName}${t}`}return`pay $${e.amount.toFixed(2)} to ${e.merchantName}`}function Im(){return Dr.join($n.homedir(),".visa-mcp","allium-results")}var ay=16*1024,cy=50*1024*1024;function Pm(){let e=Im();try{if(!Ae.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=Ae.readdirSync(e),n=0,r=0;for(let s of t)try{let o=Ae.statSync(Dr.join(e,s));o.isFile()&&(n+=o.size,r++)}catch{}return{file_count:r,size_bytes:n,path:e}}catch(t){return d.warn("allium:disk_usage_error",{error:t.message}),{file_count:0,size_bytes:0,path:e}}}async function In(e){if(!hi())try{let t=await D.getSessionToken();if(!t)return;await fetch(`${jr()}/v1/feed`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({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}}),signal:AbortSignal.timeout(5e3)}),d.info("feed:submitted",{tool:e.tool,mediaType:e.mediaType})}catch{}}async function Mm(e,t){if(!e.url||!e.url.trim())throw new Error("A URL is required for payments. Provide the merchant payment endpoint.");let n=await Ze(void 0,e.url,t);d.info("payment:attempt",{tool:"pay",amount:n.amount,merchant:n.merchantName,url:e.url});try{return await fe(async()=>{let r=await $e(e.url||"pay",n.amount,n.merchantName,Rm(n)),s=await $.pay({url:e.url||"",merchantName:e.merchantName||"Unknown",description:e.description||"",method:e.method,body:e.body,attestation:r,idempotencyKey:se.randomUUID()},t);return s.success?(d.info("payment:success",{tool:"pay",amount:n.amount,merchant:n.merchantName,rail:s.receipt?.rail}),s.receipt&&vp(s.receipt)):d.warn("payment:declined",{tool:"pay",amount:n.amount,merchant:n.merchantName,message:s.message}),s})}catch(r){if(r instanceof ne)return d.warn("payment:declined",{tool:"pay",amount:n.amount,merchant:n.merchantName,code:r.code,retryable:r.retryable}),Ee(r,n);throw d.error("payment:failure",{tool:"pay",amount:n.amount,merchant:n.merchantName,error:r.message}),r}}async function Om(e,t){let n=(e.state||"").trim().toUpperCase(),r=(e.county||"").trim(),s=(e.start_date||"").trim(),o=(e.end_date||s).trim();if(!/^[A-Z]{2}$/.test(n))throw new Error('state must be a 2-letter US state code (e.g. "VA").');if(!r)throw new Error("county is required.");if(!/^\d{4}-\d{2}$/.test(s))throw new Error('start_date must be YYYY-MM (e.g. "2025-08").');if(o&&!/^\d{4}-\d{2}$/.test(o))throw new Error("end_date must be YYYY-MM.");let i="Visa SMI",a=.1,l=`Pay $0.10 to ${i} for SMI data (${n} / ${r})`;d.info("payment:attempt",{tool:"get_visa_smi",amount:a,merchant:i});try{return await fe(async()=>{let c=await $e("get_visa_smi",a,i,l),u=await $.getVisaSmi({state:n,county:r,start_date:s,end_date:o,attestation:c,idempotencyKey:se.randomUUID()},t);return u.success?d.info("payment:success",{tool:"get_visa_smi",merchant:i,charged_cents:u.charged_cents}):d.warn("payment:declined",{tool:"get_visa_smi",merchant:i,message:u.error}),u})}catch(c){if(c instanceof ne)return d.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:c.code,retryable:c.retryable}),Ee(c,{amount:a,merchantName:i,description:"Visa SMI data"});throw d.error("payment:failure",{tool:"get_visa_smi",merchant:i,error:c.message}),c}}async function Nm(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 qr("generate_image_card",e,t);if(n)return n;let r=await Ze("generate_image_card",void 0,t),s=se.randomUUID();d.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await fe(async()=>{let o;try{o=await gt({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:ht(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof le)return je(i);throw i}return d.info("payment:success",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>xe(i)),In({prompt:e.prompt,tool:"generate_image_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):d.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof ne)return d.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),Ee(o,r);throw d.error("payment:failure",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,error:o.message}),o}}async function Um(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 qr("generate_image_fast_card",e,t);if(n)return n;let r=await Ze("generate_image_fast_card",void 0,t),s=se.randomUUID();d.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await fe(async()=>{let o;try{o=await gt({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:ht(r),userContext:t,timeoutMs:6e4,idempotencyKey:s})}catch(i){if(i instanceof le)return je(i);throw i}return d.info("payment:success",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>xe(i)),In({prompt:e.prompt,tool:"generate_image_fast_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):d.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof ne)return d.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),Ee(o,r);throw d.error("payment:failure",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,error:o.message}),o}}async function Dm(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 qr("generate_video_tempo_card",e,t);if(n)return n;let r=await Ze("generate_video_tempo_card",void 0,t),s=se.randomUUID();d.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await fe(async()=>{let o;try{o=await gt({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:ht(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof le)return je(i);throw i}return d.info("payment:success",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>xe(i)),In({prompt:e.prompt,tool:"generate_video_tempo_card",mediaUrl:o.urls[0],mediaType:"video",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):d.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof ne)return d.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),Ee(o,r);throw d.error("payment:failure",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,error:o.message}),o}}async function Lm(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 Ze("generate_music_tempo_card",void 0,t),r=se.randomUUID();d.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await fe(async()=>{let s;try{s=await gt({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:ht(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(o){if(o instanceof le)return je(o);throw o}return d.info("payment:success",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),s.urls?.length&&s.status!=="processing"?(s.urls.forEach(o=>xe(o)),In({prompt:e.prompt,tool:"generate_music_tempo_card",mediaUrl:s.urls[0],mediaType:"audio",cost:s.amount??n.amount,transactionId:s.transactionId,userContext:t})):s.urls?.length&&s.status==="processing"?(s._preliminary_urls=s.urls,delete s.urls,d.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):d.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof ne)return d.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),Ee(s,n);throw d.error("payment:failure",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,error:s.message}),s}}async function jm(e,t){let n=await Ze("check_music_status_tempo_card",void 0,t),r=se.randomUUID();d.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await fe(async()=>{let s;try{s=await gt({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:ht(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof le)return je(o);throw o}return d.info("payment:success",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),s.urls?.length&&s.urls.forEach(o=>xe(o)),s})}catch(s){if(s instanceof ne)return d.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),Ee(s,n);throw d.error("payment:failure",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,error:s.message}),s}}async function Vm(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 Ze("query_onchain_prices_card",void 0,t),r=se.randomUUID();d.info("payment:attempt",{tool:"query_onchain_prices_card",amount:n.amount,merchant:n.merchantName});try{return await fe(async()=>{let s;try{s=await gt({toolId:"query_onchain_prices_card",toolParams:e,estimatedAmountCents:ht(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof le)return je(o);throw o}if(d.info("payment:success",{tool:"query_onchain_prices_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),Array.isArray(s?.data))s.data=s.data.map(o=>{if("mint"in o&&!("address"in o)){let{mint:i,...a}=o;return{address:i,...a}}return o});else if(s&&"mint"in s&&!("address"in s)){let{mint:o,...i}=s;return{address:o,...i}}return s})}catch(s){if(s instanceof ne)return d.warn("payment:declined",{tool:"query_onchain_prices_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),Ee(s,n);throw d.error("payment:failure",{tool:"query_onchain_prices_card",amount:n.amount,merchant:n.merchantName,error:s.message}),s}}var qm=["generate_music_tempo_card"],Da=50,La=5,ja=new Map;function Va(e){let t=ja.get(e);if(t!==void 0)return t;let r=dr(e)?.isAsync===!0||qm.includes(e);return ja.set(e,r),r}var Fm=36e4,Bm=18e4,Hm=15e3,Km=12e4,Gm=2e3;async function zm(e,t){let n;if(e.requests?.some(k=>k.tool||k.tool_id)&&e.requests)n=e.requests.map(k=>{let P=k.tool||k.tool_id||e.tool;if(!P)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let U=Ds(P,k.tier||e.tier,k.prompt??t),{tool:J,tool_id:Y,tier:vt,params:K,...Ce}=k,qn=K&&typeof K=="object"?{...K,...Ce}:Ce;return{resolvedTool:U,params:qn}});else if(e.tool){let k=Ds(e.tool,e.tier,e.params?.prompt??t);n=(e.requests||(e.count&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(U=>({resolvedTool:k,params:U}))}else throw new Error("Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)throw new Error("Batch requires at least one item.");if(n.length>Da)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${Da} items. Please split into smaller batches.`};if([...new Set(n.map(k=>k.resolvedTool))].some(Va)&&n.length>La)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${La} items. Please use multiple batches for more.`};let i=[...new Set(n.map(k=>k.resolvedTool))],a=i.length===1,l={};for(let k of i)l[k]=await Ze(k,void 0,t);let c=0;for(let k of n)c+=l[k.resolvedTool].amount;let u=[...new Set(Object.values(l).map(k=>k.merchantName))].join(", "),m=a?i[0]:"mixed";d.info("payment:attempt",{tool:"batch",batchTool:m,count:n.length,totalAmount:c,merchant:u,heterogeneous:!a});let h=n.some(k=>Va(k.resolvedTool)),v=n.some(k=>k.resolvedTool.startsWith("or-")||k.resolvedTool==="run_llm"||k.resolvedTool==="execute_tool"),g=h?Fm:v?Bm+n.length*Hm:Km+n.length*Gm,x=se.randomUUID(),O=[],F=0,j=0n;return Lr(async()=>{let k=!mt();if(k)try{await ro($,$e,{toolName:"batch",userContext:t})}catch(P){return P instanceof le?je(P):(d.warn("payment:batch-prewarm-failed",{batchTool:m,count:n.length,error:P?.message||String(P)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:P?.message||"Failed to authenticate batch session",tool:m,count:n.length,failedCount:n.length,results:[]})}try{for(let K=0;K<n.length;K+=1){let Ce=n[K],qn=l[Ce.resolvedTool];try{let ee=await Ha({toolId:Ce.resolvedTool,toolParams:Ce.params,estimatedAmountCents:ht(qn),userContext:t,metaTool:"batch",timeoutMs:g,idempotencyKey:am(x,K,Ce.resolvedTool,Ce.params)});if(O.push({success:ee?.success!==!1,tool:Ce.resolvedTool,...ee,...Na(x,K,ee)}),ee?.success!==!1){let mn=pt(ee?.amountMicros??ee?.amount_micros),$o=typeof ee?.amount=="number"?ee.amount:qn.amount;mn!==null&&mn>0n?j+=mn:j+=BigInt(Math.round($o*1e6)),F+=$o}ee?.urls&&ee.urls.forEach(mn=>xe(mn))}catch(ee){if(ee instanceof le&&O.length===0)return je(ee);d.warn("payment:batch-item-failed",{tool:Ce.resolvedTool,index:K,error:ee?.message||String(ee)}),O.push({success:!1,tool:Ce.resolvedTool,...Na(x,K),error:ee?.message||String(ee)})}}let P=O.filter(K=>K?.success===!1).length,U=O.length-P,J=O.flatMap(K=>Array.isArray(K?.urls)?K.urls:[]),Y=j>0n?Number(j)/1e6:Math.round((F+Number.EPSILON)*100)/100,vt=U===0?"failure":P===0?"success":"partial";return d.info("payment:success",{tool:"batch",batchTool:m,count:n.length,totalAmount:c,totalCharged:Y,merchant:u,successCount:U,failedCount:P,outcome:vt,mode:"session",batchId:x}),{success:U>0,outcome:vt,batch_id:x,tool:a?i[0]:m,count:n.length,successCount:U,failedCount:P,totalCharged:Y,...j>0n?{totalChargedMicros:j.toString(),amountMicros:j.toString(),amount_micros:j.toString()}:{},merchantName:u,results:O,...J.length?{urls:J}:{}}}catch(P){if(P instanceof ne)return d.warn("payment:declined",{tool:"batch",batchTool:m,count:n.length,totalAmount:c,merchant:u,code:P.code,retryable:P.retryable}),Ee(P,{amount:c,merchantName:u});throw d.error("payment:failure",{tool:"batch",batchTool:m,count:n.length,totalAmount:c,merchant:u,error:P.message}),P}finally{if(k){let P=await so($);d.info("batch-session:closed",{budgetId:P.budgetId,closedServerSide:P.closedServerSide})}}})}function Wm(){let e=!1,t;try{let r=Dr.join($n.homedir(),".claude","settings.json");if(Ae.existsSync(r)){let s=JSON.parse(Ae.readFileSync(r,"utf-8")),o=typeof s.statusLine=="object"?s.statusLine.command:"";e=bt(o)}}catch{}let n=xr();return n||(t="visa-cli config shell-hud install"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function Jm(e){let[t,n]=await Promise.all([$.getStatus(e),$.getBalance().catch(o=>(d.warn("get_status:balance_fetch_failed",{error:o?.message||String(o)}),null))]);typeof t?.dailyRemaining=="number"&&(t.dailyRemaining=Math.round(t.dailyRemaining*100)/100);let r=Pm();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=Wm(),t.version=fm,Array.isArray(t.cards)&&(t.cards=t.cards.map(o=>({...o,displayName:uo(o)})),t.cardIdGuidance="cardId values are opaque tool parameters only; refer to cards by brand and last four digits."),n&&n.success&&(t.balanceCents=n.balanceCents,t.amountUsd=n.amountUsd);let s=mt();if(t.sessionMode=!!s,s){let o=Math.max(0,s.totalCents-s.estimatedCumulative);t.activeSession={budgetId:s.budgetId,capCents:s.totalCents,capUsd:s.totalCents/100,lastReceiptCumulativeCents:s.lastReceiptCumulative,estimatedCumulativeCents:s.estimatedCumulative,spentCents:s.estimatedCumulative,spentUsd:s.estimatedCumulative/100,estimatedRemainingCents:o,estimatedRemainingUsd:o/100,...s.lastToolSpend?{lastToolSpend:{toolName:s.lastToolSpend.toolName,resolvedToolId:s.lastToolSpend.resolvedToolId,estimatedAmountCents:s.lastToolSpend.estimatedAmountCents,estimatedAmountUsd:s.lastToolSpend.estimatedAmountCents/100,voucherCumulativeCents:s.lastToolSpend.voucherCumulativeCents,estimatedCumulativeCents:s.lastToolSpend.estimatedCumulativeCents,receiptDeltaCents:s.lastToolSpend.receiptDeltaCents,receiptCumulativeCents:s.lastToolSpend.receiptCumulativeCents,receiptRemainingCents:s.lastToolSpend.receiptRemainingCents,recordedAt:s.lastToolSpend.recordedAt}}:{},expiresAt:s.expiresAt}}return t}function uo(e){let t=typeof e.brand=="string"&&e.brand.trim().length>0?e.brand.trim():"card",n=t.charAt(0).toUpperCase()+t.slice(1).toLowerCase(),r=typeof e.last4=="string"&&e.last4.trim().length>0?e.last4.trim():"unknown",s=e.isDefault===!0?" (default)":"";return`${n} ending in ${r}${s}`}async function Xa(e,t){try{let r=((await $.getStatus(t)).cards||[]).find(s=>s?.id===e);if(r)return uo(r)}catch(n){d.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function Ym(e){let n=(await $.getStatus(e)).cards||[];return n.length===0?{cards:[],message:"No cards enrolled. Use the add_card tool to add a payment card."}:n.some(s=>!Number.isInteger(s?.id)||s.id<=0)?{success:!1,cards:[],message:"Card action handles are unavailable right now, so remove_card and set_default_card are temporarily disabled."}:{cards:n.map(s=>({...s,displayName:uo(s)})),message:"Use cardId only as an opaque tool parameter. When speaking to the user, refer to cards by brand and last four digits, not by card id."}}async function Zm(e,t){let n=await $.getTransactions({limit:e.limit,offset:e.offset},t);return Array.isArray(n?.transactions)&&(n.transactions=n.transactions.filter(r=>!(r.tool_name==null||r.amount===0&&r.status==="failed"))),n}async function Xm(e,t){return await $.feedback(e.message,e.transaction_id,t)}var Qm=100;async function ep(e,t){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=Math.round(e.amount*100);if(n<Qm)return{success:!1,error:"Minimum top-up is $1.00"};let r=se.randomUUID();d.info("buy_credits:attempt",{amountCents:n});try{return await fe(async()=>{let s=await $e("balance-topup",e.amount,"Visa CLI Balance",`top up balance with $${e.amount.toFixed(2)}`),o=await $.topupBalance({amount_cents:n,idempotency_key:r,attestation:s});if(o.success){d.info("buy_credits:success",{amountCents:n,balanceCents:o.balanceCents});let i=((o.balanceCents??0)/100).toFixed(2),a=(n/100).toFixed(2);return{...o,amount:n/100,amountMicros:String(n*1e4),merchantName:"Visa CLI Balance",message:`Added $${a} \u2014 balance is now $${i}`}}return d.warn("buy_credits:failed",{amountCents:n,error:o.error}),o})}catch(s){if(s instanceof ft)return Rn(s,"buy_credits");throw d.error("buy_credits:failure",{amountCents:n,error:s.message}),s}}function En(e,t){return{success:!1,error:t,code:e,message:t}}async function tp(e,t){if(!e.confirm)return En("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||e.maxTransactionAmount>1e4))return En("INVALID_VALUE","maxTransactionAmount must be between $0.01 and $10,000");if(e.dailyLimit!==void 0&&(typeof e.dailyLimit!="number"||!Number.isFinite(e.dailyLimit)||e.dailyLimit<1||e.dailyLimit>1e4))return En("INVALID_VALUE","dailyLimit must be between $1 and $10,000");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return En("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");d.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await fe(async()=>{let n=await $e("spending-controls",0,"","update spending controls"),r=await $.updateSpendingControls({maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit,confirm:!0,attestation:n},t);return d.info("spending_controls:success",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit}),r})}catch(n){if(d.error("spending_controls:failure",{error:n.message}),n instanceof ft)return Rn(n,"update_spending_controls");throw n}}async function np(e){let t=await $r({api:$,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 rp(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."};d.info("config:set",{key:e.key});try{let t=nr(e.key,e.value);return d.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 Be?"UNKNOWN_KEY":t instanceof He?"SERVER_CONTROLLED":t instanceof rt?"RETIRED_KEY":"INVALID_VALUE";return d.warn("config:set:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(ot).sort()}}}async function sp(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."};d.info("config:unset",{key:e.key});try{let t=rr(e.key);return d.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 Be?"UNKNOWN_KEY":t instanceof He?"SERVER_CONTROLLED":t instanceof rt?"RETIRED_KEY":"INVALID_VALUE";return d.warn("config:unset:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(ot).sort()}}}async function op(e){let t=await $.getStatus(e),n=t.attestationRequired!==!1,r=Vr(t),s=z(),o=n?r?s?`${Ur()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${Ur()} is not available in this process. ${lo()}`:"Biometric attestation is enabled on the account, but no attestation key is registered. Payments on this device proceed without a biometric signature; processor declines such as INVALID_OR_MISSING_CONFIG are card/account configuration issues, not something biometric setup fixes.":"Biometric attestation is NOT required for payments. Payments will proceed without biometric confirmation.";return{required:n,hasAttestationKey:!!t.hasAttestationKey,hasTelegramAttestationKey:!!t.hasTelegramAttestationKey,hasAnyAttestationKey:r,touchIdAvailable:s,platform:process.platform,effectiveRequiredOnThisDevice:n&&r&&s,canDisableFromThisDevice:!n||!r||s,message:o}}async function ip(e){d.info("biometric:on");let t=await $.setBiometricPreference({required:!0},e);return t.success?(Za(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:t.error||"unknown error"}}async function ap(e,t){if(!e.confirm)return En("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.");d.info("biometric:off");try{return await fe(async()=>{let n=await $.getStatus(t),r;if(Vr(n)&&(r=await $e("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${Ur()} confirmation required to disable \u2014 not available on this device.`);let s=await $.setBiometricPreference({required:!1,attestation:r},t);if(!s.success)throw new Error(s.error||"unknown error");return Za(),{success:!0,required:!1,message:"Touch ID is no longer required for payments."}})}catch(n){if(d.error("biometric:off:failure",{error:n.message}),n instanceof ft)return Rn(n,"biometric_off");throw n}}var qa=3e4,cp=3e5;async function Qa(e,t,n="login"){let r=se.randomUUID(),s=`${e}${e.includes("?")?"&":"?"}state=${r}`;return xe(s),ec(r,t,n)}async function ec(e,t,n="login"){let r=Date.now()+cp;for(;Date.now()<r;)try{let o=await fetch(`${jr()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:qa,...t&&{user_context:t}}),signal:AbortSignal.timeout(qa+5e3)});if(!o.ok){await nt(o,a=>{d.warn("auth_status:retry_after_http_error",{status:o.status,delayMs:a})});continue}let i=await o.json();if(i.status==="pending")continue;if(i.status==="expired")return{success:!1,message:"Session expired. Please try again."};if(i.status==="error")return{success:!1,message:i.error||"Authentication failed. Please try again."};if(i.status==="complete"){if(n==="attestation-recovery"||i.attestationCleared)return d.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,l=ya(a);if(i.sessionToken){await D.saveSessionToken(i.sessionToken);let u=i.user||"",m=i.last4||"****";return d.info("auth:login_complete",{user:u,last4:m,bonusCents:a}),{success:!0,message:`Signed in as ${u}. Card ending in ${m} enrolled and ready for payments.`,...l||{}}}let c=i.last4||"****";return d.info("auth:card_added",{last4:c,bonusCents:a}),{success:!0,message:`Card ending in ${c} enrolled and ready for payments.`,...l||{}}}}catch{await nt(void 0,o=>{d.warn("auth_status:retry_after_network_error",{delayMs:o})})}return{success:!1,message:n==="enrollment"?"Card enrollment timed out. Please try again.":n==="attestation-recovery"?"Biometric reset timed out. Please try reset again.":"Login timed out. Please try again."}}async function lp(e){let t=se.randomUUID(),n;try{n=await $.startAttestationRecovery(t,e)}catch(r){return{success:!1,message:`Could not start biometric reset: ${r?.message||"unknown error"}`}}return!n.success||!n.recoveryUrl?{success:!1,message:n.error||"Could not start biometric reset. Please try again."}:(xe(n.recoveryUrl),ec(t,e,"attestation-recovery"))}async function up(e,t){if(!e.confirm)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."};d.info("cards:remove_attempt",{cardId:n});let r=`remove-card:${n}`,s=`remove ${await Xa(n,t)}`;try{return await fe(async()=>{let o=await $e(r,0,"",s),i=await $.removeCard(n,{attestation:o},t);return d.info("cards:remove_success",{cardId:n,promotedId:i?.promotedId??null}),i})}catch(o){if(d.error("cards:remove_failure",{cardId:n,error:o.message}),o instanceof ft)return Rn(o,"remove_card");throw o}}async function dp(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."};d.info("cards:set_default_attempt",{cardId:n});let r=`set-default-card:${n}`,s=`set ${await Xa(n,t)} as default`;try{return await fe(async()=>{let o=await $e(r,0,"",s),i=await $.setDefaultCard(n,{attestation:o},t);return d.info("cards:set_default_success",{cardId:n}),i})}catch(o){if(d.error("cards:set_default_failure",{cardId:n,error:o.message}),o instanceof ft)return Rn(o,"set_default_card");throw o}}async function mp(e){return d.info("auth:login_attempt"),Qa(`${jr()}/login`,e)}function pp(e){if(e.capCents!==void 0){let t=Number(e.capCents);if(!Number.isFinite(t)||t<100||t>1e4)throw new Error("capCents must be between 100 ($1) 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 1 and 100");return Math.floor(t*100)}}async function fp(e={},t){let n;try{n=pp(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return Lr(async()=>{let r=await Ea($,$e,{toolName:"start_session",userContext:t,capCentsOverride:n});d.info("session:started",{budgetId:r.budgetId,totalCents:r.totalCents,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious});let s=(r.appliedCapCents/100).toFixed(2),o=(r.requestedCapCents/100).toFixed(2),i=`Session started with a $${s} cap. Paid calls will use this approval window until you close it, it expires, or this MCP process restarts.`,a=r.clampedReason==="balance"?`${i} Note: requested cap of $${o} was clamped to your prepaid balance of $${s}. Run buy_credits to top up if you need a larger session.`:i;return{success:!0,budgetId:r.budgetId,totalCents:r.totalCents,amountUsd:r.totalCents/100,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious,message:a}})}async function gp(){let e=mt();if(!e)return{success:!0,active:!1,message:"No active session. Paid calls are pay-as-you-go and will request approval per call."};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 session: about $${(t/100).toFixed(2)} remaining of $${(e.totalCents/100).toFixed(2)}.`}}async function hp(){return Lr(async()=>{let e=mt();if(!e)return{success:!0,message:"No active session to close.",closed:!1};let t=await so($);d.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=mm(e),r=n.micros,s=Number(r/10000n);return d.info("session:closed:final-spend",{budgetId:t.budgetId,closedServerSide:t.closedServerSide,finalSpendMicros:r.toString(),finalSpendCents:s,finalSpendSource:n.source,totalCents:e.totalCents}),{success:!0,closed:!0,closedServerSide:t.closedServerSide,budgetId:t.budgetId,finalEstimatedCumulativeCents:s,finalEstimatedCumulativeMicros:r.toString(),totalCents:e.totalCents,message:t.closedServerSide?`Session closed. Spent ${dm(r)} of $${(e.totalCents/100).toFixed(2)} cap.`:"Session cleared locally; server-side close call did not succeed (likely already closed). Paid calls will use pay-as-you-go until you start a new session."}})}async function yp(e){return d.info("auth:add_card_attempt"),await D.getSessionToken()?Qa(`${jr()}/enroll`,e,"enrollment"):{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."}}async function _p(e,t){if(!e.confirm)return{success:!1,message:"Please confirm by setting confirm: true to reset"};d.info("reset:attempt");let n=!1;try{let r=await $.getStatus(t);if(r&&Vr(r)){let s=await lp(t);if(!s.success)return s;n=!0}}catch(r){let s=r?.message||"unknown error";if(!/not logged in|session.*expired|no local credentials/i.test(s))return{success:!1,message:`Could not check server biometric state: ${s}`};d.warn("reset:server_attestation_status_unavailable",{error:s})}try{await $.logout(void 0,t)}catch{}if(await D.clearAll(),z())try{await yr()}catch{}return d.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."}}function vp(e){let t=["url","resultUrl","imageUrl","audioUrl","trackUrl"];for(let n of t){let r=e[n];r&&typeof r=="string"&&r.startsWith("http")&&xe(r)}Array.isArray(e.urls)&&e.urls.forEach(n=>{n&&typeof n=="string"&&n.startsWith("http")&&xe(n)})}async function bp(e){let t=e.query?.trim()||void 0,n=e.category?.trim()||void 0,r=!t&&!n;d.info("catalog:discover",{query:t,category:n,browseAll:r});try{let o=(await $.catalogSearch(t,n)).tools||[];if(o.length===0)return{content:[{type:"text",text:r?"The tool catalog is currently empty.":`No tools found for "${t||n}". Try a different search term.`}]};if(r){let a={};for(let c of o){let u=c.category||"other";(a[u]??=[]).push(c)}let l=Object.keys(a).sort().map(c=>{let u=a[c].map((h,v)=>`${v+1}. **${h.name}** (${h.id})
100
100
  ${h.description}
101
- Provider: ${h.provider} | Price: ${Va(h)}
101
+ Provider: ${h.provider} | Price: ${Fa(h)}
102
102
  Params: ${Object.keys(h.inputSchema?.properties||h.inputSchema||{}).join(", ")||"none"}`).join(`
103
103
 
104
104
  `);return`## ${c.length<=3?c.toUpperCase():c.charAt(0).toUpperCase()+c.slice(1)}
@@ -111,47 +111,47 @@ ${l}
111
111
 
112
112
  Use execute_tool with the tool id and required params to run any of these.`}],_tools:o}}let i=o.map((a,l)=>`${l+1}. **${a.name}** (${a.id})
113
113
  ${a.description}
114
- Provider: ${a.provider} | Category: ${a.category} | Price: ${Va(a)}
114
+ Provider: ${a.provider} | Category: ${a.category} | Price: ${Fa(a)}
115
115
  Params: ${Object.keys(a.inputSchema?.properties||a.inputSchema||{}).join(", ")||"none"}`).join(`
116
116
 
117
117
  `);return d.info("catalog:discovered",{count:o.length}),{content:[{type:"text",text:`Found ${o.length} tool(s):
118
118
 
119
119
  ${i}
120
120
 
121
- Use execute_tool with the tool id and required params to run any of these.`}],_tools:o}}catch(s){throw d.error("catalog:discover:error",{error:s.message}),new Error(`Failed to search tool catalog: ${s.message}`)}}function Va(e){return e.priceDisplay??`$${(e.priceCents/100).toFixed(2)}`}function yp(e,t){return t==="image"||t==="video"||t==="audio"?t:e?.match(/\.(mp4|webm|mov)/)?"video":"image"}function Or(e,t){return Array.isArray(e.type)?e.type.includes(t):e.type===t}function _p(e,t){let n=e.inputSchema;if(!n||n.type!=="object")return null;let r=n.properties??{};for(let s of n.required??[])if(t[s]===void 0||t[s]===null||t[s]==="")return`${s} is required for ${e.id}.`;for(let[s,o]of Object.entries(t)){let i=r[s];if(!(!i||o===void 0||o===null)){if(i.enum&&!i.enum.includes(o))return`${s} must be one of: ${i.enum.map(String).join(", ")}.`;if(Or(i,"integer")){if(typeof o!="number"||!Number.isInteger(o))return`${s} must be an integer.`}else if(Or(i,"number")){if(typeof o!="number"||!Number.isFinite(o))return`${s} must be a number.`}else if(Or(i,"string")){if(typeof o!="string")return`${s} must be a string.`;if(o.trim()==="")return`${s} is required for ${e.id}.`;if(i.minLength!==void 0&&o.length<i.minLength)return`${s} is too short.`;if(i.maxLength!==void 0&&o.length>i.maxLength)return`${s} is too long.`}else if(Or(i,"boolean")&&typeof o!="boolean")return`${s} must be a boolean.`;if(typeof o=="number"){if(i.minimum!==void 0&&o<i.minimum)return`${s} must be at least ${i.minimum}.`;if(i.maximum!==void 0&&o>i.maximum)return`${s} must be at most ${i.maximum}.`}}}return null}async function vp(e){let t=dr(e);if(t)return t;try{return await $.catalogTool(e)}catch(n){return d.warn("catalog:resolve:error",{tool:e,error:n?.message||String(n)}),null}}async function bp(e,t,n="execute_tool"){let{tool_id:r,params:s,...o}=e,i=s||o;if(!r)return oo("tool_id is required. Use discover_tools first to find available tools.","MISSING_TOOL_ID");d.info("catalog:execute",{tool:r,metaTool:n});let a=await vp(r);if(!a)return oo(`Unknown tool: '${r}'. Use discover_tools first to find available tools.`,"UNKNOWN_TOOL");let l=_p(a,i);if(l)return d.info("catalog:execute:validation_failed",{tool:r,metaTool:n,error:l}),oo(l);let c=await qr(r,i,t,n);if(c)return c;let u=await Ye(r,void 0,t),m=se.randomUUID();d.info("payment:attempt",{tool:r,amount:u.amount,merchant:u.merchantName});try{return await fe(async()=>{let h;try{h=await ft({toolId:r,toolParams:i,estimatedAmountCents:gt(u),userContext:t,metaTool:n,timeoutMs:12e4,idempotencyKey:m})}catch(v){if(v instanceof le)return Le(v);throw v}if(d.info("payment:success",{tool:r,amount:u.amount,merchant:u.merchantName,mode:"session"}),h&&typeof h=="object"&&!Array.isArray(h)&&h.merchantName==null&&(h.merchantName=a?.name??r),h.urls?.length){h.urls.forEach(g=>xe(g));let v=yp(h.urls[0],h.mediaType);Rn({prompt:i.prompt||`${r} execution`,tool:r,mediaUrl:h.urls[0],mediaType:v,cost:h.amount??u.amount,transactionId:h.transactionId,userContext:t})}return h})}catch(h){if(h instanceof ne)return d.warn("payment:declined",{tool:r,amount:u.amount,merchant:u.merchantName,code:h.code,retryable:h.retryable}),Ee(h,u);throw d.error("payment:failure",{tool:r,amount:u.amount,merchant:u.merchantName,error:h.message}),h}}var Zt=class{static async getStatus(t){return Km(t)}static async pay(t,n){return $m(t,n)}static async getVisaSmi(t,n){return Rm(t,n)}static async getCards(t){return Gm(t)}static async transactionHistory(t,n){return zm(t||{},n)}static async feedback(t,n){return Wm(t,n)}static async updateSpendingControls(t,n){return Zm(t,n)}static async configList(t){return Xm(t||{})}static async configSet(t){return Qm(t||{})}static async configUnset(t){return ep(t||{})}static async biometricStatus(t){return tp(t)}static async biometricOn(t){return np(t)}static async biometricOff(t,n){return rp(t,n)}static async reset(t,n){return fp(t,n)}static async login(t){return cp(t)}static async closeSession(t){return mp()}static async startSession(t,n){return up(t||{},n)}static async getSessionStatus(t){return dp()}static async addCard(t){return pp(t)}static async removeCard(t,n){return ip(t,n)}static async setDefaultCard(t,n){return ap(t,n)}static async buyCredits(t,n){return Ym(t,n)}static async batch(t,n){return Bm(t,n)}static async discoverTools(t){return hp(t)}static async executeTool(t,n,r="execute_tool"){return bp(t,n,r)}static async shortcut(t,n,r){switch(t){case"generate_image_card":return Im(n,r);case"generate_image_fast_card":return Pm(n,r);case"generate_video_tempo_card":return Mm(n,r);case"generate_music_tempo_card":return Om(n,r);case"check_music_status_tempo_card":return Nm(n,r);case"query_onchain_prices_card":return Um(n,r);default:{d.info("payment:attempt",{tool:t});try{let s=await ft({toolId:t,toolParams:n,estimatedAmountCents:0,userContext:r,timeoutMs:6e4});return d.info("payment:success",{tool:t,mode:"session"}),s.urls?.length&&s.urls.forEach(o=>xe(o)),s}catch(s){if(s instanceof le)return Le(s);if(s instanceof ne)return d.warn("payment:declined",{tool:t,code:s.code,retryable:s.retryable}),Ee(s,{amount:0,merchantName:t});throw d.error("payment:failure",{tool:t,error:s.message}),s}}}}static async submitFeedback(t,n,r){d.info("feedback:submit",{length:t.length});try{let s=await $.submitFeedback(t,n,r);return d.info("feedback:submitted",{message:"Feedback received"}),s}catch(s){let o=s instanceof Error?s.message:"Unknown error";throw d.error("feedback:error",{error:o}),s}}static async getFeedback(t,n){d.info("feedback:list",{limit:t||20});try{let r=await $.getFeedback(t,n);return d.info("feedback:listed",{count:r?.feedback?.length||0}),r}catch(r){let s=r instanceof Error?r.message:"Unknown error";throw d.error("feedback:error",{error:s}),r}}};function Qa(e,t=process.stderr){if(Me()||!e?.updateAvailable)return!1;let{latestVersion:n}=e.updateAvailable;if(!n)return!1;let r=`Update available: v${n}. Run: ${Xt()}`;return t.write(`
121
+ Use execute_tool with the tool id and required params to run any of these.`}],_tools:o}}catch(s){throw d.error("catalog:discover:error",{error:s.message}),new Error(`Failed to search tool catalog: ${s.message}`)}}function Fa(e){return e.priceDisplay??`$${(e.priceCents/100).toFixed(2)}`}function Sp(e,t){return t==="image"||t==="video"||t==="audio"?t:e?.match(/\.(mp4|webm|mov)/)?"video":"image"}function Or(e,t){return Array.isArray(e.type)?e.type.includes(t):e.type===t}function wp(e,t){let n=e.inputSchema;if(!n||n.type!=="object")return null;let r=n.properties??{};for(let s of n.required??[])if(t[s]===void 0||t[s]===null||t[s]==="")return`${s} is required for ${e.id}.`;for(let[s,o]of Object.entries(t)){let i=r[s];if(!(!i||o===void 0||o===null)){if(i.enum&&!i.enum.includes(o))return`${s} must be one of: ${i.enum.map(String).join(", ")}.`;if(Or(i,"integer")){if(typeof o!="number"||!Number.isInteger(o))return`${s} must be an integer.`}else if(Or(i,"number")){if(typeof o!="number"||!Number.isFinite(o))return`${s} must be a number.`}else if(Or(i,"string")){if(typeof o!="string")return`${s} must be a string.`;if(o.trim()==="")return`${s} is required for ${e.id}.`;if(i.minLength!==void 0&&o.length<i.minLength)return`${s} is too short.`;if(i.maxLength!==void 0&&o.length>i.maxLength)return`${s} is too long.`}else if(Or(i,"boolean")&&typeof o!="boolean")return`${s} must be a boolean.`;if(typeof o=="number"){if(i.minimum!==void 0&&o<i.minimum)return`${s} must be at least ${i.minimum}.`;if(i.maximum!==void 0&&o>i.maximum)return`${s} must be at most ${i.maximum}.`}}}return null}async function xp(e){let t=dr(e);if(t)return t;try{return await $.catalogTool(e)}catch(n){return d.warn("catalog:resolve:error",{tool:e,error:n?.message||String(n)}),null}}async function Cp(e,t,n="execute_tool"){let{tool_id:r,params:s,...o}=e,i=s||o;if(!r)return io("tool_id is required. Use discover_tools first to find available tools.","MISSING_TOOL_ID");d.info("catalog:execute",{tool:r,metaTool:n});let a=await xp(r);if(!a)return io(`Unknown tool: '${r}'. Use discover_tools first to find available tools.`,"UNKNOWN_TOOL");let l=wp(a,i);if(l)return d.info("catalog:execute:validation_failed",{tool:r,metaTool:n,error:l}),io(l);let c=await qr(r,i,t,n);if(c)return c;let u=await Ze(r,void 0,t),m=se.randomUUID();d.info("payment:attempt",{tool:r,amount:u.amount,merchant:u.merchantName});try{return await fe(async()=>{let h;try{h=await gt({toolId:r,toolParams:i,estimatedAmountCents:ht(u),userContext:t,metaTool:n,timeoutMs:12e4,idempotencyKey:m})}catch(v){if(v instanceof le)return je(v);throw v}if(d.info("payment:success",{tool:r,amount:u.amount,merchant:u.merchantName,mode:"session"}),h&&typeof h=="object"&&!Array.isArray(h)&&h.merchantName==null&&(h.merchantName=a?.name??r),h.urls?.length){h.urls.forEach(g=>xe(g));let v=Sp(h.urls[0],h.mediaType);In({prompt:i.prompt||`${r} execution`,tool:r,mediaUrl:h.urls[0],mediaType:v,cost:h.amount??u.amount,transactionId:h.transactionId,userContext:t})}return h})}catch(h){if(h instanceof ne)return d.warn("payment:declined",{tool:r,amount:u.amount,merchant:u.merchantName,code:h.code,retryable:h.retryable}),Ee(h,u);throw d.error("payment:failure",{tool:r,amount:u.amount,merchant:u.merchantName,error:h.message}),h}}var Le=class{static async getStatus(t){return Jm(t)}static async pay(t,n){return Mm(t,n)}static async getVisaSmi(t,n){return Om(t,n)}static async getCards(t){return Ym(t)}static async transactionHistory(t,n){return Zm(t||{},n)}static async feedback(t,n){return Xm(t,n)}static async updateSpendingControls(t,n){return tp(t,n)}static async configList(t){return np(t||{})}static async configSet(t){return rp(t||{})}static async configUnset(t){return sp(t||{})}static async biometricStatus(t){return op(t)}static async biometricOn(t){return ip(t)}static async biometricOff(t,n){return ap(t,n)}static async reset(t,n){return _p(t,n)}static async login(t){return mp(t)}static async closeSession(t){return hp()}static async startSession(t,n){return fp(t||{},n)}static async getSessionStatus(t){return gp()}static async addCard(t){return yp(t)}static async removeCard(t,n){return up(t,n)}static async setDefaultCard(t,n){return dp(t,n)}static async buyCredits(t,n){return ep(t,n)}static async batch(t,n){return zm(t,n)}static async discoverTools(t){return bp(t)}static async executeTool(t,n,r="execute_tool"){return Cp(t,n,r)}static async shortcut(t,n,r){switch(t){case"generate_image_card":return Nm(n,r);case"generate_image_fast_card":return Um(n,r);case"generate_video_tempo_card":return Dm(n,r);case"generate_music_tempo_card":return Lm(n,r);case"check_music_status_tempo_card":return jm(n,r);case"query_onchain_prices_card":return Vm(n,r);default:{d.info("payment:attempt",{tool:t});try{let s=await gt({toolId:t,toolParams:n,estimatedAmountCents:0,userContext:r,timeoutMs:6e4});return d.info("payment:success",{tool:t,mode:"session"}),s.urls?.length&&s.urls.forEach(o=>xe(o)),s}catch(s){if(s instanceof le)return je(s);if(s instanceof ne)return d.warn("payment:declined",{tool:t,code:s.code,retryable:s.retryable}),Ee(s,{amount:0,merchantName:t});throw d.error("payment:failure",{tool:t,error:s.message}),s}}}}static async submitFeedback(t,n,r){d.info("feedback:submit",{length:t.length});try{let s=await $.submitFeedback(t,n,r);return d.info("feedback:submitted",{message:"Feedback received"}),s}catch(s){let o=s instanceof Error?s.message:"Unknown error";throw d.error("feedback:error",{error:o}),s}}static async getFeedback(t,n){d.info("feedback:list",{limit:t||20});try{let r=await $.getFeedback(t,n);return d.info("feedback:listed",{count:r?.feedback?.length||0}),r}catch(r){let s=r instanceof Error?r.message:"Unknown error";throw d.error("feedback:error",{error:s}),r}}};function tc(e,t=process.stderr){if(Me()||!e?.updateAvailable)return!1;let{latestVersion:n}=e.updateAvailable;if(!n)return!1;let r=`Update available: v${n}. Run: ${Qt()}`;return t.write(`
122
122
  \x1B[33m\u2191 ${r}\x1B[0m
123
- `),!0}var Sp=20;function tc(e,t,n,r){let s=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=Ep(e.spendingControls).dailyLimit,a=Math.max(0,Pn(e.dailySpent)),l=i>0?Math.min(i,Math.max(0,Pn(e.dailyRemaining??i-a))):0,c=i>0?Math.min(1,a/i):0,m=(Array.isArray(t)?t:[]).filter(Cp),h=m.slice(0,3),v=kp(m,3),g=(e.cards??[]).slice(0,3),x=r.latestVersion?In(r.latestVersion):"",O=r.updateCheckDisabled?"update checks disabled":x?`update ready: v${x}`:"up to date",F=Math.round(c*100),j=ht(e.status,e.enrolled?"approved":"not enrolled"),P=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${j} | touch id: ${n?"ready":"unavailable"}`,`Version: v${s} | ${O}`,`Spend meter: ${ec(c)} ${String(F).padStart(3," ")}% | remaining ${an(l)}/day | daily cap ${an(i)}`,"","Spend",` Remaining ${an(l)} / ${an(i)}`,` Usage ${ec(c)} ${F}%`,` Spent today ${an(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...g.length>0?g.map(U=>` ${Ap(U)}`):[" No cards enrolled"],"","Last 3 services",...v.length>0?v.map((U,J)=>` ${J+1}. ${U}`):[" No paid services yet"],"","Recent receipts",...h.length>0?h.map(U=>` ${Tp(U)}`):[" No receipts yet"]];if(x&&!r.updateCheckDisabled){let U=In(Xt(x));P.push("",`Update: v${x} ready \u2014 run \`${U}\``),r.updateMessage&&P.push(` ${In(r.updateMessage)}`)}else r.updateMessage&&P.push("",`Update: ${In(r.updateMessage)}`);return`${P.join(`
123
+ `),!0}var kp=20;function rc(e,t,n,r){let s=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=Pp(e.spendingControls).dailyLimit,a=Math.max(0,Pn(e.dailySpent)),l=i>0?Math.min(i,Math.max(0,Pn(e.dailyRemaining??i-a))):0,c=i>0?Math.min(1,a/i):0,m=(Array.isArray(t)?t:[]).filter(Ep),h=m.slice(0,3),v=$p(m,3),g=(e.cards??[]).slice(0,3),x=r.latestVersion?yt(r.latestVersion):"",O=r.updateCheckDisabled?"update checks disabled":x?`update ready: v${x}`:"up to date",F=Math.round(c*100),j=_t(e.status,e.enrolled?"approved":"not enrolled"),P=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${j} | touch id: ${n?"ready":"unavailable"}`,`Version: v${s} | ${O}`,`Spend meter: ${nc(c)} ${String(F).padStart(3," ")}% | remaining ${cn(l)}/day | daily cap ${cn(i)}`,"","Spend",` Remaining ${cn(l)} / ${cn(i)}`,` Usage ${nc(c)} ${F}%`,` Spent today ${cn(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...g.length>0?g.map(U=>` ${Ip(U)}`):[" No cards enrolled"],"","Last 3 services",...v.length>0?v.map((U,J)=>` ${J+1}. ${U}`):[" No paid services yet"],"","Recent receipts",...h.length>0?h.map(U=>` ${Rp(U)}`):[" No receipts yet"]];if(x&&!r.updateCheckDisabled){let U=yt(Qt(x));P.push("",`Update: v${x} ready \u2014 run \`${U}\``),r.updateMessage&&P.push(` ${yt(r.updateMessage)}`)}else r.updateMessage&&P.push("",`Update: ${yt(r.updateMessage)}`);return`${P.join(`
124
124
  `)}
125
- `}function wp(e){return e.tool_name!=null}function xp(e){return Pn(e.amount)===0&&e.status==="failed"}function Cp(e){return wp(e)&&!xp(e)}function kp(e,t=1/0){let n=new Set,r=[];for(let s of e){if(r.length>=t)break;let o=ht(s.merchant_name,"Unknown merchant"),i=ht(s.tool_name,"unknown_tool"),a=`${o} :: ${i}`;n.has(a)||(n.add(a),r.push(`${o} [${i}]`))}return r}function Tp(e){let t=ht(e.merchant_name,"Unknown merchant"),n=ht(e.tool_name,"unknown_tool"),r=an(Pn(e.amount)),s=ht(e.status,"unknown"),o=$p(e.created_at);return`${r} ${s.padEnd(9)} ${t} [${n}] ${o}`}function Ap(e){let t=ht(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function Ep(e){return{dailyLimit:Pn(e?.daily_limit??e?.dailyLimit??0)}}function Pn(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function an(e){return`$${e.toFixed(2)}`}function ec(e,t=Sp){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function ht(e,t){let n=In(e??"").trim();return n.length>0?n:t}function $p(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?ht(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function In(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 Gr=A(so());var Rp=["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 Ip(){let e=new Set;for(let t of Rp)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of bn)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var my=Ip();var uo=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 yy=new Set(bn),_y=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...uo,...bn]);var ge=class extends Error{constructor(t){super(t),this.name="PayValidationError"}},nc=["GET","POST"];function rc(e){let t;try{t=new URL(e)}catch{throw new ge(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new ge(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}function sc(e){let t=(e??"GET").toUpperCase();if(!nc.includes(t))throw new ge(`Unsupported HTTP method "${e}". Supported: ${nc.join(", ")}.`);return t}function oc(e){if(e!==void 0){try{JSON.parse(e)}catch(t){throw new ge(`--body is not valid JSON: ${t?.message??"parse error"}`)}return e}}function ic(e){if(!e||typeof e!="object")throw new ge("Merchant returned no payment preview.");let t=e;if(typeof t.amount!="number"||!Number.isFinite(t.amount)||t.amount<=0)throw new ge("Could not determine payment amount from merchant.");if(typeof t.merchantName!="string"||t.merchantName.trim().length===0)throw new ge("Merchant returned an empty merchant name.");if(t.merchantName.length>200)throw new ge(`Merchant name too long (${t.merchantName.length} chars).`);if(typeof t.currency!="string"||t.currency.trim().length===0)throw new ge("Merchant returned an empty currency.");if(t.currency.length>10)throw new ge(`Currency code too long (${t.currency.length} chars).`);return{amount:t.amount,currency:t.currency,merchantName:t.merchantName}}var N=A(require("fs")),R=A(require("path")),ac=A(require("os")),H=ac.homedir(),Pp=["Claude_","Anthropic.ClaudeDesktop_"],cn=class extends Error{constructor(n,r,s){super(Op(n,r,s));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function cc(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
126
- `)}function Mp(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=cc(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function Op(e,t,n){let r=t.replace(H,"~"),s=cc(n).split(`
127
- `).find(Boolean),o=s?` (${s})`:"";return e.id==="codex"?`Could not update Codex MCP config at ${r}: filesystem access was denied${o}. In Codex, rerun with elevated filesystem access or run \`visa-cli install codex\` outside the sandbox.`:`Could not update ${e.displayName} MCP config at ${r}: filesystem access was denied${o}.`}function Mn(){return process.env.APPDATA||R.join(H,"AppData","Roaming")}function Np(){return process.env.LOCALAPPDATA||R.join(H,"AppData","Local")}function mo(e){return process.platform==="win32"?e.win32:e.posix}function lc(){if(process.platform!=="win32")return;let e=R.join(Np(),"Packages");if(N.existsSync(e))try{let t=N.readdirSync(e,"utf-8");for(let n of Pp){let r=t.filter(s=>s.startsWith(n)).sort()[0];if(r)return R.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function uc(){if(process.platform==="win32"){let e=lc();return e?R.join(e,"claude_desktop_config.json"):R.join(Mn(),"Claude","claude_desktop_config.json")}return R.join(H,"Library","Application Support","Claude","claude_desktop_config.json")}function dc(){if(process.platform!=="win32")return[R.join(H,"Library","Application Support","Claude")];let e=[R.join(Mn(),"Claude")],t=lc();return t&&e.push(t),e}function Fr(e){return e.id==="claude-desktop"?uc():e.globalConfigPath}function Up(e){return e.id==="claude-desktop"?dc():e.detectPaths}var Re=[{id:"claude",displayName:"Claude Code",globalConfigPath:R.join(H,".claude.json"),configKey:"mcpServers",detectPaths:[R.join(H,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:uc(),configKey:"mcpServers",detectPaths:dc(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:R.join(H,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[R.join(H,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:R.join(H,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[R.join(H,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:R.join(H,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[R.join(H,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:mo({win32:R.join(Mn(),"Roo","mcp_settings.json"),posix:R.join(H,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[R.join(H,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:R.join(H,".vscode","mcp.json"),configKey:"servers",detectPaths:[R.join(H,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:mo({win32:R.join(Mn(),"Zed","settings.json"),posix:R.join(H,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:mo({win32:[R.join(Mn(),"Zed")],posix:[R.join(H,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:R.join(H,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[R.join(H,".codex")],postInstallHint:"Restart Codex to connect. For the terminal HUD, run: visa-cli config hud enable"}];function po(e){return Re.find(t=>t.id===e)}function On(e){return Up(e).some(t=>{if(t.includes("*")){let n=R.dirname(t),r=R.basename(t).replaceAll("*","");if(!N.existsSync(n))return!1;try{return N.readdirSync(n).some(s=>s.startsWith(r))}catch{return!1}}return N.existsSync(t)})}function mc(){return{command:"node",args:[R.resolve(__dirname,"mcp-server/index.js")]}}function fo(e,t){return t==="project"?"json":e.configFormat??"json"}function Dp(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 go(e,t){let n=`[mcp_servers.${t}]`,r=e.findIndex(o=>o.trim()===n);if(r===-1)return;let s=r+1;for(;s<e.length&&!e[s].trim().startsWith("[");)s++;return{start:r,end:s}}function ho(e,t){let n=e.split(`
128
- `),r=go(n,t);if(!r)return;let s={};for(let o=r.start+1;o<r.end;o++){let i=n[o].trim().match(/^(\w+)\s*=\s*(.+)$/);i&&(s[i[1]]=Dp(i[2]))}return Object.keys(s).length>0?s:void 0}function Lp(e,t,n){let r=`[${n.args.map(l=>`"${l}"`).join(", ")}]`,s=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],o=e.split(`
129
- `),i=go(o,t);if(i){o.splice(i.start,i.end-i.start,...s);let l=o.join(`
125
+ `}function Tp(e){return e.tool_name!=null}function Ap(e){return Pn(e.amount)===0&&e.status==="failed"}function Ep(e){return Tp(e)&&!Ap(e)}function $p(e,t=1/0){let n=new Set,r=[];for(let s of e){if(r.length>=t)break;let o=_t(s.merchant_name,"Unknown merchant"),i=_t(s.tool_name,"unknown_tool"),a=`${o} :: ${i}`;n.has(a)||(n.add(a),r.push(`${o} [${i}]`))}return r}function Rp(e){let t=_t(e.merchant_name,"Unknown merchant"),n=_t(e.tool_name,"unknown_tool"),r=cn(Pn(e.amount)),s=_t(e.status,"unknown"),o=Mp(e.created_at);return`${r} ${s.padEnd(9)} ${t} [${n}] ${o}`}function Ip(e){let t=_t(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function Pp(e){return{dailyLimit:Pn(e?.daily_limit??e?.dailyLimit??0)}}function Pn(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function cn(e){return`$${e.toFixed(2)}`}function nc(e,t=kp){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function _t(e,t){let n=yt(e??"").trim();return n.length>0?n:t}function Mp(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?_t(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function yt(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 Op=/^[1-9]\d{0,9}$/;function mo(e){if(!Op.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 sc(e){let t=yt(e.brand||"Visa"),n=yt(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 Gr=T(oo());var Np=["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 Up(){let e=new Set;for(let t of Np)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of Sn)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var Sy=Up();var po=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 Ty=new Set(Sn),Ay=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...po,...Sn]);var ge=class extends Error{constructor(t){super(t),this.name="PayValidationError"}},oc=["GET","POST"];function ic(e){let t;try{t=new URL(e)}catch{throw new ge(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new ge(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}function ac(e){let t=(e??"GET").toUpperCase();if(!oc.includes(t))throw new ge(`Unsupported HTTP method "${e}". Supported: ${oc.join(", ")}.`);return t}function cc(e){if(e!==void 0){try{JSON.parse(e)}catch(t){throw new ge(`--body is not valid JSON: ${t?.message??"parse error"}`)}return e}}function lc(e){if(!e||typeof e!="object")throw new ge("Merchant returned no payment preview.");let t=e;if(typeof t.amount!="number"||!Number.isFinite(t.amount)||t.amount<=0)throw new ge("Could not determine payment amount from merchant.");if(typeof t.merchantName!="string"||t.merchantName.trim().length===0)throw new ge("Merchant returned an empty merchant name.");if(t.merchantName.length>200)throw new ge(`Merchant name too long (${t.merchantName.length} chars).`);if(typeof t.currency!="string"||t.currency.trim().length===0)throw new ge("Merchant returned an empty currency.");if(t.currency.length>10)throw new ge(`Currency code too long (${t.currency.length} chars).`);return{amount:t.amount,currency:t.currency,merchantName:t.merchantName}}var N=T(require("fs")),R=T(require("path")),uc=T(require("os")),H=uc.homedir(),Dp=["Claude_","Anthropic.ClaudeDesktop_"],ln=class extends Error{constructor(n,r,s){super(jp(n,r,s));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function dc(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
126
+ `)}function Lp(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=dc(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function jp(e,t,n){let r=t.replace(H,"~"),s=dc(n).split(`
127
+ `).find(Boolean),o=s?` (${s})`:"";return e.id==="codex"?`Could not update Codex MCP config at ${r}: filesystem access was denied${o}. In Codex, rerun with elevated filesystem access or run \`visa-cli install codex\` outside the sandbox.`:`Could not update ${e.displayName} MCP config at ${r}: filesystem access was denied${o}.`}function Mn(){return process.env.APPDATA||R.join(H,"AppData","Roaming")}function Vp(){return process.env.LOCALAPPDATA||R.join(H,"AppData","Local")}function fo(e){return process.platform==="win32"?e.win32:e.posix}function mc(){if(process.platform!=="win32")return;let e=R.join(Vp(),"Packages");if(N.existsSync(e))try{let t=N.readdirSync(e,"utf-8");for(let n of Dp){let r=t.filter(s=>s.startsWith(n)).sort()[0];if(r)return R.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function pc(){if(process.platform==="win32"){let e=mc();return e?R.join(e,"claude_desktop_config.json"):R.join(Mn(),"Claude","claude_desktop_config.json")}return R.join(H,"Library","Application Support","Claude","claude_desktop_config.json")}function fc(){if(process.platform!=="win32")return[R.join(H,"Library","Application Support","Claude")];let e=[R.join(Mn(),"Claude")],t=mc();return t&&e.push(t),e}function Fr(e){return e.id==="claude-desktop"?pc():e.globalConfigPath}function qp(e){return e.id==="claude-desktop"?fc():e.detectPaths}var Re=[{id:"claude",displayName:"Claude Code",globalConfigPath:R.join(H,".claude.json"),configKey:"mcpServers",detectPaths:[R.join(H,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:pc(),configKey:"mcpServers",detectPaths:fc(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:R.join(H,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[R.join(H,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:R.join(H,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[R.join(H,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:R.join(H,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[R.join(H,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:fo({win32:R.join(Mn(),"Roo","mcp_settings.json"),posix:R.join(H,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[R.join(H,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:R.join(H,".vscode","mcp.json"),configKey:"servers",detectPaths:[R.join(H,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:fo({win32:R.join(Mn(),"Zed","settings.json"),posix:R.join(H,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:fo({win32:[R.join(Mn(),"Zed")],posix:[R.join(H,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:R.join(H,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[R.join(H,".codex")],postInstallHint:"Restart Codex to connect. For the terminal HUD, run: visa-cli config hud enable"}];function go(e){return Re.find(t=>t.id===e)}function On(e){return qp(e).some(t=>{if(t.includes("*")){let n=R.dirname(t),r=R.basename(t).replaceAll("*","");if(!N.existsSync(n))return!1;try{return N.readdirSync(n).some(s=>s.startsWith(r))}catch{return!1}}return N.existsSync(t)})}function gc(){return{command:"node",args:[R.resolve(__dirname,"mcp-server/index.js")]}}function ho(e,t){return t==="project"?"json":e.configFormat??"json"}function Fp(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 yo(e,t){let n=`[mcp_servers.${t}]`,r=e.findIndex(o=>o.trim()===n);if(r===-1)return;let s=r+1;for(;s<e.length&&!e[s].trim().startsWith("[");)s++;return{start:r,end:s}}function _o(e,t){let n=e.split(`
128
+ `),r=yo(n,t);if(!r)return;let s={};for(let o=r.start+1;o<r.end;o++){let i=n[o].trim().match(/^(\w+)\s*=\s*(.+)$/);i&&(s[i[1]]=Fp(i[2]))}return Object.keys(s).length>0?s:void 0}function Bp(e,t,n){let r=`[${n.args.map(l=>`"${l}"`).join(", ")}]`,s=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],o=e.split(`
129
+ `),i=yo(o,t);if(i){o.splice(i.start,i.end-i.start,...s);let l=o.join(`
130
130
  `);return l.endsWith(`
131
131
  `)?l:l+`
132
132
  `}let a=e.trimEnd();return a+(a.length>0?`
133
133
 
134
134
  `:"")+s.join(`
135
135
  `)+`
136
- `}function jp(e,t){let n=e.split(`
137
- `),r=go(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
136
+ `}function Hp(e,t){let n=e.split(`
137
+ `),r=yo(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
138
138
  `).replace(/\n{3,}/g,`
139
139
 
140
- `)):e}function Nn(e,t="global"){let n=t==="project"?R.join(process.cwd(),".mcp.json"):Fr(e);try{let r=R.dirname(n);N.existsSync(r)||N.mkdirSync(r,{recursive:!0});let s=fo(e,t),o=mc();if(s==="toml"){let i=N.existsSync(n)?N.readFileSync(n,"utf-8"):"",a=Lp(i,"visa-cli",o);N.writeFileSync(n,a)}else{let i={};if(N.existsSync(n))try{i=JSON.parse(N.readFileSync(n,"utf-8"))}catch{i={}}i[e.configKey]=i[e.configKey]||{},i[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(o):o,N.writeFileSync(n,JSON.stringify(i,null,2)+`
141
- `)}}catch(r){throw Mp(r)?new cn(e,n,r):r}return{installed:!0,configPath:n,message:e.postInstallHint}}function yo(e,t="global"){let n=t==="project"?R.join(process.cwd(),".mcp.json"):Fr(e);if(!N.existsSync(n))return{removed:!1,configPath:n};if(fo(e,t)==="toml"){let i=N.readFileSync(n,"utf-8");return ho(i,"visa-cli")?(N.writeFileSync(n,jp(i,"visa-cli")),{removed:!0,configPath:n}):{removed:!1,configPath:n}}let s;try{s=JSON.parse(N.readFileSync(n,"utf-8"))}catch{return{removed:!1,configPath:n}}let o=s[e.configKey];return!o||!o["visa-cli"]?{removed:!1,configPath:n}:(delete o["visa-cli"],N.writeFileSync(n,JSON.stringify(s,null,2)+`
142
- `),{removed:!0,configPath:n})}function pc(e,t="global"){let n=t==="project"?R.join(process.cwd(),".mcp.json"):Fr(e);if(!N.existsSync(n))return!1;if(fo(e,t)==="toml")try{let s=N.readFileSync(n,"utf-8");return!!ho(s,"visa-cli")}catch{return!1}try{return!!JSON.parse(N.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function Vp(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 qp(e,t){if(e===t)return!0;let n=R.resolve(e),r=R.resolve(t);if(n===r)return!0;try{let s=N.realpathSync(n),o=N.realpathSync(r);return s===o}catch{return!1}}function Un(){let e=mc(),t=e.args[e.args.length-1],n=[];for(let r of Re){let s=Fr(r);if(!N.existsSync(s))continue;let o=r.configFormat??"json",i;if(o==="toml")try{let c=N.readFileSync(s,"utf-8");i=ho(c,"visa-cli")}catch{continue}else{let c;try{c=JSON.parse(N.readFileSync(s,"utf-8"))}catch{continue}i=c?.[r.configKey]?.["visa-cli"]}if(!i)continue;let a=Vp(i);if(!a||qp(a,t))continue;let l=N.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:s,currentPath:a,expectedPath:t,staleReason:l})}return n}function _o(e){return{configPath:Nn(e.client,"global").configPath}}var bo=(0,yc.promisify)(hc.execFile);function Kp(e){let t=W.homedir(),n=s=>s.replace(t,"~"),r=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
143
- ${r}: ${n(e.currentPath)}`}function _c(e,t){if(e.length===0){console.log(`${t} \u2713 All MCP client configs are up to date.`);return}console.log(`${t} Found ${e.length} stale MCP config ${e.length===1?"entry":"entries"}:`);for(let n of e)console.log(Kp(n))}function fc(e){console.log(` ! ${e.client.displayName} skipped: ${e.message}`)}var q=new gc.Command,Gp=new Set(["pay",...uo]),Kr=null,Dn=!1;function oe(){return Kr=new ve(()=>D.getSessionToken()),Kr}function zp(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function Wp(e){return/attestation required|invalid signature|rotate biometric key|biometric key/i.test(e)}async function Jp(e){let r=Date.now()+3e5;for(;Date.now()<r;)try{let s=await globalThis.fetch(`${_e()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:3e4}),signal:AbortSignal.timeout(35e3)});if(!s.ok){await tt(s,i=>{d.warn("auth_status:retry_after_http_error",{status:s.status,delayMs:i})});continue}let o=await s.json();if(o.status==="pending")continue;if(o.status==="complete"&&o.attestationCleared)return;if(o.status==="expired")throw new Error("Biometric reset session expired. Please run visa-cli config reset again.");if(o.status==="error")throw new Error(o.error||"Biometric reset failed. Please try again.")}catch(s){if(s?.message&&!/fetch failed|network|abort/i.test(s.message))throw s;await tt(void 0,o=>{d.warn("auth_status:retry_after_network_error",{delayMs:o})})}throw new Error("Biometric reset timed out after 5 minutes. Please run visa-cli config reset again.")}async function Yp(e){let t;try{t=await e.getStatus()}catch(s){let o=s?.message||"";if(/not logged in|session.*expired|no local credentials/i.test(o))return!1;throw new Error(`Could not check server biometric state: ${o||"unknown error"}`)}if(!zp(t))return!1;let n=Ln.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 os(r.recoveryUrl),await Jp(n),console.log(" Server biometric state cleared."),!0}function wo(e){return`$${(e/100).toFixed(2)}`}function So(e,t,n=!1){if(!e){let i=wo(t);return n&&t>=0?`+${i}`:i}let r=(0,Gr.fromWire)(e),s=r%10000n===0n?2:6,o=(0,Gr.toDisplay)(r,{decimals:s});return n&&r>=0n?`+${o}`:o}function Zp(e){return So(e,0)}function Xp(e){let t=`visa-cli-${W.hostname()||"local"}`,n=(e?.trim()||t).trim();if(!n)throw new Error("API key label is required.");if(n.length>128)throw new Error("API key label must be 128 characters or fewer.");return n}function Qp(e){if(!e)return;let t=e.split(",").map(o=>o.trim()).filter(Boolean),n=Array.from(new Set(t)),r=n.find(o=>o.length>64);if(r)throw new Error(`Tool id is too long: ${r}`);let s=n.find(o=>Gp.has(o));if(s)throw new Error(`Tool id "${s}" is retired for direct API-key access. Use category meta-tools or discover/execute instead.`);return n}function ef(e){if(!e)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error("--daily-cap must be a positive USD amount.");let n=Math.round(t*100);if(n<100||n>1e4)throw new Error("--daily-cap must be between 1 and 100 USD.");return n}function vc(e){return e&&e.length>0?e.join(", "):"all tools"}function xo(e,t){return t||(typeof e!="number"||!Number.isFinite(e)?"price unknown":`$${(e/100).toFixed(2)}`)}function tf(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 bc(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 vo(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function nf(e){let t=new Map;for(let n of e){let r=n.category||"other",s=t.get(r)??[];s.push(n),t.set(r,s)}return new Map([...t.entries()].sort(([n],[r])=>n.localeCompare(r)))}function rf(e){let t=Math.max(4,Math.min(28,e.reduce((s,o)=>Math.max(s,o.id.length),0))),n=7,r=Math.max(8,Math.min(12,e.reduce((s,o)=>Math.max(s,(o.category||"").length),0)));console.log(`
140
+ `)):e}function Nn(e,t="global"){let n=t==="project"?R.join(process.cwd(),".mcp.json"):Fr(e);try{let r=R.dirname(n);N.existsSync(r)||N.mkdirSync(r,{recursive:!0});let s=ho(e,t),o=gc();if(s==="toml"){let i=N.existsSync(n)?N.readFileSync(n,"utf-8"):"",a=Bp(i,"visa-cli",o);N.writeFileSync(n,a)}else{let i={};if(N.existsSync(n))try{i=JSON.parse(N.readFileSync(n,"utf-8"))}catch{i={}}i[e.configKey]=i[e.configKey]||{},i[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(o):o,N.writeFileSync(n,JSON.stringify(i,null,2)+`
141
+ `)}}catch(r){throw Lp(r)?new ln(e,n,r):r}return{installed:!0,configPath:n,message:e.postInstallHint}}function vo(e,t="global"){let n=t==="project"?R.join(process.cwd(),".mcp.json"):Fr(e);if(!N.existsSync(n))return{removed:!1,configPath:n};if(ho(e,t)==="toml"){let i=N.readFileSync(n,"utf-8");return _o(i,"visa-cli")?(N.writeFileSync(n,Hp(i,"visa-cli")),{removed:!0,configPath:n}):{removed:!1,configPath:n}}let s;try{s=JSON.parse(N.readFileSync(n,"utf-8"))}catch{return{removed:!1,configPath:n}}let o=s[e.configKey];return!o||!o["visa-cli"]?{removed:!1,configPath:n}:(delete o["visa-cli"],N.writeFileSync(n,JSON.stringify(s,null,2)+`
142
+ `),{removed:!0,configPath:n})}function hc(e,t="global"){let n=t==="project"?R.join(process.cwd(),".mcp.json"):Fr(e);if(!N.existsSync(n))return!1;if(ho(e,t)==="toml")try{let s=N.readFileSync(n,"utf-8");return!!_o(s,"visa-cli")}catch{return!1}try{return!!JSON.parse(N.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function Kp(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 Gp(e,t){if(e===t)return!0;let n=R.resolve(e),r=R.resolve(t);if(n===r)return!0;try{let s=N.realpathSync(n),o=N.realpathSync(r);return s===o}catch{return!1}}function Un(){let e=gc(),t=e.args[e.args.length-1],n=[];for(let r of Re){let s=Fr(r);if(!N.existsSync(s))continue;let o=r.configFormat??"json",i;if(o==="toml")try{let c=N.readFileSync(s,"utf-8");i=_o(c,"visa-cli")}catch{continue}else{let c;try{c=JSON.parse(N.readFileSync(s,"utf-8"))}catch{continue}i=c?.[r.configKey]?.["visa-cli"]}if(!i)continue;let a=Kp(i);if(!a||Gp(a,t))continue;let l=N.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:s,currentPath:a,expectedPath:t,staleReason:l})}return n}function bo(e){return{configPath:Nn(e.client,"global").configPath}}var wo=(0,Sc.promisify)(vc.execFile);function Yp(e){let t=W.homedir(),n=s=>s.replace(t,"~"),r=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
143
+ ${r}: ${n(e.currentPath)}`}function wc(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(Yp(n))}function yc(e){console.log(` ! ${e.client.displayName} skipped: ${e.message}`)}var q=new _c.Command,Zp=new Set(["pay",...po]),Kr=null,Dn=!1;function oe(){return Kr=new ve(()=>D.getSessionToken()),Kr}function Xp(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function Qp(e){return/attestation required|invalid signature|rotate biometric key|biometric key/i.test(e)}async function ef(e){let r=Date.now()+3e5;for(;Date.now()<r;)try{let s=await globalThis.fetch(`${_e()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:3e4}),signal:AbortSignal.timeout(35e3)});if(!s.ok){await nt(s,i=>{d.warn("auth_status:retry_after_http_error",{status:s.status,delayMs:i})});continue}let o=await s.json();if(o.status==="pending")continue;if(o.status==="complete"&&o.attestationCleared)return;if(o.status==="expired")throw new Error("Biometric reset session expired. Please run visa-cli config reset again.");if(o.status==="error")throw new Error(o.error||"Biometric reset failed. Please try again.")}catch(s){if(s?.message&&!/fetch failed|network|abort/i.test(s.message))throw s;await nt(void 0,o=>{d.warn("auth_status:retry_after_network_error",{delayMs:o})})}throw new Error("Biometric reset timed out after 5 minutes. Please run visa-cli config reset again.")}async function tf(e){let t;try{t=await e.getStatus()}catch(s){let o=s?.message||"";if(/not logged in|session.*expired|no local credentials/i.test(o))return!1;throw new Error(`Could not check server biometric state: ${o||"unknown error"}`)}if(!Xp(t))return!1;let n=Ln.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 is(r.recoveryUrl),await ef(n),console.log(" Server biometric state cleared."),!0}function Co(e){return`$${(e/100).toFixed(2)}`}function xo(e,t,n=!1){if(!e){let i=Co(t);return n&&t>=0?`+${i}`:i}let r=(0,Gr.fromWire)(e),s=r%10000n===0n?2:6,o=(0,Gr.toDisplay)(r,{decimals:s});return n&&r>=0n?`+${o}`:o}function nf(e){return xo(e,0)}function rf(e){let t=`visa-cli-${W.hostname()||"local"}`,n=(e?.trim()||t).trim();if(!n)throw new Error("API key label is required.");if(n.length>128)throw new Error("API key label must be 128 characters or fewer.");return n}function sf(e){if(!e)return;let t=e.split(",").map(o=>o.trim()).filter(Boolean),n=Array.from(new Set(t)),r=n.find(o=>o.length>64);if(r)throw new Error(`Tool id is too long: ${r}`);let s=n.find(o=>Zp.has(o));if(s)throw new Error(`Tool id "${s}" is retired for direct API-key access. Use category meta-tools or discover/execute instead.`);return n}function of(e){if(!e)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error("--daily-cap must be a positive USD amount.");let n=Math.round(t*100);if(n<100||n>1e4)throw new Error("--daily-cap must be between 1 and 100 USD.");return n}function xc(e){return e&&e.length>0?e.join(", "):"all tools"}function ko(e,t){return t||(typeof e!="number"||!Number.isFinite(e)?"price unknown":`$${(e/100).toFixed(2)}`)}function af(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 Cc(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 So(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function cf(e){let t=new Map;for(let n of e){let r=n.category||"other",s=t.get(r)??[];s.push(n),t.set(r,s)}return new Map([...t.entries()].sort(([n],[r])=>n.localeCompare(r)))}function lf(e){let t=Math.max(4,Math.min(28,e.reduce((s,o)=>Math.max(s,o.id.length),0))),n=7,r=Math.max(8,Math.min(12,e.reduce((s,o)=>Math.max(s,(o.category||"").length),0)));console.log(`
144
144
  Merchant tools
145
- `),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(28)}`);for(let s of e)console.log(` ${vo(s.id,t).padEnd(t)} ${xo(s.priceCents,s.priceDisplay).padEnd(n)} ${vo(s.category||"other",r).padEnd(r)} ${vo(bc(s),42)}`);console.log("\nUse `visa-cli merchants describe <tool>` for full details."),console.log('Shortcut: `visa-cli generate image "a lobster"`\n')}function sf(e){console.log(`
145
+ `),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(28)}`);for(let s of e)console.log(` ${So(s.id,t).padEnd(t)} ${ko(s.priceCents,s.priceDisplay).padEnd(n)} ${So(s.category||"other",r).padEnd(r)} ${So(Cc(s),42)}`);console.log("\nUse `visa-cli merchants describe <tool>` for full details."),console.log('Shortcut: `visa-cli generate image "a lobster"`\n')}function uf(e){console.log(`
146
146
  Merchant tools
147
- `);for(let[t,n]of nf(e)){console.log(t[0]?.toUpperCase()+t.slice(1));for(let r of n)console.log(` ${r.id.padEnd(28)} ${xo(r.priceCents,r.priceDisplay).padEnd(8)} ${r.description}`),console.log(` Params: ${bc(r)}`);console.log()}console.log(`Run one with: visa-cli merchants run <tool> --json '{"prompt":"a lobster"}'`),console.log(`Shortcut: visa-cli generate image "a lobster"
148
- `)}function Sc(e){if(e?.content?.[0]?.text&&typeof e.content[0].text=="string"){console.log(e.content[0].text);return}let t=Array.isArray(e?.urls)?e.urls:Array.isArray(e?.receipt?.urls)?e.receipt.urls:[];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}`),t.length>0){console.log(`
147
+ `);for(let[t,n]of cf(e)){console.log(t[0]?.toUpperCase()+t.slice(1));for(let r of n)console.log(` ${r.id.padEnd(28)} ${ko(r.priceCents,r.priceDisplay).padEnd(8)} ${r.description}`),console.log(` Params: ${Cc(r)}`);console.log()}console.log(`Run one with: visa-cli merchants run <tool> --json '{"prompt":"a lobster"}'`),console.log(`Shortcut: visa-cli generate image "a lobster"
148
+ `)}function kc(e){if(e?.content?.[0]?.text&&typeof e.content[0].text=="string"){console.log(e.content[0].text);return}let t=Array.isArray(e?.urls)?e.urls:Array.isArray(e?.receipt?.urls)?e.receipt.urls:[];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}`),t.length>0){console.log(`
149
149
  Result URLs:`);for(let r of t)console.log(` ${r}`);return}let n=JSON.stringify(e,null,2);n&&n!=="{}"&&(console.log(`
150
- Result:`),console.log(n))}async function of(e,t={}){let n=await e.catalogSearch(t.query,t.category,"discover_tools");return Array.isArray(n.tools)?n.tools:[]}function af(e){let t=`
150
+ Result:`),console.log(n))}async function df(e,t={}){let n=await e.catalogSearch(t.query,t.category,"discover_tools");return Array.isArray(n.tools)?n.tools:[]}function mf(e){let t=`
151
151
  Options:
152
152
  `,n=`
153
153
  Commands:
154
- `,r=e.indexOf(t),s=e.indexOf(n);if(r===-1||s===-1||r>s)return e;let o=h=>{let g=e.slice(h+1).search(/\n[A-Z][A-Za-z ]+:\n/);return g===-1?e.length:h+1+g},i=o(r),a=o(s),l=e.slice(0,r),c=e.slice(r,i),u=e.slice(s,a),m=e.slice(a);return`${l}${u}${c}${m}`}function cf(e){if(!e.startsWith("Usage: "))return e;let t=e.indexOf(`
154
+ `,r=e.indexOf(t),s=e.indexOf(n);if(r===-1||s===-1||r>s)return e;let o=h=>{let g=e.slice(h+1).search(/\n[A-Z][A-Za-z ]+:\n/);return g===-1?e.length:h+1+g},i=o(r),a=o(s),l=e.slice(0,r),c=e.slice(r,i),u=e.slice(s,a),m=e.slice(a);return`${l}${u}${c}${m}`}function pf(e){if(!e.startsWith("Usage: "))return e;let t=e.indexOf(`
155
155
 
156
156
  `);if(t===-1)return e;let n=e.slice(0,t),r=e.slice(t+2),s=r.indexOf(`
157
157
 
@@ -159,13 +159,13 @@ Commands:
159
159
 
160
160
  ${n}
161
161
 
162
- ${i}`:e}function lf(e){return e.replace(/(^|\n)(Commands:\n)([\s\S]*?)(?=\n[A-Z][A-Za-z ]+:\n|$)/g,(t,n,r,s)=>{let o=s.split(`
162
+ ${i}`:e}function ff(e){return e.replace(/(^|\n)(Commands:\n)([\s\S]*?)(?=\n[A-Z][A-Za-z ]+:\n|$)/g,(t,n,r,s)=>{let o=s.split(`
163
163
  `).map(i=>{let a=i.match(/^(\s{2})(\S+)(?:\s+(?:\[options\]|\[[^\]]+\]|<[^>]+>))*?(\s{2,})(\S.*)$/);if(!a)return i;let[,l,c,,u]=a,m=i.indexOf(u),h=Math.max(2,m-l.length-c.length);return`${l}${c}${" ".repeat(h)}${u}`}).join(`
164
- `);return`${n}${r}${o}`})}function uf(e){return e.replace(/^(Usage: .+?) \[options\](?= |$)/gm,"$1")}function df(e){return e.replace(/^Options:$/gm,"Flags:")}function wc(e){let t=e.helpInformation.bind(e);e.helpInformation=()=>df(uf(lf(af(cf(t())))));for(let n of e.commands)wc(n)}function mf(e){let t=new Map(e.map((r,s)=>[r,s]));q.commands.sort((r,s)=>{let o=t.get(r.name())??Number.MAX_SAFE_INTEGER,i=t.get(s.name())??Number.MAX_SAFE_INTEGER;return o-i})}q.name("visa-cli").description("Visa CLI - set up MCP payments, manage credentials, and monitor AI spend").version(Gn().version).addHelpCommand(!1);q.hook("preAction",async()=>{await Oo()});q.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 \u2014 for CI/agent use").option("--hud","Also enable the Claude Code HUD during setup").option("--no-hud","Do not install the HUD during setup (default)").action(async e=>{try{if(e.check){let g=Un();_c(g,"MCP config check:"),g.length>0&&(console.log("\nRun `visa-cli setup` (or `visa-cli install --repair`) to rewrite these entries."),process.exit(1));return}console.log("Step 1: Registering MCP server...");let t=Un(),n=new Map(t.map(g=>[g.client.id,g])),r=new Set,s=new Set,o=new Set;for(let g of Re)if(On(g)){let x;try{x=Nn(g)}catch(j){if(j instanceof cn){fc(j),s.add(g.displayName),o.add(g.id);continue}throw j}let O=n.get(g.id),F=O?` \u2014 repaired stale ${O.staleReason} entry`:"";console.log(` \u2713 ${g.displayName} (${x.configPath.replace(W.homedir(),"~")})${F}`),O&&r.add(g.id)}let i=t.filter(g=>!r.has(g.client.id)&&!o.has(g.client.id)),a=0;for(let g of i){try{_o(g)}catch(x){if(x instanceof cn){fc(x),s.add(g.client.displayName),o.add(g.client.id);continue}throw x}console.log(` \u2713 ${g.client.displayName} (${g.configPath.replace(W.homedir(),"~")}) \u2014 repaired stale ${g.staleReason} entry`),a++}let l=r.size+a;l===0&&s.size===0?console.log(" \u2713 MCP config verified \u2014 nothing to repair."):l>0&&console.log(` \u2713 Repaired ${l} stale MCP config ${l===1?"entry":"entries"}.`),s.size>0&&console.log(` ! Skipped MCP registration for: ${Array.from(s).join(", ")}. Rerun with access to those config files to complete registration.`),console.log(`
165
- Step 2: Checking authentication...`);let c=await D.getSessionToken();if(c)try{await new ve(()=>Promise.resolve(c)).getStatus(),console.log(" Already authenticated.")}catch(g){let x=g instanceof Error?g.message:"";x.includes("session has expired")||x.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await D.clearAll(),c=null):console.log(` Couldn't verify session (${x||"unknown error"}) \u2014 continuing with existing token.`)}if(!c){let g=null;try{let{stdout:x}=await bo("gh",["auth","token"],{timeout:5e3});g=x.trim()}catch{}if(g||(g=process.env.GITHUB_TOKEN||null),g)try{console.log(" Found GitHub token \u2014 attempting headless login...");let x=await globalThis.fetch(`${_e()}/v1/auth/token-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({github_token:g}),signal:AbortSignal.timeout(1e4)});if(x.ok){let O=await x.json();if(O.success&&O.sessionToken){let F=O.sessionToken;c=F,await D.saveSessionToken(F),console.log(` Signed in as ${O.user} (headless).`)}}else(await x.json().catch(()=>({}))).hint==="card_required"&&console.log(" GitHub token valid but no card on file \u2014 opening browser for card enrollment...")}catch{}}if(c||(console.log(" No session found. Opening browser for GitHub login..."),c=await new Promise(async(g,x)=>{let O=Ln.randomUUID(),F=`${_e()}/login?state=${O}`;await os(F);let j=3e4,k=300*1e3,P=Date.now()+k;for(;Date.now()<P;)try{let U=await globalThis.fetch(`${_e()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:O,timeout:j}),signal:AbortSignal.timeout(j+5e3)});if(!U.ok){await tt(U,Y=>{d.warn("auth_status:retry_after_http_error",{status:U.status,delayMs:Y})});continue}let J=await U.json();if(J.status==="pending")continue;if(J.status==="expired"){x(new Error("Session expired. Please run setup again."));return}if(J.status==="complete"&&J.sessionToken){console.log(` Signed in as ${J.user}.`),g(J.sessionToken);return}}catch{await tt(void 0,U=>{d.warn("auth_status:retry_after_network_error",{delayMs:U})})}x(new Error("Login timed out after 5 minutes. Please run setup again."))}),await D.saveSessionToken(c),console.log(" Session token saved.")),console.log(`
166
- Step 3: Setting up authentication...`),!z())console.log(" Not macOS \u2014 skipping biometric setup.");else{try{await bo("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)}try{let g=await hr();console.log(" Attestation key generated."),await oe().registerAttestationKey(g),console.log(" Attestation key registered with server.")}catch(g){let x=g?.message||"unknown error";Wp(x)&&(console.error(" Server already has a biometric key for this account, but this device cannot prove access to it."),console.error(" Run `visa-cli config reset` to clear server-side biometric state through GitHub, then run `visa-cli setup` again."),process.exit(1)),console.log(` Skipped: ${x}`)}}let u=Ze.join(W.homedir(),".claude","settings.json"),m=Ie.existsSync(Ze.join(W.homedir(),".claude.json"));if(e.hud===!0)if(!m)console.log(`
164
+ `);return`${n}${r}${o}`})}function gf(e){return e.replace(/^(Usage: .+?) \[options\](?= |$)/gm,"$1")}function hf(e){return e.replace(/^Options:$/gm,"Flags:")}function Tc(e){let t=e.helpInformation.bind(e);e.helpInformation=()=>hf(gf(ff(mf(pf(t())))));for(let n of e.commands)Tc(n)}function yf(e){let t=new Map(e.map((r,s)=>[r,s]));q.commands.sort((r,s)=>{let o=t.get(r.name())??Number.MAX_SAFE_INTEGER,i=t.get(s.name())??Number.MAX_SAFE_INTEGER;return o-i})}q.name("visa-cli").description("Visa CLI - set up MCP payments, manage credentials, and monitor AI spend").version(Gn().version).addHelpCommand(!1);q.hook("preAction",async()=>{await Uo()});q.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 \u2014 for CI/agent use").option("--hud","Also enable the Claude Code HUD during setup").option("--no-hud","Do not install the HUD during setup (default)").action(async e=>{try{if(e.check){let g=Un();wc(g,"MCP config check:"),g.length>0&&(console.log("\nRun `visa-cli setup` (or `visa-cli install --repair`) to rewrite these entries."),process.exit(1));return}console.log("Step 1: Registering MCP server...");let t=Un(),n=new Map(t.map(g=>[g.client.id,g])),r=new Set,s=new Set,o=new Set;for(let g of Re)if(On(g)){let x;try{x=Nn(g)}catch(j){if(j instanceof ln){yc(j),s.add(g.displayName),o.add(g.id);continue}throw j}let O=n.get(g.id),F=O?` \u2014 repaired stale ${O.staleReason} entry`:"";console.log(` \u2713 ${g.displayName} (${x.configPath.replace(W.homedir(),"~")})${F}`),O&&r.add(g.id)}let i=t.filter(g=>!r.has(g.client.id)&&!o.has(g.client.id)),a=0;for(let g of i){try{bo(g)}catch(x){if(x instanceof ln){yc(x),s.add(g.client.displayName),o.add(g.client.id);continue}throw x}console.log(` \u2713 ${g.client.displayName} (${g.configPath.replace(W.homedir(),"~")}) \u2014 repaired stale ${g.staleReason} entry`),a++}let l=r.size+a;l===0&&s.size===0?console.log(" \u2713 MCP config verified \u2014 nothing to repair."):l>0&&console.log(` \u2713 Repaired ${l} stale MCP config ${l===1?"entry":"entries"}.`),s.size>0&&console.log(` ! Skipped MCP registration for: ${Array.from(s).join(", ")}. Rerun with access to those config files to complete registration.`),console.log(`
165
+ Step 2: Checking authentication...`);let c=await D.getSessionToken();if(c)try{await new ve(()=>Promise.resolve(c)).getStatus(),console.log(" Already authenticated.")}catch(g){let x=g instanceof Error?g.message:"";x.includes("session has expired")||x.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await D.clearAll(),c=null):console.log(` Couldn't verify session (${x||"unknown error"}) \u2014 continuing with existing token.`)}if(!c){let g=null;try{let{stdout:x}=await wo("gh",["auth","token"],{timeout:5e3});g=x.trim()}catch{}if(g||(g=process.env.GITHUB_TOKEN||null),g)try{console.log(" Found GitHub token \u2014 attempting headless login...");let x=await globalThis.fetch(`${_e()}/v1/auth/token-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({github_token:g}),signal:AbortSignal.timeout(1e4)});if(x.ok){let O=await x.json();if(O.success&&O.sessionToken){let F=O.sessionToken;c=F,await D.saveSessionToken(F),console.log(` Signed in as ${O.user} (headless).`)}}else(await x.json().catch(()=>({}))).hint==="card_required"&&console.log(" GitHub token valid but no card on file \u2014 opening browser for card enrollment...")}catch{}}if(c||(console.log(" No session found. Opening browser for GitHub login..."),c=await new Promise(async(g,x)=>{let O=Ln.randomUUID(),F=`${_e()}/login?state=${O}`;await is(F);let j=3e4,k=300*1e3,P=Date.now()+k;for(;Date.now()<P;)try{let U=await globalThis.fetch(`${_e()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:O,timeout:j}),signal:AbortSignal.timeout(j+5e3)});if(!U.ok){await nt(U,Y=>{d.warn("auth_status:retry_after_http_error",{status:U.status,delayMs:Y})});continue}let J=await U.json();if(J.status==="pending")continue;if(J.status==="expired"){x(new Error("Session expired. Please run setup again."));return}if(J.status==="complete"&&J.sessionToken){console.log(` Signed in as ${J.user}.`),g(J.sessionToken);return}}catch{await nt(void 0,U=>{d.warn("auth_status:retry_after_network_error",{delayMs:U})})}x(new Error("Login timed out after 5 minutes. Please run setup again."))}),await D.saveSessionToken(c),console.log(" Session token saved.")),console.log(`
166
+ Step 3: Setting up authentication...`),!z())console.log(" Not macOS \u2014 skipping biometric setup.");else{try{await wo("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)}try{let g=await hr();console.log(" Attestation key generated."),await oe().registerAttestationKey(g),console.log(" Attestation key registered with server.")}catch(g){let x=g?.message||"unknown error";Qp(x)&&(console.error(" Server already has a biometric key for this account, but this device cannot prove access to it."),console.error(" Run `visa-cli config reset` to clear server-side biometric state through GitHub, then run `visa-cli setup` again."),process.exit(1)),console.log(` Skipped: ${x}`)}}let u=Xe.join(W.homedir(),".claude","settings.json"),m=Ie.existsSync(Xe.join(W.homedir(),".claude.json"));if(e.hud===!0)if(!m)console.log(`
167
167
  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(`
168
- Step 4: Enabling the Visa spend HUD...`);let g=Zn(u),x=g.installed==="new"||g.installed==="already-visa"||g.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${x}${g.message}`);try{let O=oe(),F=await O.getStatus(),j={currentVersion:O.getClientVersion(),latestVersion:O.lastSignals?.updateAvailable?.latestVersion,updateCheckDisabled:Me()},k=Bs(F,j);Hs(k,F),console.log(` Preview: ${k.split(`
168
+ Step 4: Enabling the Visa spend HUD...`);let g=Zn(u),x=g.installed==="new"||g.installed==="already-visa"||g.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${x}${g.message}`);try{let O=oe(),F=await O.getStatus(),j={currentVersion:O.getClientVersion(),latestVersion:O.lastSignals?.updateAvailable?.latestVersion,updateCheckDisabled:Me()},k=Hs(F,j);Ks(k,F),console.log(` Preview: ${k.split(`
169
169
  `)[0]}`)}catch{}}let h="\x1B[1m",v="\x1B[0m";console.log(`
170
170
  \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
171
171
  \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
@@ -186,52 +186,56 @@ Step 4: Enabling the Visa spend HUD...`);let g=Zn(u),x=g.installed==="new"||g.in
186
186
 
187
187
  ${h}Verify:${v} visa-cli status
188
188
  ${h}Docs:${v} https://visacli.sh
189
- `)}catch(t){console.error("Error:",t.message),process.exit(1)}});q.command("install [client]",{hidden:!0}).description("Register MCP server with an AI client (claude, cursor, windsurf, cline, zed, ...)").option("--all","Install for all detected clients").option("--list","Show supported clients and install status").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--repair","Repair stale MCP client configs without re-running the full setup flow").option("--scope <scope>","Install scope: global or project","global").action(async(e,t)=>{try{if(t.check){let o=Un();_c(o,"MCP config check:"),o.length>0&&process.exit(1);return}if(t.repair){let o=Un();if(o.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of o)_o(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(W.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
189
+ `)}catch(t){console.error("Error:",t.message),process.exit(1)}});q.command("install [client]",{hidden:!0}).description("Register MCP server with an AI client (claude, cursor, windsurf, cline, zed, ...)").option("--all","Install for all detected clients").option("--list","Show supported clients and install status").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--repair","Repair stale MCP client configs without re-running the full setup flow").option("--scope <scope>","Install scope: global or project","global").action(async(e,t)=>{try{if(t.check){let o=Un();wc(o,"MCP config check:"),o.length>0&&process.exit(1);return}if(t.repair){let o=Un();if(o.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of o)bo(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(W.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
190
190
  Repaired ${o.length} stale MCP config ${o.length===1?"entry":"entries"}.`);return}if(t.list){console.log(`
191
191
  \x1B[1mSupported MCP Clients\x1B[0m
192
- `),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 Re){let l=On(a),c=pc(a),u=l?"Yes":"No",m=c?"Yes":"No",h=a.globalConfigPath.replace(W.homedir(),"~");console.log(` ${a.displayName.padEnd(18)} ${u.padEnd(10)} ${m.padEnd(11)} ${h}`)}console.log("");return}let n=t.scope==="project"?"project":"global";if(t.all){let o=[],i=[];for(let a of Re){if(!On(a)){i.push(a.displayName);continue}Nn(a,n),o.push(a.displayName)}o.length>0&&console.log(`Installed for: ${o.join(", ")}.`),i.length>0&&console.log(`Skipped: ${i.map(a=>`${a} (not detected)`).join(", ")}.`),o.length===0&&i.length===0&&console.log("No supported clients found.");return}e||(console.error("Usage: visa-cli install <client>"),console.error(" visa-cli install --all"),console.error(" visa-cli install --list"),console.error(`
193
- Supported clients: ${Re.map(o=>o.id).join(", ")}`),process.exit(1));let r=po(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${Re.map(o=>o.id).join(", ")}`),process.exit(1)),n==="global"&&!On(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let s=Nn(r,n);console.log(`Registered visa-cli MCP server in ${s.configPath}`),console.log(s.message)}catch(n){console.error("Error:",n.message),process.exit(1)}});q.command("pay <url>",{hidden:!0}).description("Pay a merchant URL (amount auto-detected from HTTP 402 response)").option("-m, --method <method>","HTTP method (GET or POST)","GET").option("-b, --body <json>","JSON request body for POST endpoints").action(async(e,t)=>{try{console.warn("Warning: `visa-cli pay` is deprecated and will be removed in a future release.\n Use the MCP `pay` tool via Claude Code or Cursor instead.\n See: https://github.com/Visa-Crypto-Labs/Visa-mono/issues/1913\n"),rc(e);let n=sc(t.method),r=oc(t.body),s=new ve(()=>D.getSessionToken());console.log(`Checking payment for ${e}...`);let o=ic(await s.paymentPreview({url:e}));console.log(` Merchant: ${o.merchantName}`),console.log(` Amount: $${o.amount.toFixed(2)} ${o.currency}`),console.log(` Rail: auto-detected
194
- `);let a=(await s.getStatus()).attestationRequired!==!1;a&&!z()&&console.warn("Warning: Touch ID unavailable on this system \u2014 payment will proceed without biometric attestation.");let l=Ln.randomUUID(),c=await rn(s,async()=>{let u;if(a&&z())try{let{nonce:m}=await s.getAttestationChallenge(),h=Buffer.from(JSON.stringify({nonce:m,amount:o.amount,merchant:o.merchantName,context:e})).toString("base64");u={signature:await Yt(h,`pay $${o.amount.toFixed(2)} to ${o.merchantName}`),nonce:m,amount:o.amount,merchant:o.merchantName}}catch(m){throw new Error(`Touch ID confirmation failed: ${m?.message||"user cancelled or biometric error"}`)}return s.pay({url:e,method:n,body:r,attestation:u,idempotencyKey:l})});if(c.success){if(console.log(`Payment complete: $${(c.amount??o.amount).toFixed(2)} \u2192 ${c.merchantName??o.merchantName}`),c.receipt?.urls?.length){console.log(`
192
+ `),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 Re){let l=On(a),c=hc(a),u=l?"Yes":"No",m=c?"Yes":"No",h=a.globalConfigPath.replace(W.homedir(),"~");console.log(` ${a.displayName.padEnd(18)} ${u.padEnd(10)} ${m.padEnd(11)} ${h}`)}console.log("");return}let n=t.scope==="project"?"project":"global";if(t.all){let o=[],i=[];for(let a of Re){if(!On(a)){i.push(a.displayName);continue}Nn(a,n),o.push(a.displayName)}o.length>0&&console.log(`Installed for: ${o.join(", ")}.`),i.length>0&&console.log(`Skipped: ${i.map(a=>`${a} (not detected)`).join(", ")}.`),o.length===0&&i.length===0&&console.log("No supported clients found.");return}e||(console.error("Usage: visa-cli install <client>"),console.error(" visa-cli install --all"),console.error(" visa-cli install --list"),console.error(`
193
+ Supported clients: ${Re.map(o=>o.id).join(", ")}`),process.exit(1));let r=go(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${Re.map(o=>o.id).join(", ")}`),process.exit(1)),n==="global"&&!On(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let s=Nn(r,n);console.log(`Registered visa-cli MCP server in ${s.configPath}`),console.log(s.message)}catch(n){console.error("Error:",n.message),process.exit(1)}});q.command("pay <url>",{hidden:!0}).description("Pay a merchant URL (amount auto-detected from HTTP 402 response)").option("-m, --method <method>","HTTP method (GET or POST)","GET").option("-b, --body <json>","JSON request body for POST endpoints").action(async(e,t)=>{try{console.warn("Warning: `visa-cli pay` is deprecated and will be removed in a future release.\n Use the MCP `pay` tool via Claude Code or Cursor instead.\n See: https://github.com/Visa-Crypto-Labs/Visa-mono/issues/1913\n"),ic(e);let n=ac(t.method),r=cc(t.body),s=new ve(()=>D.getSessionToken());console.log(`Checking payment for ${e}...`);let o=lc(await s.paymentPreview({url:e}));console.log(` Merchant: ${o.merchantName}`),console.log(` Amount: $${o.amount.toFixed(2)} ${o.currency}`),console.log(` Rail: auto-detected
194
+ `);let a=(await s.getStatus()).attestationRequired!==!1;a&&!z()&&console.warn("Warning: Touch ID unavailable on this system \u2014 payment will proceed without biometric attestation.");let l=Ln.randomUUID(),c=await sn(s,async()=>{let u;if(a&&z())try{let{nonce:m}=await s.getAttestationChallenge(),h=Buffer.from(JSON.stringify({nonce:m,amount:o.amount,merchant:o.merchantName,context:e})).toString("base64");u={signature:await Xt(h,`pay $${o.amount.toFixed(2)} to ${o.merchantName}`),nonce:m,amount:o.amount,merchant:o.merchantName}}catch(m){throw new Error(`Touch ID confirmation failed: ${m?.message||"user cancelled or biometric error"}`)}return s.pay({url:e,method:n,body:r,attestation:u,idempotencyKey:l})});if(c.success){if(console.log(`Payment complete: $${(c.amount??o.amount).toFixed(2)} \u2192 ${c.merchantName??o.merchantName}`),c.receipt?.urls?.length){console.log(`
195
195
  Result URLs:`);for(let u of c.receipt.urls)console.log(` ${u}`)}}else console.error(`Payment failed: ${c.message||"Unknown error"}`),process.exit(1)}catch(n){n instanceof ge?console.error(`Error: ${n.message}`):console.error("Error:",n.message),process.exit(1)}});q.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{Dn=!1;try{let e=oe(),[t,n]=await Promise.all([e.getStatus(),e.getTransactions().catch(s=>{if(process.env.VISA_CLI_DEBUG){let o=s instanceof Error?s.message:String(s);process.stderr.write(`[visa-cli] getTransactions failed (HUD will omit): ${o}
196
- `)}return{transactions:[]}})]),r={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:Me()};process.stdout.write(tc(t,Array.isArray(n?.transactions)?n.transactions:[],z(),r)),Dn=!0}catch(e){Dn=!1,console.error("Error:",e.message),process.exit(1)}});var Co=q.command("tokens").description("Create and manage API tokens for apps and agents").addHelpCommand(!1);function ko(e){let t=e instanceof Error?e.message:String(e);console.error("Error:",t),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 tokens command with keychain access or run it from a normal terminal.")),process.exit(1)}Co.command("create [label]").description("Create an API token 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 (default: server default)").option("--json","Output raw JSON").action(async(e,t)=>{try{let r=await oe().createAppApiKey({label:Xp(e),allowed_tools:Qp(t.tools),daily_cap_cents:ef(t.dailyCap)});if(t.json){console.log(JSON.stringify(r,null,2));return}console.log("API token created."),console.log(""),console.log(`Key: ${r.key}`),console.log(`Label: ${r.label}`),console.log(`Owner: ${r.owner}`),console.log(`Allowed tools: ${vc(r.allowed_tools)}`),console.log(`Daily cap: ${wo(r.daily_cap_cents)}/day`),console.log(""),console.log("Store this key now. It will not be shown again."),console.log(""),r.biometric_enabled?(console.log("---------------------------------------------------------------"),console.log("WARNING: Biometric (Touch ID) is currently ON for this account."),console.log("API tokens bypass biometric verification. Calls will fail with an"),console.log("attestation error until you disable biometric:"),console.log(""),console.log(" visa-cli config biometric off"),console.log("---------------------------------------------------------------"),console.log("")):r.biometric_warning&&(console.log("Note: API tokens bypass biometric verification. If you later"),console.log("enable biometric, API key calls will fail until you turn it off."),console.log("")),console.log("Example:"),console.log(` curl -X POST ${_e()}/v1/api/shortcuts/or-gpt-4o-mini \\`),console.log(` -H "X-Api-Key: ${r.key}" \\`),console.log(' -H "Content-Type: application/json" \\'),console.log(` -d '{"prompt":"Say hello in one sentence."}'`)}catch(n){ko(n)}});Co.command("list").description("List API tokens for the authenticated user").option("--json","Output raw JSON").action(async e=>{try{let n=await oe().listAppApiKeys();if(e.json){console.log(JSON.stringify(n,null,2));return}let r=n.keys||[];if(r.length===0){console.log("No API tokens found. Create one with: visa-cli tokens create");return}console.log("API tokens"),console.log("");for(let s of r)console.log(`${s.id}. ${s.label} (${s.key_prefix})`),console.log(` Status: ${s.status}`),console.log(` Owner: ${s.owner}`),console.log(` Allowed tools: ${vc(s.allowed_tools)}`),console.log(` Daily cap: ${wo(s.daily_cap_cents)}/day`),console.log(` Last used: ${s.last_used_at||"never"}`)}catch(t){ko(t)}});Co.command("revoke <id>").alias("delete").description("Revoke (or delete) an API token by id").action(async e=>{try{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Error("API token id must be a positive integer. Run `visa-cli tokens list` first.");let r=await oe().revokeAppApiKey(t);console.log(`Revoked API token ${r.revoked}.`)}catch(t){ko(t)}});async function xc(){try{console.log(`Resetting Visa CLI...
197
- `);let e=oe();await Yp(e);try{await e.logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}if(await D.clearAll(),console.log(" Keychain credentials cleared."),z())try{await yr(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}console.log(`
198
- Reset complete.`)}catch(e){console.error("Error:",e.message),process.exit(1)}}q.command("reset",{hidden:!0}).description("Deprecated alias for `config reset`").action(xc);var pf=100,Cc=q.command("balance").description("Manage prepaid balance").addHelpCommand(!1);Cc.command("show").description("Show prepaid balance + recent ledger entries").action(async()=>{try{let t=await new ve(()=>D.getSessionToken()).getBalance();if(console.log(`
199
- Balance: ${So(t.balanceMicros,t.balanceCents)}
196
+ `)}return{transactions:[]}})]),r={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:Me()};process.stdout.write(rc(t,Array.isArray(n?.transactions)?n.transactions:[],z(),r)),Dn=!0}catch(e){Dn=!1,console.error("Error:",e.message),process.exit(1)}});function _f(e){let t=e.map(sc),n=Math.max(2,...t.map(i=>i.id.length)),r=Math.max(5,...t.map(i=>i.brand.length)),s=Math.max(4,...t.map(i=>i.card.length)),o=7;console.log(`
197
+ Cards
198
+ `),console.log(` ${"ID".padEnd(n)} ${"Brand".padEnd(r)} ${"Card".padEnd(s)} Default`),console.log(` ${"\u2500".repeat(n)} ${"\u2500".repeat(r)} ${"\u2500".repeat(s)} ${"\u2500".repeat(o)}`);for(let i of t)console.log(` ${i.id.padEnd(n)} ${i.brand.padEnd(r)} ${i.card.padEnd(s)} ${i.default}`);console.log(`
199
+ Use:`),console.log(" visa-cli cards default <id>"),console.log(` visa-cli cards remove <id>
200
+ `)}async function vf(e,t){if(t.yes)return"confirmed";if(!process.stdin.isTTY)return"refused-non-tty";let n=bc.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 zr=q.command("cards").description("Manage enrolled payment cards").addHelpCommand(!1);zr.command("list").description("List enrolled payment cards").action(async()=>{try{let e=await Le.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}_f(t)}catch(e){console.error("Error:",e.message),process.exit(1)}});zr.command("add").description("Add a new Visa card").action(async()=>{try{let e=await Le.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)}});zr.command("remove <card-id>").description("Remove an enrolled card").option("-y, --yes","Skip the interactive confirmation prompt").action(async(e,t)=>{try{let n=mo(e),r=await vf(`Remove card ${n}? This cannot be undone.`,t);if(r==="refused-non-tty"&&(console.error("Refusing to remove card without --yes in a non-interactive shell."),process.exit(1)),r==="declined"){console.log("Aborted.");return}let s=await Le.removeCard({cardId:n,confirm:!0},"visa-cli cards remove");s?.success===!1&&(console.error(s.error||s.message||"Failed to remove card."),process.exit(1)),console.log(s?.message||`Removed card ${n}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});zr.command("default <card-id>").alias("set-default").description("Set the default payment card").action(async e=>{try{let t=mo(e),n=await Le.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)}});var To=q.command("tokens").description("Create and manage API tokens for apps and agents").addHelpCommand(!1);function Ao(e){let t=e instanceof Error?e.message:String(e);console.error("Error:",t),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 tokens command with keychain access or run it from a normal terminal.")),process.exit(1)}To.command("create [label]").description("Create an API token 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 (default: server default)").option("--json","Output raw JSON").action(async(e,t)=>{try{let r=await oe().createAppApiKey({label:rf(e),allowed_tools:sf(t.tools),daily_cap_cents:of(t.dailyCap)});if(t.json){console.log(JSON.stringify(r,null,2));return}console.log("API token created."),console.log(""),console.log(`Key: ${r.key}`),console.log(`Label: ${r.label}`),console.log(`Owner: ${r.owner}`),console.log(`Allowed tools: ${xc(r.allowed_tools)}`),console.log(`Daily cap: ${Co(r.daily_cap_cents)}/day`),console.log(""),console.log("Store this key now. It will not be shown again."),console.log(""),r.biometric_enabled?(console.log("---------------------------------------------------------------"),console.log("WARNING: Biometric (Touch ID) is currently ON for this account."),console.log("API tokens bypass biometric verification. Calls will fail with an"),console.log("attestation error until you disable biometric:"),console.log(""),console.log(" visa-cli config biometric off"),console.log("---------------------------------------------------------------"),console.log("")):r.biometric_warning&&(console.log("Note: API tokens bypass biometric verification. If you later"),console.log("enable biometric, API key calls will fail until you turn it off."),console.log("")),console.log("Example:"),console.log(` curl -X POST ${_e()}/v1/api/shortcuts/or-gpt-4o-mini \\`),console.log(` -H "X-Api-Key: ${r.key}" \\`),console.log(' -H "Content-Type: application/json" \\'),console.log(` -d '{"prompt":"Say hello in one sentence."}'`)}catch(n){Ao(n)}});To.command("list").description("List API tokens for the authenticated user").option("--json","Output raw JSON").action(async e=>{try{let n=await oe().listAppApiKeys();if(e.json){console.log(JSON.stringify(n,null,2));return}let r=n.keys||[];if(r.length===0){console.log("No API tokens found. Create one with: visa-cli tokens create");return}console.log("API tokens"),console.log("");for(let s of r)console.log(`${s.id}. ${s.label} (${s.key_prefix})`),console.log(` Status: ${s.status}`),console.log(` Owner: ${s.owner}`),console.log(` Allowed tools: ${xc(s.allowed_tools)}`),console.log(` Daily cap: ${Co(s.daily_cap_cents)}/day`),console.log(` Last used: ${s.last_used_at||"never"}`)}catch(t){Ao(t)}});To.command("revoke <id>").alias("delete").description("Revoke (or delete) an API token by id").action(async e=>{try{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Error("API token id must be a positive integer. Run `visa-cli tokens list` first.");let r=await oe().revokeAppApiKey(t);console.log(`Revoked API token ${r.revoked}.`)}catch(t){Ao(t)}});async function Ac(){try{console.log(`Resetting Visa CLI...
201
+ `);let e=oe();await tf(e);try{await e.logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}if(await D.clearAll(),console.log(" Keychain credentials cleared."),z())try{await yr(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}console.log(`
202
+ Reset complete.`)}catch(e){console.error("Error:",e.message),process.exit(1)}}q.command("reset",{hidden:!0}).description("Deprecated alias for `config reset`").action(Ac);var bf=100,Ec=q.command("balance").description("Manage prepaid balance").addHelpCommand(!1);Ec.command("show").description("Show prepaid balance + recent ledger entries").action(async()=>{try{let t=await new ve(()=>D.getSessionToken()).getBalance();if(console.log(`
203
+ Balance: ${xo(t.balanceMicros,t.balanceCents)}
200
204
  `),t.ledger.length===0){console.log(` (no ledger entries \u2014 top up to begin: visa-cli balance topup --amount 5)
201
- `);return}let n=t.ledger.slice(0,20),r=[],s=t.balanceCents,o=t.balanceMicros?BigInt(t.balanceMicros):null;for(let u of n)r.push(o!=null?o.toString():String(s*1e4)),o!=null&&u.deltaMicros?o-=BigInt(u.deltaMicros):(o=null,s-=u.deltaCents);let i=19,a=11,l=13,c=18;console.log(` ${"TIMESTAMP".padEnd(i)} ${"DELTA".padStart(a)} ${"BALANCE".padStart(l)} ${"REASON".padEnd(c)} TOOL`),console.log(` ${"\u2500".repeat(i)} ${"\u2500".repeat(a)} ${"\u2500".repeat(l)} ${"\u2500".repeat(c)} ${"\u2500".repeat(20)}`),n.forEach((u,m)=>{let h=(u.createdAt||"").slice(0,19),v=So(u.deltaMicros,u.deltaCents,!0),g=Zp(r[m]),x=(u.reason??"").slice(0,c),O=u.toolName??"";console.log(` ${h.padEnd(i)} ${v.padStart(a)} ${g.padStart(l)} ${x.padEnd(c)} ${O}`)}),console.log()}catch(e){console.error("Error:",e.message),process.exit(1)}});Cc.command("topup").description("Top up prepaid balance from your default card (Touch ID required)").requiredOption("-a, --amount <usd>","Amount in USD (e.g. 5 or 1.50)").action(async e=>{try{let t=parseFloat(e.amount);if(!Number.isFinite(t)||t<=0)throw new Error("amount must be a positive number");let n=Math.round(t*100);if(n<pf)throw new Error("minimum top-up is $1.00");let r=new ve(()=>D.getSessionToken()),o=(await r.getStatus()).attestationRequired!==!1;o&&!z()&&console.warn("Warning: Touch ID unavailable on this system \u2014 top-up will proceed without biometric attestation.");let i=Ln.randomUUID(),a=await rn(r,async()=>{let l;if(o&&z()){let{nonce:c}=await r.getAttestationChallenge(),u=Buffer.from(JSON.stringify({nonce:c,amount:t,merchant:"Visa CLI Balance",context:"balance-topup"})).toString("base64");l={signature:await Yt(u,`top up balance with $${t.toFixed(2)}`),nonce:c,amount:t,merchant:"Visa CLI Balance"}}return r.topupBalance({amount_cents:n,idempotency_key:i,attestation:l})});if(a.success)console.log(`Top-up complete: +$${(n/100).toFixed(2)} \u2192 balance now $${((a.balanceCents??0)/100).toFixed(2)}`),a.transactionId&&console.log(`Transaction: ${a.transactionId}`);else{let l=a.error_code?` [${a.error_code}]`:"";console.error(`Top-up failed${l}: ${a.error||"Unknown error"}`),process.exit(1)}}catch(t){console.error("Error:",t.message),process.exit(1)}});var ff=q.command("session",{hidden:!0}).description("Inspect session budgets");ff.command("inspect <id>").description("Show a session-budget by id (e.g. sb_abc123)").action(async e=>{try{if(!e||e.length===0)throw new Error("session id required");let t=new ve(()=>D.getSessionToken()),[n,r]=await Promise.allSettled([t.getSessionBudget(e),t.getSessionLedger(e)]),s=n.status==="fulfilled"?n.value.budget:void 0,o=r.status==="fulfilled"?r.value:void 0;if(!s&&!o?.ledger?.length&&(console.error(`Session not found: ${e}`),process.exit(1)),console.log(`
205
+ `);return}let n=t.ledger.slice(0,20),r=[],s=t.balanceCents,o=t.balanceMicros?BigInt(t.balanceMicros):null;for(let u of n)r.push(o!=null?o.toString():String(s*1e4)),o!=null&&u.deltaMicros?o-=BigInt(u.deltaMicros):(o=null,s-=u.deltaCents);let i=19,a=11,l=13,c=18;console.log(` ${"TIMESTAMP".padEnd(i)} ${"DELTA".padStart(a)} ${"BALANCE".padStart(l)} ${"REASON".padEnd(c)} TOOL`),console.log(` ${"\u2500".repeat(i)} ${"\u2500".repeat(a)} ${"\u2500".repeat(l)} ${"\u2500".repeat(c)} ${"\u2500".repeat(20)}`),n.forEach((u,m)=>{let h=(u.createdAt||"").slice(0,19),v=xo(u.deltaMicros,u.deltaCents,!0),g=nf(r[m]),x=(u.reason??"").slice(0,c),O=u.toolName??"";console.log(` ${h.padEnd(i)} ${v.padStart(a)} ${g.padStart(l)} ${x.padEnd(c)} ${O}`)}),console.log()}catch(e){console.error("Error:",e.message),process.exit(1)}});Ec.command("topup").description("Top up prepaid balance from your default card (Touch ID required)").requiredOption("-a, --amount <usd>","Amount in USD (e.g. 5 or 1.50)").action(async e=>{try{let t=parseFloat(e.amount);if(!Number.isFinite(t)||t<=0)throw new Error("amount must be a positive number");let n=Math.round(t*100);if(n<bf)throw new Error("minimum top-up is $1.00");let r=new ve(()=>D.getSessionToken()),o=(await r.getStatus()).attestationRequired!==!1;o&&!z()&&console.warn("Warning: Touch ID unavailable on this system \u2014 top-up will proceed without biometric attestation.");let i=Ln.randomUUID(),a=await sn(r,async()=>{let l;if(o&&z()){let{nonce:c}=await r.getAttestationChallenge(),u=Buffer.from(JSON.stringify({nonce:c,amount:t,merchant:"Visa CLI Balance",context:"balance-topup"})).toString("base64");l={signature:await Xt(u,`top up balance with $${t.toFixed(2)}`),nonce:c,amount:t,merchant:"Visa CLI Balance"}}return r.topupBalance({amount_cents:n,idempotency_key:i,attestation:l})});if(a.success)console.log(`Top-up complete: +$${(n/100).toFixed(2)} \u2192 balance now $${((a.balanceCents??0)/100).toFixed(2)}`),a.transactionId&&console.log(`Transaction: ${a.transactionId}`);else{let l=a.error_code?` [${a.error_code}]`:"";console.error(`Top-up failed${l}: ${a.error||"Unknown error"}`),process.exit(1)}}catch(t){console.error("Error:",t.message),process.exit(1)}});var Sf=q.command("session",{hidden:!0}).description("Inspect session budgets");Sf.command("inspect <id>").description("Show a session-budget by id (e.g. sb_abc123)").action(async e=>{try{if(!e||e.length===0)throw new Error("session id required");let t=new ve(()=>D.getSessionToken()),[n,r]=await Promise.allSettled([t.getSessionBudget(e),t.getSessionLedger(e)]),s=n.status==="fulfilled"?n.value.budget:void 0,o=r.status==="fulfilled"?r.value:void 0;if(!s&&!o?.ledger?.length&&(console.error(`Session not found: ${e}`),process.exit(1)),console.log(`
202
206
  Session: ${e}`),s){let i=(s.totalCents/100).toFixed(2),a=(s.cumulativeCents/100).toFixed(2),l=(s.remainingCents/100).toFixed(2);console.log(` Status: ${s.status}${s.expired?" (expired)":""}`),console.log(` Budget: $${i} \xB7 spent $${a} \xB7 remaining $${l}`),console.log(` Created: ${s.createdAt}`),console.log(` Expires: ${s.expiresAt}`)}if(o?.ledger?.length){console.log(`
203
207
  PSP References (CyberSource activity):`);let i=8,a=9,l=36;console.log(` ${"TYPE".padEnd(i)} ${"AMOUNT".padStart(a)} ${"CYBERSOURCE TX ID".padEnd(l)} CREATED`),console.log(` ${"\u2500".repeat(i)} ${"\u2500".repeat(a)} ${"\u2500".repeat(l)} ${"\u2500".repeat(19)}`);for(let c of o.ledger){let u=`$${(c.amountCents/100).toFixed(2)}`;console.log(` ${c.type.padEnd(i)} ${u.padStart(a)} ${(c.transactionId||"").padEnd(l)} ${(c.createdAt||"").slice(0,19)}`)}}else s&&console.log(`
204
- (no PSP references yet \u2014 no holds placed)`);console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});async function kc(e){(!e||e.trim().length===0)&&(console.log('Usage: visa-cli config feedback "your message"'),process.exit(1));try{await D.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await oe().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}}q.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action(kc);q.command("update").description("Update Visa CLI to the latest stable version").action(async()=>{let e=js();try{console.log(`Updating Visa CLI with ${e.packageManager}: ${e.display}`);let{stdout:t,stderr:n}=await bo(e.command,e.args,{timeout:5*6e4,maxBuffer:10*1024*1024});t.trim()&&process.stdout.write(t),n.trim()&&process.stderr.write(n),console.log("Visa CLI update complete. Restart any running MCP clients to use the new version.")}catch(t){console.error(`Update failed while running: ${e.display}`),console.error(t?.message??String(t)),process.exit(1)}});var Xe=q.command("config").description("Manage CLI configuration and local integrations").addHelpCommand(!1);Xe.command("feedback",{hidden:!0}).description("Deprecated alias for `feedback`").argument("[message]","Your feedback message").action(kc);Xe.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=oe(),n=await $r({api:t,includeDev:!!e.dev});if(e.json){console.log(fa(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(pa(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});function gf(){return Object.entries(st).map(([e,t])=>` ${e.padEnd(22)} (${t.type}) ${t.description}`).join(`
205
- `)}Xe.command("set <key> <value>").description("Persist a CLI setting to ~/.visa-mcp/settings.json").addHelpText("after",`
208
+ (no PSP references yet \u2014 no holds placed)`);console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});async function $c(e){(!e||e.trim().length===0)&&(console.log('Usage: visa-cli config feedback "your message"'),process.exit(1));try{await D.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await oe().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}}q.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action($c);q.command("update").description("Update Visa CLI to the latest stable version").action(async()=>{let e=Vs();try{console.log(`Updating Visa CLI with ${e.packageManager}: ${e.display}`);let{stdout:t,stderr:n}=await wo(e.command,e.args,{timeout:5*6e4,maxBuffer:10*1024*1024});t.trim()&&process.stdout.write(t),n.trim()&&process.stderr.write(n),console.log("Visa CLI update complete. Restart any running MCP clients to use the new version.")}catch(t){console.error(`Update failed while running: ${e.display}`),console.error(t?.message??String(t)),process.exit(1)}});var Qe=q.command("config").description("Manage CLI configuration and local integrations").addHelpCommand(!1);Qe.command("feedback",{hidden:!0}).description("Deprecated alias for `feedback`").argument("[message]","Your feedback message").action($c);Qe.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=oe(),n=await $r({api:t,includeDev:!!e.dev});if(e.json){console.log(ha(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(ga(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});function wf(){return Object.entries(ot).map(([e,t])=>` ${e.padEnd(22)} (${t.type}) ${t.description}`).join(`
209
+ `)}Qe.command("set <key> <value>").description("Persist a CLI setting to ~/.visa-mcp/settings.json").addHelpText("after",`
206
210
  Settable keys:
207
- ${gf()}`).action((e,t)=>{try{let n=nr(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 Fe||n instanceof Be||n instanceof nt?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});Xe.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=rr(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)}});Xe.command("reset").description("Log out and clear all credentials").action(xc);var To=Xe.command("biometric").description("Manage Touch ID / biometric attestation enforcement");To.command("status").description("Show current biometric enforcement state").action(async()=>{try{await D.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let n=await oe().getStatus(),r=n.attestationRequired!==!1,s=!!n.hasAttestationKey,o=z();console.log(`Server policy: Touch ID ${r?"REQUIRED":"NOT required"}`),console.log(`Attestation key registered: ${s?"yes":"no"}`),console.log(`Touch ID available on this device: ${o?"yes":"no"}`)}catch(e){console.error("Error:",e.message),process.exit(1)}});To.command("on").description("Require Touch ID for payments (security upgrade \u2014 no Touch ID needed)").action(async()=>{try{await D.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=oe(),n=await t.setBiometricPreference({required:!0});n.success||(console.error(`Failed: ${n.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is now REQUIRED for payments."),(await t.getStatus()).hasAttestationKey||console.warn("Note: no attestation key is registered yet. Run `visa-cli setup` to enroll Touch ID.")}catch(e){console.error("Error:",e.message),process.exit(1)}});To.command("off").description("Disable Touch ID requirement (security downgrade \u2014 one Touch ID confirmation required)").action(async()=>{try{await D.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=oe(),n=await t.getStatus();if(n.attestationRequired===!1){console.log("Touch ID is already disabled.");return}n.hasAttestationKey&&!z()&&(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 rn(t,async()=>{let s;if(n.hasAttestationKey&&z())try{let{nonce:o}=await t.getAttestationChallenge(),i=0,a="",l=Buffer.from(JSON.stringify({nonce:o,amount:i,merchant:a,context:"biometric-preference"})).toString("base64");s={signature:await Yt(l,"disable Touch ID requirement"),nonce:o,amount:i,merchant:a}}catch(o){throw new Error(`Touch ID confirmation failed: ${o?.message||"cancelled"}`)}return t.setBiometricPreference({required:!1,attestation:s})});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 jt=Xe.command("shell-hud").description("Manage the shell prompt HUD (opt-in \u2014 prefer: visa-cli config hud enable)").addHelpCommand(!1);function zr(){let e=Cr();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function Wr(){let e=kr();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}jt.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(zr);jt.command("enable").description("Enable the persistent shell HUD").action(zr);jt.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Wr);jt.command("disable").description("Disable the persistent shell HUD").action(Wr);jt.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${Tr()}
208
- `)});jt.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,r=(m,h,v)=>{console.log(` ${h?"\u2713":"\u2717"} ${m}: ${v}`),h||(n=!1)};console.log(`Shell HUD Doctor
209
- `);let s=nn();if(r("Shell detected",!!s,s??"none (zsh, bash, or PowerShell required)"),s){let m=xn(s),h=e(m);if(r("RC file exists",h,m.replace(W.homedir(),"~")),h){let g=t(m,"utf-8").includes("visa-cli shell hud v2");r("HUD block installed",!!g,g?"found in rc file":"missing \u2014 run: visa-cli config shell-hud install")}}let o=en(),i=e(o);if(r("Cache file",i,i?o.replace(W.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let m=JSON.parse(t(o,"utf-8")),h=Date.now()-(m.renderedAt??0),v=Math.round(h/1e3),g=v<=30;console.log(` ${g?"\u2713":"\u26A0"} Cache freshness: ${v}s old${g?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{r("Cache readable",!1,"corrupt JSON")}let a=wr(),l=e(a),c="missing";if(l)try{c=t(a,"utf-8").trim().slice(0,80)}catch{c="unreadable"}r("Line file",l,c);let u=!1;try{u=!!await D.getSessionToken()}catch{}if(r("Auth token",u,u?"found in keychain":"missing \u2014 run: visa-cli setup"),u)try{await oe().getStatus(),r("API connectivity",!0,"GET /v1/status OK")}catch(m){let h=m instanceof Error?m.message:"unknown error";r("API connectivity",!1,h)}console.log(n?`
211
+ ${wf()}`).action((e,t)=>{try{let n=nr(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 Be||n instanceof He||n instanceof rt?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});Qe.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=rr(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)}});Qe.command("reset").description("Log out and clear all credentials").action(Ac);var Eo=Qe.command("biometric").description("Manage Touch ID / biometric attestation enforcement");Eo.command("status").description("Show current biometric enforcement state").action(async()=>{try{await D.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let n=await oe().getStatus(),r=n.attestationRequired!==!1,s=!!n.hasAttestationKey,o=z();console.log(`Server policy: Touch ID ${r?"REQUIRED":"NOT required"}`),console.log(`Attestation key registered: ${s?"yes":"no"}`),console.log(`Touch ID available on this device: ${o?"yes":"no"}`)}catch(e){console.error("Error:",e.message),process.exit(1)}});Eo.command("on").description("Require Touch ID for payments (security upgrade \u2014 no Touch ID needed)").action(async()=>{try{await D.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=oe(),n=await t.setBiometricPreference({required:!0});n.success||(console.error(`Failed: ${n.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is now REQUIRED for payments."),(await t.getStatus()).hasAttestationKey||console.warn("Note: no attestation key is registered yet. Run `visa-cli setup` to enroll Touch ID.")}catch(e){console.error("Error:",e.message),process.exit(1)}});Eo.command("off").description("Disable Touch ID requirement (security downgrade \u2014 one Touch ID confirmation required)").action(async()=>{try{await D.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=oe(),n=await t.getStatus();if(n.attestationRequired===!1){console.log("Touch ID is already disabled.");return}n.hasAttestationKey&&!z()&&(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 sn(t,async()=>{let s;if(n.hasAttestationKey&&z())try{let{nonce:o}=await t.getAttestationChallenge(),i=0,a="",l=Buffer.from(JSON.stringify({nonce:o,amount:i,merchant:a,context:"biometric-preference"})).toString("base64");s={signature:await Xt(l,"disable Touch ID requirement"),nonce:o,amount:i,merchant:a}}catch(o){throw new Error(`Touch ID confirmation failed: ${o?.message||"cancelled"}`)}return t.setBiometricPreference({required:!1,attestation:s})});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 qt=Qe.command("shell-hud").description("Manage the shell prompt HUD (opt-in \u2014 prefer: visa-cli config hud enable)").addHelpCommand(!1);function Wr(){let e=Cr();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function Jr(){let e=kr();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}qt.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Wr);qt.command("enable").description("Enable the persistent shell HUD").action(Wr);qt.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Jr);qt.command("disable").description("Disable the persistent shell HUD").action(Jr);qt.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${Tr()}
212
+ `)});qt.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,r=(m,h,v)=>{console.log(` ${h?"\u2713":"\u2717"} ${m}: ${v}`),h||(n=!1)};console.log(`Shell HUD Doctor
213
+ `);let s=rn();if(r("Shell detected",!!s,s??"none (zsh, bash, or PowerShell required)"),s){let m=Cn(s),h=e(m);if(r("RC file exists",h,m.replace(W.homedir(),"~")),h){let g=t(m,"utf-8").includes("visa-cli shell hud v2");r("HUD block installed",!!g,g?"found in rc file":"missing \u2014 run: visa-cli config shell-hud install")}}let o=tn(),i=e(o);if(r("Cache file",i,i?o.replace(W.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let m=JSON.parse(t(o,"utf-8")),h=Date.now()-(m.renderedAt??0),v=Math.round(h/1e3),g=v<=30;console.log(` ${g?"\u2713":"\u26A0"} Cache freshness: ${v}s old${g?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{r("Cache readable",!1,"corrupt JSON")}let a=wr(),l=e(a),c="missing";if(l)try{c=t(a,"utf-8").trim().slice(0,80)}catch{c="unreadable"}r("Line file",l,c);let u=!1;try{u=!!await D.getSessionToken()}catch{}if(r("Auth token",u,u?"found in keychain":"missing \u2014 run: visa-cli setup"),u)try{await oe().getStatus(),r("API connectivity",!0,"GET /v1/status OK")}catch(m){let h=m instanceof Error?m.message:"unknown error";r("API connectivity",!1,h)}console.log(n?`
210
214
  All checks passed.`:`
211
- Some checks failed \u2014 see above.`),n||process.exit(1)});async function Tc(e){if(!(!e.force&&ua()))try{let t=oe(),[n,r]=await Promise.allSettled([t.getStatus(),t.getBalance()]);if(n.status==="rejected")throw n.reason;let s=n.value;r.status==="fulfilled"&&r.value.success&&(s.balanceCents=r.value.balanceCents,s.amountUsd=r.value.amountUsd);let o={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:Me()},i=Bs(s,o);Hs(i,s)}catch{}finally{wn()}}jt.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(Tc);var Vt=q.command("shell-hud",{hidden:!0}).description("Deprecated alias for `config shell-hud`");Vt.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(zr);Vt.command("enable").description("Enable the persistent shell HUD").action(zr);Vt.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Wr);Vt.command("disable").description("Disable the persistent shell HUD").action(Wr);Vt.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${Tr()}
212
- `)});Vt.command("doctor").description("Show the new shell HUD doctor command").action(()=>{console.log("Run: visa-cli config shell-hud doctor")});Vt.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(Tc);async function Ac(e){try{let t=await Wo(),r=Tr().split(`
213
- `)[0],s=da();if(!t&&r.includes("loading")){process.stdout.write(`VISA | HUD not initialized \u2014 run: visa-cli config hud enable
214
- `);return}if(e.json){let i=await Qo(r,t,s);process.stdout.write(`${JSON.stringify(i,null,2)}
215
- `);return}let o=await Yo(r,t,s);process.stdout.write(`${o}
216
- `)}catch(t){let n=t instanceof Error?t.message:"unknown error";console.error(`Failed to render Visa HUD: ${n}`),process.exit(1)}}Xe.command("statusline").description("Output the Visa HUD for agent statusline integrations").option("--json","Output structured JSON for clients that render their own HUD").action(Ac);q.command("statusline",{hidden:!0}).description("Deprecated alias for `config statusline`").option("--json","Output structured JSON for clients that render their own HUD").action(Ac);var ln=Xe.command("hud").description("Manage the Visa spend HUD \u2014 one command for all surfaces").addHelpCommand(!1);ln.description("Show which HUD surfaces are currently enabled").action(()=>{let e="\x1B[1m",t="\x1B[2m",n="\x1B[32m",r="\x1B[33m",s="\x1B[0m";console.log(`
215
+ Some checks failed \u2014 see above.`),n||process.exit(1)});async function Rc(e){if(!(!e.force&&ma()))try{let t=oe(),[n,r]=await Promise.allSettled([t.getStatus(),t.getBalance()]);if(n.status==="rejected")throw n.reason;let s=n.value;r.status==="fulfilled"&&r.value.success&&(s.balanceCents=r.value.balanceCents,s.amountUsd=r.value.amountUsd);let o={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:Me()},i=Hs(s,o);Ks(i,s)}catch{}finally{xn()}}qt.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(Rc);var Ft=q.command("shell-hud",{hidden:!0}).description("Deprecated alias for `config shell-hud`");Ft.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Wr);Ft.command("enable").description("Enable the persistent shell HUD").action(Wr);Ft.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Jr);Ft.command("disable").description("Disable the persistent shell HUD").action(Jr);Ft.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${Tr()}
216
+ `)});Ft.command("doctor").description("Show the new shell HUD doctor command").action(()=>{console.log("Run: visa-cli config shell-hud doctor")});Ft.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(Rc);async function Ic(e){try{let t=await Yo(),r=Tr().split(`
217
+ `)[0],s=pa();if(!t&&r.includes("loading")){process.stdout.write(`VISA | HUD not initialized \u2014 run: visa-cli config hud enable
218
+ `);return}if(e.json){let i=await ti(r,t,s);process.stdout.write(`${JSON.stringify(i,null,2)}
219
+ `);return}let o=await Xo(r,t,s);process.stdout.write(`${o}
220
+ `)}catch(t){let n=t instanceof Error?t.message:"unknown error";console.error(`Failed to render Visa HUD: ${n}`),process.exit(1)}}Qe.command("statusline").description("Output the Visa HUD for agent statusline integrations").option("--json","Output structured JSON for clients that render their own HUD").action(Ic);q.command("statusline",{hidden:!0}).description("Deprecated alias for `config statusline`").option("--json","Output structured JSON for clients that render their own HUD").action(Ic);var un=Qe.command("hud").description("Manage the Visa spend HUD \u2014 one command for all surfaces").addHelpCommand(!1);un.description("Show which HUD surfaces are currently enabled").action(()=>{let e="\x1B[1m",t="\x1B[2m",n="\x1B[32m",r="\x1B[33m",s="\x1B[0m";console.log(`
217
221
  ${e}Visa HUD Status${s}
218
- `);let o=Ze.join(W.homedir(),".claude","settings.json"),i=!1,a=!1;try{if(Ie.existsSync(o)){let v=JSON.parse(Ie.readFileSync(o,"utf-8")),g=typeof v.statusLine=="object"?v.statusLine.command:"";i=_t(g),a=!!v.statusLine&&!i}}catch{}let l=i?`${n}\u2713${s}`:`${t}\u2717${s}`,c=i?"registered in ~/.claude/settings.json":a?`${r}another HUD is configured${s} \u2014 edit settings.json to switch`:"not enabled";console.log(` ${l} ${e}Claude Code${s} (statusLine) ${c}`);let u=xr(),m=u?`${n}\u2713${s}`:`${t}\u2717${s}`;console.log(` ${m} ${e}Shell prompt${s} ${u?"installed in shell rc file":"not installed (opt-in)"}`),console.log(`
219
- ${e}Quick start:${s}`),i||console.log(` visa-cli config hud enable ${t}# Claude Code statusLine (recommended)${s}`),u||console.log(` visa-cli config hud enable shell ${t}# zsh/bash prompt line (opt-in)${s}`),i&&u&&console.log(` ${n}All surfaces enabled.${s}`),(i||u)&&console.log(` visa-cli config hud disable [shell] ${t}# remove a surface${s}`),console.log(` visa-cli config hud doctor ${t}# diagnose connectivity${s}`),console.log()});ln.command("enable").description("Enable the Visa HUD \u2014 auto-detects Claude Code, or specify: shell, codex, all").argument("[surface]","Target surface: claude (default), shell, codex, or all").action(e=>{let t=e??"claude",n=ms(t);if(t==="shell"||t==="prompt"){let r=Cr();r.installed||(console.error(r.message),process.exit(1)),console.log(r.message);return}if(n||(console.error(`Unknown HUD surface: ${t}`),console.error("Supported: claude (default), shell, codex, all"),process.exit(1)),n==="claude"||n==="claude-code"||n==="all"){let r=Ze.join(W.homedir(),".claude","settings.json"),s=Zn(r);console.log(s.message),(s.installed==="error"||s.installed==="malformed-json")&&process.exit(1)}if(n==="codex"||n==="all"){let r=Cr();console.log(r.message),console.log("Codex structured HUD payload is available with: visa-cli config statusline --json"),r.installed||process.exit(1)}});ln.command("disable").description("Disable the Visa HUD from a surface: claude (default), shell, codex, or all").argument("[surface]","Target surface: claude (default), shell, codex, or all").action(e=>{let t=e??"claude";if(t==="shell"||t==="prompt"){let o=kr();o.removed||(console.error(o.message),process.exit(1)),console.log(o.message);return}let n=ms(t);n||(console.error(`Unknown HUD surface: ${t}`),console.error("Supported: claude (default), shell, codex, all"),process.exit(1));let r=!1,s=!1;if(n==="claude"||n==="claude-code"||n==="all"){let o=Ze.join(W.homedir(),".claude","settings.json"),i=is(o);console.log(i.message),i.removed&&(s=!0),!i.removed&&n!=="all"&&(r=!0)}if(n==="codex"||n==="all"){let o=kr();console.log(o.message),o.removed&&(s=!0),!o.removed&&n!=="all"&&(r=!0)}n==="all"&&!s&&(r=!0),r&&process.exit(1)});ln.command("doctor").description("Diagnose HUD installation and connectivity across all surfaces").action(async()=>{let e=!0,t=(l,c,u)=>{console.log(` ${c?"\u2713":"\u2717"} ${l}: ${u}`),c||(e=!1)};console.log(`Visa HUD Doctor
220
- `);let n=Ze.join(W.homedir(),".claude","settings.json"),r=!1;try{if(Ie.existsSync(n)){let l=JSON.parse(Ie.readFileSync(n,"utf-8")),c=typeof l.statusLine=="object"?l.statusLine.command:"";r=_t(c)}}catch{}t("Claude Code statusLine",r,r?"registered":"not registered \u2014 run: visa-cli config hud enable");let s=nn();if(t("Shell detected",!!s,s??"none (zsh, bash, or PowerShell required)"),s){let l=xn(s),c=Ie.existsSync(l);if(t("RC file exists",c,l.replace(W.homedir(),"~")),c){let m=Ie.readFileSync(l,"utf-8").includes("visa-cli shell hud v2");console.log(` ${m?"\u2713":"\u2013"} Shell HUD block: ${m?"installed":"not installed (opt-in \u2014 run: visa-cli config hud enable shell)"}`)}}let o=en(),i=Ie.existsSync(o);if(t("HUD cache file",i,i?o.replace(W.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let l=JSON.parse(Ie.readFileSync(o,"utf-8")),c=Date.now()-(l.renderedAt??0),u=Math.round(c/1e3),m=u<=30;console.log(` ${m?"\u2713":"\u26A0"} Cache freshness: ${u}s old${m?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{t("Cache readable",!1,"corrupt JSON")}let a=!1;try{a=!!await D.getSessionToken()}catch{}if(t("Auth token",a,a?"found in keychain":"missing \u2014 run: visa-cli setup"),a)try{await oe().getStatus(),t("API connectivity",!0,"GET /v1/status OK")}catch(l){let c=l instanceof Error?l.message:"unknown error";t("API connectivity",!1,c)}console.log(e?`
222
+ `);let o=Xe.join(W.homedir(),".claude","settings.json"),i=!1,a=!1;try{if(Ie.existsSync(o)){let v=JSON.parse(Ie.readFileSync(o,"utf-8")),g=typeof v.statusLine=="object"?v.statusLine.command:"";i=bt(g),a=!!v.statusLine&&!i}}catch{}let l=i?`${n}\u2713${s}`:`${t}\u2717${s}`,c=i?"registered in ~/.claude/settings.json":a?`${r}another HUD is configured${s} \u2014 edit settings.json to switch`:"not enabled";console.log(` ${l} ${e}Claude Code${s} (statusLine) ${c}`);let u=xr(),m=u?`${n}\u2713${s}`:`${t}\u2717${s}`;console.log(` ${m} ${e}Shell prompt${s} ${u?"installed in shell rc file":"not installed (opt-in)"}`),console.log(`
223
+ ${e}Quick start:${s}`),i||console.log(` visa-cli config hud enable ${t}# Claude Code statusLine (recommended)${s}`),u||console.log(` visa-cli config hud enable shell ${t}# zsh/bash prompt line (opt-in)${s}`),i&&u&&console.log(` ${n}All surfaces enabled.${s}`),(i||u)&&console.log(` visa-cli config hud disable [shell] ${t}# remove a surface${s}`),console.log(` visa-cli config hud doctor ${t}# diagnose connectivity${s}`),console.log()});un.command("enable").description("Enable the Visa HUD \u2014 auto-detects Claude Code, or specify: shell, codex, all").argument("[surface]","Target surface: claude (default), shell, codex, or all").action(e=>{let t=e??"claude",n=ps(t);if(t==="shell"||t==="prompt"){let r=Cr();r.installed||(console.error(r.message),process.exit(1)),console.log(r.message);return}if(n||(console.error(`Unknown HUD surface: ${t}`),console.error("Supported: claude (default), shell, codex, all"),process.exit(1)),n==="claude"||n==="claude-code"||n==="all"){let r=Xe.join(W.homedir(),".claude","settings.json"),s=Zn(r);console.log(s.message),(s.installed==="error"||s.installed==="malformed-json")&&process.exit(1)}if(n==="codex"||n==="all"){let r=Cr();console.log(r.message),console.log("Codex structured HUD payload is available with: visa-cli config statusline --json"),r.installed||process.exit(1)}});un.command("disable").description("Disable the Visa HUD from a surface: claude (default), shell, codex, or all").argument("[surface]","Target surface: claude (default), shell, codex, or all").action(e=>{let t=e??"claude";if(t==="shell"||t==="prompt"){let o=kr();o.removed||(console.error(o.message),process.exit(1)),console.log(o.message);return}let n=ps(t);n||(console.error(`Unknown HUD surface: ${t}`),console.error("Supported: claude (default), shell, codex, all"),process.exit(1));let r=!1,s=!1;if(n==="claude"||n==="claude-code"||n==="all"){let o=Xe.join(W.homedir(),".claude","settings.json"),i=as(o);console.log(i.message),i.removed&&(s=!0),!i.removed&&n!=="all"&&(r=!0)}if(n==="codex"||n==="all"){let o=kr();console.log(o.message),o.removed&&(s=!0),!o.removed&&n!=="all"&&(r=!0)}n==="all"&&!s&&(r=!0),r&&process.exit(1)});un.command("doctor").description("Diagnose HUD installation and connectivity across all surfaces").action(async()=>{let e=!0,t=(l,c,u)=>{console.log(` ${c?"\u2713":"\u2717"} ${l}: ${u}`),c||(e=!1)};console.log(`Visa HUD Doctor
224
+ `);let n=Xe.join(W.homedir(),".claude","settings.json"),r=!1;try{if(Ie.existsSync(n)){let l=JSON.parse(Ie.readFileSync(n,"utf-8")),c=typeof l.statusLine=="object"?l.statusLine.command:"";r=bt(c)}}catch{}t("Claude Code statusLine",r,r?"registered":"not registered \u2014 run: visa-cli config hud enable");let s=rn();if(t("Shell detected",!!s,s??"none (zsh, bash, or PowerShell required)"),s){let l=Cn(s),c=Ie.existsSync(l);if(t("RC file exists",c,l.replace(W.homedir(),"~")),c){let m=Ie.readFileSync(l,"utf-8").includes("visa-cli shell hud v2");console.log(` ${m?"\u2713":"\u2013"} Shell HUD block: ${m?"installed":"not installed (opt-in \u2014 run: visa-cli config hud enable shell)"}`)}}let o=tn(),i=Ie.existsSync(o);if(t("HUD cache file",i,i?o.replace(W.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let l=JSON.parse(Ie.readFileSync(o,"utf-8")),c=Date.now()-(l.renderedAt??0),u=Math.round(c/1e3),m=u<=30;console.log(` ${m?"\u2713":"\u26A0"} Cache freshness: ${u}s old${m?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{t("Cache readable",!1,"corrupt JSON")}let a=!1;try{a=!!await D.getSessionToken()}catch{}if(t("Auth token",a,a?"found in keychain":"missing \u2014 run: visa-cli setup"),a)try{await oe().getStatus(),t("API connectivity",!0,"GET /v1/status OK")}catch(l){let c=l instanceof Error?l.message:"unknown error";t("API connectivity",!1,c)}console.log(e?`
221
225
  All checks passed.`:`
222
- Some checks failed \u2014 see above.`),e||process.exit(1)});ln.command("enable-claude").description("Alias for: hud enable claude").action(()=>{let e=Ze.join(W.homedir(),".claude","settings.json"),t=Zn(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});ln.command("disable-claude").description("Alias for: hud disable claude").action(()=>{let e=Ze.join(W.homedir(),".claude","settings.json"),t=is(e);console.log(t.message),t.removed||process.exit(1)});var un=q.command("merchants").description("List discoverable platform merchants and refresh JIT tools").addHelpCommand(!1);un.description("Discover and run paid merchant tools");un.command("list").description("List live platform merchants and the tools they expose").option("--json","Print machine-readable JSON").action(async e=>{try{let t=new ve(()=>D.getSessionToken()),n=await t.listPublicMerchants();if(n.length===0){e.json?console.log(JSON.stringify({merchants:[]},null,2)):console.log(`
226
+ Some checks failed \u2014 see above.`),e||process.exit(1)});un.command("enable-claude").description("Alias for: hud enable claude").action(()=>{let e=Xe.join(W.homedir(),".claude","settings.json"),t=Zn(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});un.command("disable-claude").description("Alias for: hud disable claude").action(()=>{let e=Xe.join(W.homedir(),".claude","settings.json"),t=as(e);console.log(t.message),t.removed||process.exit(1)});var dn=q.command("merchants").description("List discoverable platform merchants and refresh JIT tools").addHelpCommand(!1);dn.description("Discover and run paid merchant tools");dn.command("list").description("List live platform merchants and the tools they expose").option("--json","Print machine-readable JSON").action(async e=>{try{let t=new ve(()=>D.getSessionToken()),n=await t.listPublicMerchants();if(n.length===0){e.json?console.log(JSON.stringify({merchants:[]},null,2)):console.log(`
223
227
  No live platform merchants on this auth server.
224
228
  `);return}let r=await Promise.all(n.map(async a=>{let l=await t.getPublicMerchantDiscover(a.slug);return{slug:a.slug,display_name:a.display_name,provider:l?.title??a.display_name,merchant_of_record:l?.merchant_of_record??a.display_name,upstream:l?.upstream,tools:(l?.routes??[]).filter(c=>c.tool_id).map(c=>({tool_id:c.tool_id,mcp_name:c.tool_id.replace(/-/g,"_"),method:c.method,path:c.path,price_cents:c.price_cents,category:c.category??null,description:c.description??null}))}}));if(e.json){console.log(JSON.stringify({merchants:r},null,2));return}let s="\x1B[1m",o="\x1B[2m",i="\x1B[0m";console.log();for(let a of r){let l=a.merchant_of_record!==a.provider?` ${o}(MoR: ${a.merchant_of_record})${i}`:"";if(console.log(` ${s}${a.provider}${i}${l} ${o}\u2014 slug: ${a.slug}${i}`),a.upstream&&console.log(` ${o}upstream: ${a.upstream}${i}`),a.tools.length===0)console.log(` ${o}(no routes with tool_id \u2014 agents can't see this merchant yet)${i}`);else for(let c of a.tools){let u=c.category?` ${o}[${c.category}]${i}`:"",m=`$${(c.price_cents/100).toFixed(2)}`;console.log(` ${c.tool_id}${u} ${o}\u2192 Claude: ${c.mcp_name}${i} ${m} ${o}${c.method} ${c.path}${i}`),c.description&&console.log(` ${o}${c.description}${i}`)}console.log()}console.log(` ${o}To enable JIT tools in your MCP server, set: visa-cli config set merchants.discover all (or =<slug,...>)${i}
225
- `)}catch(t){console.error("Error:",t.message),process.exit(1)}});un.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("--verbose","Show grouped cards with descriptions").option("--json","Print machine-readable JSON").action(async e=>{try{let t=oe(),n=await of(t,{query:e.query,category:e.category});if(e.json){console.log(JSON.stringify({tools:n},null,2));return}if(n.length===0){console.log("No merchant tools found. Try: visa-cli merchants tools --category image");return}e.verbose?sf(n):rf(n)}catch(t){console.error("Error:",t.message),process.exit(1)}});un.command("describe <tool>").description("Show tool schema, price, and examples").action(async e=>{try{let n=await oe().catalogTool(e,"discover_tools");n||(console.error(`Tool not found: ${e}`),console.error('Search with: visa-cli merchants tools --query "what you want to do"'),process.exit(1)),console.log(`
229
+ `)}catch(t){console.error("Error:",t.message),process.exit(1)}});dn.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("--verbose","Show grouped cards with descriptions").option("--json","Print machine-readable JSON").action(async e=>{try{let t=oe(),n=await df(t,{query:e.query,category:e.category});if(e.json){console.log(JSON.stringify({tools:n},null,2));return}if(n.length===0){console.log("No merchant tools found. Try: visa-cli merchants tools --category image");return}e.verbose?uf(n):lf(n)}catch(t){console.error("Error:",t.message),process.exit(1)}});dn.command("describe <tool>").description("Show tool schema, price, and examples").action(async e=>{try{let n=await oe().catalogTool(e,"discover_tools");n||(console.error(`Tool not found: ${e}`),console.error('Search with: visa-cli merchants tools --query "what you want to do"'),process.exit(1)),console.log(`
226
230
  ${n.id}
227
231
  `),console.log(n.description),console.log(`
228
- Price`),console.log(` ${xo(n.priceCents,n.priceDisplay)}`),console.log(`
232
+ Price`),console.log(` ${ko(n.priceCents,n.priceDisplay)}`),console.log(`
229
233
  Provider`),console.log(` ${n.provider} \xB7 ${n.category}`),console.log(`
230
234
  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;for(let[o,i]of Object.entries(r)){let a=s.has(o)?"required":"optional",l=i?.description?` - ${i.description}`:"";console.log(` ${o.padEnd(12)} ${a}${l}`)}}else console.log(" No published schema. Use --json with the request body.");console.log(`
231
- Examples`),console.log(` visa-cli merchants run ${n.id} --json '{"prompt":"a lobster"}'`),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)}});function hf(e){return["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"].includes(e)}async function Ec(e,t,n){return hf(e)?Zt.shortcut(e,t,n):Zt.executeTool({tool_id:e,params:t},n,"execute_tool")}un.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").action(async(e,t)=>{try{let n=tf(t.json,"--json");if(t.prompt&&(n.prompt=t.prompt),Object.keys(n).length===0)throw new Error("Provide tool params with --json or --prompt.");console.log(`Running ${e}`);let r=await Ec(e,n,`visa-cli merchants run ${e}`);Sc(r)}catch(n){console.error("Error:",n.message),process.exit(1)}});un.command("refresh").description("Hint: restart the MCP server (Claude/Cursor) to refresh discovered tools \u2014 discovery is in-process").action(()=>{console.log(`
235
+ Examples`),console.log(` visa-cli merchants run ${n.id} --json '{"prompt":"a lobster"}'`),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)}});function xf(e){return["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"].includes(e)}async function Pc(e,t,n){return xf(e)?Le.shortcut(e,t,n):Le.executeTool({tool_id:e,params:t},n,"execute_tool")}dn.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").action(async(e,t)=>{try{let n=af(t.json,"--json");if(t.prompt&&(n.prompt=t.prompt),Object.keys(n).length===0)throw new Error("Provide tool params with --json or --prompt.");console.log(`Running ${e}`);let r=await Pc(e,n,`visa-cli merchants run ${e}`);kc(r)}catch(n){console.error("Error:",n.message),process.exit(1)}});dn.command("refresh").description("Hint: restart the MCP server (Claude/Cursor) to refresh discovered tools \u2014 discovery is in-process").action(()=>{console.log(`
232
236
  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.
233
237
  `)});var jn=q.command("generate").description("Generate media with merchant tools").addHelpCommand(!1);async function Vn(e){console.log(`
234
238
  ${e.kind}
235
239
  `),console.log(`Using: ${e.toolId}`),console.log(`Prompt: ${e.prompt}
236
- `);let t=await Ec(e.toolId,e.params,`visa-cli generate ${e.kind.toLowerCase()}: ${e.prompt}`);Sc(t)}var yf=(e,t)=>n=>(t.includes(n)||q.error(`error: option '${e}' accepts ${t.map(r=>`'${r}'`).join(", ")} (got '${n}')`,{exitCode:2}),n);jn.command("image <prompt>").description("Generate an image from a prompt").option("--quality <quality>","Image quality: standard or high",yf("--quality",["standard","high"]),"standard").option("--fast","Use the fast image tool").option("--tool <tool>","Exact tool id override").action(async(e,t)=>{try{let n=t.tool??(t.fast||t.quality!=="high"?"generate_image_fast_card":"generate_image_card");await Vn({kind:"Image generation",toolId:n,params:{prompt:e},prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});jn.command("video <prompt>").description("Generate a video from a prompt").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").action(async(e,t)=>{try{let n={prompt:e};t.aspectRatio&&(n.aspect_ratio=t.aspectRatio),t.duration&&(n.duration=Number(t.duration)),await Vn({kind:"Video generation",toolId:t.tool??"generate_video_tempo_card",params:n,prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});jn.command("music <prompt>").description("Generate music from a prompt").option("--tool <tool>","Exact tool id override").option("--instrumental","Generate instrumental music").option("--model <model>","Suno model, when supported","V4").action(async(e,t)=>{try{await Vn({kind:"Music generation",toolId:t.tool??"generate_music_tempo_card",params:{prompt:e,instrumental:!!t.instrumental,model:t.model??"V4"},prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});jn.command("speech <text>").description("Generate speech from text").option("--tool <tool>","Exact tool id override").option("--ref-audio-url <url>","Reference audio URL for voice cloning").option("--ref-text <text>","Transcription of reference audio").option("--remove-silence","Remove silence from generated speech").action(async(e,t)=>{try{let n={gen_text:e};t.refAudioUrl&&(n.ref_audio_url=t.refAudioUrl),t.refText&&(n.ref_text=t.refText),t.removeSilence&&(n.remove_silence=!0),await Vn({kind:"Speech generation",toolId:t.tool??"generate_speech_card",params:n,prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});jn.command("3d <prompt>").alias("model").description("Generate a 3D model from a prompt").option("--tool <tool>","Exact tool id override").option("--style <style>","Style prompt for the generated model").option("--negative <prompt>","Negative prompt").option("--art-style <style>","Art style, when supported by the selected tool").action(async(e,t)=>{try{let n={object_prompt:e};t.style&&(n.style_prompt=t.style),t.negative&&(n.negative_prompt=t.negative),t.artStyle&&(n.art_style=t.artStyle),await Vn({kind:"3D generation",toolId:t.tool??"generate_3d_card",params:n,prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});q.command("uninstall [client]").description("Remove MCP server from an AI client").option("--all","Remove from all clients").option("--scope <scope>","Uninstall scope: global or project","global").action(async(e,t)=>{try{let n=t.scope==="project"?"project":"global";if(t.all){let o=[];for(let i of Re)yo(i,n).removed&&o.push(i.displayName);o.length>0?console.log(`Removed visa-cli from: ${o.join(", ")}.`):console.log("visa-cli was not installed in any client.");return}e||(console.error("Usage: visa-cli uninstall <client>"),console.error(" visa-cli uninstall --all"),console.error(`
237
- Supported clients: ${Re.map(o=>o.id).join(", ")}`),process.exit(1));let r=po(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${Re.map(o=>o.id).join(", ")}`),process.exit(1));let s=yo(r,n);s.removed?console.log(`Removed visa-cli from ${s.configPath}`):console.log(`visa-cli was not installed for ${r.displayName}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});q.hook("postAction",()=>{if(Dn){Dn=!1;return}Kr&&Qa(Kr.lastSignals)});mf(["setup","install","status","tokens","balance","merchants","generate","config","feedback","update","uninstall"]);wc(q);q.parseAsync().catch(async e=>{console.error("Error:",e instanceof Error?e.message:String(e));let{reportFatal:t}=await Promise.resolve().then(()=>(Hr(),Br));await t(e)});process.on("uncaughtException",async e=>{console.error("Uncaught exception:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(Hr(),Br));await t(e)});process.on("unhandledRejection",async e=>{console.error("Unhandled rejection:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(Hr(),Br));await t(e)});
240
+ `);let t=await Pc(e.toolId,e.params,`visa-cli generate ${e.kind.toLowerCase()}: ${e.prompt}`);kc(t)}var Cf=(e,t)=>n=>(t.includes(n)||q.error(`error: option '${e}' accepts ${t.map(r=>`'${r}'`).join(", ")} (got '${n}')`,{exitCode:2}),n);jn.command("image <prompt>").description("Generate an image from a prompt").option("--quality <quality>","Image quality: standard or high",Cf("--quality",["standard","high"]),"standard").option("--fast","Use the fast image tool").option("--tool <tool>","Exact tool id override").action(async(e,t)=>{try{let n=t.tool??(t.fast||t.quality!=="high"?"generate_image_fast_card":"generate_image_card");await Vn({kind:"Image generation",toolId:n,params:{prompt:e},prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});jn.command("video <prompt>").description("Generate a video from a prompt").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").action(async(e,t)=>{try{let n={prompt:e};t.aspectRatio&&(n.aspect_ratio=t.aspectRatio),t.duration&&(n.duration=Number(t.duration)),await Vn({kind:"Video generation",toolId:t.tool??"generate_video_tempo_card",params:n,prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});jn.command("music <prompt>").description("Generate music from a prompt").option("--tool <tool>","Exact tool id override").option("--instrumental","Generate instrumental music").option("--model <model>","Suno model, when supported","V4").action(async(e,t)=>{try{await Vn({kind:"Music generation",toolId:t.tool??"generate_music_tempo_card",params:{prompt:e,instrumental:!!t.instrumental,model:t.model??"V4"},prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});jn.command("speech <text>").description("Generate speech from text").option("--tool <tool>","Exact tool id override").option("--ref-audio-url <url>","Reference audio URL for voice cloning").option("--ref-text <text>","Transcription of reference audio").option("--remove-silence","Remove silence from generated speech").action(async(e,t)=>{try{let n={gen_text:e};t.refAudioUrl&&(n.ref_audio_url=t.refAudioUrl),t.refText&&(n.ref_text=t.refText),t.removeSilence&&(n.remove_silence=!0),await Vn({kind:"Speech generation",toolId:t.tool??"generate_speech_card",params:n,prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});jn.command("3d <prompt>").alias("model").description("Generate a 3D model from a prompt").option("--tool <tool>","Exact tool id override").option("--style <style>","Style prompt for the generated model").option("--negative <prompt>","Negative prompt").option("--art-style <style>","Art style, when supported by the selected tool").action(async(e,t)=>{try{let n={object_prompt:e};t.style&&(n.style_prompt=t.style),t.negative&&(n.negative_prompt=t.negative),t.artStyle&&(n.art_style=t.artStyle),await Vn({kind:"3D generation",toolId:t.tool??"generate_3d_card",params:n,prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});q.command("uninstall [client]").description("Remove MCP server from an AI client").option("--all","Remove from all clients").option("--scope <scope>","Uninstall scope: global or project","global").action(async(e,t)=>{try{let n=t.scope==="project"?"project":"global";if(t.all){let o=[];for(let i of Re)vo(i,n).removed&&o.push(i.displayName);o.length>0?console.log(`Removed visa-cli from: ${o.join(", ")}.`):console.log("visa-cli was not installed in any client.");return}e||(console.error("Usage: visa-cli uninstall <client>"),console.error(" visa-cli uninstall --all"),console.error(`
241
+ Supported clients: ${Re.map(o=>o.id).join(", ")}`),process.exit(1));let r=go(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${Re.map(o=>o.id).join(", ")}`),process.exit(1));let s=vo(r,n);s.removed?console.log(`Removed visa-cli from ${s.configPath}`):console.log(`visa-cli was not installed for ${r.displayName}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});q.hook("postAction",()=>{if(Dn){Dn=!1;return}Kr&&tc(Kr.lastSignals)});yf(["setup","install","status","cards","tokens","balance","merchants","generate","config","feedback","update","uninstall"]);Tc(q);q.parseAsync().catch(async e=>{console.error("Error:",e instanceof Error?e.message:String(e));let{reportFatal:t}=await Promise.resolve().then(()=>(Hr(),Br));await t(e)});process.on("uncaughtException",async e=>{console.error("Uncaught exception:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(Hr(),Br));await t(e)});process.on("unhandledRejection",async e=>{console.error("Unhandled rejection:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(Hr(),Br));await t(e)});