@visa/cli 2.3.0-rc.0 → 2.3.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,8 +1,8 @@
1
- "use strict";var Vu=Object.create;var wr=Object.defineProperty;var qu=Object.getOwnPropertyDescriptor;var Hu=Object.getOwnPropertyNames;var Bu=Object.getPrototypeOf,Ku=Object.prototype.hasOwnProperty;var Gu=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ni=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),No=(e,t)=>{for(var n in t)wr(e,n,{get:t[n],enumerable:!0})},Di=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Hu(t))!Ku.call(e,o)&&o!==n&&wr(e,o,{get:()=>t[o],enumerable:!(r=qu(t,o))||r.enumerable});return e};var E=(e,t,n)=>(n=e!=null?Vu(Bu(e)):{},Di(t||!e||!e.__esModule?wr(n,"default",{value:e,enumerable:!0}):n,e)),zu=e=>Di(wr({},"__esModule",{value:!0}),e);var Er=Ni((By,id)=>{id.exports={name:"@visa/cli",version:"2.3.0-rc.0",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{"sync:server-json":"node scripts/sync-server-json.mjs","check:server-json":"node scripts/sync-server-json.mjs --check",prebuild:"node scripts/sync-server-json.mjs && pnpm --filter @visa/money build && pnpm --filter @visa-cli/tools build",build:"tsc --noEmit && node esbuild.config.js",prepack:"node scripts/sync-server-json.mjs --check",dev:"tsc --watch",pretest:"pnpm build",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0",commander:"^12.1.0",zod:"^3.23.0"},devDependencies:{"@visa/money":"workspace:*","@visa/observability":"workspace:*","@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.31.0","@types/jest":"^30.0.0","@types/node":"^25.9.0","@typescript-eslint/eslint-plugin":"^8.59.4","@typescript-eslint/parser":"^8.59.4","@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.4.10",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","server.json","README.md","LICENSE"]}});var lr=Ni(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.micros=Rf;te.fromCents=If;te.fromUsdc=$f;te.fromUsd=Pf;te.toCents=Mf;te.toCentsForAcquirer=Of;te.toUsdc=Nf;te.toWire=Df;te.fromWire=Lf;te.toDisplay=Uf;te.toUsdRounded2dp=jf;te.add=Ff;te.sub=Vf;te.clampNonNegative=qf;te.isNonNegative=Hf;te.max=Bf;te.min=Kf;var ot=10000n,al=1000000n;function Rf(e){return e}function If(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*ot}function $f(e){return e}function Pf(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function Mf(e){if(e>=0n)return Number(e/ot);let t=e/ot,n=e%ot;return Number(n===0n?t:t-1n)}function Of(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/ot)}function Nf(e){return e}function Df(e){return e.toString()}function Lf(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 Uf(e,t={}){let n=t.decimals??2,r=t.symbol??"$",o=e<0n,s=o?-e:e,i=s/al,a=s%al,l=o?"-":"";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 jf(e){let t=e<0n,n=t?-e:e,r=n/ot,s=n%ot*2n,i;s<ot?i=r:s>ot?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function Ff(e,t){return e+t}function Vf(e,t){return e-t}function qf(e){return e<0n?0n:e}function Hf(e){return e>=0n}function Bf(e,t){return e>t?e:t}function Kf(e,t){return e<t?e:t}});var Ao={};No(Ao,{initSentry:()=>Qh,isSentryConfigured:()=>Xh,reportFatal:()=>ey});function Xh(){return!1}async function Qh(){return null}async function ey(e,t){process.exit(t?.exitCode??1)}var Ro=Gu(()=>{});var Ly={};No(Ly,{printGroupHelpAndExit:()=>Ne});module.exports=zu(Ly);var hu=require("commander"),$o=E(require("crypto")),z=E(require("fs")),F=E(require("os")),oe=E(require("path")),yu=require("child_process"),_u=E(require("node:readline/promises")),vu=require("util");var kr=require("child_process"),Gi=require("util"),mt=E(require("fs")),Tr=E(require("os")),Vo=E(require("path"));var Fi=E(require("crypto"));var Ye="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";var Vi="VISA_ALLOW_INSECURE_MOCKS",Li,Ui,ji;function Do(e){return`${e}-${Fi.randomBytes(24).toString("base64url")}`}function qi(e=process.env){return e.NODE_ENV==="test"||e[Vi]==="true"}function ut(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&qi(e)}function pn(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&qi(e)}function Lo(){return`Set ${Vi}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function Hi(){return Li??=Do("mock-session"),Li}function Bi(e=process.env){return e.NODE_ENV==="test"?Ye:(Ui??=Do("mock-rc"),Ui)}function Ki(){return ji??=Do("mock-signature"),ji}var De=(0,Gi.promisify)(kr.execFile),qo=Vo.join(Tr.homedir(),".visa-mcp"),jn=Vo.join(qo,"session-token"),ke="visa-cli",dt="session-token",xr="rc-access",Wu=5e3,Cr=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function Ju(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
2
- `)}function zi(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=Ju(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function Yu(){try{let{stdout:e}=await De("security",["find-generic-password","-s",ke,"-a",dt,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(zi(e))throw new Cr("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 Zu(e){try{try{await De("security",["delete-generic-password","-s",ke,"-a",dt],{timeout:5e3})}catch{}return await De("security",["add-generic-password","-s",ke,"-a",dt,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function Xu(){try{await De("security",["delete-generic-password","-s",ke,"-a",dt],{timeout:5e3})}catch{}}async function Qu(){if(!Ho())return null;try{let{stdout:e}=await De("secret-tool",["lookup","service",ke,"account",dt],{timeout:5e3});return e.trim()||null}catch{return null}}async function ed(e){if(!Ho())return!1;try{let t=(0,kr.execFile)("secret-tool",["store","--label",`${ke} ${dt}`,"service",ke,"account",dt]);return t.stdin?(t.stdin.write(e),t.stdin.end(),await Promise.race([new Promise((n,r)=>{t.on("exit",o=>o===0?n():r(new Error(`secret-tool exited ${o}`))),t.on("error",r)}),new Promise((n,r)=>setTimeout(()=>{t.kill(),r(new Error("secret-tool timed out"))},Wu))]),!0):!1}catch{return!1}}async function td(){if(Ho())try{await De("secret-tool",["clear","service",ke,"account",dt],{timeout:5e3})}catch{}}function Ho(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function nd(){try{let{stdout:e}=await De("security",["find-generic-password","-s",ke,"-a",xr,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function rd(e){try{try{await De("security",["delete-generic-password","-s",ke,"-a",xr],{timeout:5e3})}catch{}await De("security",["add-generic-password","-s",ke,"-a",xr,"-w",e],{timeout:5e3})}catch{}}async function od(){try{await De("security",["delete-generic-password","-s",ke,"-a",xr],{timeout:5e3})}catch{}}function jo(){try{return mt.readFileSync(jn,"utf-8").trim()||null}catch(e){if(zi(e))throw new Cr(`Unable to read Visa CLI credentials from ${jn}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function Wi(e){mt.mkdirSync(qo,{recursive:!0,mode:448}),mt.writeFileSync(jn,e,{mode:384}),process.platform==="win32"&&sd(jn)}function Fo(){try{mt.unlinkSync(jn)}catch{}}function sd(e){try{let t=Tr.userInfo().username;(0,kr.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 Uo(){switch(process.platform){case"darwin":return{get:Yu,store:Zu,delete:Xu};case"linux":return{get:Qu,store:ed,delete:td};default:return{get:async()=>jo(),store:async e=>{try{return Wi(e),!0}catch{return!1}},delete:async()=>Fo(),storesInSessionFile:!0}}}var U=class{static async getSessionToken(){if(ut())return Promise.resolve(Hi());let t=Uo(),n=await t.get();if(n)return n;let r=jo();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(ut())return;let n=Uo();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||Fo();return}await n.delete()}if(Wi(t),jo()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${qo} is writable.`))}static async getRcAccessToken(){return ut()?Bi():nd()}static async saveRcAccessToken(t){ut()||await rd(t)}static async deleteSessionToken(){if(ut())return;await Uo().delete(),Fo()}static async clearAll(){await this.deleteSessionToken(),await od()}};var Ar=E(require("crypto")),Rr=E(require("tty")),Ir=E(require("fs"));function ad(e){return/-rc\.|-beta\./.test(e)}function Bo(e){return Ar.createHash("sha256").update(e.trim()).digest("hex")}function Ji(e){return Ye==="SKIP"?!0:Ar.timingSafeEqual(Buffer.from(Bo(e)),Buffer.from(Ye))}function cd(){try{let e=Ir.openSync("/dev/tty","r+"),t=new Rr.ReadStream(e),n=new Rr.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{Ir.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 ld(e){return new Promise((t,n)=>{let r;try{r=cd()}catch(u){n(u);return}let{input:o,output:s,cleanupStreams:i}=r,a=()=>{o.off("data",c);try{o.setRawMode?.(!1)}catch{}i()};s.write(e),o.setRawMode?.(!0),o.resume(),o.setEncoding("utf8");let l="",c=u=>{u==="\r"||u===`
1
+ "use strict";var Ku=Object.create;var wr=Object.defineProperty;var Gu=Object.getOwnPropertyDescriptor;var zu=Object.getOwnPropertyNames;var Wu=Object.getPrototypeOf,Ju=Object.prototype.hasOwnProperty;var Yu=(e,t)=>()=>(e&&(t=e(e=0)),t);var Vi=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Fo=(e,t)=>{for(var n in t)wr(e,n,{get:t[n],enumerable:!0})},qi=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of zu(t))!Ju.call(e,o)&&o!==n&&wr(e,o,{get:()=>t[o],enumerable:!(r=Gu(t,o))||r.enumerable});return e};var E=(e,t,n)=>(n=e!=null?Ku(Wu(e)):{},qi(t||!e||!e.__esModule?wr(n,"default",{value:e,enumerable:!0}):n,e)),Zu=e=>qi(wr({},"__esModule",{value:!0}),e);var Er=Vi((Xy,ud)=>{ud.exports={name:"@visa/cli",version:"2.3.0-rc.1",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{"sync:server-json":"node scripts/sync-server-json.mjs","check:server-json":"node scripts/sync-server-json.mjs --check",prebuild:"node scripts/sync-server-json.mjs && pnpm --filter @visa/money build && pnpm --filter @visa-cli/tools build",build:"tsc --noEmit && node esbuild.config.js",prepack:"node scripts/sync-server-json.mjs --check",dev:"tsc --watch",pretest:"pnpm build",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0",commander:"^12.1.0",zod:"^3.23.0"},devDependencies:{"@visa/money":"workspace:*","@visa/observability":"workspace:*","@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.31.0","@types/jest":"^30.0.0","@types/node":"^25.9.0","@typescript-eslint/eslint-plugin":"^8.59.4","@typescript-eslint/parser":"^8.59.4","@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.4.10",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","server.json","README.md","LICENSE"]}});var lr=Vi(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.micros=Df;ne.fromCents=Uf;ne.fromUsdc=jf;ne.fromUsd=Ff;ne.toCents=Vf;ne.toCentsForAcquirer=qf;ne.toUsdc=Hf;ne.toWire=Bf;ne.fromWire=Kf;ne.toDisplay=Gf;ne.toUsdRounded2dp=zf;ne.add=Wf;ne.sub=Jf;ne.clampNonNegative=Yf;ne.isNonNegative=Zf;ne.max=Xf;ne.min=Qf;var st=10000n,dl=1000000n;function Df(e){return e}function Uf(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*st}function jf(e){return e}function Ff(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function Vf(e){if(e>=0n)return Number(e/st);let t=e/st,n=e%st;return Number(n===0n?t:t-1n)}function qf(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/st)}function Hf(e){return e}function Bf(e){return e.toString()}function Kf(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 Gf(e,t={}){let n=t.decimals??2,r=t.symbol??"$",o=e<0n,s=o?-e:e,i=s/dl,a=s%dl,l=o?"-":"";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 zf(e){let t=e<0n,n=t?-e:e,r=n/st,s=n%st*2n,i;s<st?i=r:s>st?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function Wf(e,t){return e+t}function Jf(e,t){return e-t}function Yf(e){return e<0n?0n:e}function Zf(e){return e>=0n}function Xf(e,t){return e>t?e:t}function Qf(e,t){return e<t?e:t}});var Mo={};Fo(Mo,{initSentry:()=>ay,isSentryConfigured:()=>iy,reportFatal:()=>cy});function iy(){return!1}async function ay(){return null}async function cy(e,t){process.exit(t?.exitCode??1)}var Oo=Yu(()=>{});var Ky={};Fo(Ky,{printGroupHelpAndExit:()=>Ne});module.exports=Zu(Ky);var bu=require("commander"),Lo=E(require("crypto")),z=E(require("fs")),D=E(require("os")),ee=E(require("path")),Su=require("child_process"),wu=E(require("node:readline/promises")),xu=require("util");var kr=require("child_process"),Xi=require("util"),pt=E(require("fs")),Tr=E(require("os")),Go=E(require("path"));var Gi=E(require("crypto"));var Ye="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";var zi="VISA_ALLOW_INSECURE_MOCKS",Hi,Bi,Ki;function Vo(e){return`${e}-${Gi.randomBytes(24).toString("base64url")}`}function Wi(e=process.env){return e.NODE_ENV==="test"||e[zi]==="true"}function dt(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&Wi(e)}function fn(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&Wi(e)}function qo(){return`Set ${zi}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function Ji(){return Hi??=Vo("mock-session"),Hi}function Yi(e=process.env){return e.NODE_ENV==="test"?Ye:(Bi??=Vo("mock-rc"),Bi)}function Zi(){return Ki??=Vo("mock-signature"),Ki}var Le=(0,Xi.promisify)(kr.execFile),zo=Go.join(Tr.homedir(),".visa-mcp"),jn=Go.join(zo,"session-token"),ke="visa-cli",mt="session-token",xr="rc-access",Xu=5e3,Cr=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function Qu(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
2
+ `)}function Qi(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=Qu(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function ed(){try{let{stdout:e}=await Le("security",["find-generic-password","-s",ke,"-a",mt,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(Qi(e))throw new Cr("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 td(e){try{try{await Le("security",["delete-generic-password","-s",ke,"-a",mt],{timeout:5e3})}catch{}return await Le("security",["add-generic-password","-s",ke,"-a",mt,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function nd(){try{await Le("security",["delete-generic-password","-s",ke,"-a",mt],{timeout:5e3})}catch{}}async function rd(){if(!Wo())return null;try{let{stdout:e}=await Le("secret-tool",["lookup","service",ke,"account",mt],{timeout:5e3});return e.trim()||null}catch{return null}}async function od(e){if(!Wo())return!1;try{let t=(0,kr.execFile)("secret-tool",["store","--label",`${ke} ${mt}`,"service",ke,"account",mt]);return t.stdin?(t.stdin.write(e),t.stdin.end(),await Promise.race([new Promise((n,r)=>{t.on("exit",o=>o===0?n():r(new Error(`secret-tool exited ${o}`))),t.on("error",r)}),new Promise((n,r)=>setTimeout(()=>{t.kill(),r(new Error("secret-tool timed out"))},Xu))]),!0):!1}catch{return!1}}async function sd(){if(Wo())try{await Le("secret-tool",["clear","service",ke,"account",mt],{timeout:5e3})}catch{}}function Wo(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function id(){try{let{stdout:e}=await Le("security",["find-generic-password","-s",ke,"-a",xr,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function ad(e){try{try{await Le("security",["delete-generic-password","-s",ke,"-a",xr],{timeout:5e3})}catch{}await Le("security",["add-generic-password","-s",ke,"-a",xr,"-w",e],{timeout:5e3})}catch{}}async function cd(){try{await Le("security",["delete-generic-password","-s",ke,"-a",xr],{timeout:5e3})}catch{}}function Bo(){try{return pt.readFileSync(jn,"utf-8").trim()||null}catch(e){if(Qi(e))throw new Cr(`Unable to read Visa CLI credentials from ${jn}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function ea(e){pt.mkdirSync(zo,{recursive:!0,mode:448}),pt.writeFileSync(jn,e,{mode:384}),process.platform==="win32"&&ld(jn)}function Ko(){try{pt.unlinkSync(jn)}catch{}}function ld(e){try{let t=Tr.userInfo().username;(0,kr.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 Ho(){switch(process.platform){case"darwin":return{get:ed,store:td,delete:nd};case"linux":return{get:rd,store:od,delete:sd};default:return{get:async()=>Bo(),store:async e=>{try{return ea(e),!0}catch{return!1}},delete:async()=>Ko(),storesInSessionFile:!0}}}var j=class{static async getSessionToken(){if(dt())return Promise.resolve(Ji());let t=Ho(),n=await t.get();if(n)return n;let r=Bo();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(dt())return;let n=Ho();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||Ko();return}await n.delete()}if(ea(t),Bo()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${zo} is writable.`))}static async getRcAccessToken(){return dt()?Yi():id()}static async saveRcAccessToken(t){dt()||await ad(t)}static async deleteSessionToken(){if(dt())return;await Ho().delete(),Ko()}static async clearAll(){await this.deleteSessionToken(),await cd()}};var Ar=E(require("crypto")),Rr=E(require("tty")),Ir=E(require("fs"));function dd(e){return/-rc\.|-beta\./.test(e)}function Jo(e){return Ar.createHash("sha256").update(e.trim()).digest("hex")}function ta(e){return Ye==="SKIP"?!0:Ar.timingSafeEqual(Buffer.from(Jo(e)),Buffer.from(Ye))}function md(){try{let e=Ir.openSync("/dev/tty","r+"),t=new Rr.ReadStream(e),n=new Rr.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{Ir.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 pd(e){return new Promise((t,n)=>{let r;try{r=md()}catch(u){n(u);return}let{input:o,output:s,cleanupStreams:i}=r,a=()=>{o.off("data",c);try{o.setRawMode?.(!1)}catch{}i()};s.write(e),o.setRawMode?.(!0),o.resume(),o.setEncoding("utf8");let l="",c=u=>{u==="\r"||u===`
3
3
  `?(s.write(`
4
4
  `),a(),t(l)):u===""?(s.write(`
5
- `),a(),n(new Error("Cancelled"))):u==="\x7F"||u==="\b"?l.length>0&&(l=l.slice(0,-1),s.write("\b \b")):(l+=u,s.write("\u2022"))};o.on("data",c)})}var ud=`
5
+ `),a(),n(new Error("Cancelled"))):u==="\x7F"||u==="\b"?l.length>0&&(l=l.slice(0,-1),s.write("\b \b")):(l+=u,s.write("\u2022"))};o.on("data",c)})}var fd=`
6
6
  \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
7
7
  \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557
8
8
  \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551
@@ -11,25 +11,25 @@
11
11
  \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D
12
12
 
13
13
  This is a Release Candidate build. Access is restricted to Visa employees.
14
- `;async function Yi(e={}){let t=e.version??Er().version;if(!ad(t))return;let n=process.env.VISA_RC_CODE;if(n&&Ji(n)){await U.saveRcAccessToken(Bo(n));return}if(e.isMcp??!1){let i=await U.getRcAccessToken();if(i&&(Ye==="SKIP"||i===Ye))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
15
- `),process.exit(1)}let o=await U.getRcAccessToken();if(o&&(Ye==="SKIP"||o===Ye))return;console.log(ud);let s=3;for(let i=1;i<=s;i++){let a;try{a=await ld(" Enter RC access code: ")}catch{process.exit(1)}if(Ji(a)){await U.saveRcAccessToken(Bo(a)),console.log(`
14
+ `;async function na(e={}){let t=e.version??Er().version;if(!dd(t))return;let n=process.env.VISA_RC_CODE;if(n&&ta(n)){await j.saveRcAccessToken(Jo(n));return}if(e.isMcp??!1){let i=await j.getRcAccessToken();if(i&&(Ye==="SKIP"||i===Ye))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
15
+ `),process.exit(1)}let o=await j.getRcAccessToken();if(o&&(Ye==="SKIP"||o===Ye))return;console.log(fd);let s=3;for(let i=1;i<=s;i++){let a;try{a=await pd(" Enter RC access code: ")}catch{process.exit(1)}if(ta(a)){await j.saveRcAccessToken(Jo(a)),console.log(`
16
16
  Access granted. Welcome.
17
17
  `);return}i<s&&console.log(`
18
18
  Invalid code. ${s-i} attempt(s) remaining.
19
19
  `)}console.log(`
20
20
  Invalid code. Contact your team lead.
21
- `),process.exit(1)}var $r=E(require("fs")),Zi=E(require("os")),Ko=E(require("path")),dd=[{prefix:"iVBORw0KGgo",sig:{mime:"image/png",ext:"png"}},{prefix:"/9j/",sig:{mime:"image/jpeg",ext:"jpg"}},{prefix:"R0lGOD",sig:{mime:"image/gif",ext:"gif"}},{prefix:"UklGR",sig:{mime:"image/webp",ext:"webp"}}],md=/^data:(image\/(png|jpeg|jpg|gif|webp));base64,([A-Za-z0-9+/=]+)$/;function Go(e){if(typeof e!="string"||e.length===0)return null;let t=e.trim(),n=md.exec(t);if(n){let o=n[2]==="jpg"?"jpeg":n[2],s=o==="png"?{mime:"image/png",ext:"png"}:o==="jpeg"?{mime:"image/jpeg",ext:"jpg"}:o==="gif"?{mime:"image/gif",ext:"gif"}:{mime:"image/webp",ext:"webp"};return{base64:n[3],sig:s}}if(!/^[A-Za-z0-9+/=\s]+$/.test(t)||t.length<64)return null;let r=t.replace(/\s+/g,"");for(let{prefix:o,sig:s}of dd)if(r.startsWith(o))return{base64:r,sig:s};return null}function zo(e,t={}){let n=t.outputDir??Ko.join(Zi.tmpdir(),"visa-cli");$r.mkdirSync(n,{recursive:!0});let r=(t.tag??"media").toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"media",o=new Date().toISOString().replace(/[:.]/g,"-"),s=Ko.join(n,`${r}-${o}.${e.sig.ext}`),i=Buffer.from(e.base64,"base64");return $r.writeFileSync(s,i,{mode:384}),{filePath:s,bytes:i.length,mime:e.sig.mime}}function pd(e,t={}){let n={success:!0,command:e,ts:new Date().toISOString()};for(let[r,o]of Object.entries(t))o!==void 0&&(n[r]=o);return n}function Fn(e,t,n={}){let r={success:!1,command:e,ts:new Date().toISOString(),error:t};for(let[o,s]of Object.entries(n))s!==void 0&&(r[o]=s);return r}function Wo(e,t){if(!t||typeof t!="object")return Fn(e,"No result payload from tool");let n=t;if(n.success===!1)return Fn(e,typeof n.error=="string"?n.error:"Tool execution failed",{error_code:typeof n.error_code=="string"?n.error_code:typeof n.code=="string"?n.code:void 0,transactionId:typeof n.transactionId=="string"?n.transactionId:null});let r=Array.isArray(n.urls)?n.urls.filter(u=>typeof u=="string"):Array.isArray(n.receipt?.urls)?n.receipt.urls.filter(u=>typeof u=="string"):void 0,o=n.data&&typeof n.data=="object"?n.data:void 0,s=n.result&&typeof n.result=="object"?n.result:void 0,i=s&&Array.isArray(s.choices)?s.choices:void 0,a=i&&i[0]&&typeof i[0]=="object"?i[0]:void 0,l=a&&a.message&&typeof a.message=="object"?a.message:void 0,c;if(o&&typeof o.content=="string")c=o.content;else if(o&&typeof o.text=="string")c=o.text;else if(typeof n.content=="string")c=n.content;else if(typeof n.text=="string")c=n.text;else if(l&&typeof l.content=="string")c=l.content;else if(a&&typeof a.text=="string")c=a.text;else if(Array.isArray(n.content)&&n.content[0]&&typeof n.content[0]=="object"){let u=n.content[0].text;typeof u=="string"&&(c=u)}return pd(e,{transactionId:typeof n.transactionId=="string"?n.transactionId:void 0,amount:typeof n.amount=="number"?n.amount:void 0,currency:typeof n.currency=="string"?n.currency:void 0,merchantName:typeof n.merchantName=="string"?n.merchantName:void 0,toolId:typeof n.toolId=="string"?n.toolId:typeof n.tool_id=="string"?n.tool_id:void 0,urls:r,text:c})}var Jo=require("process");async function Yo(){let e="";Jo.stdin.setEncoding("utf8");for await(let t of Jo.stdin)e+=t;return e.endsWith(`
22
- `)?e.slice(0,-1):e}async function Ot(e,t){if(e==="-"||t.stdin===!0&&!e){let o=(await Yo()).trim();if(!o)throw new Error("stdin was empty \u2014 pipe a prompt or pass it as the positional argument");return o}if(e&&e.length>0)return e;throw new Error("prompt required (positional arg, `-`, or --stdin)")}function Zo(e,t){if(!(t?.isTty??!!process.stdout.isTTY)&&!e.yes)throw new Error("Non-TTY shell detected on a paid command. Pass --yes to confirm you intend to charge the card from a pipe/script.")}var ta=E(require("fs")),Pr=E(require("path"));var pt=class extends Error{constructor(t){super(t),this.name="FromStdinFieldError"}},Xi=new Set;function fd(e){Xi.add(e)}function Qi(e){return Xi.has(e)}function ea(e,t){if(!t.startsWith("."))throw new pt(`--from-stdin path must start with "." (got: "${t}")`);let n=gd(t),r=e;for(let s of n){if(r==null)throw new pt(`--from-stdin path "${t}" failed: hit ${r===null?"null":"undefined"} at segment "${s}"`);if(typeof r!="object")throw new pt(`--from-stdin path "${t}" failed: cannot descend into primitive at segment "${s}"`);if(typeof s=="number"){if(!Array.isArray(r))throw new pt(`--from-stdin path "${t}" failed: expected array at segment [${s}], got object`);r=r[s]}else r=r[s]}if(r==null)throw new pt(`--from-stdin path "${t}" resolved to ${r===null?"null":"undefined"}`);if(typeof r=="object")throw new pt(`--from-stdin path "${t}" resolved to ${Array.isArray(r)?"an array":"an object"} \u2014 refusing to coerce non-primitive to flag value`);let o=String(r);return fd(o),o}function gd(e){let t=e.slice(1),n=[];for(let r of t.split(".")){if(!r)continue;let o=/^([^[\]]+)|\[(\d+)\]/g,s;for(;(s=o.exec(r))!==null;)s[1]!==void 0?/^\d+$/.test(s[1])?n.push(Number(s[1])):n.push(s[1]):s[2]!==void 0&&n.push(Number(s[2]))}return n}var Xo=class extends Error{constructor(t){super(t),this.name="FileShorthandStdinSourceError"}};async function na(e){if(e===void 0)return;if(!e.startsWith("@"))return e;if(Qi(e))throw new Xo("Refusing to expand @file from a --from-stdin-sourced value: upstream JSON cannot be allowed to read arbitrary local files. If the file path is legitimate, pass it as an argv flag instead of routing it through --from-stdin.");let t=e.slice(1),n=t.startsWith("~")?Pr.join(process.env.HOME??"",t.slice(1)):Pr.resolve(process.cwd(),t),r=await ta.promises.readFile(n,"utf8");return r.endsWith(`
23
- `)?r.slice(0,-1):r}var Vn=require("process"),ft=["json","yaml","tsv","table"];function Mr(e){return ft.includes(e)}function qn(e,t){switch(t){case"json":Vn.stdout.write(JSON.stringify(e)+`
24
- `);return;case"yaml":Vn.stdout.write(hd(e)+`
25
- `);return;case"tsv":Vn.stdout.write(yd(e)+`
26
- `);return;case"table":Vn.stdout.write(_d(e)+`
27
- `);return}}function hd(e){let t=[];for(let[n,r]of Object.entries(e))if(r!==void 0)if(Array.isArray(r)){t.push(`${n}:`);for(let o of r)t.push(` - ${ra(o)}`)}else r!==null&&typeof r=="object"?t.push(`${n}: ${JSON.stringify(r)}`):t.push(`${n}: ${ra(r)}`);return t.join(`
28
- `)}function ra(e){if(e===null)return"null";if(typeof e=="boolean"||typeof e=="number")return String(e);let t=String(e);return t===""?'""':/^[-?:,\[\]{}#&*!|>'"%@`]/.test(t)||/:\s|\s#/.test(t)||/^\s|\s$/.test(t)?JSON.stringify(t):t}function yd(e){let t=[];for(let[n,r]of Object.entries(e)){if(r===void 0)continue;let o=Array.isArray(r)||r!==null&&typeof r=="object"?JSON.stringify(r):String(r);t.push(`${n} ${o}`)}return t.join(`
29
- `)}function _d(e){let t=[];for(let[r,o]of Object.entries(e)){if(o===void 0)continue;let s=Array.isArray(o)||o!==null&&typeof o=="object"?JSON.stringify(o):String(o);t.push([r,s])}let n=Math.max(...t.map(([r])=>r.length),1);return t.map(([r,o])=>`${r.padEnd(n)} ${o}`).join(`
30
- `)}var sa=require("child_process");function Qo(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 vd(e){let n=e.length+4;return[`\u250C${"\u2500".repeat(n)}\u2510`,`\u2502${" ".repeat(2)}${e}${" ".repeat(2)}\u2502`,`\u2514${"\u2500".repeat(n)}\u2518`].join(`
31
- `)}function Hn(e){if(typeof e!="string"||e.length===0)return null;let t;try{t=new URL(e)}catch{return null}return t.protocol!=="https:"&&t.protocol!=="http:"?null:t.toString()}function ia(e,t){let n=Hn(e);if(!n)return null;let r,o;try{r=new URL(n),o=new URL(t)}catch{return null}return r.origin===o.origin?n:null}function aa(e,t){return t==="darwin"?{cmd:"open",args:[e]}:t==="win32"?{cmd:"rundll32.exe",args:["url.dll,FileProtocolHandler",e]}:t==="linux"?{cmd:"xdg-open",args:[e]}:null}function ca(e,t=process.platform){let n=Hn(e);return n?aa(n,t):null}function oa(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function es(e,t={}){let n=t.log??(c=>console.log(c)),r=t.env??process.env,o=t.platform??process.platform,s=Hn(e),i=t.spawn??((c,u,d)=>{(0,sa.execFile)(c,u,g=>d(g))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let c of vd(s??e).split(`
32
- `))n(` ${c}`);if(n(""),!s){n(" (Auth URL is not a valid absolute http(s) URL \u2014 skipping browser auto-open.)"),n(" Open the URL above manually to continue."),n("");return}let a=Qo(r,o);if(a.headless){n(` (${a.reason} \u2014 skipping browser auto-open.)`),n(" Open the URL above on any device with a browser. The CLI will"),n(" continue waiting for you to complete sign-in."),n("");return}let l=aa(s,o);if(!l){n(` No known browser-open command for platform "${o}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(c=>{let u=d=>{d?oa(n,d):(n(" Opened browser. Waiting for you to sign in..."),n("")),c()};try{i(l.cmd,l.args,u)}catch(d){oa(n,d instanceof Error?d:new Error(String(d))),c()}})}function bd(e){return new Promise(t=>setTimeout(t,e))}function la(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 ua(e){return!Number.isFinite(e)||e===null||e<=0?1e3:Math.min(Math.max(Math.ceil(e),1e3),3e4)}async function Sd(e,t=Math.random()*250){let n=o=>Math.min(o+Math.max(0,Math.ceil(t)),3e4);if(!e||e.status!==429)return n(1e3);let r=la(e.headers?.get("Retry-After"));if(r!==null)return n(ua(r));if(typeof e.json=="function")try{let o=await e.json();return n(ua(la(o?.retryAfter)))}catch{return n(1e3)}return n(1e3)}async function gt(e,t){let n=await Sd(e);return t?.(n),await bd(n),n}var Ta=E(require("crypto")),Ea=require("child_process"),fe=E(require("fs")),Aa=E(require("os")),be=E(require("path"));var j=E(require("fs")),Dt=E(require("os")),V=E(require("path")),pa=require("child_process"),fa=require("crypto"),wd=2,Or="# >>> visa-cli shell hud v2 >>>",Nr="# <<< visa-cli shell hud v2 <<<",xd="# >>> visa-cli shell hud >>>",Cd="# <<< visa-cli shell hud <<<",ga=3e4,kd=6e4,Td="VISA | HUD not ready \u2014 run: visa-cli config hud doctor",Ed={currentVersion:"0.0.0"},Ad=15e3;function rs(){try{return V.join(is(),".visa-cli")}catch{return V.join(Dt.tmpdir(),".visa-cli")}}function ht(){return V.join(rs(),"shell-hud.json")}function Bn(){return V.join(rs(),"shell-hud.line")}function ha(){return V.join(rs(),"shell-hud.lock")}function hn(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 Kn(e){let t=is();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 ya(e,t){let n=t??is(),r=[{shell:"zsh",rcPath:V.join(n,".zshrc")},{shell:"bash",rcPath:V.join(n,".bashrc")},{shell:"bash",rcPath:V.join(n,".bash_profile")},{shell:"powershell",rcPath:V.join(n,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:V.join(n,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:V.join(n,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:V.join(n,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:V.join(n,".config","powershell","Microsoft.PowerShell_profile.ps1")}];if(!e)return r;let o=r.filter(i=>i.shell===e),s=r.filter(i=>i.shell!==e);return[...o,...s]}function Rd(e){let t="$HOME/.visa-cli/shell-hud.line",n=Kd(e),r=Gd(e);if(e==="zsh")return`${Or}
21
+ `),process.exit(1)}var $r=E(require("fs")),ra=E(require("os")),Yo=E(require("path")),gd=[{prefix:"iVBORw0KGgo",sig:{mime:"image/png",ext:"png"}},{prefix:"/9j/",sig:{mime:"image/jpeg",ext:"jpg"}},{prefix:"R0lGOD",sig:{mime:"image/gif",ext:"gif"}},{prefix:"UklGR",sig:{mime:"image/webp",ext:"webp"}}],hd=/^data:(image\/(png|jpeg|jpg|gif|webp));base64,([A-Za-z0-9+/=]+)$/;function Zo(e){if(typeof e!="string"||e.length===0)return null;let t=e.trim(),n=hd.exec(t);if(n){let o=n[2]==="jpg"?"jpeg":n[2],s=o==="png"?{mime:"image/png",ext:"png"}:o==="jpeg"?{mime:"image/jpeg",ext:"jpg"}:o==="gif"?{mime:"image/gif",ext:"gif"}:{mime:"image/webp",ext:"webp"};return{base64:n[3],sig:s}}if(!/^[A-Za-z0-9+/=\s]+$/.test(t)||t.length<64)return null;let r=t.replace(/\s+/g,"");for(let{prefix:o,sig:s}of gd)if(r.startsWith(o))return{base64:r,sig:s};return null}function Xo(e,t={}){let n=t.outputDir??Yo.join(ra.tmpdir(),"visa-cli");$r.mkdirSync(n,{recursive:!0});let r=(t.tag??"media").toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"media",o=new Date().toISOString().replace(/[:.]/g,"-"),s=Yo.join(n,`${r}-${o}.${e.sig.ext}`),i=Buffer.from(e.base64,"base64");return $r.writeFileSync(s,i,{mode:384}),{filePath:s,bytes:i.length,mime:e.sig.mime}}function yd(e,t={}){let n={success:!0,command:e,ts:new Date().toISOString()};for(let[r,o]of Object.entries(t))o!==void 0&&(n[r]=o);return n}function Fn(e,t,n={}){let r={success:!1,command:e,ts:new Date().toISOString(),error:t};for(let[o,s]of Object.entries(n))s!==void 0&&(r[o]=s);return r}function Qo(e,t){if(!t||typeof t!="object")return Fn(e,"No result payload from tool");let n=t;if(n.success===!1)return Fn(e,typeof n.error=="string"?n.error:"Tool execution failed",{error_code:typeof n.error_code=="string"?n.error_code:typeof n.code=="string"?n.code:void 0,transactionId:typeof n.transactionId=="string"?n.transactionId:null});let r=Array.isArray(n.urls)?n.urls.filter(u=>typeof u=="string"):Array.isArray(n.receipt?.urls)?n.receipt.urls.filter(u=>typeof u=="string"):void 0,o=n.data&&typeof n.data=="object"?n.data:void 0,s=n.result&&typeof n.result=="object"?n.result:void 0,i=s&&Array.isArray(s.choices)?s.choices:void 0,a=i&&i[0]&&typeof i[0]=="object"?i[0]:void 0,l=a&&a.message&&typeof a.message=="object"?a.message:void 0,c;if(o&&typeof o.content=="string")c=o.content;else if(o&&typeof o.text=="string")c=o.text;else if(typeof n.content=="string")c=n.content;else if(typeof n.text=="string")c=n.text;else if(l&&typeof l.content=="string")c=l.content;else if(a&&typeof a.text=="string")c=a.text;else if(Array.isArray(n.content)&&n.content[0]&&typeof n.content[0]=="object"){let u=n.content[0].text;typeof u=="string"&&(c=u)}return yd(e,{transactionId:typeof n.transactionId=="string"?n.transactionId:void 0,amount:typeof n.amount=="number"?n.amount:void 0,currency:typeof n.currency=="string"?n.currency:void 0,merchantName:typeof n.merchantName=="string"?n.merchantName:void 0,toolId:typeof n.toolId=="string"?n.toolId:typeof n.tool_id=="string"?n.tool_id:void 0,urls:r,text:c})}var es=require("process");async function ts(){let e="";es.stdin.setEncoding("utf8");for await(let t of es.stdin)e+=t;return e.endsWith(`
22
+ `)?e.slice(0,-1):e}async function Nt(e,t){if(e==="-"||t.stdin===!0&&!e){let o=(await ts()).trim();if(!o)throw new Error("stdin was empty \u2014 pipe a prompt or pass it as the positional argument");return o}if(e&&e.length>0)return e;throw new Error("prompt required (positional arg, `-`, or --stdin)")}function ns(e,t){if(!(t?.isTty??!!process.stdout.isTTY)&&!e.yes)throw new Error("Non-TTY shell detected on a paid command. Pass --yes to confirm you intend to charge the card from a pipe/script.")}var aa=E(require("fs")),Pr=E(require("path"));var ft=class extends Error{constructor(t){super(t),this.name="FromStdinFieldError"}},oa=new Set;function _d(e){oa.add(e)}function sa(e){return oa.has(e)}function ia(e,t){if(!t.startsWith("."))throw new ft(`--from-stdin path must start with "." (got: "${t}")`);let n=vd(t),r=e;for(let s of n){if(r==null)throw new ft(`--from-stdin path "${t}" failed: hit ${r===null?"null":"undefined"} at segment "${s}"`);if(typeof r!="object")throw new ft(`--from-stdin path "${t}" failed: cannot descend into primitive at segment "${s}"`);if(typeof s=="number"){if(!Array.isArray(r))throw new ft(`--from-stdin path "${t}" failed: expected array at segment [${s}], got object`);r=r[s]}else r=r[s]}if(r==null)throw new ft(`--from-stdin path "${t}" resolved to ${r===null?"null":"undefined"}`);if(typeof r=="object")throw new ft(`--from-stdin path "${t}" resolved to ${Array.isArray(r)?"an array":"an object"} \u2014 refusing to coerce non-primitive to flag value`);let o=String(r);return _d(o),o}function vd(e){let t=e.slice(1),n=[];for(let r of t.split(".")){if(!r)continue;let o=/^([^[\]]+)|\[(\d+)\]/g,s;for(;(s=o.exec(r))!==null;)s[1]!==void 0?/^\d+$/.test(s[1])?n.push(Number(s[1])):n.push(s[1]):s[2]!==void 0&&n.push(Number(s[2]))}return n}var rs=class extends Error{constructor(t){super(t),this.name="FileShorthandStdinSourceError"}};async function ca(e){if(e===void 0)return;if(!e.startsWith("@"))return e;if(sa(e))throw new rs("Refusing to expand @file from a --from-stdin-sourced value: upstream JSON cannot be allowed to read arbitrary local files. If the file path is legitimate, pass it as an argv flag instead of routing it through --from-stdin.");let t=e.slice(1),n=t.startsWith("~")?Pr.join(process.env.HOME??"",t.slice(1)):Pr.resolve(process.cwd(),t),r=await aa.promises.readFile(n,"utf8");return r.endsWith(`
23
+ `)?r.slice(0,-1):r}var Vn=require("process"),gt=["json","yaml","tsv","table"];function Mr(e){return gt.includes(e)}function qn(e,t){switch(t){case"json":Vn.stdout.write(JSON.stringify(e)+`
24
+ `);return;case"yaml":Vn.stdout.write(bd(e)+`
25
+ `);return;case"tsv":Vn.stdout.write(Sd(e)+`
26
+ `);return;case"table":Vn.stdout.write(wd(e)+`
27
+ `);return}}function bd(e){let t=[];for(let[n,r]of Object.entries(e))if(r!==void 0)if(Array.isArray(r)){t.push(`${n}:`);for(let o of r)t.push(` - ${la(o)}`)}else r!==null&&typeof r=="object"?t.push(`${n}: ${JSON.stringify(r)}`):t.push(`${n}: ${la(r)}`);return t.join(`
28
+ `)}function la(e){if(e===null)return"null";if(typeof e=="boolean"||typeof e=="number")return String(e);let t=String(e);return t===""?'""':/^[-?:,\[\]{}#&*!|>'"%@`]/.test(t)||/:\s|\s#/.test(t)||/^\s|\s$/.test(t)?JSON.stringify(t):t}function Sd(e){let t=[];for(let[n,r]of Object.entries(e)){if(r===void 0)continue;let o=Array.isArray(r)||r!==null&&typeof r=="object"?JSON.stringify(r):String(r);t.push(`${n} ${o}`)}return t.join(`
29
+ `)}function wd(e){let t=[];for(let[r,o]of Object.entries(e)){if(o===void 0)continue;let s=Array.isArray(o)||o!==null&&typeof o=="object"?JSON.stringify(o):String(o);t.push([r,s])}let n=Math.max(...t.map(([r])=>r.length),1);return t.map(([r,o])=>`${r.padEnd(n)} ${o}`).join(`
30
+ `)}var da=require("child_process");function os(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 xd(e){let n=e.length+4;return[`\u250C${"\u2500".repeat(n)}\u2510`,`\u2502${" ".repeat(2)}${e}${" ".repeat(2)}\u2502`,`\u2514${"\u2500".repeat(n)}\u2518`].join(`
31
+ `)}function Hn(e){if(typeof e!="string"||e.length===0)return null;let t;try{t=new URL(e)}catch{return null}return t.protocol!=="https:"&&t.protocol!=="http:"?null:t.toString()}function ma(e,t){let n=Hn(e);if(!n)return null;let r,o;try{r=new URL(n),o=new URL(t)}catch{return null}return r.origin===o.origin?n:null}function pa(e,t){return t==="darwin"?{cmd:"open",args:[e]}:t==="win32"?{cmd:"rundll32.exe",args:["url.dll,FileProtocolHandler",e]}:t==="linux"?{cmd:"xdg-open",args:[e]}:null}function fa(e,t=process.platform){let n=Hn(e);return n?pa(n,t):null}function ua(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function ss(e,t={}){let n=t.log??(c=>console.log(c)),r=t.env??process.env,o=t.platform??process.platform,s=Hn(e),i=t.spawn??((c,u,d)=>{(0,da.execFile)(c,u,f=>d(f))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let c of xd(s??e).split(`
32
+ `))n(` ${c}`);if(n(""),!s){n(" (Auth URL is not a valid absolute http(s) URL \u2014 skipping browser auto-open.)"),n(" Open the URL above manually to continue."),n("");return}let a=os(r,o);if(a.headless){n(` (${a.reason} \u2014 skipping browser auto-open.)`),n(" Open the URL above on any device with a browser. The CLI will"),n(" continue waiting for you to complete sign-in."),n("");return}let l=pa(s,o);if(!l){n(` No known browser-open command for platform "${o}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(c=>{let u=d=>{d?ua(n,d):(n(" Opened browser. Waiting for you to sign in..."),n("")),c()};try{i(l.cmd,l.args,u)}catch(d){ua(n,d instanceof Error?d:new Error(String(d))),c()}})}function Cd(e){return new Promise(t=>setTimeout(t,e))}function ga(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 ha(e){return!Number.isFinite(e)||e===null||e<=0?1e3:Math.min(Math.max(Math.ceil(e),1e3),3e4)}async function kd(e,t=Math.random()*250){let n=o=>Math.min(o+Math.max(0,Math.ceil(t)),3e4);if(!e||e.status!==429)return n(1e3);let r=ga(e.headers?.get("Retry-After"));if(r!==null)return n(ha(r));if(typeof e.json=="function")try{let o=await e.json();return n(ha(ga(o?.retryAfter)))}catch{return n(1e3)}return n(1e3)}async function ht(e,t){let n=await kd(e);return t?.(n),await Cd(n),n}var Pa=E(require("crypto")),Ma=require("child_process"),oe=E(require("fs")),Oa=E(require("os")),pe=E(require("path"));var F=E(require("fs")),Dt=E(require("os")),V=E(require("path")),va=require("child_process"),ba=require("crypto"),Td=2,Or="# >>> visa-cli shell hud v2 >>>",Nr="# <<< visa-cli shell hud v2 <<<",Ed="# >>> visa-cli shell hud >>>",Ad="# <<< visa-cli shell hud <<<",Sa=3e4,Rd=6e4,Id="VISA | HUD not ready \u2014 run: visa-cli config hud doctor",$d={currentVersion:"0.0.0"},Pd=15e3;function cs(){try{return V.join(ds(),".visa-cli")}catch{return V.join(Dt.tmpdir(),".visa-cli")}}function yt(){return V.join(cs(),"shell-hud.json")}function Bn(){return V.join(cs(),"shell-hud.line")}function wa(){return V.join(cs(),"shell-hud.lock")}function yn(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 Kn(e){let t=ds();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 xa(e,t){let n=t??ds(),r=[{shell:"zsh",rcPath:V.join(n,".zshrc")},{shell:"bash",rcPath:V.join(n,".bashrc")},{shell:"bash",rcPath:V.join(n,".bash_profile")},{shell:"powershell",rcPath:V.join(n,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:V.join(n,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:V.join(n,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:V.join(n,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:V.join(n,".config","powershell","Microsoft.PowerShell_profile.ps1")}];if(!e)return r;let o=r.filter(i=>i.shell===e),s=r.filter(i=>i.shell!==e);return[...o,...s]}function Md(e){let t="$HOME/.visa-cli/shell-hud.line",n=Jd(e),r=Yd(e);if(e==="zsh")return`${Or}
33
33
  _visa_cli_shell_hud_precmd() {
34
34
  setopt localoptions no_bg_nice
35
35
  if [[ -f "${t}" ]]; then
@@ -82,49 +82,50 @@ case ";$PROMPT_COMMAND;" in
82
82
  *";__visa_cli_shell_hud_precmd;"*) ;;
83
83
  *) PROMPT_COMMAND="__visa_cli_shell_hud_precmd\${PROMPT_COMMAND:+;$PROMPT_COMMAND}" ;;
84
84
  esac
85
- ${Nr}`}function Id(e){return e.includes("_visa_cli_shell_hud_precmd")||e.includes("visa-cli config shell-hud refresh")||e.includes("shell-hud.line")||e.includes("__visa_cli_original_prompt")||e.includes("function global:prompt")}function $d(e,t,n){let r=new RegExp(`(^|\\n)([ \\t]*${ma(t)}[ \\t]*\\r?\\n)([\\s\\S]*?)(\\r?\\n[ \\t]*${ma(n)}[ \\t]*)(?=\\r?\\n|$)(\\r?\\n)?`,"g");return e.replace(r,(o,s,i,a,l,c,u)=>{if(!Id(a))return o;let d=u>0?e[u-1]:"";return s===`
85
+ ${Nr}`}function Od(e){return e.includes("_visa_cli_shell_hud_precmd")||e.includes("visa-cli config shell-hud refresh")||e.includes("shell-hud.line")||e.includes("__visa_cli_original_prompt")||e.includes("function global:prompt")}function Nd(e,t,n){let r=new RegExp(`(^|\\n)([ \\t]*${_a(t)}[ \\t]*\\r?\\n)([\\s\\S]*?)(\\r?\\n[ \\t]*${_a(n)}[ \\t]*)(?=\\r?\\n|$)(\\r?\\n)?`,"g");return e.replace(r,(o,s,i,a,l,c,u)=>{if(!Od(a))return o;let d=u>0?e[u-1]:"";return s===`
86
86
  `&&d!==`
87
87
  `?`
88
- `:""})}function Gn(e){let t=e;for(let[n,r]of[[Or,Nr],[xd,Cd]])t=$d(t,n,r);return t.trimEnd()}function _a(e){return Gn(e)!==e.trimEnd()}function Pd(e,t){let n=Gn(e).trimEnd(),r=Rd(t);return n.length>0?`${n}
88
+ `:""})}function Gn(e){let t=e;for(let[n,r]of[[Or,Nr],[Ed,Ad]])t=Nd(t,n,r);return t.trimEnd()}function Ca(e){return Gn(e)!==e.trimEnd()}function Ld(e,t){let n=Gn(e).trimEnd(),r=Md(t);return n.length>0?`${n}
89
89
 
90
90
  ${r}
91
91
  `:`${r}
92
- `}function Dr(e=hn()){if(!e)return!1;try{let t=Kn(e),n=j.readFileSync(t,"utf-8");return _a(n)}catch{return!1}}function yn(e=Dt.homedir()){let t=[],n=Md(e);for(let r of n)try{if(!j.existsSync(r))continue;let o=j.readFileSync(r,"utf-8");_a(o)&&t.push(r)}catch{}return t}function Md(e){return ya(null,e).map(t=>t.rcPath)}function Lr(e=hn()){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=Kn(e);let n=j.existsSync(t)?j.readFileSync(t,"utf-8"):"",r=Pd(n,e),o=r!==n;return o&&gn(t,r),{installed:!0,changed:o,shell:e,rcPath:t,message:o?`Persistent shell HUD installed in ${t}. Open a new terminal to start seeing it. Disable it any time with: visa-cli config shell-hud disable`:`Persistent shell HUD already installed in ${t}. Disable it any time with: visa-cli config shell-hud disable`}}catch(n){return{installed:!1,changed:!1,shell:e,rcPath:t,message:`Failed to install persistent shell HUD in ${t}: ${ns(n)}`}}}function _t(e=hn(),t){let n=[],r=[],o=[];try{for(let s of ya(e,t))if(r.push(s.rcPath),!!j.existsSync(s.rcPath))try{let i=j.readFileSync(s.rcPath,"utf-8"),a=Gn(i);if(a===i.trimEnd())continue;gn(s.rcPath,a.length>0?`${a}
93
- `:""),n.push(s.rcPath)}catch(i){o.push(`${s.rcPath}: ${ns(i)}`)}return n.length>0?{removed:!0,shell:e,rcPath:n[0],rcPaths:n,message:o.length>0?`Removed persistent shell HUD from ${n.join(", ")}. Some rc files could not be updated: ${o.join("; ")}.`:`Removed persistent shell HUD from ${n.join(", ")}.`}:o.length>0?{removed:!1,shell:e,rcPath:r[0],rcPaths:r,message:`Failed to remove persistent shell HUD: ${o.join("; ")}`}:{removed:!0,shell:e,rcPath:r[0],rcPaths:r,message:"Persistent shell HUD was not installed in any supported shell rc file."}}catch(s){return{removed:!1,shell:e,message:`Failed to remove persistent shell HUD: ${ns(s)}`}}}function os(e,t){let n=t??Ed,r=n.currentVersion==="0.0.0"&&e.version?e.version:n.currentVersion,o=yt(r),s=` ${K("\u2502",H.dim)} `,i=va(n),a=Ud(n,i),l=n.updateCheckDisabled?"":i,c=Ld(o,l);if(!e.enrolled)return[c,K("setup needed",H.visaGold),a].filter(Boolean).join(s);let u=Hd(e),d=Dd(e),g=yt(Dt.hostname().split(".")[0]),p=[c,g?K(g,H.dim):"",K(u,H.visaGold),a].filter(Boolean).join(s),_=[d,Od(e)].filter(Boolean),h=_.length>0?_.join(s):"";return h?`${p}
94
- ${h}`:p}function Od(e){let t=` ${K("\u2502",H.dim)} `,n=[];if(typeof e.dailySpent=="number"&&Number.isFinite(e.dailySpent)){let r=Math.max(0,e.dailySpent);n.push(K(`spent today ${fn(r)}`,H.dim))}if(typeof e.apiKeyCount=="number"&&Number.isFinite(e.apiKeyCount)){let r=Math.max(0,Math.floor(e.apiKeyCount)),o=r===1?"api key":"api keys";n.push(K(`${r} ${o}`,H.dim))}if(e.lastService&&typeof e.lastService.toolName=="string"&&e.lastService.toolName.length>0){let r=yt(e.lastService.toolName),o=Nd(e.lastService.createdAt),s=K(o?`last ${r} ${o}`:`last ${r}`,H.dim);n.push(s)}return n.join(t)}function Nd(e){if(!e)return"";let t=Date.parse(e);if(!Number.isFinite(t))return"";let n=Date.now()-t;if(n<0)return"";let r=Math.floor(n/1e3);if(r<60)return`${r}s`;let o=Math.floor(r/60);if(o<60)return`${o}m`;let s=Math.floor(o/60);return s<24?`${s}h`:`${Math.floor(s/24)}d`}function Dd(e){let t=typeof e.balanceCents=="number"?e.balanceCents:typeof e.prepaidBalance?.cents=="number"?e.prepaidBalance.cents:null,n=e.activeSession;if(t===null)return K("balance unknown",H.dim);let r=t/100;if(n){let i=Math.max(0,n.capCents),a=Math.max(0,n.estimatedRemainingCents),l=Math.max(0,i-a),c=i>0?Math.max(0,Math.min(1,l/i)):0;return`${qd(c)} ${K(`${fn(a/100)} in session`,H.green)} ${K(`(${fn(l/100)}/${fn(i/100)} cap)`,H.dim)} ${K("\xB7",H.dim)} ${K(`${fn(r)} balance`,H.dim)}`}let o=10,s=`balance ${fn(r)}`;return t>=o?K(s,H.green):K(`${s} \u2014 top up via buy_credits`,H.visaGold)}function Ld(e,t){let n=e,r=`${K("VISA CLI",H.visaBlue)} ${K(`v${n}`,H.visaBlueSoft)}`;if(!t)return r;let o=t;return`${r} ${K("\u2B06 update",H.visaGold)} ${K(`v${o}`,H.visaGold)}`}function Ud(e,t){return t&&!e.updateCheckDisabled?K("run: visa-cli update",H.visaGold):t?null:jd(e)}function va(e){return e.latestVersion?yt(e.latestVersion):""}function jd(e){let t=va(e);return t?K(`update ready v${t}`,H.visaGold):null}function ba(){let e=zn();return!(!e||Date.now()-e.renderedAt>ga||e.cwd&&e.cwd!==process.cwd())}function Ur(){let e=zn(),t=Date.now();if(e&&t-e.renderedAt<=ga||(Vd(),e?.line))return da(e.line,e,t);try{let n=Bn();if(j.existsSync(n)){let r=j.readFileSync(n,"utf-8").trimEnd();if(r&&!jr(r))return r}}catch{}return Td}function da(e,t,n){let r=n-t.renderedAt,o=typeof t.refreshFailedAt=="number"&&t.refreshFailedAt>t.renderedAt,s=[];if(r>=kd&&s.push(`stale ${Fd(r)}`),o&&s.push("\u26A0 refresh failed"),s.length===0)return e;let i=` ${K("\xB7",H.dim)} ${K(s.join(" \xB7 "),H.visaGold)}`,a=e.split(`
92
+ `}function Lr(e=yn()){if(!e)return!1;try{let t=Kn(e),n=F.readFileSync(t,"utf-8");return Ca(n)}catch{return!1}}function Ut(e=Dt.homedir()){let t=[],n=Dd(e);for(let r of n)try{if(!F.existsSync(r))continue;let o=F.readFileSync(r,"utf-8");Ca(o)&&t.push(r)}catch{}return t}function Dd(e){return xa(null,e).map(t=>t.rcPath)}function Dr(e=yn()){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=Kn(e);let n=F.existsSync(t)?F.readFileSync(t,"utf-8"):"",r=Ld(n,e),o=r!==n;return o&&hn(t,r),{installed:!0,changed:o,shell:e,rcPath:t,message:o?`Persistent shell HUD installed in ${t}. Open a new terminal to start seeing it. Disable it any time with: visa-cli config shell-hud disable`:`Persistent shell HUD already installed in ${t}. Disable it any time with: visa-cli config shell-hud disable`}}catch(n){return{installed:!1,changed:!1,shell:e,rcPath:t,message:`Failed to install persistent shell HUD in ${t}: ${as(n)}`}}}function Ze(e=yn(),t){let n=[],r=[],o=[];try{for(let s of xa(e,t))if(r.push(s.rcPath),!!F.existsSync(s.rcPath))try{let i=F.readFileSync(s.rcPath,"utf-8"),a=Gn(i);if(a===i.trimEnd())continue;hn(s.rcPath,a.length>0?`${a}
93
+ `:""),n.push(s.rcPath)}catch(i){o.push(`${s.rcPath}: ${as(i)}`)}return n.length>0?{removed:!0,shell:e,rcPath:n[0],rcPaths:n,message:o.length>0?`Removed persistent shell HUD from ${n.join(", ")}. Some rc files could not be updated: ${o.join("; ")}.`:`Removed persistent shell HUD from ${n.join(", ")}.`}:o.length>0?{removed:!1,shell:e,rcPath:r[0],rcPaths:r,message:`Failed to remove persistent shell HUD: ${o.join("; ")}`}:{removed:!0,shell:e,rcPath:r[0],rcPaths:r,message:"Persistent shell HUD was not installed in any supported shell rc file."}}catch(s){return{removed:!1,shell:e,message:`Failed to remove persistent shell HUD: ${as(s)}`}}}function ls(e,t){let n=t??$d,r=n.currentVersion==="0.0.0"&&e.version?e.version:n.currentVersion,o=_t(r),s=` ${K("\u2502",H.dim)} `,i=ka(n),a=qd(n,i),l=n.updateCheckDisabled?"":i,c=Vd(o,l);if(!e.enrolled)return[c,K("setup needed",H.visaGold),a].filter(Boolean).join(s);let u=zd(e),d=Fd(e),f=_t(Dt.hostname().split(".")[0]),p=[c,f?K(f,H.dim):"",K(u,H.visaGold),a].filter(Boolean).join(s),_=[d,Ud(e)].filter(Boolean),h=_.length>0?_.join(s):"";return h?`${p}
94
+ ${h}`:p}function Ud(e){let t=` ${K("\u2502",H.dim)} `,n=[];if(typeof e.dailySpent=="number"&&Number.isFinite(e.dailySpent)){let r=Math.max(0,e.dailySpent);n.push(K(`spent today ${gn(r)}`,H.dim))}if(typeof e.apiKeyCount=="number"&&Number.isFinite(e.apiKeyCount)){let r=Math.max(0,Math.floor(e.apiKeyCount)),o=r===1?"api key":"api keys";n.push(K(`${r} ${o}`,H.dim))}if(e.lastService&&typeof e.lastService.toolName=="string"&&e.lastService.toolName.length>0){let r=_t(e.lastService.toolName),o=jd(e.lastService.createdAt),s=K(o?`last ${r} ${o}`:`last ${r}`,H.dim);n.push(s)}return n.join(t)}function jd(e){if(!e)return"";let t=Date.parse(e);if(!Number.isFinite(t))return"";let n=Date.now()-t;if(n<0)return"";let r=Math.floor(n/1e3);if(r<60)return`${r}s`;let o=Math.floor(r/60);if(o<60)return`${o}m`;let s=Math.floor(o/60);return s<24?`${s}h`:`${Math.floor(s/24)}d`}function Fd(e){let t=typeof e.balanceCents=="number"?e.balanceCents:typeof e.prepaidBalance?.cents=="number"?e.prepaidBalance.cents:null,n=e.activeSession;if(t===null)return K("balance unknown",H.dim);let r=t/100;if(n){let i=Math.max(0,n.capCents),a=Math.max(0,n.estimatedRemainingCents),l=Math.max(0,i-a),c=i>0?Math.max(0,Math.min(1,l/i)):0;return`${Gd(c)} ${K(`${gn(a/100)} in session`,H.green)} ${K(`(${gn(l/100)}/${gn(i/100)} cap)`,H.dim)} ${K("\xB7",H.dim)} ${K(`${gn(r)} balance`,H.dim)}`}let o=10,s=`balance ${gn(r)}`;return t>=o?K(s,H.green):K(`${s} \u2014 top up via buy_credits`,H.visaGold)}function Vd(e,t){let n=e,r=`${K("VISA CLI",H.visaBlue)} ${K(`v${n}`,H.visaBlueSoft)}`;if(!t)return r;let o=t;return`${r} ${K("\u2B06 update",H.visaGold)} ${K(`v${o}`,H.visaGold)}`}function qd(e,t){return t&&!e.updateCheckDisabled?K("run: visa-cli update",H.visaGold):t?null:Hd(e)}function ka(e){return e.latestVersion?_t(e.latestVersion):""}function Hd(e){let t=ka(e);return t?K(`update ready v${t}`,H.visaGold):null}function Ta(){let e=zn();return!(!e||Date.now()-e.renderedAt>Sa||e.cwd&&e.cwd!==process.cwd())}function Ur(){let e=zn(),t=Date.now();if(e&&t-e.renderedAt<=Sa||(Kd(),e?.line))return ya(e.line,e,t);try{let n=Bn();if(F.existsSync(n)){let r=F.readFileSync(n,"utf-8").trimEnd();if(r&&!jr(r))return r}}catch{}return Id}function ya(e,t,n){let r=n-t.renderedAt,o=typeof t.refreshFailedAt=="number"&&t.refreshFailedAt>t.renderedAt,s=[];if(r>=Rd&&s.push(`stale ${Bd(r)}`),o&&s.push("\u26A0 refresh failed"),s.length===0)return e;let i=` ${K("\xB7",H.dim)} ${K(s.join(" \xB7 "),H.visaGold)}`,a=e.split(`
95
95
  `);for(let l=a.length-1;l>=0;l--)if(a[l].length>0)return a[l]=`${a[l]}${i}`,a.join(`
96
- `);return`${e}${i}`}function Fd(e){if(e<0)return"0s";let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60);if(n<60)return`${n}m`;let r=Math.floor(n/60);return r<24?`${r}h`:`${Math.floor(r/24)}d`}function ss(e,t){try{let n=V.dirname(ht());j.mkdirSync(n,{recursive:!0});let r=e.split(`
97
- `).map(s=>yt(s)).filter(s=>s.length>0).join(`
98
- `),o={hudVersion:wd,renderedAt:Date.now(),line:r,cwd:process.cwd(),status:t};gn(ht(),JSON.stringify(o)+`
99
- `),gn(Bn(),r+`
100
- `)}catch{}}function Sa(e){try{let t=zn();if(!t)return;let n=Math.max(Date.now(),t.renderedAt+1),r={...t,refreshFailedAt:n,refreshErrorReason:yt(e).slice(0,200)};gn(ht(),JSON.stringify(r)+`
101
- `)}catch{}}function wa(){try{let e=zn();if(!e)return;let t={...e,renderedAt:0};gn(ht(),JSON.stringify(t)+`
102
- `)}catch{}}function Nt(){try{j.unlinkSync(ha())}catch{}}function zn(){let e=ht();if(!j.existsSync(e))return null;try{let t=JSON.parse(j.readFileSync(e,"utf-8"));return typeof t?.line=="string"&&jr(t.line)?null:t}catch{return null}}function jr(e){for(let t of e.split(`
103
- `)){let n=t.trim();if(n.length===0)continue;let r=n.replace(/\[[0-?]*[ -/]*[@-~]/g,"").trim();if(/^VISA\s*\|\s*loading\b/i.test(r)||/^VISA\s*\|\s*HUD\s+not\s+(ready|initialized)\b/i.test(r))return!0}return!1}function xa(){return zn()?.status??null}function Vd(){if(process.env.JEST_WORKER_ID)return;let e=ha();try{if(j.mkdirSync(V.dirname(e),{recursive:!0}),!zd(e))return;let t=process.argv[1]?V.resolve(process.argv[1]):"";if(!t){Nt();return}let n=(0,pa.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});n.once("error",Nt),n.unref()}catch{Nt()}}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," ").trim()}function qd(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),o="\u2591".repeat(10-n);return`${K(r||"",H.green)}${K(o||"",H.dim)}`}function fn(e){return`$${e.toFixed(2)}`}function Hd(e){let t=e.cards?.find(a=>a.isDefault)??e.cards?.[0];if(!t)return"card none";let n=typeof t.brand=="string"?t.brand:"card",r=typeof t.last4=="string"?t.last4:"????",o=yt(n.toUpperCase()),s=yt(r);return`${t.isDefault?"default":"active"} ${o} ****${s}`}function Bd(){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 ts=Bd(),H={reset:"\x1B[0m",visaBlue:ts?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:ts?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:ts?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function K(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${H.reset}`}function ma(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function is(){let e=Dt.homedir();if(!e||!V.isAbsolute(e))throw new Error("unable to determine a valid home directory");return V.resolve(e)}function Kd(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function Gd(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function zd(e){for(let t=0;t<2;t+=1){let n;try{return n=j.openSync(e,"wx"),j.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let o=j.statSync(e);if(Date.now()-o.mtimeMs<=Ad)return!1;j.unlinkSync(e)}catch{}}finally{n!==void 0&&j.closeSync(n)}}return!1}function ns(e){return e instanceof Error?e.message:"unknown file system error"}function gn(e,t){j.mkdirSync(V.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${(0,fa.randomBytes)(8).toString("hex")}.tmp`;try{j.writeFileSync(n,t),j.renameSync(n,e)}catch(r){try{j.unlinkSync(n)}catch{}throw r}}function Ra(e,t){fe.mkdirSync(be.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Ta.randomBytes(8).toString("hex")}.tmp`;try{fe.writeFileSync(n,JSON.stringify(t,null,2)+`
104
- `),fe.renameSync(n,e)}catch(r){try{fe.unlinkSync(n)}catch{}throw r}}function Ca(e){return`'${e.replace(/'/g,"'\\''")}'`}var as="# visa-cli-hud-v1";function Wd(e,t){if(!e&&!t&&Jd())return`visa-cli config statusline ${as}`;let n=e??process.execPath,r=t??process.argv[1]??"",o=r?be.resolve(r):"";return`${o?`${Ca(n)} ${Ca(o)} config statusline`:"visa-cli config statusline"} ${as}`}function Jd(){try{return(0,Ea.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function Lt(e){return typeof e!="string"?!1:e.includes(as)?!0:e.includes("visa-cli")&&e.includes("statusline")}function Ia(e){let t=be.dirname(be.resolve(e));return be.basename(t)===".claude"?be.dirname(t):Aa.homedir()}function cs(e,t){let n=be.relative(t,e);return!n.startsWith("..")&&!be.isAbsolute(n)?`~/${n}`:e}function Yd(e,t){let n=Ia(t),r=yn(n);if(r.length===0)return e;let o=r.map(s=>cs(s,n)).join(", ");return`${e}
105
- Note: a shell-prompt HUD block was detected in ${o}. If it is unintended, remove it with: visa-cli config hud disable shell`}function ls(e=process.env.VISA_HUD_KEEP_SHELL){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function ka(e,t){let n=Ia(t),r=yn(n);if(r.length===0)return e;let o=r.map(i=>cs(i,n)).join(", ");if(ls())return`${e}
106
- Note: a legacy shell-prompt HUD block was detected in ${o}. VISA_HUD_KEEP_SHELL set \u2014 leaving it in place. Remove it any time with: visa-cli config hud disable shell`;let s=_t(null,n);if(s.removed&&s.rcPaths&&s.rcPaths.length>0){let i=s.rcPaths.map(a=>cs(a,n)).join(", ");return`${e}
96
+ `);return`${e}${i}`}function Bd(e){if(e<0)return"0s";let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60);if(n<60)return`${n}m`;let r=Math.floor(n/60);return r<24?`${r}h`:`${Math.floor(r/24)}d`}function us(e,t){try{let n=V.dirname(yt());F.mkdirSync(n,{recursive:!0});let r=e.split(`
97
+ `).map(s=>_t(s)).filter(s=>s.length>0).join(`
98
+ `),o={hudVersion:Td,renderedAt:Date.now(),line:r,cwd:process.cwd(),status:t};hn(yt(),JSON.stringify(o)+`
99
+ `),hn(Bn(),r+`
100
+ `)}catch{}}function Ea(e){try{let t=zn();if(!t)return;let n=Math.max(Date.now(),t.renderedAt+1),r={...t,refreshFailedAt:n,refreshErrorReason:_t(e).slice(0,200)};hn(yt(),JSON.stringify(r)+`
101
+ `)}catch{}}function Aa(){try{let e=zn();if(!e)return;let t={...e,renderedAt:0};hn(yt(),JSON.stringify(t)+`
102
+ `)}catch{}}function Lt(){try{F.unlinkSync(wa())}catch{}}function zn(){let e=yt();if(!F.existsSync(e))return null;try{let t=JSON.parse(F.readFileSync(e,"utf-8"));return typeof t?.line=="string"&&jr(t.line)?null:t}catch{return null}}function jr(e){for(let t of e.split(`
103
+ `)){let n=t.trim();if(n.length===0)continue;let r=n.replace(/\[[0-?]*[ -/]*[@-~]/g,"").trim();if(/^VISA\s*\|\s*loading\b/i.test(r)||/^VISA\s*\|\s*HUD\s+not\s+(ready|initialized)\b/i.test(r))return!0}return!1}function Ra(){return zn()?.status??null}function Kd(){if(process.env.JEST_WORKER_ID)return;let e=wa();try{if(F.mkdirSync(V.dirname(e),{recursive:!0}),!Zd(e))return;let t=process.argv[1]?V.resolve(process.argv[1]):"";if(!t){Lt();return}let n=(0,va.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});n.once("error",Lt),n.unref()}catch{Lt()}}function _t(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 Gd(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),o="\u2591".repeat(10-n);return`${K(r||"",H.green)}${K(o||"",H.dim)}`}function gn(e){return`$${e.toFixed(2)}`}function zd(e){let t=e.cards?.find(a=>a.isDefault)??e.cards?.[0];if(!t)return"card none";let n=typeof t.brand=="string"?t.brand:"card",r=typeof t.last4=="string"?t.last4:"????",o=_t(n.toUpperCase()),s=_t(r);return`${t.isDefault?"default":"active"} ${o} ****${s}`}function Wd(){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 is=Wd(),H={reset:"\x1B[0m",visaBlue:is?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:is?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:is?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function K(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${H.reset}`}function _a(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ds(){let e=Dt.homedir();if(!e||!V.isAbsolute(e))throw new Error("unable to determine a valid home directory");return V.resolve(e)}function Jd(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function Yd(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function Zd(e){for(let t=0;t<2;t+=1){let n;try{return n=F.openSync(e,"wx"),F.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let o=F.statSync(e);if(Date.now()-o.mtimeMs<=Pd)return!1;F.unlinkSync(e)}catch{}}finally{n!==void 0&&F.closeSync(n)}}return!1}function as(e){return e instanceof Error?e.message:"unknown file system error"}function hn(e,t){F.mkdirSync(V.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${(0,ba.randomBytes)(8).toString("hex")}.tmp`;try{F.writeFileSync(n,t),F.renameSync(n,e)}catch(r){try{F.unlinkSync(n)}catch{}throw r}}var Xd=1440*60*1e3;function Vr(e,t){oe.mkdirSync(pe.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Pa.randomBytes(8).toString("hex")}.tmp`;try{oe.writeFileSync(n,JSON.stringify(t,null,2)+`
104
+ `),oe.renameSync(n,e)}catch(r){try{oe.unlinkSync(n)}catch{}throw r}}function Ia(e){return`'${e.replace(/'/g,"'\\''")}'`}var ps="# visa-cli-hud-v1";function qr(e,t){if(!e&&!t&&Qd())return`visa-cli config statusline ${ps}`;let n=e??process.execPath,r=t??process.argv[1]??"",o=r?pe.resolve(r):"";return`${o?`${Ia(n)} ${Ia(o)} config statusline`:"visa-cli config statusline"} ${ps}`}function Qd(){try{return(0,Ma.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function vt(e){return typeof e!="string"?!1:e.includes(ps)?!0:e.includes("visa-cli")&&e.includes("statusline")}function em(){return"2.3.0-rc.1"}function Hr(e){let t=pe.dirname(pe.resolve(e));return pe.basename(t)===".claude"?pe.dirname(t):Oa.homedir()}function Fr(e,t){let n=pe.relative(t,e);return!n.startsWith("..")&&!pe.isAbsolute(n)?`~/${n}`:e}function tm(e){return pe.join(Hr(e),".visa-cli","hud-self-heal.json")}function nm(e,t,n,r){try{if(!oe.existsSync(e))return!1;let o=JSON.parse(oe.readFileSync(e,"utf-8"));return o.version===t&&typeof o.checkedAt=="number"&&n-o.checkedAt<r}catch{return!1}}function ms(e,t,n){try{Vr(e,{version:t,checkedAt:n})}catch{}}function rm(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function fs(e,t={}){let n=t.now??Date.now(),r=t.version??em(),o=t.stampPath??tm(e),s=t.minIntervalMs??Xd,i=[],a=!1,l=!1;if(!t.force&&nm(o,r,n,s))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:i,skippedReason:"recently checked"};try{if(!oe.existsSync(e))return ms(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:l,messages:i};let c=JSON.parse(oe.readFileSync(e,"utf-8")),u=c.statusLine,d=u&&typeof u=="object"&&!Array.isArray(u)?u.command:"";if(!vt(d))return ms(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:l,messages:i};let f=(t.getCommand??qr)();if(d!==f&&(c.statusLine=rm(u,f),Vr(e,c),a=!0,i.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!Br()){let p=Hr(e);if(Ut(p).length>0){let h=Ze(null,p);if(h.removed&&h.rcPaths&&h.rcPaths.length>0){let S=h.rcPaths.map(I=>Fr(I,p)).join(", ");l=!0,i.push(`Cleaned legacy shell-prompt HUD block from ${S}.`)}}}return ms(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:l,messages:i}}catch(c){if(t.force){let u=c instanceof Error?c.message:"unknown error";try{process.stderr.write(`visa-cli: HUD self-heal skipped \u2014 ${u}. Run: visa-cli config hud doctor
105
+ `)}catch{}}return{checked:!0,statusLineRepaired:a,shellHudRemoved:l,messages:i}}}function om(e,t){let n=Hr(t),r=Ut(n);if(r.length===0)return e;let o=r.map(s=>Fr(s,n)).join(", ");return`${e}
106
+ Note: a shell-prompt HUD block was detected in ${o}. If it is unintended, remove it with: visa-cli config hud disable shell`}function Br(e=process.env.VISA_HUD_KEEP_SHELL){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function $a(e,t){let n=Hr(t),r=Ut(n);if(r.length===0)return e;let o=r.map(i=>Fr(i,n)).join(", ");if(Br())return`${e}
107
+ Note: a legacy shell-prompt HUD block was detected in ${o}. VISA_HUD_KEEP_SHELL set \u2014 leaving it in place. Remove it any time with: visa-cli config hud disable shell`;let s=Ze(null,n);if(s.removed&&s.rcPaths&&s.rcPaths.length>0){let i=s.rcPaths.map(a=>Fr(a,n)).join(", ");return`${e}
107
108
  Cleaned legacy shell-prompt HUD block from ${i} (was leaking output above every shell prompt). Set VISA_HUD_KEEP_SHELL=true to keep both surfaces (also accepts 1, yes, on).`}return`${e}
108
- Note: a legacy shell-prompt HUD block was detected in ${o} but could not be auto-removed (${s.message}). Remove it manually with: visa-cli config hud disable shell`}function Wn(e,t=Wd){let n={},r=!1;if(fe.existsSync(e)){r=!0;try{n=JSON.parse(fe.readFileSync(e,"utf-8"))}catch(o){return{installed:"malformed-json",message:`~/.claude/settings.json is not valid JSON (${o.message}). Fix the file manually, then run: visa-cli config hud enable claude`}}}if(n.statusLine){let o=typeof n.statusLine=="object"?n.statusLine.command:"";return Lt(o)?{installed:"already-visa",message:ka("Visa HUD already registered in ~/.claude/settings.json.",e)}:{installed:"other-hud-present",message:Yd("Another HUD is already configured (keeping it). To switch to Visa HUD, edit ~/.claude/settings.json \u2192 statusLine.command",e)}}try{return n.statusLine={type:"command",command:t()},Ra(e,n),{installed:"new",message:ka(`Visa HUD registered in ~/.claude/settings.json${r?"":" (new file)"}. Restart Claude Code to see it pinned below the input.`,e)}}catch(o){return{installed:"error",message:`Failed to write settings: ${o.message}. Enable manually later with: visa-cli config hud enable claude`}}}function us(e){if(!fe.existsSync(e))return{removed:!1,status:"missing-settings",message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(fe.readFileSync(e,"utf-8"))}catch(r){return{removed:!1,status:"malformed-json",message:`~/.claude/settings.json is not valid JSON: ${r.message}`}}if(!t.statusLine)return{removed:!1,status:"missing-statusline",message:"No statusLine configured."};let n=typeof t.statusLine=="object"?t.statusLine.command:"";if(!Lt(n))return{removed:!1,status:"foreign-statusline",message:"statusLine is owned by another tool \u2014 leaving it alone."};delete t.statusLine;try{Ra(e,t)}catch(r){return{removed:!1,status:"error",message:`Failed to write ~/.claude/settings.json: ${r.message}`}}return{removed:!0,status:"removed",message:"Visa HUD removed from ~/.claude/settings.json. Restart Claude Code to take effect."}}var Ze=E(require("fs")),Le=E(require("path")),Zd=1,Ut={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},Xd=["terminal","claude","claude-code","all"];function Vr(e){let t=e.toLowerCase();return Xd.includes(t)?t:null}var Qd=50,em=64*1024,$a=10,ds=80;function tm(){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 ms=tm(),x={reset:"\x1B[0m",visaBlue:ms?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:ms?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:ms?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function T(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${x.reset}`}function Pa(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function Da(e=process.stdin){return e.isTTY?null:new Promise(t=>{let n=[],r=!1,o=()=>{e.removeListener("data",i),e.removeListener("end",a),e.removeListener("error",l),clearTimeout(c)},s=u=>{r||(r=!0,o(),t(u))},i=u=>{n.push(typeof u=="string"?Buffer.from(u):u)},a=()=>{let u=Buffer.concat(n).toString("utf-8").trim();if(!u)return s(null);try{let d=JSON.parse(u);s(d&&typeof d=="object"?d:null)}catch{s(null)}},l=()=>s(null),c=setTimeout(()=>{n.length>0?a():s(null)},Qd);e.on("data",i),e.on("end",a),e.on("error",l)})}function Jn(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),o="\u2591".repeat(10-n);return`${T(r||"",x.visaBlueSoft)}${T(o||"",x.dim)}`}function Yn(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 nm(e){if(Ga(e))return om(e);let t=` ${T("\u2502",x.dim)} `,n=Fr(e)||"claude",r=e.cwd?Z(Le.basename(e.cwd)):"",o=qr(e.workspace),s=r||o,i=o&&o!==s?` ${T(`@${o}`,x.visaBlueSoft)}`:"",a=[T(`[${n}]`,x.visaBlueSoft)];s&&a.push(`${T(s,x.visaGold)}${i}`);let l=Z(e.git_branch??e.branch??"");l&&a.push(`${T("git:(",x.dim)}${T(l,x.visaBlueSoft)}${T(")",x.dim)}`);let c=a.join(t),u=Number(e.context_window?.context_window_size??0),d=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,g=e.context_window?.current_usage,p=[g?.input_tokens,g?.output_tokens,g?.cache_creation_input_tokens,g?.cache_read_input_tokens].filter(W=>typeof W=="number"&&Number.isFinite(W)),_=p.length>0?p.reduce((W,B)=>W+B,0):null,h=Number(e.context_window?.total_input_tokens??_??g?.input_tokens??0),S=d!==null?Math.max(0,Math.min(1,d/100)):u>0?Math.max(0,Math.min(1,h/u)):0,I=d!==null&&u>0?Math.round(S*u):h,$;if(u>0||d!==null){let W=`${String(Math.round(S*100)).padStart(2," ")}%`,B=u>0?` ${T(`(${Yn(I)}/${Yn(u)})`,x.dim)}`:"";$=`${T("Context",x.dim)} ${Jn(S)} ${T(W,x.green)}${B}`}else $=`${T("Context",x.dim)} ${T("-",x.dim)}`;let C=La(e.rate_limits),k=[$];C&&k.push(C);let q=k.join(t);return`${c}
109
- ${q}`}function rm(e){if(Ga(e))return null;let t=` ${T("\u2502",x.dim)} `,n=Fr(e)||"claude",r=e.cwd?Z(Le.basename(e.cwd)):"",o=qr(e.workspace),s=r||o,i=o&&o!==s?` ${T(`@${o}`,x.visaBlueSoft)}`:"",a=[T(`[${n}]`,x.visaBlueSoft)];s&&a.push(`${T(s,x.visaGold)}${i}`);let l=Z(e.git_branch??e.branch??"");l&&a.push(`${T("git:(",x.dim)}${T(l,x.visaBlueSoft)}${T(")",x.dim)}`);let 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,d=e.context_window?.current_usage,g=[d?.input_tokens,d?.output_tokens,d?.cache_creation_input_tokens,d?.cache_read_input_tokens].filter(k=>typeof k=="number"&&Number.isFinite(k)),p=g.length>0?g.reduce((k,q)=>k+q,0):null,_=Number(e.context_window?.total_input_tokens??p??d?.input_tokens??0),h=u!==null?Math.max(0,Math.min(1,u/100)):c>0?Math.max(0,Math.min(1,_/c)):0,S=u!==null&&c>0?Math.round(h*c):_,I;if(c>0||u!==null){let k=`${String(Math.round(h*100)).padStart(2," ")}%`,q=c>0?` ${T(`(${Yn(S)}/${Yn(c)})`,x.dim)}`:"";I=`${T("Context",x.dim)} ${Jn(h)} ${T(k,x.green)}${q}`}else I=`${T("Context",x.dim)} ${T("-",x.dim)}`;let $=La(e.rate_limits),C=[I];return $&&C.push($),{identity:a.join(t),metrics:C.join(t)}}function om(e){let t=` ${T("\u2502",x.dim)} `,n=za(e),r=n.model||"codex",o=[T(`[${r}]`,x.visaBlueSoft)];n.project&&o.push(T(n.project,x.visaGold)),n.gitBranch&&o.push(`${T("git",x.dim)} ${T(n.gitBranch,x.visaGold)}`);let s=o.join(t),i=[];if(typeof n.contextUsedPercent=="number"){let l=Math.max(0,Math.min(1,n.contextUsedPercent/100));i.push(`${T("Context",x.dim)} ${Jn(l)} ${T(`${Math.round(n.contextUsedPercent)}%`,x.green)}`)}else if(typeof n.contextRemainingPercent=="number"){let l=100-n.contextRemainingPercent,c=Math.max(0,Math.min(1,l/100));i.push(`${T("Context",x.dim)} ${Jn(c)} ${T(`${Math.round(l)}%`,x.green)}`)}typeof n.usedTokens=="number"&&i.push(`${T("Tokens",x.dim)} ${Yn(n.usedTokens)}`),n.status&&i.push(`${T("Status",x.dim)} ${T(n.status,x.visaBlueSoft)}`),n.threadTitle&&i.push(`${T("Thread",x.dim)} ${T(n.threadTitle,x.visaBlueSoft)}`);let a=i.length>0?i.join(t):`${T("Context",x.dim)} ${T("-",x.dim)}`;return`${s}
110
- ${a}`}function sm(e){if(typeof e!="number"||e<=0)return"";let n=(e>1e12?e:e*1e3)-Date.now();if(n<=0||n>=10080*60*1e3)return"";let r=Math.floor(n/6e4),o=Math.floor(r/60),s=r%60;return o>0?`${o}h ${s}m`:`${s}m`}function Ma(e,t){if(!e||typeof e.used_percentage!="number")return null;let n=Math.max(0,Math.min(100,e.used_percentage)),r=n/100,o=Jn(r),s=n>=90?"\x1B[38;5;196m":n>=70?x.visaGold:x.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=sm(e.resets_at),l=a?` ${T(`(${a} / ${t})`,x.dim)}`:` ${T(`(${t})`,x.dim)}`;return`${o} ${T(i,s)}${l}`}function La(e){if(!e)return null;let t=Ma(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?Ma(e.seven_day,"7d"):null;if(!t&&!r)return null;let o=` ${T("\u2502",x.dim)} `,s=[t,r].filter(Boolean);return`${T("Usage",x.dim)} ${s.join(o)}`}function Ua(e){let t;try{let n=Ze.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let o=Math.min(r,em),s=r-o;t=Ze.openSync(e,"r");let i=Buffer.alloc(o);Ze.readSync(t,i,0,o,s);let a=i.toString("utf-8");if(s>0){let l=Buffer.alloc(1);if(Ze.readSync(t,l,0,1,s-1),l[0]!==10){let c=a.indexOf(`
111
- `);c>=0&&(a=a.slice(c+1))}}return a}catch{return null}finally{if(t!==void 0)try{Ze.closeSync(t)}catch{}}}function im(e){if(!e||typeof e!="object")return;let t=e,n=["file_path","path","notebook_path","pattern","command","url"];for(let r of n){let o=t[r];if(typeof o=="string"&&o.length>0){if(r.endsWith("_path")||r==="path"){let s=Le.basename(Le.dirname(o)),i=Le.basename(o);return s&&s!=="."&&s!=="/"?`${s}/${i}`:i}return o}}}function am(e){let t=e.split(`
112
- `),n=[],r=new Set;for(let o=t.length-1;o>=0&&n.length<$a*3;o-=1){let s=t[o].trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{continue}if(!i||typeof i!="object")continue;let 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 d=u;if(d.type==="tool_result"&&typeof d.tool_use_id=="string")r.add(d.tool_use_id);else if(d.type==="tool_use"&&typeof d.name=="string"){let g=typeof d.id=="string"?d.id:"",p=g.length>0?!r.has(g):!1;n.push({name:d.name,target:im(d.input),running:p})}}}return n.reverse(),n.slice(Math.max(0,n.length-$a))}function cm(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 lm(e){let t=e.running?T("\u25D0",x.visaGold):T("\u2713",x.green),n=e.running?x.visaGold:x.visaBlueSoft,r=T(Z(e.name),n),o=e.target?Z(e.target):"",s=o?`${T(":",x.dim)} ${T(o,x.dim)}`:"",i=e.count>1?` ${T(`\xD7${e.count}`,x.dim)}`:"";return s?`${t} ${r}${s}${i}`:`${t} ${r}${i}`}function um(e){let t=` ${T("\u2502",x.dim)} `,n=Pa(t),r=e.slice();for(;r.length>0;){let l=r.join(t);if(Pa(l)<=ds)return l;r=r.slice(1)}if(e.length===0)return"";let o="\u2026",i=e[e.length-1].replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,""),a=i.length>ds-n-1?i.slice(0,ds-n-1)+o:i;return`${T(o,x.dim)}${t}${a}`}async function Oa(e){if(!e||typeof e!="string")return null;let t=Ua(e);if(!t)return null;let n;try{n=am(t)}catch{return null}if(n.length===0)return null;let o=cm(n).map(lm);return um(o)||null}async function ja(e,t,n){return(await Va(e,t,n)).join(`
113
- `)}function Fa(e,t,n){let r=!!t?.activeSession||e.includes("in session"),o=n?mm(n):!1;return{isActive:r||o,hasSession:r,hasToolActivity:o}}async function Va(e,t,n){let{isActive:r}=Fa(e,n,t?.transcript_path),o=e.split(`
114
- `).filter(a=>a.length>0),i=t&&!r?o.map(a=>T(ps(a),x.dim)):[...o];if(t){let a=rm(t);if(a){if(i.push(a.identity),t.transcript_path){let l=await Oa(t.transcript_path);l&&i.push(...l.split(`
115
- `))}i.push(a.metrics)}else{let l=nm(t);if(l&&i.push(...l.split(`
116
- `)),t.transcript_path){let c=await Oa(t.transcript_path);c&&i.push(...c.split(`
117
- `))}}}return i}var dm=["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 mm(e){let t=Ua(e);if(!t)return!1;let n=t.slice(-16384).toLowerCase();return dm.some(r=>n.includes(`"${r}"`))}async function qa(e,t,n){let r=await Va(e,t,n),o=r.join(`
118
- `),{isActive:s}=Fa(e,n,t?.transcript_path);return{schemaVersion:Zd,client:t?Ka(t):Ut.UNKNOWN,rendered:o,lines:r.map(ps),visa:{spendLine:ps(e),balanceCents:n?.balanceCents,balanceUsd:n?.amountUsd,sessionMode:n?.sessionMode,activeSession:n?.activeSession,isVisaActive:s},context:t?za(t):{}}}function Z(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 qr(e){if(typeof e=="string")return Z(Le.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 Z(t?Le.basename(t):e.name)}function Ha(e){return Z(e.app_name??e.appName??e.app??e.client)}function Fr(e){return Z(e.model?.display_name??e.model?.id??e.model_name??e.modelName)}function Ba(e){return Z(e.cwd??e.current_dir??e.project_root)}function Na(e){let t=Z(e.project);if(t)return t;let n=Ba(e);if(n)return Z(Le.basename(n));let r=qr(e.workspace);return r||""}function Re(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function Ka(e){let t=Ha(e).toLowerCase();return t.includes("codex")?Ut.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?Ut.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||Re(e.context_used)!==void 0?Ut.CODEX:Ut.UNKNOWN}function Ga(e){return Ka(e)===Ut.CODEX}function za(e){let t=Ha(e),n=Ba(e),r=qr(e.workspace),o=Re(e.context_used)??Re(e.context_window?.used_percentage??void 0),s=Re(e.context_remaining)??Re(e.context_window?.remaining_percentage??void 0);return{...t?{app:t}:{},...Fr(e)?{model:Fr(e)}:{},...Na(e)?{project:Na(e)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...Z(e.git_branch??e.branch)?{gitBranch:Z(e.git_branch??e.branch)}:{},...Z(e.status??e.run_state??e.runState)?{status:Z(e.status??e.run_state??e.runState)}:{},...Z(e.thread_title??e.threadTitle)?{threadTitle:Z(e.thread_title??e.threadTitle)}:{},...o!==void 0?{contextUsedPercent:o}:{},...s!==void 0?{contextRemainingPercent:s}:{},...Re(e.used_tokens)!==void 0?{usedTokens:Re(e.used_tokens)}:{},...Re(e.total_input_tokens)!==void 0?{totalInputTokens:Re(e.total_input_tokens)}:{},...Re(e.total_output_tokens)!==void 0?{totalOutputTokens:Re(e.total_output_tokens)}:{}}}function ps(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}var Ja=E(require("path"));function Wa(e){return e instanceof Error?e.message:String(e)}function fs(e,t){let n=[],r=[],o=e??"claude",s=Vr(o);if(o==="shell"||o==="prompt")try{let a=t.installShellHud();return a.installed?{ok:!0,messages:[a.message],errors:r}:{ok:!1,messages:n,errors:[a.message]}}catch(a){return{ok:!1,messages:n,errors:[`Failed to install shell HUD: ${Wa(a)}`]}}if(!s)return{ok:!1,messages:n,errors:[`Unknown HUD surface: ${o}`,"Supported: claude (default), shell, all"]};let i=!0;if(s==="claude"||s==="claude-code"||s==="all"){let a=Ja.join(t.homeDir,".claude","settings.json");try{let l=t.installVisaStatusLine(a);n.push(l.message),(l.installed==="error"||l.installed==="malformed-json")&&(i=!1)}catch(l){i=!1,r.push(`Failed to install Claude HUD: ${Wa(l)}`)}}return{ok:i,messages:n,errors:r}}function Ya(e){if(!e||typeof e!="object")return"";let t=e;return Array.isArray(t.enum)&&t.enum.length>0?"enum":typeof t.type=="string"?t.type:Array.isArray(t.type)?t.type.filter(n=>typeof n=="string").join("|"):""}async function jt(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,o=setTimeout(()=>r.abort(),n);try{let{timeoutMs:s,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(o)}}var Ft=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},_n=class extends Error{code;budgetId;status;constructor(t,n,r={}){super(t),this.name="SessionInvalidError",this.code=n,this.budgetId=r.budgetId,this.status=r.status}},Vt=class extends Error{code="SESSION_LOCK_CONTENDED";retryAfterSecs;status;constructor(t,n=1,r){super(t),this.name="SessionLockContendedError",this.retryAfterSecs=n,this.status=r}},ce=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(t,n,r,o,s,i,a,l){super(t),this.name="CardDeclinedError",this.retryable=n,this.code=r,this.reason=o,this.paymentErrorClass=s,this.correlationId=i,this.transactionId=a,this.retryAfter=l}};var Za={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&&Za[n]?Za[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 ge=E(require("fs")),_s=E(require("path")),Xa=E(require("os")),ys=_s.join(Xa.homedir(),".visa-mcp"),Zn=_s.join(ys,"mcp-server.log"),pm=5*1024*1024,hs=null;function fm(){ge.existsSync(ys)||ge.mkdirSync(ys,{recursive:!0,mode:448})}function gm(){if(!hs){if(fm(),ge.existsSync(Zn)&&ge.statSync(Zn).size>pm){let t=Zn+".1";ge.existsSync(t)&&ge.unlinkSync(t),ge.renameSync(Zn,t)}hs=ge.createWriteStream(Zn,{flags:"a"})}return hs}function hm(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function Hr(e,...t){let n=new Date().toISOString(),r=t.map(s=>typeof s=="string"?s:JSON.stringify(s,null,2)).join(" "),o=`[${n}] [${e}] ${r}
119
- `;hm(e)&&process.stderr.write(o),gm().write(o)}var m={debug:(...e)=>Hr("DEBUG",...e),info:(...e)=>Hr("INFO",...e),warn:(...e)=>Hr("WARN",...e),error:(...e)=>Hr("ERROR",...e)};var ym=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function ec(e,t){let n=Qa(e),r=Qa(t);if(!n||!r)return!1;for(let o=0;o<3;o++)if(n.main[o]!==r.main[o])return n.main[o]>r.main[o];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:_m(n.pre,r.pre)>0}function Qa(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(ym);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function _m(e,t){let n=e.split("."),r=t.split("."),o=Math.max(n.length,r.length);for(let s=0;s<o;s++){if(s>=n.length)return-1;if(s>=r.length)return 1;let i=n[s],a=r[s],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 Ue(){return!!(tc(process.env.VISA_CLI_NO_UPDATE_CHECK)||tc(process.env.CI)||process.env.NODE_ENV==="test")}function tc(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var bt=E(require("fs")),ws=require("node:net"),sc=E(require("os")),ic=E(require("path"));var Br=E(require("fs")),nc=E(require("path")),rc=E(require("os"));var vs=nc.join(rc.homedir(),".visa-mcp"),Xn=class{static ensureConfigDir(){Br.existsSync(vs)||Br.mkdirSync(vs,{recursive:!0,mode:448})}static getConfigDir(){return vs}static TOOL_STATES={login:!0,get_status:!0,get_cards:!0,add_card:!0,pay:!1,transaction_history:!0,update_spending_controls:!0,enroll_device:!1,verify_otp:!1,reset:!0,batch:!0,generate_x402_image:!1,browser_launch:!1,browser_navigate:!1,browser_snapshot:!1,browser_click:!1,browser_type:!1,browser_scroll:!1,generate_music_card:!1,generate_image_card:!1,query_onchain_prices_card:!1,generate_music_tempo_card:!1,check_music_status_tempo_card:!1,generate_image_fast_card:!1,generate_video_tempo_card:!1};static loadToolStates(){return{...this.TOOL_STATES}}static getDisabledTools(){let t=new Set;for(let[n,r]of Object.entries(this.TOOL_STATES))r||t.add(n);return t}static isToolDisabled(t){return this.TOOL_STATES[t]===!1}};function oc(e){let t=sc.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}var vm="settings.json",bm="must use https unless it points at localhost/loopback for local development";function Qn(){return ic.join(Xn.getConfigDir(),vm)}function ac(e){if((0,ws.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function Sm(e){let t=e.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!t)return!1;let n=Number.parseInt(t[1],16),r=Number.parseInt(t[2],16);if(!Number.isFinite(n)||!Number.isFinite(r))return!1;let o=[n>>8&255,n&255,r>>8&255,r&255].join(".");return ac(o)}function wm(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,ws.isIP)(t);return n===4?ac(t):n===6?t==="::1"||Sm(t):!1}function bs(e,t="auth.serverUrl"){let n;try{n=new URL(e)}catch{throw new Error(`${t} must be a valid URL (got: ${JSON.stringify(e)})`)}if(n.username||n.password)throw new Error(`${t} must not include username or password credentials`);if(n.protocol!=="https:"&&!(n.protocol==="http:"&&wm(n.hostname)))throw new Error(`${t} ${bm}`)}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");bs(e)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."},"ui.suppressFeed":{type:"boolean",description:"When true, generated images/music are not auto-submitted to the public Made-with-Visa feed."},"tools.meta":{type:"boolean",description:"Show category meta-tools (generate_image, generate_video, generate_music, run_llm, ...). Restart required.",requiresRestart:!0},"tools.discover":{type:"boolean",description:"Show the dynamic-catalog tools (discover_tools, execute_tool). Restart required.",requiresRestart:!0},"merchants.discover":{type:"string",description:'Platform-merchant JIT tool discovery: "all" = every live merchant, "off" = none, comma-separated slugs = exactly those. Equivalent to VISA_MERCHANT_DISCOVER / VISA_MERCHANT_SLUGS env. Restart required.',requiresRestart:!0,validate:e=>{if(typeof e!="string")throw new Error("merchants.discover must be a string");let t=e.trim().toLowerCase();if(t===""||t==="all"||t==="off"||t==="*")return;let n=/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/,r=e.split(",").map(o=>o.trim()).filter(Boolean);for(let o of r)if(!n.test(o))throw new Error(`merchants.discover: "${o}" is not a valid merchant slug`)}},"credit.sessionCapCents":{type:"number",description:"Default cap (in cents) for start_session and pay-as-you-go one-shot approvals. Server clamps to [10, 10000] = $0.10\u2013$100. Default 500 ($5).",validate:e=>{if(typeof e!="number"||!Number.isFinite(e))throw new Error("credit.sessionCapCents must be a number");if(!Number.isInteger(e))throw new Error("credit.sessionCapCents must be a whole number of cents (no fractional cents)");if(e<10||e>1e4)throw new Error("credit.sessionCapCents must be between 10 ($0.10) and 10000 ($100)")}}},xs=500,Kr={"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 qt(){let e=Qn();if(!bt.existsSync(e))return{};try{let t=bt.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?(m.warn("settings:corrupt",{path:oc(e),reason:"not_object"}),{}):n}catch(t){return m.warn("settings:corrupt",{path:oc(e),error:t?.message||String(t)}),{}}}function Ss(e){Xn.ensureConfigDir();let t=Qn(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
120
- `;bt.writeFileSync(n,r,{mode:384}),bt.renameSync(n,t)}function Cs(e){let t=qt()[e];return typeof t=="string"?t:void 0}function Gr(e){let t=qt()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function ks(e){let t=qt()[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 Xe=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"}},Qe=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"}},vt=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+Kr[t]),this.name="RetiredSettingKeyError"}},cc=["biometric.","spending.","account.","cards.","biometric"];function zr(e,t){if(cc.some(s=>e.startsWith(s)))throw new Qe(e);if(e in Kr)throw new vt(e);let n=St[e];if(!n)throw new Xe(e);let r;if(n.type==="boolean")if(typeof t=="boolean")r=t;else if(typeof t=="string"){let s=t.toLowerCase();if(s==="true")r=!0;else if(s==="false")r=!1;else throw new Error(`${e} expects true or false (got: ${JSON.stringify(t)})`)}else throw new Error(`${e} expects a boolean (got: ${typeof t})`);else if(n.type==="number")if(typeof t=="number")r=t;else if(typeof t=="string"&&t.trim().length>0){let s=Number(t);if(!Number.isFinite(s))throw new Error(`${e} expects a number (got: ${JSON.stringify(t)})`);r=s}else throw new Error(`${e} expects a number (got: ${typeof t})`);else{if(typeof t!="string"||t.length===0)throw new Error(`${e} expects a non-empty string`);r=t}n.validate&&n.validate(r);let o=qt();return o[e]=r,Ss(o),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:Qn()}}function Wr(e){if(cc.some(s=>e.startsWith(s)))throw new Qe(e);let t=St[e];if(e in Kr){let s=qt(),i=e in s;return i&&(delete s[e],Ss(s)),{key:e,removed:i,requiresRestart:!1,path:Qn()}}if(!t)throw new Xe(e);let r=qt(),o=e in r;return o&&(delete r[e],Ss(r)),{key:e,removed:o,requiresRestart:o&&!!t.requiresRestart,path:Qn()}}function lc(){let e=qt();return Object.entries(Kr).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}var xm="https://auth.visacli.sh",Cm="https://auth-visa-code-preview.up.railway.app";function km(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function Tm(){try{let e=Er();return km(e.version)}catch{return!1}}function Em(e){return e.envVar!==void 0&&e.envVar!==""?(bs(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(bs(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?Cm:xm}function he(){return Em({envVar:process.env.VISA_AUTH_URL,settingValue:Cs("auth.serverUrl"),isPrerelease:Tm()})}function uc(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":Gr("ui.suppressBrowser")??!1}function dc(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":Gr("ui.suppressFeed")??!1}function mc(){let e=process.env.VISA_CREDIT_SESSION_CAP_CENTS;if(e!==void 0){let n=Number(e);if(Number.isFinite(n)&&n>=10&&n<=1e4)return Math.floor(n)}let t=ks("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):xs}var Am="CARD_REENROLLMENT_REQUIRED",Rm="https://auth.visacli.sh/enroll-card";function Im(){try{return new URL("/enroll-card",he()).toString()}catch{return Rm}}function $m(e){let t=Im();if(typeof e!="string")return t;try{let n=new URL(e),r=new URL(t);if(n.origin===r.origin&&n.pathname==="/enroll-card")return n.toString()}catch{}return m.warn("card-reenroll:reenroll_url_rejected_fallback",{reason:"untrusted_or_malformed_reenroll_url",fallbackPath:"/enroll-card"}),t}var er="2.3.0-rc.0",Pm=/^vk_[A-Za-z0-9_-]{32,}$/;function Mm(e){if(typeof e!="string")return null;switch(e){case"BUDGET_CLOSED":case"BUDGET_NOT_FOUND":case"BUDGET_EXPIRED":return e;default:return null}}var Om="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function vn(e){return typeof e=="string"?e.trim():""}function pc(e){let t=e&&typeof e=="object"?e:{},n=vn(t.error)||vn(t.message);if(!n)return Om;let r=vn(t.error_code),o=[["surface",vn(t.disabled_surface)],["flag",vn(t.flag)],["correlation_id",vn(t.correlation_id)]].filter(([,i])=>i).map(([i,a])=>`${i}=${a}`),s=o.length?` (${o.join(" ")})`:"";return r?`503 [${r}] ${n}${s}`:`503 ${n}${s}`}function fc(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?Pm.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(`
121
- `)}var Se=class{constructor(t){this.getSessionToken=t;this.baseUrl=he()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!Ue()){let r=t.headers.get("X-Latest-Version");r&&ec(r,er)&&(this.lastSignals.updateAvailable={currentVersion:er,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return er}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new Ft(t.error||"Your biometric key is out of sync with the server.",typeof t.hint=="string"?t.hint:void 0)}async throwServerUnavailable(t){let n=null;try{n=await t.json()}catch{}throw new Error(pc(n))}async request(t,n,r,o,s,i){let a=await this.getSessionToken();if(!a)throw new Error(fc());let l={Authorization:`Bearer ${a}`};s&&(t==="GET"?l["X-User-Context"]=encodeURIComponent(s.replace(/[\r\n\0]/g," ").slice(0,1e3)):r={...r||{},user_context:s}),i&&(l["X-Visa-Meta-Tool"]=i),r&&(l["Content-Type"]="application/json");let c;try{c=await jt(`${this.baseUrl}${n}`,{method:t,headers:{...l,"X-Visa-CLI-Version":er,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:o})}catch(d){throw new Error(gs(d))}if(this.parseServerSignals(c),c.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(c.status===429){let d=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${d}s. Tip: use the batch tool to combine multiple requests into one.`)}c.status===503&&await this.throwServerUnavailable(c);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(this.throwIfAttestationDrift(u),typeof u?.error_code=="string"&&u.error_code===Am){let d=typeof u?.last4=="string"?u.last4:"",g=typeof u?.brand=="string"?u.brand:"card",p=$m(u?.reenroll_url),_=d?`${g} ending in ${d}`:"your card";throw new Error(`Please re-add ${_} to keep payments running. Open: ${p}`)}if(u?.declined){let d=Number(u.retryAfter??c.headers.get("Retry-After"));throw new ce(u.error||"Your card was declined.",!!u.retryable,u.code,u.reason,u.payment_error_class,u.correlation_id,u.transactionId,Number.isFinite(d)&&d>0?d:void 0)}if(c.status===402){let d=u?.error||"Gateway returned 402",g=typeof u?.error_code=="string"?u.error_code:"";throw g==="SPENDING_LIMIT_EXCEEDED"||g==="DAILY_LIMIT_EXCEEDED"||g==="PER_TXN_LIMIT_EXCEEDED"?new Error(`${d}. Check your limits with get_status or run: visa-cli update-spending-controls`):new Error(d)}throw new Error(u?.error||`Request failed (${c.status}). Try again.`)}return u}async shortcut(t,n,r,o,s){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,o,s)}async shortcutWithSession(t,n,r,o,s,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,l=await this.getSessionToken();if(!l)throw new Error(fc());let c={Authorization:`Bearer ${l}`,"X-Visa-CLI-Version":er,"X-Source":"cli","Content-Type":"application/json"};i&&(c["X-Visa-Meta-Tool"]=i);let u={...n,...r};s&&(u.user_context=s.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await jt(`${this.baseUrl}${a}`,{method:"POST",headers:c,body:JSON.stringify(u),timeoutMs:o})}catch(_){throw new Error(gs(_))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let _=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${_}s. Tip: use the batch tool to combine multiple requests into one.`)}let g=d.headers.get("X-Voucher-Receipt"),p;try{p=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(p),d.status===503){if(p?.error_code==="SESSION_LOCK_CONTENDED"){let h=Number(d.headers.get("Retry-After"))||1;throw new Vt(p?.message||p?.error||"Session budget is being modified by another request. Retry shortly.",h,d.status)}throw new Error(pc(p))}let _=Mm(p?.error_code);if(_||d.status===410){let h=_??"BUDGET_CLOSED";throw new _n(p?.message||p?.error||"Your session was invalidated by the server.",h,{budgetId:n.session_budget_id,status:d.status})}if(p?.declined){let h=Number(p.retryAfter??d.headers.get("Retry-After"));throw new ce(p.error||"Your card was declined.",!!p.retryable,p.code,p.reason,p.payment_error_class,p.correlation_id,p.transactionId,Number.isFinite(h)&&h>0?h:void 0)}throw new Error(p?.error||`Request failed (${d.status}). Try again.`)}return{data:p,voucherReceiptHeader:g}}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async catalogSearch(t,n,r,o){let s=r??"discover_tools",i=new URLSearchParams;t&&i.set("q",t),n&&i.set("category",n),o?.limit!=null&&i.set("limit",String(o.limit)),o?.offset!=null&&i.set("offset",String(o.offset));let a=i.toString();return this.request("GET",`/v1/catalog${a?`?${a}`:""}`,void 0,void 0,void 0,s)}async catalogTool(t,n){let r=n??"discover_tools";try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(t)}`,void 0,void 0,void 0,r)}catch{return null}}async discoverMerchantRoutes(t){try{return await this.request("GET",`/v1/platform/discover/${encodeURIComponent(t)}`)}catch{return null}}async listPublicMerchants(){try{let t=await jt(`${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 jt(`${this.baseUrl}/v1/platform/discover/${encodeURIComponent(t)}`,{method:"GET",timeoutMs:8e3});return n.ok?await n.json():null}catch{return null}}async paymentPreview(t,n){return this.request("POST","/v1/payment-preview",t,void 0,n)}async getBalance(){return this.request("GET","/v1/balance")}async topupBalance(t){return this.request("POST","/v1/balance/topup",t)}async createEnrollCode(){return this.request("POST","/v1/enroll-code")}async getAutoTopup(){let t=await this.getBalance();return{success:t.success,targetCents:t.autoTopupCents??null,thresholdCents:t.autoTopupThresholdCents??0}}async disableAutoTopup(){return this.request("PATCH","/v1/balance/auto-topup",{auto_topup_cents:null})}async createSessionBudget(t){return this.request("POST","/v1/session-budget/create",{...t,mode:"prepaid"})}async closeSession(t){return this.request("POST","/v1/session/close",{session_budget_id:t})}async getSessionBudget(t){return this.request("GET",`/v1/session-budget/${encodeURIComponent(t)}`)}async getSessionLedger(t){return this.request("GET",`/v1/session/${encodeURIComponent(t)}/ledger`)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getVisaSmi(t,n){return this.request("POST","/v1/visa/smi",t,6e4,n)}async getTransactions(t,n){let r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.offset!=null&&r.set("offset",String(t.offset));let o=r.toString(),s=o?`/v1/transactions?${o}`:"/v1/transactions";return this.request("GET",s,void 0,void 0,n)}async updateSpendingControls(t,n){return this.request("POST","/v1/spending-controls",t,void 0,n)}async removeCard(t,n,r){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(t))}`,n,void 0,r)}async setDefaultCard(t,n,r){return this.request("POST",`/v1/cards/${encodeURIComponent(String(t))}/default`,n,void 0,r)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t,n){return this.request("POST","/v1/attestation-key",{publicKey:t,...n?{attestation:n}:{}})}async startAttestationRecovery(t,n){return this.request("POST","/v1/attestation-key/recovery/start",{state:t},void 0,n)}async setBiometricPreference(t,n){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,n)}async logout(t,n){return this.request("POST","/v1/logout",t,void 0,n)}async feedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async createAppApiKey(t){return this.request("POST","/v1/api/keys",t)}async listAppApiKeys(){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 o=r.toString();return this.request("GET",`/v1/feedback${o?"?"+o:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}};var f={};No(f,{BRAND:()=>ip,DIRTY:()=>Ht,EMPTY_PATH:()=>Um,INVALID:()=>A,NEVER:()=>Bp,OK:()=>le,ParseStatus:()=>ae,Schema:()=>N,ZodAny:()=>Ct,ZodArray:()=>rt,ZodBigInt:()=>Kt,ZodBoolean:()=>Gt,ZodBranded:()=>nr,ZodCatch:()=>rn,ZodDate:()=>zt,ZodDefault:()=>nn,ZodDiscriminatedUnion:()=>Zr,ZodEffects:()=>Ae,ZodEnum:()=>en,ZodError:()=>ye,ZodFirstPartyTypeKind:()=>R,ZodFunction:()=>Qr,ZodIntersection:()=>Zt,ZodIssueCode:()=>y,ZodLazy:()=>Xt,ZodLiteral:()=>Qt,ZodMap:()=>kn,ZodNaN:()=>En,ZodNativeEnum:()=>tn,ZodNever:()=>Ie,ZodNull:()=>Jt,ZodNullable:()=>Ve,ZodNumber:()=>Bt,ZodObject:()=>_e,ZodOptional:()=>Te,ZodParsedType:()=>b,ZodPipeline:()=>rr,ZodPromise:()=>kt,ZodReadonly:()=>on,ZodRecord:()=>Xr,ZodSchema:()=>N,ZodSet:()=>Tn,ZodString:()=>xt,ZodSymbol:()=>xn,ZodTransformer:()=>Ae,ZodTuple:()=>Fe,ZodType:()=>N,ZodUndefined:()=>Wt,ZodUnion:()=>Yt,ZodUnknown:()=>nt,ZodVoid:()=>Cn,addIssueToContext:()=>v,any:()=>gp,array:()=>vp,bigint:()=>up,boolean:()=>kc,coerce:()=>Hp,custom:()=>wc,date:()=>dp,datetimeRegex:()=>bc,defaultErrorMap:()=>et,discriminatedUnion:()=>xp,effect:()=>Np,enum:()=>Pp,function:()=>Rp,getErrorMap:()=>bn,getParsedType:()=>je,instanceof:()=>cp,intersection:()=>Cp,isAborted:()=>Jr,isAsync:()=>Sn,isDirty:()=>Yr,isValid:()=>wt,late:()=>ap,lazy:()=>Ip,literal:()=>$p,makeIssue:()=>tr,map:()=>Ep,nan:()=>lp,nativeEnum:()=>Mp,never:()=>yp,null:()=>fp,nullable:()=>Lp,number:()=>Cc,object:()=>bp,objectUtil:()=>Ts,oboolean:()=>qp,onumber:()=>Vp,optional:()=>Dp,ostring:()=>Fp,pipeline:()=>jp,preprocess:()=>Up,promise:()=>Op,quotelessJson:()=>Nm,record:()=>Tp,set:()=>Ap,setErrorMap:()=>Lm,strictObject:()=>Sp,string:()=>xc,symbol:()=>mp,transformer:()=>Np,tuple:()=>kp,undefined:()=>pp,union:()=>wp,unknown:()=>hp,util:()=>D,void:()=>_p});var D;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},e.getValidEnumValues=o=>{let s=e.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return e.objectValues(i)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},e.find=(o,s)=>{for(let i of o)if(s(i))return i},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(D||(D={}));var Ts;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Ts||(Ts={}));var b=D.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),je=e=>{switch(typeof e){case"undefined":return b.undefined;case"string":return b.string;case"number":return Number.isNaN(e)?b.nan:b.number;case"boolean":return b.boolean;case"function":return b.function;case"bigint":return b.bigint;case"symbol":return b.symbol;case"object":return Array.isArray(e)?b.array:e===null?b.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?b.promise:typeof Map<"u"&&e instanceof Map?b.map:typeof Set<"u"&&e instanceof Set?b.set:typeof Date<"u"&&e instanceof Date?b.date:b.object;default:return b.unknown}};var y=D.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"]),Nm=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ye=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,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 o(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,D.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];n[s]=n[s]||[],n[s].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};ye.create=e=>new ye(e);var Dm=(e,t)=>{let n;switch(e.code){case y.invalid_type:e.received===b.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case y.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,D.jsonStringifyReplacer)}`;break;case y.unrecognized_keys:n=`Unrecognized key(s) in object: ${D.joinValues(e.keys,", ")}`;break;case y.invalid_union:n="Invalid input";break;case y.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${D.joinValues(e.options)}`;break;case y.invalid_enum_value:n=`Invalid enum value. Expected ${D.joinValues(e.options)}, received '${e.received}'`;break;case y.invalid_arguments:n="Invalid function arguments";break;case y.invalid_return_type:n="Invalid function return type";break;case y.invalid_date:n="Invalid date";break;case y.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}"`:D.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case y.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 y.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 y.custom:n="Invalid input";break;case y.invalid_intersection_types:n="Intersection results could not be merged";break;case y.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case y.not_finite:n="Number must be finite";break;default:n=t.defaultError,D.assertNever(e)}return{message:n}},et=Dm;var gc=et;function Lm(e){gc=e}function bn(){return gc}var tr=e=>{let{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)a=c(i,{data:t,defaultError:a}).message;return{...o,path:s,message:a}},Um=[];function v(e,t){let n=bn(),r=tr({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===et?void 0:et].filter(o=>!!o)});e.common.issues.push(r)}var ae=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let o of n){if(o.status==="aborted")return A;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let o of n){let s=await o.key,i=await o.value;r.push({key:s,value:i})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let o of n){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return A;s.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:t.value,value:r}}},A=Object.freeze({status:"aborted"}),Ht=e=>({status:"dirty",value:e}),le=e=>({status:"valid",value:e}),Jr=e=>e.status==="aborted",Yr=e=>e.status==="dirty",wt=e=>e.status==="valid",Sn=e=>typeof Promise<"u"&&e instanceof Promise;var w;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(w||(w={}));var Ee=class{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},hc=(e,t)=>{if(wt(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 ye(e.common.issues);return this._error=n,this._error}}};function M(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(i,a)=>{let{message: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:o}}var N=class{get description(){return this._def.description}_getType(t){return je(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:je(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ae,ctx:{common:t.parent.common,data:t.data,parsedType:je(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Sn(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:je(t)},o=this._parseSync({data:t,path:r.path,parent:r});return hc(r,o)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:je(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return wt(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=>wt(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:je(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(Sn(o)?o:Promise.resolve(o));return hc(r,s)}refine(t,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{let i=t(o),a=()=>s.addIssue({code:y.custom,...r(o)});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,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Ae({schema:this,typeName:R.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 Te.create(this,this._def)}nullable(){return Ve.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return rt.create(this)}promise(){return kt.create(this,this._def)}or(t){return Yt.create([this,t],this._def)}and(t){return Zt.create(this,t,this._def)}transform(t){return new Ae({...M(this._def),schema:this,typeName:R.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new nn({...M(this._def),innerType:this,defaultValue:n,typeName:R.ZodDefault})}brand(){return new nr({typeName:R.ZodBranded,type:this,...M(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new rn({...M(this._def),innerType:this,catchValue:n,typeName:R.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return rr.create(this,t)}readonly(){return on.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},jm=/^c[^\s-]{8,}$/i,Fm=/^[0-9a-z]+$/,Vm=/^[0-9A-HJKMNP-TV-Z]{26}$/i,qm=/^[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,Hm=/^[a-z0-9_-]{21}$/i,Bm=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Km=/^[-+]?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)?)??$/,Gm=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,zm="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Es,Wm=/^(?:(?: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])$/,Jm=/^(?:(?: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])$/,Ym=/^(([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]))$/,Zm=/^(([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])$/,Xm=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Qm=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,_c="((\\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])))",ep=new RegExp(`^${_c}$`);function vc(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 tp(e){return new RegExp(`^${vc(e)}$`)}function bc(e){let t=`${_c}T${vc(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 np(e,t){return!!((t==="v4"||!t)&&Wm.test(e)||(t==="v6"||!t)&&Ym.test(e))}function rp(e,t){if(!Bm.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function op(e,t){return!!((t==="v4"||!t)&&Jm.test(e)||(t==="v6"||!t)&&Zm.test(e))}var xt=class e extends N{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==b.string){let s=this._getOrReturnCtx(t);return v(s,{code:y.invalid_type,expected:b.string,received:s.parsedType}),A}let r=new ae,o;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),v(o,{code:y.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),v(o,{code:y.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let i=t.data.length>s.value,a=t.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(t,o),i?v(o,{code:y.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&v(o,{code:y.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")Gm.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"email",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Es||(Es=new RegExp(zm,"u")),Es.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"emoji",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")qm.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"uuid",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")Hm.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"nanoid",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")jm.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"cuid",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")Fm.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"cuid2",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")Vm.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"ulid",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),v(o,{validation:"url",code:y.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"regex",code:y.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),v(o,{code:y.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),v(o,{code:y.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),v(o,{code:y.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?bc(s).test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{code:y.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?ep.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{code:y.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?tp(s).test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{code:y.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?Km.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"duration",code:y.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?np(t.data,s.version)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"ip",code:y.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?rp(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"jwt",code:y.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?op(t.data,s.version)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"cidr",code:y.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?Xm.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"base64",code:y.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?Qm.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"base64url",code:y.invalid_string,message:s.message}),r.dirty()):D.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:y.invalid_string,...w.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...w.errToObj(t)})}url(t){return this._addCheck({kind:"url",...w.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...w.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...w.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...w.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...w.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...w.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...w.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...w.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...w.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...w.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...w.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...w.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,...w.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,...w.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...w.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...w.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...w.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...w.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...w.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...w.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...w.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...w.errToObj(n)})}nonempty(t){return this.min(1,w.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}};xt.create=e=>new xt({checks:[],typeName:R.ZodString,coerce:e?.coerce??!1,...M(e)});function sp(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/10**o}var Bt=class e extends N{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)!==b.number){let s=this._getOrReturnCtx(t);return v(s,{code:y.invalid_type,expected:b.number,received:s.parsedType}),A}let r,o=new ae;for(let s of this._def.checks)s.kind==="int"?D.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),v(r,{code:y.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),v(r,{code:y.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),v(r,{code:y.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?sp(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),v(r,{code:y.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),v(r,{code:y.not_finite,message:s.message}),o.dirty()):D.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,w.toString(n))}gt(t,n){return this.setLimit("min",t,!1,w.toString(n))}lte(t,n){return this.setLimit("max",t,!0,w.toString(n))}lt(t,n){return this.setLimit("max",t,!1,w.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:w.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:w.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:w.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:w.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:w.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:w.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:w.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:w.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:w.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:w.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"&&D.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)}};Bt.create=e=>new Bt({checks:[],typeName:R.ZodNumber,coerce:e?.coerce||!1,...M(e)});var Kt=class e extends N{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)!==b.bigint)return this._getInvalidInput(t);let r,o=new ae;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),v(r,{code:y.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),v(r,{code:y.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),v(r,{code:y.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):D.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return v(n,{code:y.invalid_type,expected:b.bigint,received:n.parsedType}),A}gte(t,n){return this.setLimit("min",t,!0,w.toString(n))}gt(t,n){return this.setLimit("min",t,!1,w.toString(n))}lte(t,n){return this.setLimit("max",t,!0,w.toString(n))}lt(t,n){return this.setLimit("max",t,!1,w.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:w.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:w.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:w.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:w.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:w.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:w.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}};Kt.create=e=>new Kt({checks:[],typeName:R.ZodBigInt,coerce:e?.coerce??!1,...M(e)});var Gt=class extends N{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==b.boolean){let r=this._getOrReturnCtx(t);return v(r,{code:y.invalid_type,expected:b.boolean,received:r.parsedType}),A}return le(t.data)}};Gt.create=e=>new Gt({typeName:R.ZodBoolean,coerce:e?.coerce||!1,...M(e)});var zt=class e extends N{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==b.date){let s=this._getOrReturnCtx(t);return v(s,{code:y.invalid_type,expected:b.date,received:s.parsedType}),A}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return v(s,{code:y.invalid_date}),A}let r=new ae,o;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),v(o,{code:y.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),v(o,{code:y.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):D.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:w.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:w.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}};zt.create=e=>new zt({checks:[],coerce:e?.coerce||!1,typeName:R.ZodDate,...M(e)});var xn=class extends N{_parse(t){if(this._getType(t)!==b.symbol){let r=this._getOrReturnCtx(t);return v(r,{code:y.invalid_type,expected:b.symbol,received:r.parsedType}),A}return le(t.data)}};xn.create=e=>new xn({typeName:R.ZodSymbol,...M(e)});var Wt=class extends N{_parse(t){if(this._getType(t)!==b.undefined){let r=this._getOrReturnCtx(t);return v(r,{code:y.invalid_type,expected:b.undefined,received:r.parsedType}),A}return le(t.data)}};Wt.create=e=>new Wt({typeName:R.ZodUndefined,...M(e)});var Jt=class extends N{_parse(t){if(this._getType(t)!==b.null){let r=this._getOrReturnCtx(t);return v(r,{code:y.invalid_type,expected:b.null,received:r.parsedType}),A}return le(t.data)}};Jt.create=e=>new Jt({typeName:R.ZodNull,...M(e)});var Ct=class extends N{constructor(){super(...arguments),this._any=!0}_parse(t){return le(t.data)}};Ct.create=e=>new Ct({typeName:R.ZodAny,...M(e)});var nt=class extends N{constructor(){super(...arguments),this._unknown=!0}_parse(t){return le(t.data)}};nt.create=e=>new nt({typeName:R.ZodUnknown,...M(e)});var Ie=class extends N{_parse(t){let n=this._getOrReturnCtx(t);return v(n,{code:y.invalid_type,expected:b.never,received:n.parsedType}),A}};Ie.create=e=>new Ie({typeName:R.ZodNever,...M(e)});var Cn=class extends N{_parse(t){if(this._getType(t)!==b.undefined){let r=this._getOrReturnCtx(t);return v(r,{code:y.invalid_type,expected:b.void,received:r.parsedType}),A}return le(t.data)}};Cn.create=e=>new Cn({typeName:R.ZodVoid,...M(e)});var rt=class e extends N{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==b.array)return v(n,{code:y.invalid_type,expected:b.array,received:n.parsedType}),A;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(v(n,{code:i?y.too_big:y.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(v(n,{code:y.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(v(n,{code:y.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>o.type._parseAsync(new Ee(n,i,n.path,a)))).then(i=>ae.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new Ee(n,i,n.path,a)));return ae.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:w.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:w.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:w.toString(n)}})}nonempty(t){return this.min(1,t)}};rt.create=(e,t)=>new rt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:R.ZodArray,...M(t)});function wn(e){if(e instanceof _e){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Te.create(wn(r))}return new _e({...e._def,shape:()=>t})}else return e instanceof rt?new rt({...e._def,type:wn(e.element)}):e instanceof Te?Te.create(wn(e.unwrap())):e instanceof Ve?Ve.create(wn(e.unwrap())):e instanceof Fe?Fe.create(e.items.map(t=>wn(t))):e}var _e=class e extends N{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=D.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==b.object){let c=this._getOrReturnCtx(t);return v(c,{code:y.invalid_type,expected:b.object,received:c.parsedType}),A}let{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ie&&this._def.unknownKeys==="strip"))for(let c in o.data)i.includes(c)||a.push(c);let l=[];for(let c of i){let u=s[c],d=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Ee(o,d,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Ie){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")a.length>0&&(v(o,{code:y.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 d=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Ee(o,d,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of l){let d=await u.key,g=await u.value;c.push({key:d,value:g,alwaysSet:u.alwaysSet})}return c}).then(c=>ae.mergeObjectSync(r,c)):ae.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return w.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:w.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:R.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 D.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 D.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return wn(this)}partial(t){let n={};for(let r of D.objectKeys(this.shape)){let o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let r of D.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Te;)s=s._def.innerType;n[r]=s}return new e({...this._def,shape:()=>n})}keyof(){return Sc(D.objectKeys(this.shape))}};_e.create=(e,t)=>new _e({shape:()=>e,unknownKeys:"strip",catchall:Ie.create(),typeName:R.ZodObject,...M(t)});_e.strictCreate=(e,t)=>new _e({shape:()=>e,unknownKeys:"strict",catchall:Ie.create(),typeName:R.ZodObject,...M(t)});_e.lazycreate=(e,t)=>new _e({shape:e,unknownKeys:"strip",catchall:Ie.create(),typeName:R.ZodObject,...M(t)});var Yt=class extends N{_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new ye(a.ctx.common.issues));return v(n,{code:y.invalid_union,unionErrors:i}),A}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let 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"&&!s&&(s={result:u,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(l=>new ye(l));return v(n,{code:y.invalid_union,unionErrors:a}),A}}get options(){return this._def.options}};Yt.create=(e,t)=>new Yt({options:e,typeName:R.ZodUnion,...M(t)});var tt=e=>e instanceof Xt?tt(e.schema):e instanceof Ae?tt(e.innerType()):e instanceof Qt?[e.value]:e instanceof en?e.options:e instanceof tn?D.objectValues(e.enum):e instanceof nn?tt(e._def.innerType):e instanceof Wt?[void 0]:e instanceof Jt?[null]:e instanceof Te?[void 0,...tt(e.unwrap())]:e instanceof Ve?[null,...tt(e.unwrap())]:e instanceof nr||e instanceof on?tt(e.unwrap()):e instanceof rn?tt(e._def.innerType):[],Zr=class e extends N{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.object)return v(n,{code:y.invalid_type,expected:b.object,received:n.parsedType}),A;let r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(v(n,{code:y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),A)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let o=new Map;for(let s of n){let i=tt(s.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);o.set(a,s)}}return new e({typeName:R.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...M(r)})}};function As(e,t){let n=je(e),r=je(t);if(e===t)return{valid:!0,data:e};if(n===b.object&&r===b.object){let o=D.objectKeys(t),s=D.objectKeys(e).filter(a=>o.indexOf(a)!==-1),i={...e,...t};for(let a of s){let l=As(e[a],t[a]);if(!l.valid)return{valid:!1};i[a]=l.data}return{valid:!0,data:i}}else if(n===b.array&&r===b.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let s=0;s<e.length;s++){let i=e[s],a=t[s],l=As(i,a);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===b.date&&r===b.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Zt=class extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=(s,i)=>{if(Jr(s)||Jr(i))return A;let a=As(s.value,i.value);return a.valid?((Yr(s)||Yr(i))&&n.dirty(),{status:n.value,value:a.data}):(v(r,{code:y.invalid_intersection_types}),A)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Zt.create=(e,t,n)=>new Zt({left:e,right:t,typeName:R.ZodIntersection,...M(n)});var Fe=class e extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.array)return v(r,{code:y.invalid_type,expected:b.array,received:r.parsedType}),A;if(r.data.length<this._def.items.length)return v(r,{code:y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),A;!this._def.rest&&r.data.length>this._def.items.length&&(v(r,{code:y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Ee(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>ae.mergeArray(n,i)):ae.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Fe.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Fe({items:e,typeName:R.ZodTuple,rest:null,...M(t)})};var Xr=class e extends N{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!==b.object)return v(r,{code:y.invalid_type,expected:b.object,received:r.parsedType}),A;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new Ee(r,a,r.path,a)),value:i._parse(new Ee(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?ae.mergeObjectAsync(n,o):ae.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof N?new e({keyType:t,valueType:n,typeName:R.ZodRecord,...M(r)}):new e({keyType:xt.create(),valueType:t,typeName:R.ZodRecord,...M(n)})}},kn=class extends N{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!==b.map)return v(r,{code:y.invalid_type,expected:b.map,received:r.parsedType}),A;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,l],c)=>({key:o._parse(new Ee(r,a,r.path,[c,"key"])),value:s._parse(new Ee(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 A;(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 A;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}}}};kn.create=(e,t,n)=>new kn({valueType:t,keyType:e,typeName:R.ZodMap,...M(n)});var Tn=class e extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.set)return v(r,{code:y.invalid_type,expected:b.set,received:r.parsedType}),A;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(v(r,{code:y.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(v(r,{code:y.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(l){let c=new Set;for(let u of l){if(u.status==="aborted")return A;u.status==="dirty"&&n.dirty(),c.add(u.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((l,c)=>s._parse(new Ee(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:w.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:w.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};Tn.create=(e,t)=>new Tn({valueType:e,minSize:null,maxSize:null,typeName:R.ZodSet,...M(t)});var Qr=class e extends N{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.function)return v(n,{code:y.invalid_type,expected:b.function,received:n.parsedType}),A;function r(a,l){return tr({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,bn(),et].filter(c=>!!c),issueData:{code:y.invalid_arguments,argumentsError:l}})}function o(a,l){return tr({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,bn(),et].filter(c=>!!c),issueData:{code:y.invalid_return_type,returnTypeError:l}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof kt){let a=this;return le(async function(...l){let c=new ye([]),u=await a._def.args.parseAsync(l,s).catch(p=>{throw c.addIssue(r(l,p)),c}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,s).catch(p=>{throw c.addIssue(o(d,p)),c})})}else{let a=this;return le(function(...l){let c=a._def.args.safeParse(l,s);if(!c.success)throw new ye([r(l,c.error)]);let u=Reflect.apply(i,this,c.data),d=a._def.returns.safeParse(u,s);if(!d.success)throw new ye([o(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Fe.create(t).rest(nt.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||Fe.create([]).rest(nt.create()),returns:n||nt.create(),typeName:R.ZodFunction,...M(r)})}},Xt=class extends N{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})}};Xt.create=(e,t)=>new Xt({getter:e,typeName:R.ZodLazy,...M(t)});var Qt=class extends N{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return v(n,{received:n.data,code:y.invalid_literal,expected:this._def.value}),A}return{status:"valid",value:t.data}}get value(){return this._def.value}};Qt.create=(e,t)=>new Qt({value:e,typeName:R.ZodLiteral,...M(t)});function Sc(e,t){return new en({values:e,typeName:R.ZodEnum,...M(t)})}var en=class e extends N{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return v(n,{expected:D.joinValues(r),received:n.parsedType,code:y.invalid_type}),A}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 v(n,{received:n.data,code:y.invalid_enum_value,options:r}),A}return le(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})}};en.create=Sc;var tn=class extends N{_parse(t){let n=D.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==b.string&&r.parsedType!==b.number){let o=D.objectValues(n);return v(r,{expected:D.joinValues(o),received:r.parsedType,code:y.invalid_type}),A}if(this._cache||(this._cache=new Set(D.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let o=D.objectValues(n);return v(r,{received:r.data,code:y.invalid_enum_value,options:o}),A}return le(t.data)}get enum(){return this._def.values}};tn.create=(e,t)=>new tn({values:e,typeName:R.ZodNativeEnum,...M(t)});var kt=class extends N{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.promise&&n.common.async===!1)return v(n,{code:y.invalid_type,expected:b.promise,received:n.parsedType}),A;let r=n.parsedType===b.promise?n.data:Promise.resolve(n.data);return le(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};kt.create=(e,t)=>new kt({type:e,typeName:R.ZodPromise,...M(t)});var Ae=class extends N{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===R.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:i=>{v(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return A;let l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?A:l.status==="dirty"?Ht(l.value):n.value==="dirty"?Ht(l.value):l});{if(n.value==="aborted")return A;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?A:a.status==="dirty"?Ht(a.value):n.value==="dirty"?Ht(a.value):a}}if(o.type==="refinement"){let i=a=>{let l=o.refinement(a,s);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"?A:(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"?A:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!wt(i))return A;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>wt(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):A);D.assertNever(o)}};Ae.create=(e,t,n)=>new Ae({schema:e,typeName:R.ZodEffects,effect:t,...M(n)});Ae.createWithPreprocess=(e,t,n)=>new Ae({schema:t,effect:{type:"preprocess",transform:e},typeName:R.ZodEffects,...M(n)});var Te=class extends N{_parse(t){return this._getType(t)===b.undefined?le(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Te.create=(e,t)=>new Te({innerType:e,typeName:R.ZodOptional,...M(t)});var Ve=class extends N{_parse(t){return this._getType(t)===b.null?le(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ve.create=(e,t)=>new Ve({innerType:e,typeName:R.ZodNullable,...M(t)});var nn=class extends N{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===b.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};nn.create=(e,t)=>new nn({innerType:e,typeName:R.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...M(t)});var rn=class extends N{_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Sn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ye(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ye(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};rn.create=(e,t)=>new rn({innerType:e,typeName:R.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...M(t)});var En=class extends N{_parse(t){if(this._getType(t)!==b.nan){let r=this._getOrReturnCtx(t);return v(r,{code:y.invalid_type,expected:b.nan,received:r.parsedType}),A}return{status:"valid",value:t.data}}};En.create=e=>new En({typeName:R.ZodNaN,...M(e)});var ip=Symbol("zod_brand"),nr=class extends N{_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}},rr=class e extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?A:s.status==="dirty"?(n.dirty(),Ht(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?A:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:R.ZodPipeline})}},on=class extends N{_parse(t){let n=this._def.innerType._parse(t),r=o=>(wt(o)&&(o.value=Object.freeze(o.value)),o);return Sn(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};on.create=(e,t)=>new on({innerType:e,typeName:R.ZodReadonly,...M(t)});function yc(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function wc(e,t={},n){return e?Ct.create().superRefine((r,o)=>{let s=e(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=yc(t,r),l=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:l})}});if(!s){let i=yc(t,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Ct.create()}var ap={object:_e.lazycreate},R;(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"})(R||(R={}));var cp=(e,t={message:`Input not instance of ${e.name}`})=>wc(n=>n instanceof e,t),xc=xt.create,Cc=Bt.create,lp=En.create,up=Kt.create,kc=Gt.create,dp=zt.create,mp=xn.create,pp=Wt.create,fp=Jt.create,gp=Ct.create,hp=nt.create,yp=Ie.create,_p=Cn.create,vp=rt.create,bp=_e.create,Sp=_e.strictCreate,wp=Yt.create,xp=Zr.create,Cp=Zt.create,kp=Fe.create,Tp=Xr.create,Ep=kn.create,Ap=Tn.create,Rp=Qr.create,Ip=Xt.create,$p=Qt.create,Pp=en.create,Mp=tn.create,Op=kt.create,Np=Ae.create,Dp=Te.create,Lp=Ve.create,Up=Ae.createWithPreprocess,jp=rr.create,Fp=()=>xc().optional(),Vp=()=>Cc().optional(),qp=()=>kc().optional(),Hp={string:(e=>xt.create({...e,coerce:!0})),number:(e=>Bt.create({...e,coerce:!0})),boolean:(e=>Gt.create({...e,coerce:!0})),bigint:(e=>Kt.create({...e,coerce:!0})),date:(e=>zt.create({...e,coerce:!0}))};var Bp=A;var Tc=["tempo","mpp_self","merchant_self"];var Is=f.object({inputPerMillion:f.number().positive(),outputPerMillion:f.number().positive(),contextWindow:f.number().int().positive().optional(),maxOutput:f.number().int().positive().optional(),perRequestFeeCents:f.number().nonnegative().optional()}),Kp=f.object({strategy:f.enum(["flat","token","band"]).optional(),pricingModel:f.enum(["per-call","per-token","band"]).optional(),priceCents:f.number().nonnegative().optional(),currency:f.string().optional(),display:f.string().optional(),estimate:f.boolean().optional(),source:f.string().optional(),priceBand:f.record(f.unknown()).optional(),tokenPricing:Is.optional()}).passthrough(),$s=f.discriminatedUnion("type",[f.object({type:f.literal("shortcut"),routedPath:f.string().min(1).startsWith("/")}),f.object({type:f.literal("custom"),merchantSlug:f.string().min(1),subPath:f.string().optional()}),f.object({type:f.literal("local"),fn:f.string().min(1)}),f.object({type:f.literal("read")})]),Ps=f.object({amount:f.number().nonnegative(),currency:f.string().length(3).optional(),display:f.string().optional(),free:f.boolean().optional(),batchDiscount:f.number().min(0).max(100).optional()}),Ec=f.object({attestation:f.boolean().optional(),rateLimitMs:f.number().positive().optional()}),Ac=f.object({displayName:f.string().optional(),feedbackEligible:f.boolean().optional(),suggestionEligible:f.boolean().optional(),batchable:f.boolean().optional()}),Gp=f.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),zp=120,Wp=120,Jp=1200,Yp=/^[^\u0000-\u001F\u007F]+$/;function Rs(e,t){return f.string().min(1).max(e).regex(Yp,`${t} must not contain control characters`)}var Ms={id:f.string().min(1),name:Rs(zp,"name"),description:Rs(Jp,"description"),provider:f.string().min(1),model:f.string().min(1),category:Gp,priceCents:f.number().nonnegative(),inputSchema:f.record(f.unknown()),gatewayUrl:f.string().min(1),merchantName:Rs(Wp,"merchantName"),isAsync:f.boolean().optional(),pollUrl:f.string().optional(),pollInterval:f.number().positive().optional(),pollTimeout:f.number().positive().optional(),tags:f.array(f.string()).optional(),tokenPricing:Is.optional(),priceDisplay:f.string().optional(),pricingModel:f.enum(["per-call","per-token","band"]).optional(),pricingInfo:Kp.optional(),status:f.enum(["available","unavailable"]).optional(),handler:$s.optional(),pricing:Ps.optional(),security:Ec.optional(),engagement:Ac.optional(),enabled:f.boolean().optional(),beta:f.boolean().optional(),deprecated:f.boolean().optional(),replacementTool:f.string().optional(),minCliVersion:f.string().optional(),sunsetAt:f.string().optional(),rail:f.enum(Tc).optional(),pricingStrategy:f.enum(["flat","token","band"]).optional()},Rc=f.object({...Ms,dispatch:f.literal("routed"),routedPath:f.string().min(1).startsWith("/")}).strict(),Ic=f.object({...Ms,dispatch:f.literal("enveloped")}).strict(),$c=f.object({...Ms,handler:$s,pricing:Ps}).strict(),Pc=f.union([f.discriminatedUnion("dispatch",[Rc,Ic]),$c]);var Os=/^[a-z0-9][a-z0-9_-]*$/;var Xp="https://fal.run",Dc="https://openrouter.mpp.tempo.xyz";function Qp(e){let{attestation:t,tool_id:n,...r}=e;return r}var Mc={"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 eo(e){let{attestation:t,tool_id:n,aspect_ratio:r,image_size:o,...s}=e,i={...s};return typeof o=="string"&&o.length>0?(i.image_size=o,i):(typeof r=="string"&&Mc[r]&&(i.image_size=Mc[r]),i)}function Oc(e){let t={chain:e.chain,token_address:e.token_address};if(e.start_timestamp){let n=e.end_timestamp||new Date().toISOString(),r=e.time_granularity;if(!r){let o=new Date(e.start_timestamp).getTime();(new Date(n).getTime()-o)/(1e3*60*60*24)<=2?r="1h":r="1d"}return{addresses:[t],start_timestamp:e.start_timestamp,end_timestamp:n,time_granularity:r}}return[t]}function ef(e,t,n,r,o,s,i,a,l){return{id:e,name:t,description:n,provider:r,model:o.replace(/^\//,""),category:s,gatewayUrl:`https://${r}${o}`,merchantName:t,inputSchema:a,handler:{type:"custom",merchantSlug:r,subPath:o},pricing:{amount:i,currency:"USD",display:`$${(i/100).toFixed(2)}`},priceCents:i,tags:[],...l}}function tf(e,t,n,r,o,s,i,a){return ef(e,t,n,"suno-ai",r,o,s,i,{merchantName:"Suno AI",...a})}function X(e,t,n,r,o,s,i,a){return{dispatch:"routed",id:e,name:t,description:n,provider:"fal",model:r,category:o,priceCents:s,inputSchema:i,routedPath:`/api/v1/fal/${r}`,gatewayUrl:`${Xp}/${r}`,merchantName:"fal.ai",buildBody:Qp,tags:[],...a}}function nf(e){return t=>{let{attestation:n,tool_id:r,prompt:o,system_prompt:s,max_tokens:i,temperature:a,...l}=t;return{model:e,messages:[...s?[{role:"system",content:s}]:[],{role:"user",content:o}],max_tokens:i??1024,temperature:a??.7,...l}}}function rf(e){return t=>{let{attestation:n,tool_id:r,prompt:o,image_url:s,aspect_ratio:i,max_tokens:a,temperature:l,...c}=t,u=[{type:"text",text:o}];return typeof s=="string"&&s.length>0&&u.push({type:"image_url",image_url:{url:s}}),{model:e,messages:[{role:"user",content:u}],max_tokens:a??1024,temperature:l??.7,...typeof i=="string"&&i.length>0?{image_config:{aspect_ratio:i}}:{},...c}}}function ee(e,t,n,r,o,s,i){let a=i?.perRequestFeeCents??0,l=500/1e6*o*100,c=500/1e6*s*100,u=Math.max(1,Math.ceil(l+c+a)),{perRequestFeeCents:d,...g}=i??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"llm",priceCents:u,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:`${Dc}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:nf(r),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:o,outputPerMillion:s,...a>0?{perRequestFeeCents:a}:{}},...g}}function Ns(e,t,n,r,o,s){return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"image",priceCents:o,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate or edit"},image_url:{type:"string",description:"Optional source image URL for edits"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"1:1"},max_tokens:{type:"integer",description:"Maximum text tokens in response metadata (default: 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:`${Dc}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:rf(r),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...s}}var Ds=[X("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"]}),X("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:eo}),X("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:eo}),X("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:eo}),X("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"]}),Ns("or-gemini-nano-banana","Nano Banana","Google Gemini 2.5 Flash Image via OpenRouter for image generation and edits.","google/gemini-2.5-flash-image",4),Ns("or-gemini-nano-banana-2","Nano Banana 2","Google Gemini 3.1 Flash Image Preview via OpenRouter for fast image generation and edits.","google/gemini-3.1-flash-image-preview",5,{tags:["image","gemini","google","nano-banana","edit","fast"],tokenPricing:{inputPerMillion:.5,outputPerMillion:3}}),Ns("or-gemini-nano-banana-pro","Nano Banana Pro","Google Gemini 3 Pro Image Preview via OpenRouter for professional image generation, edits, and text rendering.","google/gemini-3-pro-image-preview",8,{tags:["image","gemini","google","nano-banana","pro","text-rendering"],tokenPricing:{inputPerMillion:2,outputPerMillion:12}}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("fal-stable-audio","Stable Audio","Generate sound effects and ambient audio from text descriptions.","fal-ai/stable-audio","audio",4,{type:"object",properties:{prompt:{type:"string",description:"Description of the audio to generate"},seconds_total:{type:"number",description:"Duration in seconds (max 47)",default:30}},required:["prompt"]},{tags:["audio","sound-effects","ambient"]}),X("fal-ace-step-music","ACE-Step Music","Generate full music tracks from a prompt, with optional vocals or instrumentals.","fal-ai/ace-step/prompt-to-audio","audio",2,{type:"object",properties:{prompt:{type:"string",description:"Description of the song, genre, mood, instruments, and lyrics direction"},instrumental:{type:"boolean",description:"Generate instrumental music without vocals",default:!1},duration:{type:"number",description:"Duration in seconds",default:60}},required:["prompt"]},{tags:["music","song","vocals","instrumental","ace-step"]}),tf("suno-music","Suno Music","AI music generation. Create full songs with vocals or instrumentals.","/suno/generate-music","audio",10,{type:"object",properties:{prompt:{type:"string",description:"Description of the song (genre, mood, instruments)"},instrumental:{type:"boolean",description:"Instrumental only, no vocals",default:!1}},required:["prompt"]},{isAsync:!0,pollUrl:"https://api.sunoapi.org/suno/get-music-status",deprecated:!0,tags:["music","song","vocals","instrumental"],buildBody:e=>{let{attestation:t,tool_id:n,prompt:r,instrumental:o,...s}=e;return{prompt:r,customMode:!1,instrumental:typeof o=="boolean"?o:!1,model:"V4",...s}}}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),ee("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"]}),ee("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"]}),ee("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"]}),ee("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"]}),ee("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"]}),ee("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"]}),ee("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"]}),ee("or-gemini-3-flash","Gemini 3 Flash","Google's high-speed thinking model for agentic workflows, coding, and multimodal tasks.","google/gemini-3-flash-preview",.5,3,{tags:["llm","gemini","google","agentic","coding","fast"]}),ee("or-gemini-3-pro","Gemini 3 Pro","Google's flagship frontier model for deep reasoning, multimodal analysis, and agentic coding.","google/gemini-3-pro-preview",2,12,{tags:["llm","gemini","google","reasoning","coding","multimodal"]}),ee("or-gemini-3-lite","Gemini 3.1 Flash Lite","Google's efficient multimodal model optimized for low-latency, high-volume agent workloads.","google/gemini-3.1-flash-lite",.25,1.5,{tags:["llm","gemini","google","fast","cheap","multimodal"]}),ee("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"]}),ee("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"]}),ee("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"]}),ee("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"]}),ee("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"]}),ee("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"]}),ee("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"]}),ee("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"]}),ee("or-perplexity-sonar","Perplexity Sonar","Search-augmented LLM. Answers with real-time web sources and citations.","perplexity/sonar",1,1,{perRequestFeeCents:.5,tags:["llm","perplexity","search","web","citations","real-time"]}),{dispatch:"enveloped",id:"query_onchain_prices",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly and daily granularity.",provider:"allium",model:"allium-prices",category:"onchain",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly) or '1d' (daily). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:Oc,tags:["onchain","prices","allium","crypto"]},{dispatch:"enveloped",id:"generate_image_card",name:"Generate Image (Ultra)",description:"Generate a high-quality AI image (FLUX Pro Ultra, 2K, ~$0.06).",provider:"fal",model:"fal-ai/flux-pro/v1.1-ultra",category:"image",priceCents:6,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1-ultra",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro-ultra",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),t},tags:["image","flux","ultra","legacy"]},{dispatch:"enveloped",id:"generate_image_fast_card",name:"Generate Image (Fast)",description:"Generate an AI image (FLUX Pro v1.1, 1K, ~$0.04).",provider:"fal",model:"fal-ai/flux-pro/v1.1",category:"image",priceCents:4,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro",buildBody:e=>eo({prompt:e.prompt,aspect_ratio:e.aspect_ratio}),tags:["image","flux","legacy"]},{dispatch:"enveloped",id:"generate_image_schnell_card",name:"Generate Image (Cheap)",description:"Cheap, fast FLUX image generation (~$0.01).",provider:"fal",model:"fal-ai/flux/schnell",category:"image",priceCents:1,inputSchema:{type:"object",properties:{prompt:{type:"string"},image_size:{type:"string"},num_inference_steps:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux/schnell",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-schnell",buildBody:e=>{let t={prompt:e.prompt};return e.image_size&&(t.image_size=e.image_size),e.num_inference_steps!==void 0&&(t.num_inference_steps=e.num_inference_steps),e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","flux","schnell","legacy"]},{dispatch:"enveloped",id:"generate_image_recraft_card",name:"Generate Image (Recraft)",description:"Recraft V3 image generation with style control.",provider:"fal",model:"fal-ai/recraft-v3",category:"image",priceCents:5,inputSchema:{type:"object",properties:{prompt:{type:"string"},style:{type:"string"},image_size:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/recraft-v3",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-recraft-v3",buildBody:e=>{let t={prompt:e.prompt};return e.style&&(t.style=e.style),e.image_size&&(t.image_size=e.image_size),t},tags:["image","recraft","legacy"]},{dispatch:"enveloped",id:"generate_image_ideogram_card",name:"Generate Image (Ideogram)",description:"Ideogram V2 image generation, strong with text rendering.",provider:"fal",model:"fal-ai/ideogram/v2",category:"image",priceCents:8,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},style_type:{type:"string"},negative_prompt:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/ideogram/v2",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-ideogram-v2",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.style_type&&(t.style_type=e.style_type),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),t},tags:["image","ideogram","text","legacy"]},X("upscale_image_card","Upscale Image","Upscale an image using ESRGAN.","fal-ai/esrgan","upscale",2,{type:"object",properties:{image_url:{type:"string"},scale:{type:"number"}},required:["image_url"]},{buildBody:e=>{let t={image_url:e.image_url};return e.scale!==void 0&&(t.scale=e.scale),t},tags:["upscale","esrgan"],deprecated:!0,replacementTool:"fal-aura-sr"}),X("edit_image_seed_card","Edit Image (SeedEdit)","Inpaint/edit an image with a prompt using SeedEdit.","fal-ai/bytedance/seededit","image",5,{type:"object",properties:{image_url:{type:"string"},prompt:{type:"string"},seed:{type:"number"}},required:["image_url","prompt"]},{buildBody:e=>{let t={image_url:e.image_url,prompt:e.prompt};return e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","edit","inpaint","seededit"],deprecated:!0,replacementTool:"or-gemini-nano-banana"}),{dispatch:"enveloped",id:"generate_video_tempo_card",name:"Generate Video (Grok)",description:"Generate a video from a text prompt using Grok Imagine Video.",provider:"fal",model:"xai/grok-imagine-video/text-to-video",category:"video",priceCents:30,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/xai/grok-imagine-video/text-to-video",merchantName:"Grok Video via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),t},tags:["video","grok","legacy"]},{dispatch:"enveloped",id:"generate_video_kling_card",name:"Generate Video (Kling)",description:"Generate a video using Kling v1.6 (async, ~$0.40).",provider:"fal",model:"fal-ai/kling-video/v1.6/standard/text-to-video",category:"video",priceCents:40,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/kling-video/v1.6/standard/text-to-video",merchantName:"Kling via fal.ai",deprecated:!0,replacementTool:"fal-kling-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","kling","legacy"]},{dispatch:"enveloped",id:"generate_video_wan_card",name:"Generate Video (Wan)",description:"Generate a video using Wan T2V (async, ~$0.25).",provider:"fal",model:"fal-ai/wan/t2v-1.3b",category:"video",priceCents:25,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/wan/t2v-1.3b",merchantName:"Wan T2V via fal.ai",deprecated:!0,replacementTool:"fal-wan-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","wan","legacy"]},{dispatch:"enveloped",id:"generate_video_minimax_card",name:"Generate Video (MiniMax)",description:"Generate a video using MiniMax (async, ~$0.35).",provider:"fal",model:"fal-ai/minimax/video-01",category:"video",priceCents:35,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/minimax/video-01",merchantName:"MiniMax via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","minimax","legacy"]},{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",deprecated:!0,replacementTool:"fal-trellis-3d",buildBody:e=>{let t={object_prompt:e.object_prompt};return e.style_prompt&&(t.style_prompt=e.style_prompt),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.art_style&&(t.art_style=e.art_style),e.seed!==void 0&&(t.seed=e.seed),t},tags:["3d","mesh","meshy","legacy"]},{dispatch:"enveloped",id:"generate_speech_card",name:"Generate Speech",description:"Text-to-speech using F5-TTS with optional voice cloning.",provider:"fal",model:"fal-ai/f5-tts",category:"tts",priceCents:3,inputSchema:{type:"object",properties:{gen_text:{type:"string",description:"Text to synthesize"},ref_audio_url:{type:"string",description:"Reference audio URL (for voice cloning)"},ref_text:{type:"string",description:"Transcription of ref audio"},remove_silence:{type:"boolean"}},required:["gen_text"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/f5-tts",merchantName:"fal.ai",buildBody:e=>{let t={gen_text:e.gen_text};return e.ref_audio_url&&(t.ref_audio_url=e.ref_audio_url),e.ref_text&&(t.ref_text=e.ref_text),e.remove_silence!==void 0&&(t.remove_silence=e.remove_silence),t},deprecated:!0,replacementTool:"fal-metavoice",tags:["tts","speech","f5-tts","legacy"]},{dispatch:"enveloped",id:"generate_music_tempo_card",name:"Generate Music (Suno)",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,deprecated:!0,replacementTool:"fal-ace-step-music",tags:["music","audio","suno","async","legacy"]},{dispatch:"enveloped",id:"check_music_status_tempo_card",name:"Check Music Status",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}),deprecated:!0,tags:["music","status","suno","legacy"]},{dispatch:"enveloped",id:"query_onchain_prices_card",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly, daily, and weekly granularity.",provider:"allium",model:"allium-prices",category:"llm",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly), '1d' (daily), or '1w' (weekly). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",deprecated:!0,replacementTool:"query_onchain_prices",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:Oc,tags:["onchain","prices","allium","crypto","legacy"]}];function or(e){return Ds.find(t=>t.id===e)}var Lc=1,Uc=["pick_one","fan_out"],jc=["concat","dedupe_by_url","top_k_by_score"],af=8,cf=f.object({type:f.string().min(1),description:f.string().min(1),enum:f.array(f.string()).optional(),default:f.unknown().optional(),minimum:f.number().optional(),maximum:f.number().optional()}),lf=f.object({toolId:f.string().min(1),notes:f.string().min(1)}),uf=f.string().regex(/^[a-z0-9_-]{1,32}$/,"tier key must be 1-32 chars [a-z0-9_-]"),df=f.object({providers:f.array(f.string().min(1)).min(1).max(af),merge:f.enum(jc),maxResults:f.number().int().positive().optional()}),Fc=f.object({mode:f.enum(Uc).default("pick_one"),intro:f.string().min(1),defaultTier:f.string().min(1),tiers:f.record(uf,lf).refine(e=>Object.keys(e).length>0,{message:"must have at least one tier"}),fanOut:df.optional(),guidance:f.string().min(1),inputProperties:f.record(f.string(),cf),required:f.array(f.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"]}),mf=f.object({version:f.literal(Lc),generatedAt:f.string().datetime(),tools:f.record(f.string().regex(Os,"tool name must match MCP naming rules"),Fc).refine(e=>Object.keys(e).length>0,{message:"manifest must have at least one tool"})});var ro=require("child_process"),Kc=require("util"),Gc=E(require("crypto")),ue=E(require("fs")),zc=E(require("os")),qe=E(require("path"));var An=(0,Kc.promisify)(ro.execFile),oo=qe.join(zc.homedir(),".visa-mcp","bin"),sn=qe.join(oo,"Visa CLI"),gf=qe.join(__dirname,"..","native"),Vc="6",qc=qe.join(oo,"visa-keychain.version"),Hc=qe.join(oo,"visa-keychain.sha256");function Bc(e){let t=ue.readFileSync(e);return Gc.createHash("sha256").update(t).digest("hex")}async function Us(){try{if(ue.readFileSync(qc,"utf-8").trim()===Vc&&ue.existsSync(sn)){let r=ue.readFileSync(Hc,"utf-8").trim();if(Bc(sn)!==r)m.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),ue.unlinkSync(sn);else return sn}}catch{}let e=qe.join(gf,"visa-keychain.m");if(ue.existsSync(e)||(e=qe.resolve(__dirname,"..","..","native","visa-keychain.m")),ue.existsSync(e)||(e=qe.resolve(__dirname,"..","native","visa-keychain.m")),!ue.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");ue.mkdirSync(oo,{recursive:!0,mode:448});try{await An("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",sn,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=Bc(sn);return ue.writeFileSync(Hc,t,{mode:384}),ue.writeFileSync(qc,Vc,{mode:384}),sn}async function Wc(e){let t=await Us(),n;try{n=(await An(t,e,{timeout:6e4})).stdout}catch(s){n=s.stdout||"";let i=n.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(s.stderr?.trim()||s.message||"Unknown error")}let r=n.trim();if(r.startsWith("OK:"))return r.slice(3);if(r==="OK")return;let o=r.startsWith("ERROR:")?r.slice(6):"Unknown error";throw new Error(o)}var Ls=null;function re(){return pn()?!0:process.platform!=="darwin"?!1:Ls!==null?Ls:(Ls=!0,!0)}var to="visa-cli",no="attestation-key";async function hf(e){try{await An("security",["delete-generic-password","-s",to,"-a",no],{timeout:5e3})}catch{}await An("security",["add-generic-password","-s",to,"-a",no,"-w",e],{timeout:5e3})}async function js(){try{let{stdout:e}=await An("security",["find-generic-password","-s",to,"-a",no,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function so(){let e=await Wc(["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 hf(n),r}async function Jc(){return await js()!==null}async function Yc(){if(pn())return"mock-public-key-spki";let e=await js();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await Us();return new Promise((n,r)=>{let o=(0,ro.execFile)(t,["public-key"],{timeout:6e4},(s,i)=>{let a=(i||"").trim();if(s){a.startsWith("ERROR:")?r(new Error(a.slice(6))):r(new Error(s.stderr?.trim()||s.message||"Unknown error"));return}a.startsWith("OK:")?n(a.slice(3)):r(new Error(a.startsWith("ERROR:")?a.slice(6):"Unknown error"))});o.stdin.write(e),o.stdin.end()})}async function Rn(e,t){if(pn())return Promise.resolve(Ki());let n=await js();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await Us(),o=["sign",e];return t&&o.push(t),new Promise((s,i)=>{let a=(0,ro.execFile)(r,o,{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:")?s(u.slice(3)):i(new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error"))});a.stdin.write(n),a.stdin.end()})}async function io(){try{await An("security",["delete-generic-password","-s",to,"-a",no],{timeout:5e3})}catch{}try{await Wc(["delete-key"])}catch{}}var yf=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],_f=[...yf.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 Vs(e,t=_f){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=Fs(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(Fs(r.match.provider)))&&r.match.keywords.every(o=>n.includes(Fs(o))))return r.targetToolId;return null}function Fs(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}var sr={generate_image:{intro:'Generate an AI image from a text prompt \u2014 useful for hero shots, marketing assets, social posts, blog covers, app mockups, or any time the user asks for art, a logo, an icon, a thumbnail, or "a picture of \u2026". From $0.01 (fast) to $0.06 (pro), returns a hosted PNG/JPG URL. Default tier: balanced ($0.04, 1K, ~10s).',tiers:{balanced:{toolId:"fal-flux-pro",notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",notes:"Recraft V3 \u2014 vector/flat/illustration styles"}},guidance:"If the user didn't specify a tier, pick 'balanced' unless the prompt clearly signals otherwise (text \u2192 text_heavy, logo/icon \u2192 vector, quick test \u2192 fast, hero/print \u2192 pro).",inputProperties:{prompt:{type:"string",description:"Text description of the image to generate."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9", "1:1", "9:16".',default:"16:9"}},required:["prompt"]},generate_video:{intro:'Generate a short AI video from a text prompt \u2014 useful for product demos, social clips, mood reels, ad concepts, or any "make me a video of \u2026" request. $0.10\u2013$0.40 per ~6s clip depending on tier. Async: returns a request_id; use execute_tool with tool_id "check_fal_status_card" to resolve it (60\u2013180s).',tiers:{balanced:{toolId:"fal-minimax-video",notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",notes:"Kling \u2014 highest quality, cinematic"}},guidance:'Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate and are processed asynchronously. The response includes a request_id and model_path. Poll with execute_tool using tool_id "check_fal_status_card" and params {request_id, model_path}. Do not poll more than once per 30 seconds.',inputProperties:{prompt:{type:"string",description:"Text description of the video scene."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9" or "9:16".',default:"16:9"}},required:["prompt"]},generate_music:{intro:'Generate an original music track from a prompt via ACE-Step. ~$0.02 for the default 60s track. Use for songs, backing tracks, jingles, vocal music, instrumental music, or any "make a song/music/track" request. Takes ~60-90s and may return a request_id to poll with check_fal_status_card. For SFX, chimes, ambient beds, or TTS, use generate_audio instead.',tiers:{ace_step:{toolId:"fal-ace-step-music",notes:"ACE-Step \u2014 prompt-to-music with vocals or instrumentals"}},guidance:"Use for songs and music tracks. Takes ~60-90s and may return a request_id to poll with check_fal_status_card. For sound effects, chimes, ambient beds, or TTS, use generate_audio instead.",inputProperties:{prompt:{type:"string",description:"Musical style, mood, instruments, subject, and lyrics direction."},instrumental:{type:"boolean",description:"True for instrumental music with no vocals; false for vocal tracks.",default:!1},duration:{type:"number",description:"Duration in seconds.",default:60}},required:["prompt"]},generate_audio:{intro:'Generate sound effects from a text prompt (sfx tier \u2014 default), or voice-cloned speech from text + a reference audio URL (tts tier). $0.03\u2013$0.04. Use for SFX, chimes, UI sounds, ambient audio (default sfx), or voice cloning when a reference audio URL is available (pass tier:"tts"). Default tier is sfx; pass tier:"tts" for voice cloning.',tiers:{sfx:{toolId:"fal-stable-audio",notes:"Stable Audio \u2014 sound effects and ambient from a prompt"},tts:{toolId:"fal-metavoice",notes:"MetaVoice \u2014 voice cloning TTS (requires a voice sample URL)"}},guidance:'Default tier is sfx: pass prompt describing the sound. For tts (voice cloning): pass tier:"tts" + text + audio_url.',inputProperties:{prompt:{type:"string",description:"Description of sound to generate (sfx tier, default)."},text:{type:"string",description:"Text to speak aloud (tts tier)."},audio_url:{type:"string",description:"URL of a voice sample to clone (tts tier, required for voice cloning)."}},required:[]},generate_3d:{intro:"Generate a 3D mesh (GLB) from an image URL via Trellis. ~$0.08, ~30\u201360s. Use when the user shares an image and asks for a 3D model, asset, AR-ready mesh, or game-ready GLB.",tiers:{trellis:{toolId:"fal-trellis-3d",notes:"Trellis \u2014 image-to-3D, returns a GLB mesh URL"}},guidance:"Pass an image URL. Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{image_url:{type:"string",description:"URL of the image to convert to a 3D model."}},required:["image_url"]},upscale_image:{intro:'Upscale an image to 4\xD7 resolution via Aura SR (preserves detail without hallucination). ~$0.03. Use whenever the user shares a low-res image and asks to "upscale", "make this higher resolution", "4x this", "enhance", or to print/export at larger size.',tiers:{aura:{toolId:"fal-aura-sr",notes:"Aura SR \u2014 default; preserves detail without hallucination"}},guidance:"Pass the existing image URL. Returns an upscaled version.",inputProperties:{image_url:{type:"string",description:"URL of the image to upscale."}},required:["image_url"]},transcribe_audio:{intro:'Transcribe speech in an audio or video file (URL) to text via OpenAI Whisper. ~$0.02 per file, multilingual, handles long files. Use whenever the user asks to "transcribe this", "what does this audio say", "make subtitles", "convert this to text", or shares an audio/video URL with no other clear intent.',tiers:{whisper:{toolId:"fal-whisper",notes:"OpenAI Whisper \u2014 fast, multilingual"}},guidance:"Pass the URL. Returns the transcript text.",inputProperties:{audio_url:{type:"string",description:"URL of the audio or video file to transcribe."}},required:["audio_url"]},run_llm:{intro:"Run a text prompt through a different LLM (GPT-4o-mini, Claude Sonnet, DeepSeek R1/V3, Perplexity Sonar with web search, or Llama 70B). Token-metered, typically ~$0.01\u2013$0.10 per call. Use for: web-grounded answers (search tier), second-opinion reasoning (reasoning tier), code generation in a different family (coding tier), deep math/logic (deep_reasoning tier), or fast cheap text cleanup (fast tier). Pair with batch for multi-model councils.",tiers:{fast:{toolId:"or-gpt-4o-mini",notes:"GPT-4o Mini. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",notes:"Claude Sonnet. Strong reasoning, long-context. Warn user it is materially pricier than `fast`."},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 an(e,t,n){if(!Xc(e))return wf(e,n);let r=Zc[e];if(!r)return e;let o=Object.keys(r.tiers),s=t||o[0],i=xf(e,s,n);return i||Cf(e,r,s,o)}function wf(e,t){return Vs({requestedTool:e,intentText:t})??e}function xf(e,t,n){return Vs({requestedTool:e,metaTool:e,tier:t,intentText:n})}function Cf(e,t,n,r){let o=t.tiers[n];if(!o)throw new Error(`Unknown tier '${n}' for ${e}. Valid tiers: ${r.join(", ")}`);return o.toolId}var Zc=sr;function Xc(e){return e in Zc}var ir=Object.keys(sr);function qs(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function Qc(e=process.env){return qs(e)!==null}var Dl=require("child_process"),de=E(require("crypto")),Me=E(require("fs")),dr=E(require("os")),So=E(require("path"));var el=!1;async function ar(e,t,n){try{return await t()}catch(r){if(!(r.message==="Invalid signature"||r.code==="ATTESTATION_KEY_DRIFT"||r.error_code==="ATTESTATION_KEY_DRIFT"||r.name==="AttestationDriftError")||!re())throw r;if(m.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(el)throw m.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;el=!0,m.info("attestation:starting-browser-recovery");try{let s=await n();if(!s.success)throw m.error("attestation:browser-recovery-failed",{message:s.message}),r;let i=await so();return await e.registerAttestationKey(i),await e.setBiometricPreference({required:!0}),m.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),m.info("attestation:key-reregistered-after-recovery"),await t()}catch(s){throw m.error("attestation:recovery-failure",{error:s.message}),r}}throw r}}var tl="2.3.0-rc.0";function Hs(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function co(e,t,n){let r=process.env[e];if(r!==void 0)return{value:n==="opt-in"?r==="true":r!=="false",source:{kind:"env",var:e}};let o=Gr(t);return o!==void 0?{value:o,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function we(e){return e==null?"\u2014":e?"yes":"no"}function lo(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function kf(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function Tf(){let e=process.env.VISA_CREDIT_SESSION_CAP_CENTS;if(e!==void 0){let n=Number(e);if(Number.isFinite(n)&&n>=10&&n<=1e4)return{value:Math.floor(n),source:{kind:"env",var:"VISA_CREDIT_SESSION_CAP_CENTS"}}}let t=ks("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:xs,source:{kind:"default"}}}async function cr(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(B){n=B?.message||"unknown error"}let r=[],o=process.env.VISA_AUTH_URL,s=Cs("auth.serverUrl"),i=he(),a=o!==void 0&&o!==""?{kind:"env",var:"VISA_AUTH_URL"}:s!==void 0?{kind:"settings"}:{kind:"default"};r.push({key:"auth.serverUrl",value:i,formatted:i,source:a,hint:a.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),r.push({key:"account.enrolled",value:t?.enrolled??null,formatted:we(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:we(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:we(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:re(),formatted:we(re()),source:{kind:"device"}});let c=t?.spendingControls,u=c?c.max_transaction_amount??c.maxTransactionAmount??null:null,d=c?c.daily_limit??c.dailyLimit??null:null;r.push({key:"spending.maxPerTxn",value:u,formatted:lo(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:lo(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:lo(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:lo(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 g=t?.cards?.find(B=>B.isDefault)??t?.cards?.[0];g&&r.push({key:"cards.default",value:{brand:g.brand??null,last4:g.last4},formatted:`${g.brand||"card"} \u2022\u2022\u2022\u2022 ${g.last4}`,source:{kind:"server"}});let p=Tf();r.push({key:"credit.sessionCapCents",value:p.value,formatted:kf(p.value),source:p.source});let _=lc();_.length>0&&r.push({key:"settings.retired",value:_.map(B=>B.key),formatted:_.map(B=>B.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${_.map(B=>`visa-cli config unset ${B.key}`).join(" && ")}`});let h=co("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:h.value,formatted:we(h.value),source:h.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let S=co("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:S.value,formatted:we(S.value),source:S.source});let I=Ue(),$;process.env.VISA_CLI_NO_UPDATE_CHECK?$={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?$={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?$={kind:"env",var:"NODE_ENV"}:$={kind:"default"},r.push({key:"ui.updateCheck",value:!I,formatted:we(!I),source:$});let C=co("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:C.value,formatted:we(C.value),source:C.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let k=co("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:k.value,formatted:we(k.value),source:k.source});let q=process.env.VISA_DRY_RUN,W=Qc();if(r.push({key:"tools.dryRun",value:W,formatted:we(W),source:q===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:tl,formatted:tl,source:{kind:"default"}}),e.includeDev){let B=process.env.VISA_MOCK_KEYCHAIN,ct=ut();r.push({key:"dev.mockKeychain",value:ct,formatted:we(ct),source:Hs("VISA_MOCK_KEYCHAIN",!!B),hint:Lo()});let ne=process.env.VISA_MOCK_TOUCHID,pe=pn();r.push({key:"dev.mockTouchid",value:pe,formatted:we(pe),source:Hs("VISA_MOCK_TOUCHID",!!ne),hint:Lo()});let lt=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!lt,formatted:we(!!lt),source:Hs("VISA_CLI_DEBUG",!!lt)})}return{entries:r,statusError:n}}function Ef(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 nl(e,t={}){if(e.length===0)return"";let n=Math.max(...e.map(s=>s.key.length)),r=Math.max(...e.map(s=>s.formatted.length)),o=[];for(let s of e){let i=s.key.padEnd(n+2),a=s.formatted.padEnd(r+2);o.push(`${i}${a}(${Ef(s.source)})`),t.verbose&&s.hint&&o.push(` ${"\u21B3".padStart(n)} ${s.hint}`)}return o.join(`
122
- `)}function rl(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 ol(e){if(e<=0)return null;let t=(e/100).toFixed(2);return{_credits_prompt:{message:`You've got $${t} in free credits \u2014 enough for about ${Math.floor(e/6)} images. Try something now, or save them for later.`,balanceUsd:t,examples:[{tool:"generate_image",cost:"$0.06",what:"an AI image"},{tool:"run_llm",cost:"token-priced",what:"a quick model call"},{tool:"generate_music",cost:"$0.02",what:"a music track"}]}}}var Tt=require("fs"),il=require("os"),Bs=require("path"),Af=(0,Bs.join)((0,il.homedir)(),".visa-mcp"),sl=(0,Bs.join)(Af,"mcp-session-budget.json");function uo(){try{(0,Tt.existsSync)(sl)&&(0,Tt.unlinkSync)(sl)}catch{}}var Gs=require("crypto"),Pe=E(lr()),cn=null,xe=0,In=0,ve=0,Et=null,zs=null,Ws=null,po=Promise.resolve();function Gf(e){return Number((0,Pe.fromCents)(e))}function ll(e){return(0,Pe.toCents)((0,Pe.micros)(BigInt(e)))}function cl(e){return(0,Pe.toWire)((0,Pe.fromCents)(e))}function Ks(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function mo(e){return typeof e=="string"&&/^\d+$/.test(e)}var zf=43,Wf=new RegExp(`^[A-Za-z0-9_-]{${zf}}$`);function Jf(e){return typeof e=="string"&&Wf.test(e)}function Yf(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||cn&&e.session_id!==cn||typeof e.nonce!="string"||e.nonce.length===0||!Jf(e.server_signature)||!Ks(e.cumulative)||!Ks(e.remaining)||!Ks(e.delta)||e.cumulative<xe||ve>0&&e.cumulative>ve||ve>0&&e.remaining>ve||e.cumulative_micros!==void 0&&!mo(e.cumulative_micros)||e.remaining_micros!==void 0&&!mo(e.remaining_micros)||e.delta_micros!==void 0&&!mo(e.delta_micros)||e.reserved_micros!==void 0&&!mo(e.reserved_micros))}function st(e){cn=e,xe=0,In=0,ve=0,Et=null,zs=null,Ws=null,po=Promise.resolve()}function ur(e){ve=Math.max(0,Math.floor(e))}function Js(){return cn}function Ys(e){if(!cn)return null;let t=xe+In;return ve>0&&t>ve&&(t=ve),{session_budget_id:cn,cumulative_micros:Gf(t),nonce:(0,Gs.randomUUID)(),idempotency_key:e||(0,Gs.randomUUID)()}}function Zs(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 Yf(r)?(xe=Math.max(xe,r.cumulative),In=0,Et=r,r):null}function ul(){return Et}function Xs(e){let t=ll(e.cumulative_micros);xe=Math.max(xe,t),In=0;let n={status:"accepted",session_id:e.session_budget_id,cumulative:xe,remaining:Math.max(0,ve-xe),delta:0,cumulative_micros:cl(xe),remaining_micros:cl(Math.max(0,ve-xe)),delta_micros:"0",nonce:e.nonce};return Et=n,n}function Qs(e){if(!e||typeof e!="object")return;let t=e.cumulative_micros;if(typeof t!="string"||!/^\d+$/.test(t))return;let n;try{n=BigInt(t)}catch{return}if(n<0n)return;let r=(0,Pe.toCents)((0,Pe.micros)(n));if(!Number.isFinite(r)||r<0)return;zs=t;let o=e,s=typeof o.session_id=="string"?o.session_id:cn??"";Et?(typeof o.remaining_micros=="string"&&/^\d+$/.test(o.remaining_micros)&&(Et.remaining_micros=o.remaining_micros),typeof o.charged_micros=="string"&&/^\d+$/.test(o.charged_micros)&&(Et.delta_micros=o.charged_micros)):Et={session_id:s,cumulative:r,remaining:0,delta:0,nonce:typeof o.transaction_id=="string"?o.transaction_id:"",remaining_micros:typeof o.remaining_micros=="string"&&/^\d+$/.test(o.remaining_micros)?o.remaining_micros:void 0,delta_micros:typeof o.charged_micros=="string"&&/^\d+$/.test(o.charged_micros)?o.charged_micros:void 0}}function dl(e){let t=e.receipt??null;Ws={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:ll(e.voucher.cumulative_micros),estimatedCumulativeCents:fo(),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 ml(){return Ws}function pl(){return xe}function fl(){return zs}function fo(){let e=xe+In;return ve>0&&e>ve&&(e=ve),e}function gl(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return po=po.then(()=>{In+=t}),po}var Zf=10,Xf=1,J=null,hl=Promise.resolve();function ei(e){let t=hl.catch(()=>{}).then(e);return hl=t.then(()=>{},()=>{}),t}var me=class extends Error{balanceCents;minRequiredCents;constructor(t,n){super(`Prepaid balance is $${(t/100).toFixed(2)}; at least $${(n/100).toFixed(2)} required to open a credit session. Top up via the buy_credits tool first.`),this.name="InsufficientBalanceError"}};async function ti(e,t,n){return ei(()=>yl(e,t,n))}async function yl(e,t,n){if(uo(),J&&new Date(J.expiresAt).getTime()>Date.now())return Js()!==J.budgetId&&(st(J.budgetId),ur(J.totalCents)),m.info("mcp-session:active-hit",{budgetId:J.budgetId,tool:n.toolName,remainingEstimatedCents:J.totalCents-fo()}),{budgetId:J.budgetId,isFresh:!1,totalCents:J.totalCents,requestedCapCents:J.totalCents,appliedCapCents:J.totalCents,clampedReason:null};J&&(J=null,st(null));let r=await e.getBalance();if(!r.success)throw new Error(`Could not read balance: ${r.error||"unknown error"}`);let o=n.sessionKind??"explicit",s=o==="one_shot"?Xf:Zf,i=Math.max(s,Math.ceil(n.minRequiredCents??s));if(r.balanceCents<i)throw new me(r.balanceCents,i);let a=n.capCentsOverride??mc(),l=Math.min(a,r.balanceCents),c=l<a?"balance":null,u=await t("session_create",l,"Visa CLI Session",`open credit-model session with $${(l/100).toFixed(2)} cap`,n.userContext),d=await e.createSessionBudget({total_cents:l,session_kind:o,...u?{attestation:u}:{}});if(!d.success||!d.budget){let p=d.error||"unknown error";throw new Error(`Failed to open credit session: ${p}`)}let g={budgetId:d.budget.id,expiresAt:d.budget.expiresAt,totalCents:d.budget.totalCents,createdAt:d.budget.createdAt};return J=g,st(g.budgetId),ur(g.totalCents),m.info("mcp-session:opened",{budgetId:g.budgetId,capCents:g.totalCents,requestedCapCents:a,clampedReason:c,sessionKind:o,expiresAt:g.expiresAt,tool:n.toolName}),{budgetId:g.budgetId,isFresh:!0,totalCents:g.totalCents,requestedCapCents:a,appliedCapCents:g.totalCents,clampedReason:c}}async function _l(e,t,n){return ei(async()=>{let o=At()?await vl(e):null,s=await yl(e,t,n);return{budgetId:s.budgetId,totalCents:s.totalCents,closedPrevious:o,requestedCapCents:s.requestedCapCents,appliedCapCents:s.appliedCapCents,clampedReason:s.clampedReason}})}async function vl(e){let n=At()?.budgetId??Js(),r=!1,o,s;if(n)try{let i=await e.closeSession(n);r=!!i?.success,typeof i?.finalCumulativeCents=="number"&&(o=i.finalCumulativeCents),typeof i?.finalCumulativeMicros=="string"&&(s=i.finalCumulativeMicros)}catch(i){m.warn("mcp-session:close-server-failed",{budgetId:n,error:i?.message||String(i)})}return uo(),J=null,st(null),{closedServerSide:r,budgetId:n,finalCumulativeCents:o,finalCumulativeMicros:s}}async function go(e){return ei(()=>vl(e))}function At(){return uo(),J?new Date(J.expiresAt).getTime()<=Date.now()?(J=null,st(null),null):{budgetId:J.budgetId,totalCents:J.totalCents,lastReceiptCumulative:pl(),lastReceiptCumulativeMicros:ul()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:fl(),estimatedCumulative:fo(),lastToolSpend:ml(),expiresAt:J.expiresAt}:null}var Sl=E(lr()),bl=10000n;function Qf(e){return e<=0n?0:Number((e+bl-1n)/bl)}function wl(e){return Qf((0,Sl.fromUsd)(e))}var ho="Buying credits currently requires local biometric attestation from a macOS Touch ID-capable CLI/MCP process. This device cannot create the required attestation, so no card charge was attempted. Credits are account-level, so you can top up this account from any interactive Touch ID-capable CLI, then use the balance from this remote server. For unattended workloads, scoped API keys with daily caps are also supported.",xl="Tell the user that buying credits requires a local Touch ID-capable CLI/MCP process today. Credits are account-level: suggest topping up the same account from any interactive Touch ID-capable CLI, then continuing on this remote server. For unattended workloads, scoped API keys with daily caps are also supported. Do not retry buy_credits from this process; it cannot produce the required card-charge attestation.";var Cl=Promise.resolve(),kl=!1;function wo(e){let t=Cl.catch(()=>{}).then(e);return Cl=t.then(()=>{},()=>{}),t}async function Ll(e){let t=await ti(P,ze,{toolName:e.toolId,userContext:e.userContext}),n=Ys(e.idempotencyKey);if(!n)throw new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await ig(),o,s,i=async()=>P.shortcutWithSession(e.toolId,n,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);try{try{({data:o,voucherReceiptHeader:s}=await i())}catch(u){if(u instanceof Vt){let d=Math.min(Math.max(u.retryAfterSecs,0),5)*1e3;m.warn("mcp-session:lock-contended-retrying",{tool:e.toolId,retryAfterSecs:u.retryAfterSecs}),await new Promise(g=>setTimeout(g,d)),{data:o,voucherReceiptHeader:s}=await i()}else throw u}}catch(u){if(u instanceof _n){if(m.warn("mcp-session:server-invalidated-budget",{code:u.code,budgetId:u.budgetId??t.budgetId,tool:e.toolId}),await go(P),process.env.VISA_REQUIRE_EXPLICIT_SESSION==="true")throw new Error(`Your session was closed by another process (${u.code}). Restart MCP or run start_session again.`);return kl||(kl=!0,console.error(`[visa-cli] Your session was closed by another process; reopened automatically as pay-as-you-go.
123
- To require an explicit session approval instead, set VISA_REQUIRE_EXPLICIT_SESSION=true.`)),m.info("mcp-session:falling-back-to-payg",{code:u.code,tool:e.toolId}),Ul(e)}throw u instanceof Vt?(m.warn("mcp-session:lock-contended-give-up",{tool:e.toolId}),new Error("Another paid call is currently in progress on this session. Wait a moment and try again.")):u}let a=Zs(s)??(n?Xs(n):null);if(Qs(o?.receipt_v2),await gl(e.estimatedAmountCents),dl({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),Fl(o))return o;let l=await jl();if(e.idempotencyKey&&Vl(o,l,e.idempotencyKey))return o;let c=l?vo(l):null;return ql(o,r,c)}function Be(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function oi(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(oi).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${oi(r)}`).join(",")}}`}function eg(e,t,n,r){let o=de.createHash("sha256").update(`${n}:${oi(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${o}`}function tg(e,t){return`${e}:${t}`}function ng(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 Tl(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,o=He(r),s=o!==null?o.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=ng(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),l=i!=null?String(i):a;return{batch_id:e,item_id:tg(e,t),index:t,...l!==void 0?{transaction_id:l}:{},...a!==void 0?{ledger_id:a}:{},...s?{amountMicros:s,amount_micros:s,cost_micros:s}:{}}}async function Ul(e){let t=Math.max(1,Math.ceil(e.estimatedAmountCents)),n=await P.getBalance();if(!n.success)throw new Error(`Could not read balance: ${n.error||"unknown error"}`);if(n.balanceCents<t)throw new me(n.balanceCents,t);let r=t,o=vo(n),s=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(r/100).toFixed(2)})`,i=await ze("session_create",r,"Visa CLI Session",s,e.userContext),a=await P.createSessionBudget({total_cents:r,session_kind:"one_shot",...i?{attestation:i}:{}});if(!a.success||!a.budget)throw new Error(`Failed to open on-demand session: ${a.error||"unknown error"}`);let l=a.budget.id;st(l),ur(a.budget.totalCents),m.info("on-demand-session:opened",{budgetId:l,capCents:a.budget.totalCents,tool:e.toolId});try{let c=Ys(e.idempotencyKey);if(!c)throw new Error(`Internal: mintVoucher returned null after on-demand session-open ${l}`);let{data:u,voucherReceiptHeader:d}=await P.shortcutWithSession(e.toolId,c,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(Zs(d)||Xs(c),Qs(u?.receipt_v2),Fl(u))return u;let g=await jl();if(e.idempotencyKey&&Vl(u,g,e.idempotencyKey))return u;let p=g?vo(g):null;return ql(u,o,p)}finally{try{await P.closeSession(l)}catch(c){m.warn("on-demand-session:close-failed",{budgetId:l,error:c?.message||String(c)})}st(null),m.info("on-demand-session:closed",{budgetId:l,tool:e.toolId})}}async function It(e){return wo(async()=>At()?Ll(e):Ul(e))}function xo(){return he()}var P=new Se(()=>U.getSessionToken());function He(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function vo(e){return He(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function rg(e){if(e<0n&&(e=0n),e>=1000000n){let r=(e+5000n)/10000n,o=r/100n,s=r%100n;return`$${o.toString()}.${s.toString().padStart(2,"0")}`}let t=e%1000000n;return t===0n?"$0.00":`$0.${t.toString().padStart(6,"0").replace(/0+$/,"")}`}function og(e){let t=He(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=He(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=He(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function yo(e,t="INVALID_TOOL_PARAMS"){return{success:!1,error_code:t,code:t,error:e,message:e}}function sg(e){return{success:!1,error_code:"TOOL_EXECUTION_FAILED",code:"TOOL_EXECUTION_FAILED",error:e.message||"Tool execution failed.",message:e.message||"Tool execution failed.",tool_id:e.toolId,surface:e.surface,merchantName:e.merchantName,amount:e.amount,payment_finalized:!1,charged:!1}}async function ig(){try{let e=await P.getBalance();return e.success?vo(e):null}catch{return null}}async function jl(){try{let e=await P.getBalance();return e.success?e:null}catch{return null}}function Fl(e){if(!e||e.success===!1)return!1;let t=He(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=He(e.amountMicros??e.amount_micros??e.charged_micros),r=t??n;if(r===null||r<=0n)return!1;let o=r.toString();return e.amountMicros??=o,e.amount_micros??=o,e.charged_micros??=o,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),!0}function Vl(e,t,n){if(!e||e.success===!1||!t||!Array.isArray(t.ledger))return!1;let r=t.ledger.find(a=>a.idempotencyKey===n);if(!r)return!1;let o=He(r.deltaMicros)??BigInt(r.deltaCents)*10000n,s=o<0n?-o:o;if(s<=0n)return!1;let i=s.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(s)/1e6),!0}function ql(e,t,n){if(!e||e.success===!1||t===null||n===null)return e;let r=t-n;if(r<=0n)return e;let o=r.toString();return e.amountMicros??=o,e.amount_micros??=o,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),e}var ag="2.3.0-rc.0",Bb=["","","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(`
124
- `);function Ke(e){if(!e||typeof e!="string"||uc())return;let t=Hn(e);if(!t)return;let n=Qo();if(n.headless){m.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`);return}let r=ia(t,xo());if(!r){m.info(`Browser auto-open skipped (non-internal host). URL: ${t}`);return}let o=ca(r);if(!o){m.info(`No browser command for platform "${dr.platform()}". URL: ${r}`);return}(0,Dl.execFile)(o.cmd,o.args,s=>{s&&m.warn(`Browser open failed: ${s.message}. URL: ${r}`)})}async function Ce(e){return ar(P,e,Jl)}var Hl="get_cards",Bl="set_default_card";function cg(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 '${Hl}' to see enrolled cards and '${Bl}' to switch, then retry the original request.`}function lg(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 '${Hl}' to see enrolled cards and '${Bl}' to switch. Do not retry automatically.`}function Ge(e,t){let n=e.retryable?cg(e.code,e.retryAfter):lg(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 $n=null,ug=3e4;function Kl(){$n=null}var Rt=class extends Error{constructor(n){super(`${bo()} attestation is required for this action, but it is not available in this MCP process. `+si());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function Co(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. `+si()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function dg(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:ho,agent_guidance:xl}}function bo(){return process.platform==="darwin"?"Touch ID":"local biometric"}function si(){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 ko(e){return typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0}async function mg(e){let t=Date.now();if($n&&$n.expiresAt>t)return{required:$n.required,hasRegisteredKey:$n.hasRegisteredKey};try{let n=await P.getStatus(e),r=n.attestationRequired!==!1,o=ko(n);return $n={required:r,hasRegisteredKey:o,expiresAt:t+ug},{required:r,hasRegisteredKey:o}}catch{return{required:!0,hasRegisteredKey:!0}}}async function ze(e,t,n,r,o,s){if(!s?.forceRequired){let i=await mg(o);if(!i.required){m.info("attestation:skipped-by-server-policy",{context:e});return}if(!i.hasRegisteredKey){m.info("attestation:skipped-no-registered-key",{context:e});return}}if(!re())throw m.warn("attestation:unavailable",{context:e}),new Rt(e);m.info("attestation:attempt",{context:e,amount:t,merchant:n});try{let{nonce:i}=await P.getAttestationChallenge(),a=Buffer.from(JSON.stringify({nonce:i,amount:t,merchant:n,context:e})).toString("base64");m.info("touchid:prompt",{context:e,amount:t,merchant:n});let l=await Rn(a,r);return m.info("attestation:success",{context:e,amount:t,merchant:n}),{signature:l,nonce:i,amount:t,merchant:n}}catch(i){throw m.error("attestation:failure",{context:e,amount:t,merchant:n,error:i.message}),i}}var El="[dry-run] https://placeholder.visa-cli.dev/image.png",pg=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"]),fg=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 gg(e,t){return t==="run_llm"||e.startsWith("or-")?"llm":t==="generate_image"||pg.has(e)?"image":t==="generate_video"||fg.has(e)?"video":null}function hg(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function yg(e){return e==="llm"?"OpenRouter":"fal.ai"}function Pn(e,t,n,r){let o={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:yg(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${hg(n)}`;return{...o,content:i,data:{content:i,model:t,dry_run:!0}}}return{...o,urls:[El],data:{[e==="video"?"videoUrl":"imageUrl"]:El,metadata:{dry_run:!0}}}}async function ni(e){let t=e.mode??"mock",n=t==="preflight"?"/v1/telemetry/preflight":"/v1/telemetry/dry-run",r=t==="preflight"?"preflight":null;try{await P.emitTelemetry([{id:de.randomUUID(),timestamp:new Date().toISOString(),tool_name:e.toolName,user_prompt:e.userContext??"",tool_params:JSON.stringify(e.toolParams),result_success:!0,result_error:null,result_json:JSON.stringify(e.result),payment_rail:r,payment_amount:0,payment_currency:"USD",merchant_name:e.result.merchantName,transaction_id:e.result.transactionId,tx_hash:null,protocol:null,http_status:200,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",event_kind:"mcp_tool",endpoint:n,resolved_model:e.resolvedModel,session_budget_id:null}])}catch(o){m.warn("dry_run:telemetry_failed",{tool:e.toolName,error:o?.message||String(o),mode:t})}}var _g="https://openrouter.ai/api/v1/chat/completions",vg="openrouter/free",bg=50,Sg=15e3;function wg(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 xg(e,t,n){let r=process.env.OPENROUTER_API_KEY;if(!r)return m.warn("preflight:no_openrouter_key_falling_back_to_mock",{tool:e}),{result:Pn("llm",e,t,n),degraded:!0,resolvedModel:null};let o=wg(t),s;try{s=await jt(_g,{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:vg,messages:[{role:"user",content:o}],max_tokens:bg}),timeoutMs:Sg})}catch(u){return m.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:Pn("llm",e,t,n),degraded:!0,resolvedModel:null}}if(!s.ok){let u=await s.text().catch(()=>"");return m.warn("preflight:openrouter_http_error_falling_back_to_mock",{tool:e,status:s.status,bodyExcerpt:u.slice(0,200)}),{result:Pn("llm",e,t,n),degraded:!0,resolvedModel:null}}let i;try{i=await s.json()}catch(u){return m.warn("preflight:openrouter_invalid_json_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:Pn("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 To(e,t,n,r){let o=qs();if(!o)return null;let s=gg(e,r);if(!s)return null;let i=Date.now();if(o==="mock"){let c=Pn(s,e,t,r);return await ni({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:c,userContext:n,startedAt:i,mode:"mock"}),m.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:s,mode:o}),c}if(s!=="llm"){m.warn("preflight:not_supported_for_kind_falling_back_to_mock",{tool:e,kind:s});let c=Pn(s,e,t,r);return await ni({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 xg(e,t,r);return await ni({toolName:r??e,resolvedModel:l??(r&&r!==e?e:null),toolParams:t,result:a,userContext:n,startedAt:i,mode:"preflight"}),m.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:s,mode:o}),a}async function it(e,t,n){let r=await P.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 at(e){return wl(e.amount)}function Cg(){return So.join(dr.homedir(),".visa-mcp","allium-results")}var Kb=16*1024,Gb=50*1024*1024;function kg(){let e=Cg();try{if(!Me.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=Me.readdirSync(e),n=0,r=0;for(let o of t)try{let s=Me.statSync(So.join(e,o));s.isFile()&&(n+=s.size,r++)}catch{}return{file_count:r,size_bytes:n,path:e}}catch(t){return m.warn("allium:disk_usage_error",{error:t.message}),{file_count:0,size_bytes:0,path:e}}}var Al=3600*1e3,ri=0;function Tg(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function mr(e){if(!dc()&&!(Date.now()<ri))try{if(!await U.getSessionToken())return;await P.feedSubmit({prompt:e.prompt,tool:e.tool,media_url:e.mediaUrl,media_type:e.mediaType,cost:e.cost,transaction_id:e.transactionId,auto:!0,...e.userContext&&{user_context:e.userContext}}),m.info("feed:submitted",{tool:e.tool,mediaType:e.mediaType,transactionId:e.transactionId})}catch(t){if(Tg(t)){let n=ri===0;ri=Date.now()+Al,n&&m.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:Al});return}m.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function Eg(e,t){let n=(e.state||"").trim().toUpperCase(),r=(e.county||"").trim(),o=(e.start_date||"").trim(),s=(e.end_date||o).trim();if(!/^[A-Z]{2}$/.test(n))throw new Error('state must be a 2-letter US state code (e.g. "VA").');if(!r)throw new Error("county is required.");if(!/^\d{4}-\d{2}$/.test(o))throw new Error('start_date must be YYYY-MM (e.g. "2025-08").');if(s&&!/^\d{4}-\d{2}$/.test(s))throw new Error("end_date must be YYYY-MM.");let i="Visa SMI",a=.1,l=`Pay $0.10 to ${i} for SMI data (${n} / ${r})`;m.info("payment:attempt",{tool:"get_visa_smi",amount:a,merchant:i});try{return await Ce(async()=>{let c=await ze("get_visa_smi",a,i,l),u=await P.getVisaSmi({state:n,county:r,start_date:o,end_date:s,attestation:c,idempotencyKey:de.randomUUID()},t);return u.success?m.info("payment:success",{tool:"get_visa_smi",merchant:i,charged_cents:u.charged_cents}):m.warn("payment:declined",{tool:"get_visa_smi",merchant:i,message:u.error}),u})}catch(c){if(c instanceof ce)return m.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:c.code,retryable:c.retryable}),Ge(c,{amount:a,merchantName:i,description:"Visa SMI data"});throw m.error("payment:failure",{tool:"get_visa_smi",merchant:i,error:c.message}),c}}async function Ag(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 To("generate_image_card",e,t);if(n)return n;let r=await it("generate_image_card",void 0,t),o=de.randomUUID();m.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await Ce(async()=>{let s;try{s=await It({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:at(r),userContext:t,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof me)return Be(i);throw i}return m.info("payment:success",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Ke(i)),mr({prompt:e.prompt,tool:"generate_image_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):m.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof ce)return m.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Ge(s,r);throw m.error("payment:failure",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function Rg(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 To("generate_image_fast_card",e,t);if(n)return n;let r=await it("generate_image_fast_card",void 0,t),o=de.randomUUID();m.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await Ce(async()=>{let s;try{s=await It({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:at(r),userContext:t,timeoutMs:6e4,idempotencyKey:o})}catch(i){if(i instanceof me)return Be(i);throw i}return m.info("payment:success",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Ke(i)),mr({prompt:e.prompt,tool:"generate_image_fast_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):m.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof ce)return m.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Ge(s,r);throw m.error("payment:failure",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function Ig(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 To("generate_video_tempo_card",e,t);if(n)return n;let r=await it("generate_video_tempo_card",void 0,t),o=de.randomUUID();m.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await Ce(async()=>{let s;try{s=await It({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:at(r),userContext:t,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof me)return Be(i);throw i}return m.info("payment:success",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Ke(i)),mr({prompt:e.prompt,tool:"generate_video_tempo_card",mediaUrl:s.urls[0],mediaType:"video",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):m.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof ce)return m.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Ge(s,r);throw m.error("payment:failure",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function $g(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 it("generate_music_tempo_card",void 0,t),r=de.randomUUID();m.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await Ce(async()=>{let o;try{o=await It({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:at(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(s){if(s instanceof me)return Be(s);throw s}return m.info("payment:success",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),o.urls?.length&&o.status!=="processing"?(o.urls.forEach(s=>Ke(s)),mr({prompt:e.prompt,tool:"generate_music_tempo_card",mediaUrl:o.urls[0],mediaType:"audio",cost:o.amount??n.amount,transactionId:o.transactionId,userContext:t})):o.urls?.length&&o.status==="processing"?(o._preliminary_urls=o.urls,delete o.urls,m.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):m.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof ce)return m.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Ge(o,n);throw m.error("payment:failure",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}async function Pg(e,t){let n=await it("check_music_status_tempo_card",void 0,t),r=de.randomUUID();m.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await Ce(async()=>{let o;try{o=await It({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:at(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof me)return Be(s);throw s}return m.info("payment:success",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),o.urls?.length&&o.urls.forEach(s=>Ke(s)),o})}catch(o){if(o instanceof ce)return m.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Ge(o,n);throw m.error("payment:failure",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}async function Mg(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 it("query_onchain_prices",void 0,t),r=de.randomUUID();m.info("payment:attempt",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName});try{return await Ce(async()=>{let o;try{o=await It({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:at(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof me)return Be(s);throw s}if(m.info("payment:success",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,mode:"session"}),Array.isArray(o?.data))o.data=o.data.map(s=>{if("mint"in s&&!("address"in s)){let{mint:i,...a}=s;return{address:i,...a}}return s});else if(o&&"mint"in o&&!("address"in o)){let{mint:s,...i}=o;return{address:s,...i}}return o})}catch(o){if(o instanceof ce)return m.warn("payment:declined",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Ge(o,n);throw m.error("payment:failure",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}var Og=["generate_music_tempo_card"],Rl=10,Il=5,$l=new Map;function Pl(e){let t=$l.get(e);if(t!==void 0)return t;let r=or(e)?.isAsync===!0||Og.includes(e);return $l.set(e,r),r}var Ng=36e4,Dg=18e4,Lg=15e3,Ug=12e4,jg=2e3;function Ml(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}async function Fg(e,t){let n;if(e.requests?.some(C=>C.tool||C.tool_id)&&e.requests)n=e.requests.map(C=>{let k=C.tool||C.tool_id||e.tool;if(!k)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let q=an(k,C.tier||e.tier,C.prompt??t),{tool:W,tool_id:B,tier:ct,params:ne,...pe}=C,lt=ne&&typeof ne=="object"?{...ne,...pe}:pe;return{resolvedTool:q,params:lt}});else if(e.tool){let C=an(e.tool,e.tier,e.params?.prompt??t);n=(e.requests||(e.count&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(q=>({resolvedTool:C,params:q}))}else return Ml("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return Ml("BATCH_EMPTY","Batch requires at least one item.");if(n.length>Rl)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${Rl} items. Please split into smaller batches.`};if([...new Set(n.map(C=>C.resolvedTool))].some(Pl)&&n.length>Il)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${Il} items. Please use multiple batches for more.`};let i=[...new Set(n.map(C=>C.resolvedTool))],a=i.length===1,l={};for(let C of i)l[C]=await it(C,void 0,t);let c=0;for(let C of n)c+=l[C.resolvedTool].amount;let u=[...new Set(Object.values(l).map(C=>C.merchantName))].join(", "),d=a?i[0]:"mixed";m.info("payment:attempt",{tool:"batch",batchTool:d,count:n.length,totalAmount:c,merchant:u,heterogeneous:!a});let g=n.some(C=>Pl(C.resolvedTool)),p=n.some(C=>C.resolvedTool.startsWith("or-")||C.resolvedTool==="run_llm"||C.resolvedTool==="execute_tool"),_=g?Ng:p?Dg+n.length*Lg:Ug+n.length*jg,h=de.randomUUID(),S=[],I=0,$=0n;return wo(async()=>{let C=!At();if(C)try{let k=Math.max(1,Math.ceil(c*100));await ti(P,ze,{toolName:"batch",userContext:t,sessionKind:"one_shot",minRequiredCents:k,capCentsOverride:k})}catch(k){return k instanceof me?Be(k):(m.warn("payment:batch-prewarm-failed",{batchTool:d,count:n.length,error:k?.message||String(k)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:k?.message||"Failed to authenticate batch session",tool:d,count:n.length,failedCount:n.length,results:[]})}try{for(let ne=0;ne<n.length;ne+=1){let pe=n[ne],lt=l[pe.resolvedTool];try{let ie=await Ll({toolId:pe.resolvedTool,toolParams:pe.params,estimatedAmountCents:at(lt),userContext:t,metaTool:"batch",timeoutMs:_,idempotencyKey:eg(h,ne,pe.resolvedTool,pe.params)});if(S.push({success:ie?.success!==!1,tool:pe.resolvedTool,...ie,...Tl(h,ne,ie)}),ie?.success!==!1){let Un=He(ie?.amountMicros??ie?.amount_micros),Oi=typeof ie?.amount=="number"?ie.amount:lt.amount;Un!==null&&Un>0n?$+=Un:$+=BigInt(Math.round(Oi*1e6)),I+=Oi}ie?.urls&&ie.urls.forEach(Un=>Ke(Un))}catch(ie){if(ie instanceof me&&S.length===0)return Be(ie);m.warn("payment:batch-item-failed",{tool:pe.resolvedTool,index:ne,error:ie?.message||String(ie)}),S.push({success:!1,tool:pe.resolvedTool,...Tl(h,ne),error:ie?.message||String(ie)})}}let k=S.filter(ne=>ne?.success===!1).length,q=S.length-k,W=S.flatMap(ne=>Array.isArray(ne?.urls)?ne.urls:[]),B=$>0n?Number($)/1e6:Math.round((I+Number.EPSILON)*100)/100,ct=q===0?"failure":k===0?"success":"partial";return m.info("payment:success",{tool:"batch",batchTool:d,count:n.length,totalAmount:c,totalCharged:B,merchant:u,successCount:q,failedCount:k,outcome:ct,mode:"session",batchId:h}),{success:q>0,outcome:ct,batch_id:h,tool:a?i[0]:d,count:n.length,successCount:q,failedCount:k,totalCharged:B,...$>0n?{totalChargedMicros:$.toString(),amountMicros:$.toString(),amount_micros:$.toString()}:{},merchantName:u,results:S,...W.length?{urls:W}:{}}}catch(k){if(k instanceof ce)return m.warn("payment:declined",{tool:"batch",batchTool:d,count:n.length,totalAmount:c,merchant:u,code:k.code,retryable:k.retryable}),Ge(k,{amount:c,merchantName:u});throw m.error("payment:failure",{tool:"batch",batchTool:d,count:n.length,totalAmount:c,merchant:u,error:k.message}),k}finally{if(C){let k=await go(P);m.info("batch-session:closed",{budgetId:k.budgetId,closedServerSide:k.closedServerSide})}}})}function Vg(){let e=!1,t;try{let r=So.join(dr.homedir(),".claude","settings.json");if(Me.existsSync(r)){let o=JSON.parse(Me.readFileSync(r,"utf-8")),s=typeof o.statusLine=="object"?o.statusLine.command:"";e=Lt(s)}}catch{}let n=Dr();return n||(t="visa-cli config hud enable"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function qg(e){let[t,n]=await Promise.all([P.getStatus(e),P.getBalance().catch(s=>(m.warn("get_status:balance_fetch_failed",{error:s?.message||String(s)}),null))]);typeof t?.dailyRemaining=="number"&&(t.dailyRemaining=Math.round(t.dailyRemaining*100)/100);let r=kg();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=Vg(),t.version=ag,Array.isArray(t.cards)&&(t.cards=t.cards.map(s=>({...s,displayName:ii(s)})),t.cardIdGuidance="cardId values are opaque tool parameters only; refer to cards by brand and last four digits."),n&&n.success&&(t.balanceCents=n.balanceCents,t.amountUsd=n.amountUsd);let o=At();if(t.sessionMode=!!o,o){let s=Math.max(0,o.totalCents-o.estimatedCumulative);t.activeSession={budgetId:o.budgetId,capCents:o.totalCents,capUsd:o.totalCents/100,lastReceiptCumulativeCents:o.lastReceiptCumulative,estimatedCumulativeCents:o.estimatedCumulative,spentCents:o.estimatedCumulative,spentUsd:o.estimatedCumulative/100,estimatedRemainingCents:s,estimatedRemainingUsd:s/100,...o.lastToolSpend?{lastToolSpend:{toolName:o.lastToolSpend.toolName,resolvedToolId:o.lastToolSpend.resolvedToolId,estimatedAmountCents:o.lastToolSpend.estimatedAmountCents,estimatedAmountUsd:o.lastToolSpend.estimatedAmountCents/100,voucherCumulativeCents:o.lastToolSpend.voucherCumulativeCents,estimatedCumulativeCents:o.lastToolSpend.estimatedCumulativeCents,receiptDeltaCents:o.lastToolSpend.receiptDeltaCents,receiptCumulativeCents:o.lastToolSpend.receiptCumulativeCents,receiptRemainingCents:o.lastToolSpend.receiptRemainingCents,recordedAt:o.lastToolSpend.recordedAt}}:{},expiresAt:o.expiresAt}}return t}function ii(e){let t=typeof e.brand=="string"&&e.brand.trim().length>0?e.brand.trim():"card",n=t.charAt(0).toUpperCase()+t.slice(1).toLowerCase(),r=typeof e.last4=="string"&&e.last4.trim().length>0?e.last4.trim():"unknown",o=e.isDefault===!0?" (default)":"";return`${n} ending in ${r}${o}`}async function Gl(e,t){try{let r=((await P.getStatus(t)).cards||[]).find(o=>o?.id===e);if(r)return ii(r)}catch(n){m.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function Hg(e){let n=(await P.getStatus(e)).cards||[];return n.length===0?{cards:[],message:"No cards enrolled. Use the add_card tool to add a payment card."}:n.some(o=>!Number.isInteger(o?.id)||o.id<=0)?{success:!1,cards:[],message:"Card action handles are unavailable right now, so remove_card and set_default_card are temporarily disabled."}:{cards:n.map(o=>({...o,displayName:ii(o)})),message:"Use cardId only as an opaque tool parameter. When speaking to the user, refer to cards by brand and last four digits, not by card id."}}async function Bg(e,t){return await P.getTransactions({limit:e.limit,offset:e.offset},t)}async function Kg(e,t){return await P.feedback(e.message,e.transaction_id,t)}var Gg=100;async function zg(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return ln("MISSING_CONFIRMATION","Please confirm by setting confirm: true to charge your enrolled card for credits.");if(!e.amount||!Number.isFinite(e.amount)||e.amount<=0)return{success:!1,error:"amount must be a positive number in USD (e.g. 5.00)"};let n=Math.round(e.amount*100);if(n<Gg)return{success:!1,error:"Minimum top-up is $1.00"};let r=de.randomUUID();m.info("buy_credits:attempt",{amountCents:n});try{return await Ce(async()=>{let o=await ze("balance-topup",e.amount,"Visa CLI Balance",`top up balance with $${e.amount.toFixed(2)}`,t,{forceRequired:!0}),s=await P.topupBalance({amount_cents:n,idempotency_key:r,attestation:o});if(s.success){m.info("buy_credits:success",{amountCents:n,balanceCents:s.balanceCents});let i=((s.balanceCents??0)/100).toFixed(2),a=(n/100).toFixed(2);return{...s,amount:n/100,amountMicros:String(n*1e4),merchantName:"Visa CLI Balance",message:`Added $${a} \u2014 balance is now $${i}`}}return m.warn("buy_credits:failed",{amountCents:n,error:s.error}),s})}catch(o){if(o instanceof Rt)return dg();throw m.error("buy_credits:failure",{amountCents:n,error:o.message}),o}}function ln(e,t){return{success:!1,error:t,code:e,message:t}}async function Wg(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return ln("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>100))return ln("INVALID_VALUE","maxTransactionAmount must be between $0.01 and $100");if(e.dailyLimit!==void 0&&(typeof e.dailyLimit!="number"||!Number.isFinite(e.dailyLimit)||e.dailyLimit<1||e.dailyLimit>100))return ln("INVALID_VALUE","dailyLimit must be between $1 and $100");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return ln("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");m.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await Ce(async()=>{let n=await ze("spending-controls",0,"","update spending controls"),r=await P.updateSpendingControls({maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit,confirm:!0,attestation:n},t);return m.info("spending_controls:success",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit}),r})}catch(n){if(m.error("spending_controls:failure",{error:n.message}),n instanceof Rt)return Co(n,"update_spending_controls");if(String(n?.message||n).includes("Attestation required"))return ln("ATTESTATION_REQUIRED","Changing spending controls requires local attestation, even when payment biometric prompts are disabled.");throw n}}async function Jg(e){let t=await cr({api:P,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 Yg(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."};m.info("config:set",{key:e.key});try{let t=zr(e.key,e.value);return m.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 Xe?"UNKNOWN_KEY":t instanceof Qe?"SERVER_CONTROLLED":t instanceof vt?"RETIRED_KEY":"INVALID_VALUE";return m.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 Zg(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."};m.info("config:unset",{key:e.key});try{let t=Wr(e.key);return m.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 Xe?"UNKNOWN_KEY":t instanceof Qe?"SERVER_CONTROLLED":t instanceof vt?"RETIRED_KEY":"INVALID_VALUE";return m.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 Xg(e){let t=await P.getStatus(e),n=t.attestationRequired!==!1,r=ko(t),o=re(),s=n?r?o?`${bo()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${bo()} is not available in this process. ${si()}`:"Biometric attestation is enabled on the account, but no attestation key is registered. Payments on this device proceed without a biometric signature; processor declines such as INVALID_OR_MISSING_CONFIG are card/account configuration issues, not something biometric setup fixes.":"Biometric attestation is NOT required for payments. Payments will proceed without biometric confirmation.";return{required:n,hasAttestationKey:!!t.hasAttestationKey,hasTelegramAttestationKey:!!t.hasTelegramAttestationKey,hasAnyAttestationKey:r,touchIdAvailable:o,platform:process.platform,effectiveRequiredOnThisDevice:n&&r&&o,canDisableFromThisDevice:!n||!r||o,message:s}}async function Qg(e){m.info("biometric:on");let t=await P.setBiometricPreference({required:!0},e);return t.success?(Kl(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:t.error||"unknown error"}}async function eh(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return ln("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.");m.info("biometric:off");try{return await Ce(async()=>{let n=await P.getStatus(t),r;if(ko(n)&&(r=await ze("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${bo()} confirmation required to disable \u2014 not available on this device.`);let o=await P.setBiometricPreference({required:!1,attestation:r},t);if(!o.success)throw new Error(o.error||"unknown error");return Kl(),{success:!0,required:!1,message:"Touch ID is no longer required for payments."}})}catch(n){if(m.error("biometric:off:failure",{error:n.message}),n instanceof Rt)return Co(n,"biometric_off");throw n}}var Ol=3e4,th=3e5;async function zl(e,t,n="login"){let r=de.randomUUID(),o=`${e}${e.includes("?")?"&":"?"}state=${r}`;return Ke(o),Wl(r,t,n)}async function Wl(e,t,n="login"){let r=Date.now()+th;for(;Date.now()<r;)try{let s=await fetch(`${xo()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:Ol,...t&&{user_context:t}}),signal:AbortSignal.timeout(Ol+5e3)});if(!s.ok){await gt(s,a=>{m.warn("auth_status:retry_after_http_error",{status:s.status,delayMs:a})});continue}let i=await s.json();if(i.status==="pending")continue;if(i.status==="expired")return{success:!1,message:"Session expired. Please try again."};if(i.status==="error")return{success:!1,message:i.error||"Authentication failed. Please try again."};if(i.status==="complete"){if(n==="attestation-recovery"||i.attestationCleared)return m.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=ol(a);if(i.sessionToken){await U.saveSessionToken(i.sessionToken);let u=i.user||"",d=i.last4||"****";return m.info("auth:login_complete",{user:u,last4:d,bonusCents:a}),{success:!0,message:`Signed in as ${u}. Card ending in ${d} enrolled and ready for payments.`,...l||{}}}let c=i.last4||"****";return m.info("auth:card_added",{last4:c,bonusCents:a}),{success:!0,message:`Card ending in ${c} enrolled and ready for payments.`,...l||{}}}}catch{await gt(void 0,s=>{m.warn("auth_status:retry_after_network_error",{delayMs:s})})}return{success:!1,message:n==="enrollment"?"Card enrollment timed out. Please try again.":n==="attestation-recovery"?"Biometric reset timed out. Please try reset again.":"Login timed out. Please try again."}}async function Jl(e){let t=de.randomUUID(),n;try{n=await P.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."}:(Ke(n.recoveryUrl),Wl(t,e,"attestation-recovery"))}async function nh(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to remove this card."};let n=e.cardId;if(!Number.isInteger(n)||n<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to get the opaque cardId for the card you want to remove."};m.info("cards:remove_attempt",{cardId:n});let r=`remove-card:${n}`,o=`remove ${await Gl(n,t)}`;try{return await Ce(async()=>{let s=await ze(r,0,"",o,t,{forceRequired:!0}),i=await P.removeCard(n,{attestation:s},t);return m.info("cards:remove_success",{cardId:n,promotedId:i?.promotedId??null}),i})}catch(s){if(m.error("cards:remove_failure",{cardId:n,error:s.message}),s instanceof Rt)return Co(s,"remove_card");throw s}}async function rh(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."};m.info("cards:set_default_attempt",{cardId:n});let r=`set-default-card:${n}`,o=`set ${await Gl(n,t)} as default`;try{return await Ce(async()=>{let s=await ze(r,0,"",o,t,{forceRequired:!0}),i=await P.setDefaultCard(n,{attestation:s},t);return m.info("cards:set_default_success",{cardId:n}),i})}catch(s){if(m.error("cards:set_default_failure",{cardId:n,error:s.message}),s instanceof Rt)return Co(s,"set_default_card");throw s}}async function oh(e){return m.info("auth:login_attempt"),zl(`${xo()}/login`,e)}function sh(e){if(e.capCents!==void 0){let t=Number(e.capCents);if(!Number.isFinite(t)||t<10||t>1e4)throw new Error("capCents must be between 10 ($0.10) and 10000 ($100)");return Math.floor(t)}if(e.capUsd!==void 0){let t=Number(e.capUsd);if(!Number.isFinite(t)||t<.1||t>100)throw new Error("capUsd must be between 0.10 and 100");return Math.floor(t*100)}}async function ih(e={},t){let n;try{n=sh(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return wo(async()=>{let r=await _l(P,ze,{toolName:"start_session",userContext:t,capCentsOverride:n});m.info("session:started",{budgetId:r.budgetId,totalCents:r.totalCents,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious});let o=(r.appliedCapCents/100).toFixed(2),s=(r.requestedCapCents/100).toFixed(2),i=`Session started with a $${o} cap. Paid calls will use this approval window until you close it, it expires, or this MCP process restarts.`,a=r.clampedReason==="balance"?`${i} Note: requested cap of $${s} was clamped to your prepaid balance of $${o}. Run buy_credits to top up if you need a larger session.`:i;return{success:!0,budgetId:r.budgetId,totalCents:r.totalCents,amountUsd:r.totalCents/100,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious,message:a}})}async function ah(){let e=At();if(!e)return{success:!0,active:!1,message:"No active explicit approval window. Paid calls use a one-shot session in pay-as-you-go mode; see transaction_history for records."};let t=Math.max(0,e.totalCents-e.estimatedCumulative);return{success:!0,active:!0,budgetId:e.budgetId,totalCents:e.totalCents,estimatedCumulativeCents:e.estimatedCumulative,estimatedRemainingCents:t,expiresAt:e.expiresAt,lastToolSpend:e.lastToolSpend,message:`Active explicit approval window: about $${(t/100).toFixed(2)} remaining of $${(e.totalCents/100).toFixed(2)}.`}}async function ch(){return wo(async()=>{let e=At();if(!e)return{success:!0,message:"No active explicit approval window to close. Paid calls remain pay-as-you-go.",closed:!1};let t=await go(P);m.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=og(e),r=He(t.finalCumulativeMicros),o=r??(typeof t.finalCumulativeCents=="number"?BigInt(Math.max(0,t.finalCumulativeCents))*10000n:n.micros),s=Number(o/10000n);return m.info("session:closed:final-spend",{budgetId:t.budgetId,closedServerSide:t.closedServerSide,finalSpendMicros:o.toString(),finalSpendCents:s,finalSpendSource:r!==null?"server.finalCumulativeMicros":typeof t.finalCumulativeCents=="number"?"server.finalCumulativeCents":n.source,totalCents:e.totalCents}),{success:!0,closed:!0,closedServerSide:t.closedServerSide,budgetId:t.budgetId,finalEstimatedCumulativeCents:s,finalEstimatedCumulativeMicros:o.toString(),totalCents:e.totalCents,message:t.closedServerSide?`Explicit approval window closed. Spent ${rg(o)} of $${(e.totalCents/100).toFixed(2)} cap. Future paid calls are pay-as-you-go until you start a new explicit approval window.`:"Explicit approval window cleared locally; server-side close call did not succeed (likely already closed). Future paid calls are pay-as-you-go until you start a new explicit approval window."}})}async function lh(e){if(m.info("auth:add_card_attempt"),!await U.getSessionToken())return{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."};let{code:n}=await P.createEnrollCode();return zl(`${xo()}/enroll-card?code=${encodeURIComponent(n)}`,e,"enrollment")}async function uh(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};m.info("reset:attempt");let n=!1;try{let r=await P.getStatus(t);if(r&&ko(r)){let o=await Jl(t);if(!o.success)return o;n=!0}}catch(r){let o=r?.message||"unknown error";if(!/not logged in|session.*expired|no local credentials/i.test(o))return{success:!1,message:`Could not check server biometric state: ${o}`};m.warn("reset:server_attestation_status_unavailable",{error:o})}try{await P.logout(void 0,t)}catch{}if(await U.clearAll(),re())try{await io()}catch{}return m.info("reset:success"),{success:!0,message:n?"Device reset. Server-side biometric state and local credentials have been cleared. Use the login tool or visa-cli setup to re-enroll.":"Device reset. Local credentials and keys have been removed. Use the login tool or visa-cli setup to re-enroll."}}async function dh(e){let t=e.query?.trim()||void 0,n=e.category?.trim()||void 0,r=!t&&!n;m.info("catalog:discover",{query:t,category:n,browseAll:r});try{let s=(await P.catalogSearch(t,n)).tools||[];if(s.length===0)return{content:[{type:"text",text:r?"The tool catalog is currently empty.":`No tools found for "${t||n}". Try a different search term.`}]};if(r){let a={};for(let c of s){let u=c.category||"other";(a[u]??=[]).push(c)}let l=Object.keys(a).sort().map(c=>{let u=a[c].map((g,p)=>`${p+1}. **${g.name}** (${g.id})
125
- ${g.description}
126
- Provider: ${g.provider} | Price: ${Nl(g)}
127
- Params: ${Object.keys(g.inputSchema?.properties||g.inputSchema||{}).join(", ")||"none"}`).join(`
109
+ Note: a legacy shell-prompt HUD block was detected in ${o} but could not be auto-removed (${s.message}). Remove it manually with: visa-cli config hud disable shell`}function Wn(e,t=qr){let n={},r=!1;if(oe.existsSync(e)){r=!0;try{n=JSON.parse(oe.readFileSync(e,"utf-8"))}catch(o){return{installed:"malformed-json",message:`~/.claude/settings.json is not valid JSON (${o.message}). Fix the file manually, then run: visa-cli config hud enable claude`}}}if(n.statusLine){let o=typeof n.statusLine=="object"?n.statusLine.command:"";return vt(o)?{installed:"already-visa",message:$a("Visa HUD already registered in ~/.claude/settings.json.",e)}:{installed:"other-hud-present",message:om("Another HUD is already configured (keeping it). To switch to Visa HUD, edit ~/.claude/settings.json \u2192 statusLine.command",e)}}try{return n.statusLine={type:"command",command:t()},Vr(e,n),{installed:"new",message:$a(`Visa HUD registered in ~/.claude/settings.json${r?"":" (new file)"}. Restart Claude Code to see it pinned below the input.`,e)}}catch(o){return{installed:"error",message:`Failed to write settings: ${o.message}. Enable manually later with: visa-cli config hud enable claude`}}}function gs(e){if(!oe.existsSync(e))return{removed:!1,status:"missing-settings",message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(oe.readFileSync(e,"utf-8"))}catch(r){return{removed:!1,status:"malformed-json",message:`~/.claude/settings.json is not valid JSON: ${r.message}`}}if(!t.statusLine)return{removed:!1,status:"missing-statusline",message:"No statusLine configured."};let n=typeof t.statusLine=="object"?t.statusLine.command:"";if(!vt(n))return{removed:!1,status:"foreign-statusline",message:"statusLine is owned by another tool \u2014 leaving it alone."};delete t.statusLine;try{Vr(e,t)}catch(r){return{removed:!1,status:"error",message:`Failed to write ~/.claude/settings.json: ${r.message}`}}return{removed:!0,status:"removed",message:"Visa HUD removed from ~/.claude/settings.json. Restart Claude Code to take effect."}}var Xe=E(require("fs")),De=E(require("path")),sm=1,jt={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},im=["terminal","claude","claude-code","all"];function Gr(e){let t=e.toLowerCase();return im.includes(t)?t:null}var am=50,cm=64*1024,Na=10,hs=80;function lm(){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 ys=lm(),x={reset:"\x1B[0m",visaBlue:ys?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:ys?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:ys?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function T(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${x.reset}`}function La(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function Fa(e=process.stdin){return e.isTTY?null:new Promise(t=>{let n=[],r=!1,o=()=>{e.removeListener("data",i),e.removeListener("end",a),e.removeListener("error",l),clearTimeout(c)},s=u=>{r||(r=!0,o(),t(u))},i=u=>{n.push(typeof u=="string"?Buffer.from(u):u)},a=()=>{let u=Buffer.concat(n).toString("utf-8").trim();if(!u)return s(null);try{let d=JSON.parse(u);s(d&&typeof d=="object"?d:null)}catch{s(null)}},l=()=>s(null),c=setTimeout(()=>{n.length>0?a():s(null)},am);e.on("data",i),e.on("end",a),e.on("error",l)})}function Jn(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),o="\u2591".repeat(10-n);return`${T(r||"",x.visaBlueSoft)}${T(o||"",x.dim)}`}function Yn(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 um(e){if(Ya(e))return mm(e);let t=` ${T("\u2502",x.dim)} `,n=Kr(e)||"claude",r=e.cwd?Z(De.basename(e.cwd)):"",o=zr(e.workspace),s=r||o,i=o&&o!==s?` ${T(`@${o}`,x.visaBlueSoft)}`:"",a=[T(`[${n}]`,x.visaBlueSoft)];s&&a.push(`${T(s,x.visaGold)}${i}`);let l=Z(e.git_branch??e.branch??"");l&&a.push(`${T("git:(",x.dim)}${T(l,x.visaBlueSoft)}${T(")",x.dim)}`);let c=a.join(t),u=Number(e.context_window?.context_window_size??0),d=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,f=e.context_window?.current_usage,p=[f?.input_tokens,f?.output_tokens,f?.cache_creation_input_tokens,f?.cache_read_input_tokens].filter(W=>typeof W=="number"&&Number.isFinite(W)),_=p.length>0?p.reduce((W,B)=>W+B,0):null,h=Number(e.context_window?.total_input_tokens??_??f?.input_tokens??0),S=d!==null?Math.max(0,Math.min(1,d/100)):u>0?Math.max(0,Math.min(1,h/u)):0,I=d!==null&&u>0?Math.round(S*u):h,$;if(u>0||d!==null){let W=`${String(Math.round(S*100)).padStart(2," ")}%`,B=u>0?` ${T(`(${Yn(I)}/${Yn(u)})`,x.dim)}`:"";$=`${T("Context",x.dim)} ${Jn(S)} ${T(W,x.green)}${B}`}else $=`${T("Context",x.dim)} ${T("-",x.dim)}`;let C=Va(e.rate_limits),k=[$];C&&k.push(C);let q=k.join(t);return`${c}
110
+ ${q}`}function dm(e){if(Ya(e))return null;let t=` ${T("\u2502",x.dim)} `,n=Kr(e)||"claude",r=e.cwd?Z(De.basename(e.cwd)):"",o=zr(e.workspace),s=r||o,i=o&&o!==s?` ${T(`@${o}`,x.visaBlueSoft)}`:"",a=[T(`[${n}]`,x.visaBlueSoft)];s&&a.push(`${T(s,x.visaGold)}${i}`);let l=Z(e.git_branch??e.branch??"");l&&a.push(`${T("git:(",x.dim)}${T(l,x.visaBlueSoft)}${T(")",x.dim)}`);let 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,d=e.context_window?.current_usage,f=[d?.input_tokens,d?.output_tokens,d?.cache_creation_input_tokens,d?.cache_read_input_tokens].filter(k=>typeof k=="number"&&Number.isFinite(k)),p=f.length>0?f.reduce((k,q)=>k+q,0):null,_=Number(e.context_window?.total_input_tokens??p??d?.input_tokens??0),h=u!==null?Math.max(0,Math.min(1,u/100)):c>0?Math.max(0,Math.min(1,_/c)):0,S=u!==null&&c>0?Math.round(h*c):_,I;if(c>0||u!==null){let k=`${String(Math.round(h*100)).padStart(2," ")}%`,q=c>0?` ${T(`(${Yn(S)}/${Yn(c)})`,x.dim)}`:"";I=`${T("Context",x.dim)} ${Jn(h)} ${T(k,x.green)}${q}`}else I=`${T("Context",x.dim)} ${T("-",x.dim)}`;let $=Va(e.rate_limits),C=[I];return $&&C.push($),{identity:a.join(t),metrics:C.join(t)}}function mm(e){let t=` ${T("\u2502",x.dim)} `,n=Za(e),r=n.model||"codex",o=[T(`[${r}]`,x.visaBlueSoft)];n.project&&o.push(T(n.project,x.visaGold)),n.gitBranch&&o.push(`${T("git",x.dim)} ${T(n.gitBranch,x.visaGold)}`);let s=o.join(t),i=[];if(typeof n.contextUsedPercent=="number"){let l=Math.max(0,Math.min(1,n.contextUsedPercent/100));i.push(`${T("Context",x.dim)} ${Jn(l)} ${T(`${Math.round(n.contextUsedPercent)}%`,x.green)}`)}else if(typeof n.contextRemainingPercent=="number"){let l=100-n.contextRemainingPercent,c=Math.max(0,Math.min(1,l/100));i.push(`${T("Context",x.dim)} ${Jn(c)} ${T(`${Math.round(l)}%`,x.green)}`)}typeof n.usedTokens=="number"&&i.push(`${T("Tokens",x.dim)} ${Yn(n.usedTokens)}`),n.status&&i.push(`${T("Status",x.dim)} ${T(n.status,x.visaBlueSoft)}`),n.threadTitle&&i.push(`${T("Thread",x.dim)} ${T(n.threadTitle,x.visaBlueSoft)}`);let a=i.length>0?i.join(t):`${T("Context",x.dim)} ${T("-",x.dim)}`;return`${s}
111
+ ${a}`}function pm(e){if(typeof e!="number"||e<=0)return"";let n=(e>1e12?e:e*1e3)-Date.now();if(n<=0||n>=10080*60*1e3)return"";let r=Math.floor(n/6e4),o=Math.floor(r/60),s=r%60;return o>0?`${o}h ${s}m`:`${s}m`}function Da(e,t){if(!e||typeof e.used_percentage!="number")return null;let n=Math.max(0,Math.min(100,e.used_percentage)),r=n/100,o=Jn(r),s=n>=90?"\x1B[38;5;196m":n>=70?x.visaGold:x.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=pm(e.resets_at),l=a?` ${T(`(${a} / ${t})`,x.dim)}`:` ${T(`(${t})`,x.dim)}`;return`${o} ${T(i,s)}${l}`}function Va(e){if(!e)return null;let t=Da(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?Da(e.seven_day,"7d"):null;if(!t&&!r)return null;let o=` ${T("\u2502",x.dim)} `,s=[t,r].filter(Boolean);return`${T("Usage",x.dim)} ${s.join(o)}`}function qa(e){let t;try{let n=Xe.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let o=Math.min(r,cm),s=r-o;t=Xe.openSync(e,"r");let i=Buffer.alloc(o);Xe.readSync(t,i,0,o,s);let a=i.toString("utf-8");if(s>0){let l=Buffer.alloc(1);if(Xe.readSync(t,l,0,1,s-1),l[0]!==10){let c=a.indexOf(`
112
+ `);c>=0&&(a=a.slice(c+1))}}return a}catch{return null}finally{if(t!==void 0)try{Xe.closeSync(t)}catch{}}}function fm(e){if(!e||typeof e!="object")return;let t=e,n=["file_path","path","notebook_path","pattern","command","url"];for(let r of n){let o=t[r];if(typeof o=="string"&&o.length>0){if(r.endsWith("_path")||r==="path"){let s=De.basename(De.dirname(o)),i=De.basename(o);return s&&s!=="."&&s!=="/"?`${s}/${i}`:i}return o}}}function gm(e){let t=e.split(`
113
+ `),n=[],r=new Set;for(let o=t.length-1;o>=0&&n.length<Na*3;o-=1){let s=t[o].trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{continue}if(!i||typeof i!="object")continue;let 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 d=u;if(d.type==="tool_result"&&typeof d.tool_use_id=="string")r.add(d.tool_use_id);else if(d.type==="tool_use"&&typeof d.name=="string"){let f=typeof d.id=="string"?d.id:"",p=f.length>0?!r.has(f):!1;n.push({name:d.name,target:fm(d.input),running:p})}}}return n.reverse(),n.slice(Math.max(0,n.length-Na))}function hm(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 ym(e){let t=e.running?T("\u25D0",x.visaGold):T("\u2713",x.green),n=e.running?x.visaGold:x.visaBlueSoft,r=T(Z(e.name),n),o=e.target?Z(e.target):"",s=o?`${T(":",x.dim)} ${T(o,x.dim)}`:"",i=e.count>1?` ${T(`\xD7${e.count}`,x.dim)}`:"";return s?`${t} ${r}${s}${i}`:`${t} ${r}${i}`}function _m(e){let t=` ${T("\u2502",x.dim)} `,n=La(t),r=e.slice();for(;r.length>0;){let l=r.join(t);if(La(l)<=hs)return l;r=r.slice(1)}if(e.length===0)return"";let o="\u2026",i=e[e.length-1].replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,""),a=i.length>hs-n-1?i.slice(0,hs-n-1)+o:i;return`${T(o,x.dim)}${t}${a}`}async function Ua(e){if(!e||typeof e!="string")return null;let t=qa(e);if(!t)return null;let n;try{n=gm(t)}catch{return null}if(n.length===0)return null;let o=hm(n).map(ym);return _m(o)||null}async function Ha(e,t,n){return(await Ka(e,t,n)).join(`
114
+ `)}function Ba(e,t,n){let r=!!t?.activeSession||e.includes("in session"),o=n?bm(n):!1;return{isActive:r||o,hasSession:r,hasToolActivity:o}}async function Ka(e,t,n){let{isActive:r}=Ba(e,n,t?.transcript_path),o=e.split(`
115
+ `).filter(a=>a.length>0),i=t&&!r?o.map(a=>T(_s(a),x.dim)):[...o];if(t){let a=dm(t);if(a){if(i.push(a.identity),t.transcript_path){let l=await Ua(t.transcript_path);l&&i.push(...l.split(`
116
+ `))}i.push(a.metrics)}else{let l=um(t);if(l&&i.push(...l.split(`
117
+ `)),t.transcript_path){let c=await Ua(t.transcript_path);c&&i.push(...c.split(`
118
+ `))}}}return i}var vm=["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 bm(e){let t=qa(e);if(!t)return!1;let n=t.slice(-16384).toLowerCase();return vm.some(r=>n.includes(`"${r}"`))}async function Ga(e,t,n){let r=await Ka(e,t,n),o=r.join(`
119
+ `),{isActive:s}=Ba(e,n,t?.transcript_path);return{schemaVersion:sm,client:t?Ja(t):jt.UNKNOWN,rendered:o,lines:r.map(_s),visa:{spendLine:_s(e),balanceCents:n?.balanceCents,balanceUsd:n?.amountUsd,sessionMode:n?.sessionMode,activeSession:n?.activeSession,isVisaActive:s},context:t?Za(t):{}}}function Z(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 zr(e){if(typeof e=="string")return Z(De.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 Z(t?De.basename(t):e.name)}function za(e){return Z(e.app_name??e.appName??e.app??e.client)}function Kr(e){return Z(e.model?.display_name??e.model?.id??e.model_name??e.modelName)}function Wa(e){return Z(e.cwd??e.current_dir??e.project_root)}function ja(e){let t=Z(e.project);if(t)return t;let n=Wa(e);if(n)return Z(De.basename(n));let r=zr(e.workspace);return r||""}function Re(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function Ja(e){let t=za(e).toLowerCase();return t.includes("codex")?jt.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?jt.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||Re(e.context_used)!==void 0?jt.CODEX:jt.UNKNOWN}function Ya(e){return Ja(e)===jt.CODEX}function Za(e){let t=za(e),n=Wa(e),r=zr(e.workspace),o=Re(e.context_used)??Re(e.context_window?.used_percentage??void 0),s=Re(e.context_remaining)??Re(e.context_window?.remaining_percentage??void 0);return{...t?{app:t}:{},...Kr(e)?{model:Kr(e)}:{},...ja(e)?{project:ja(e)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...Z(e.git_branch??e.branch)?{gitBranch:Z(e.git_branch??e.branch)}:{},...Z(e.status??e.run_state??e.runState)?{status:Z(e.status??e.run_state??e.runState)}:{},...Z(e.thread_title??e.threadTitle)?{threadTitle:Z(e.thread_title??e.threadTitle)}:{},...o!==void 0?{contextUsedPercent:o}:{},...s!==void 0?{contextRemainingPercent:s}:{},...Re(e.used_tokens)!==void 0?{usedTokens:Re(e.used_tokens)}:{},...Re(e.total_input_tokens)!==void 0?{totalInputTokens:Re(e.total_input_tokens)}:{},...Re(e.total_output_tokens)!==void 0?{totalOutputTokens:Re(e.total_output_tokens)}:{}}}function _s(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}var Qa=E(require("path"));function Xa(e){return e instanceof Error?e.message:String(e)}function vs(e,t){let n=[],r=[],o=e??"claude",s=Gr(o);if(o==="shell"||o==="prompt")try{let a=t.installShellHud();return a.installed?{ok:!0,messages:[a.message],errors:r}:{ok:!1,messages:n,errors:[a.message]}}catch(a){return{ok:!1,messages:n,errors:[`Failed to install shell HUD: ${Xa(a)}`]}}if(!s)return{ok:!1,messages:n,errors:[`Unknown HUD surface: ${o}`,"Supported: claude (default), shell, all"]};let i=!0;if(s==="claude"||s==="claude-code"||s==="all"){let a=Qa.join(t.homeDir,".claude","settings.json");try{let l=t.installVisaStatusLine(a);n.push(l.message),(l.installed==="error"||l.installed==="malformed-json")&&(i=!1)}catch(l){i=!1,r.push(`Failed to install Claude HUD: ${Xa(l)}`)}}return{ok:i,messages:n,errors:r}}function ec(e){if(!e||typeof e!="object")return"";let t=e;return Array.isArray(t.enum)&&t.enum.length>0?"enum":typeof t.type=="string"?t.type:Array.isArray(t.type)?t.type.filter(n=>typeof n=="string").join("|"):""}async function Ft(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,o=setTimeout(()=>r.abort(),n);try{let{timeoutMs:s,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(o)}}var Vt=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},_n=class extends Error{code;budgetId;status;constructor(t,n,r={}){super(t),this.name="SessionInvalidError",this.code=n,this.budgetId=r.budgetId,this.status=r.status}},qt=class extends Error{code="SESSION_LOCK_CONTENDED";retryAfterSecs;status;constructor(t,n=1,r){super(t),this.name="SessionLockContendedError",this.retryAfterSecs=n,this.status=r}},le=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(t,n,r,o,s,i,a,l){super(t),this.name="CardDeclinedError",this.retryable=n,this.code=r,this.reason=o,this.paymentErrorClass=s,this.correlationId=i,this.transactionId=a,this.retryAfter=l}};var tc={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 bs(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&&tc[n]?tc[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 he=E(require("fs")),xs=E(require("path")),nc=E(require("os")),ws=xs.join(nc.homedir(),".visa-mcp"),Zn=xs.join(ws,"mcp-server.log"),Sm=5*1024*1024,Ss=null;function wm(){he.existsSync(ws)||he.mkdirSync(ws,{recursive:!0,mode:448})}function xm(){if(!Ss){if(wm(),he.existsSync(Zn)&&he.statSync(Zn).size>Sm){let t=Zn+".1";he.existsSync(t)&&he.unlinkSync(t),he.renameSync(Zn,t)}Ss=he.createWriteStream(Zn,{flags:"a"})}return Ss}function Cm(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function Wr(e,...t){let n=new Date().toISOString(),r=t.map(s=>typeof s=="string"?s:JSON.stringify(s,null,2)).join(" "),o=`[${n}] [${e}] ${r}
120
+ `;Cm(e)&&process.stderr.write(o),xm().write(o)}var m={debug:(...e)=>Wr("DEBUG",...e),info:(...e)=>Wr("INFO",...e),warn:(...e)=>Wr("WARN",...e),error:(...e)=>Wr("ERROR",...e)};var km=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function oc(e,t){let n=rc(e),r=rc(t);if(!n||!r)return!1;for(let o=0;o<3;o++)if(n.main[o]!==r.main[o])return n.main[o]>r.main[o];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:Tm(n.pre,r.pre)>0}function rc(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(km);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function Tm(e,t){let n=e.split("."),r=t.split("."),o=Math.max(n.length,r.length);for(let s=0;s<o;s++){if(s>=n.length)return-1;if(s>=r.length)return 1;let i=n[s],a=r[s],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 Ue(){return!!(sc(process.env.VISA_CLI_NO_UPDATE_CHECK)||sc(process.env.CI)||process.env.NODE_ENV==="test")}function sc(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var St=E(require("fs")),Es=require("node:net"),lc=E(require("os")),uc=E(require("path"));var Jr=E(require("fs")),ic=E(require("path")),ac=E(require("os"));var Cs=ic.join(ac.homedir(),".visa-mcp"),Xn=class{static ensureConfigDir(){Jr.existsSync(Cs)||Jr.mkdirSync(Cs,{recursive:!0,mode:448})}static getConfigDir(){return Cs}static TOOL_STATES={login:!0,get_status:!0,get_cards:!0,add_card:!0,pay:!1,transaction_history:!0,update_spending_controls:!0,enroll_device:!1,verify_otp:!1,reset:!0,batch:!0,generate_x402_image:!1,browser_launch:!1,browser_navigate:!1,browser_snapshot:!1,browser_click:!1,browser_type:!1,browser_scroll:!1,generate_music_card:!1,generate_image_card:!1,query_onchain_prices_card:!1,generate_music_tempo_card:!1,check_music_status_tempo_card:!1,generate_image_fast_card:!1,generate_video_tempo_card:!1};static loadToolStates(){return{...this.TOOL_STATES}}static getDisabledTools(){let t=new Set;for(let[n,r]of Object.entries(this.TOOL_STATES))r||t.add(n);return t}static isToolDisabled(t){return this.TOOL_STATES[t]===!1}};function cc(e){let t=lc.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}var Em="settings.json",Am="must use https unless it points at localhost/loopback for local development";function Qn(){return uc.join(Xn.getConfigDir(),Em)}function dc(e){if((0,Es.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function Rm(e){let t=e.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!t)return!1;let n=Number.parseInt(t[1],16),r=Number.parseInt(t[2],16);if(!Number.isFinite(n)||!Number.isFinite(r))return!1;let o=[n>>8&255,n&255,r>>8&255,r&255].join(".");return dc(o)}function Im(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,Es.isIP)(t);return n===4?dc(t):n===6?t==="::1"||Rm(t):!1}function ks(e,t="auth.serverUrl"){let n;try{n=new URL(e)}catch{throw new Error(`${t} must be a valid URL (got: ${JSON.stringify(e)})`)}if(n.username||n.password)throw new Error(`${t} must not include username or password credentials`);if(n.protocol!=="https:"&&!(n.protocol==="http:"&&Im(n.hostname)))throw new Error(`${t} ${Am}`)}var wt={"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");ks(e)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."},"ui.suppressFeed":{type:"boolean",description:"When true, generated images/music are not auto-submitted to the public Made-with-Visa feed."},"tools.meta":{type:"boolean",description:"Show category meta-tools (generate_image, generate_video, generate_music, run_llm, ...). Restart required.",requiresRestart:!0},"tools.discover":{type:"boolean",description:"Show the dynamic-catalog tools (discover_tools, execute_tool). Restart required.",requiresRestart:!0},"merchants.discover":{type:"string",description:'Platform-merchant JIT tool discovery: "all" = every live merchant, "off" = none, comma-separated slugs = exactly those. Equivalent to VISA_MERCHANT_DISCOVER / VISA_MERCHANT_SLUGS env. Restart required.',requiresRestart:!0,validate:e=>{if(typeof e!="string")throw new Error("merchants.discover must be a string");let t=e.trim().toLowerCase();if(t===""||t==="all"||t==="off"||t==="*")return;let n=/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/,r=e.split(",").map(o=>o.trim()).filter(Boolean);for(let o of r)if(!n.test(o))throw new Error(`merchants.discover: "${o}" is not a valid merchant slug`)}},"credit.sessionCapCents":{type:"number",description:"Default cap (in cents) for start_session and pay-as-you-go one-shot approvals. Server clamps to [10, 10000] = $0.10\u2013$100. Default 500 ($5).",validate:e=>{if(typeof e!="number"||!Number.isFinite(e))throw new Error("credit.sessionCapCents must be a number");if(!Number.isInteger(e))throw new Error("credit.sessionCapCents must be a whole number of cents (no fractional cents)");if(e<10||e>1e4)throw new Error("credit.sessionCapCents must be between 10 ($0.10) and 10000 ($100)")}}},As=500,Yr={"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 Ht(){let e=Qn();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)?(m.warn("settings:corrupt",{path:cc(e),reason:"not_object"}),{}):n}catch(t){return m.warn("settings:corrupt",{path:cc(e),error:t?.message||String(t)}),{}}}function Ts(e){Xn.ensureConfigDir();let t=Qn(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
121
+ `;St.writeFileSync(n,r,{mode:384}),St.renameSync(n,t)}function Rs(e){let t=Ht()[e];return typeof t=="string"?t:void 0}function Zr(e){let t=Ht()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function Is(e){let t=Ht()[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 Qe=class extends Error{constructor(t){let n=Object.keys(wt).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"}},et=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"}},bt=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+Yr[t]),this.name="RetiredSettingKeyError"}},mc=["biometric.","spending.","account.","cards.","biometric"];function Xr(e,t){if(mc.some(s=>e.startsWith(s)))throw new et(e);if(e in Yr)throw new bt(e);let n=wt[e];if(!n)throw new Qe(e);let r;if(n.type==="boolean")if(typeof t=="boolean")r=t;else if(typeof t=="string"){let s=t.toLowerCase();if(s==="true")r=!0;else if(s==="false")r=!1;else throw new Error(`${e} expects true or false (got: ${JSON.stringify(t)})`)}else throw new Error(`${e} expects a boolean (got: ${typeof t})`);else if(n.type==="number")if(typeof t=="number")r=t;else if(typeof t=="string"&&t.trim().length>0){let s=Number(t);if(!Number.isFinite(s))throw new Error(`${e} expects a number (got: ${JSON.stringify(t)})`);r=s}else throw new Error(`${e} expects a number (got: ${typeof t})`);else{if(typeof t!="string"||t.length===0)throw new Error(`${e} expects a non-empty string`);r=t}n.validate&&n.validate(r);let o=Ht();return o[e]=r,Ts(o),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:Qn()}}function Qr(e){if(mc.some(s=>e.startsWith(s)))throw new et(e);let t=wt[e];if(e in Yr){let s=Ht(),i=e in s;return i&&(delete s[e],Ts(s)),{key:e,removed:i,requiresRestart:!1,path:Qn()}}if(!t)throw new Qe(e);let r=Ht(),o=e in r;return o&&(delete r[e],Ts(r)),{key:e,removed:o,requiresRestart:o&&!!t.requiresRestart,path:Qn()}}function pc(){let e=Ht();return Object.entries(Yr).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}var $m="https://auth.visacli.sh",Pm="https://auth-visa-code-preview.up.railway.app";function Mm(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function Om(){try{let e=Er();return Mm(e.version)}catch{return!1}}function Nm(e){return e.envVar!==void 0&&e.envVar!==""?(ks(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(ks(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?Pm:$m}function ye(){return Nm({envVar:process.env.VISA_AUTH_URL,settingValue:Rs("auth.serverUrl"),isPrerelease:Om()})}function fc(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":Zr("ui.suppressBrowser")??!1}function gc(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":Zr("ui.suppressFeed")??!1}function hc(){let e=process.env.VISA_CREDIT_SESSION_CAP_CENTS;if(e!==void 0){let n=Number(e);if(Number.isFinite(n)&&n>=10&&n<=1e4)return Math.floor(n)}let t=Is("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):As}var Lm="CARD_REENROLLMENT_REQUIRED",Dm="https://auth.visacli.sh/enroll-card";function Um(){try{return new URL("/enroll-card",ye()).toString()}catch{return Dm}}function jm(e){let t=Um();if(typeof e!="string")return t;try{let n=new URL(e),r=new URL(t);if(n.origin===r.origin&&n.pathname==="/enroll-card")return n.toString()}catch{}return m.warn("card-reenroll:reenroll_url_rejected_fallback",{reason:"untrusted_or_malformed_reenroll_url",fallbackPath:"/enroll-card"}),t}var er="2.3.0-rc.1",Fm=/^vk_[A-Za-z0-9_-]{32,}$/;function Vm(e){if(typeof e!="string")return null;switch(e){case"BUDGET_CLOSED":case"BUDGET_NOT_FOUND":case"BUDGET_EXPIRED":return e;default:return null}}var qm="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function vn(e){return typeof e=="string"?e.trim():""}function yc(e){let t=e&&typeof e=="object"?e:{},n=vn(t.error)||vn(t.message);if(!n)return qm;let r=vn(t.error_code),o=[["surface",vn(t.disabled_surface)],["flag",vn(t.flag)],["correlation_id",vn(t.correlation_id)]].filter(([,i])=>i).map(([i,a])=>`${i}=${a}`),s=o.length?` (${o.join(" ")})`:"";return r?`503 [${r}] ${n}${s}`:`503 ${n}${s}`}function _c(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?Fm.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(`
122
+ `)}var Se=class{constructor(t){this.getSessionToken=t;this.baseUrl=ye()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!Ue()){let r=t.headers.get("X-Latest-Version");r&&oc(r,er)&&(this.lastSignals.updateAvailable={currentVersion:er,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return er}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new Vt(t.error||"Your biometric key is out of sync with the server.",typeof t.hint=="string"?t.hint:void 0)}async throwServerUnavailable(t){let n=null;try{n=await t.json()}catch{}throw new Error(yc(n))}async request(t,n,r,o,s,i){let a=await this.getSessionToken();if(!a)throw new Error(_c());let l={Authorization:`Bearer ${a}`};s&&(t==="GET"?l["X-User-Context"]=encodeURIComponent(s.replace(/[\r\n\0]/g," ").slice(0,1e3)):r={...r||{},user_context:s}),i&&(l["X-Visa-Meta-Tool"]=i),r&&(l["Content-Type"]="application/json");let c;try{c=await Ft(`${this.baseUrl}${n}`,{method:t,headers:{...l,"X-Visa-CLI-Version":er,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:o})}catch(d){throw new Error(bs(d))}if(this.parseServerSignals(c),c.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(c.status===429){let d=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${d}s. Tip: use the batch tool to combine multiple requests into one.`)}c.status===503&&await this.throwServerUnavailable(c);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(this.throwIfAttestationDrift(u),typeof u?.error_code=="string"&&u.error_code===Lm){let d=typeof u?.last4=="string"?u.last4:"",f=typeof u?.brand=="string"?u.brand:"card",p=jm(u?.reenroll_url),_=d?`${f} ending in ${d}`:"your card";throw new Error(`Please re-add ${_} to keep payments running. Open: ${p}`)}if(u?.declined){let d=Number(u.retryAfter??c.headers.get("Retry-After"));throw new le(u.error||"Your card was declined.",!!u.retryable,u.code,u.reason,u.payment_error_class,u.correlation_id,u.transactionId,Number.isFinite(d)&&d>0?d:void 0)}if(c.status===402){let d=u?.error||"Gateway returned 402",f=typeof u?.error_code=="string"?u.error_code:"";throw f==="SPENDING_LIMIT_EXCEEDED"||f==="DAILY_LIMIT_EXCEEDED"||f==="PER_TXN_LIMIT_EXCEEDED"?new Error(`${d}. Check your limits with get_status or run: visa-cli update-spending-controls`):new Error(d)}throw new Error(u?.error||`Request failed (${c.status}). Try again.`)}return u}async shortcut(t,n,r,o,s){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,o,s)}async shortcutWithSession(t,n,r,o,s,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,l=await this.getSessionToken();if(!l)throw new Error(_c());let c={Authorization:`Bearer ${l}`,"X-Visa-CLI-Version":er,"X-Source":"cli","Content-Type":"application/json"};i&&(c["X-Visa-Meta-Tool"]=i);let u={...n,...r};s&&(u.user_context=s.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await Ft(`${this.baseUrl}${a}`,{method:"POST",headers:c,body:JSON.stringify(u),timeoutMs:o})}catch(_){throw new Error(bs(_))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let _=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${_}s. Tip: use the batch tool to combine multiple requests into one.`)}let f=d.headers.get("X-Voucher-Receipt"),p;try{p=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(p),d.status===503){if(p?.error_code==="SESSION_LOCK_CONTENDED"){let h=Number(d.headers.get("Retry-After"))||1;throw new qt(p?.message||p?.error||"Session budget is being modified by another request. Retry shortly.",h,d.status)}throw new Error(yc(p))}let _=Vm(p?.error_code);if(_||d.status===410){let h=_??"BUDGET_CLOSED";throw new _n(p?.message||p?.error||"Your session was invalidated by the server.",h,{budgetId:n.session_budget_id,status:d.status})}if(p?.declined){let h=Number(p.retryAfter??d.headers.get("Retry-After"));throw new le(p.error||"Your card was declined.",!!p.retryable,p.code,p.reason,p.payment_error_class,p.correlation_id,p.transactionId,Number.isFinite(h)&&h>0?h:void 0)}throw new Error(p?.error||`Request failed (${d.status}). Try again.`)}return{data:p,voucherReceiptHeader:f}}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async catalogSearch(t,n,r,o){let s=r??"discover_tools",i=new URLSearchParams;t&&i.set("q",t),n&&i.set("category",n),o?.limit!=null&&i.set("limit",String(o.limit)),o?.offset!=null&&i.set("offset",String(o.offset));let a=i.toString();return this.request("GET",`/v1/catalog${a?`?${a}`:""}`,void 0,void 0,void 0,s)}async catalogTool(t,n){let r=n??"discover_tools";try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(t)}`,void 0,void 0,void 0,r)}catch{return null}}async discoverMerchantRoutes(t){try{return await this.request("GET",`/v1/platform/discover/${encodeURIComponent(t)}`)}catch{return null}}async listPublicMerchants(){try{let t=await Ft(`${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 Ft(`${this.baseUrl}/v1/platform/discover/${encodeURIComponent(t)}`,{method:"GET",timeoutMs:8e3});return n.ok?await n.json():null}catch{return null}}async paymentPreview(t,n){return this.request("POST","/v1/payment-preview",t,void 0,n)}async getBalance(){return this.request("GET","/v1/balance")}async topupBalance(t){return this.request("POST","/v1/balance/topup",t)}async createEnrollCode(){return this.request("POST","/v1/enroll-code")}async getAutoTopup(){let t=await this.getBalance();return{success:t.success,targetCents:t.autoTopupCents??null,thresholdCents:t.autoTopupThresholdCents??0}}async disableAutoTopup(){return this.request("PATCH","/v1/balance/auto-topup",{auto_topup_cents:null})}async createSessionBudget(t){return this.request("POST","/v1/session-budget/create",{...t,mode:"prepaid"})}async closeSession(t){return this.request("POST","/v1/session/close",{session_budget_id:t})}async getSessionBudget(t){return this.request("GET",`/v1/session-budget/${encodeURIComponent(t)}`)}async getSessionLedger(t){return this.request("GET",`/v1/session/${encodeURIComponent(t)}/ledger`)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getVisaSmi(t,n){return this.request("POST","/v1/visa/smi",t,6e4,n)}async getTransactions(t,n){let r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.offset!=null&&r.set("offset",String(t.offset));let o=r.toString(),s=o?`/v1/transactions?${o}`:"/v1/transactions";return this.request("GET",s,void 0,void 0,n)}async updateSpendingControls(t,n){return this.request("POST","/v1/spending-controls",t,void 0,n)}async removeCard(t,n,r){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(t))}`,n,void 0,r)}async setDefaultCard(t,n,r){return this.request("POST",`/v1/cards/${encodeURIComponent(String(t))}/default`,n,void 0,r)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t,n){return this.request("POST","/v1/attestation-key",{publicKey:t,...n?{attestation:n}:{}})}async startAttestationRecovery(t,n){return this.request("POST","/v1/attestation-key/recovery/start",{state:t},void 0,n)}async setBiometricPreference(t,n){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,n)}async logout(t,n){return this.request("POST","/v1/logout",t,void 0,n)}async feedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async createAppApiKey(t){return this.request("POST","/v1/api/keys",t)}async listAppApiKeys(){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 o=r.toString();return this.request("GET",`/v1/feedback${o?"?"+o:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}};var g={};Fo(g,{BRAND:()=>fp,DIRTY:()=>Bt,EMPTY_PATH:()=>Gm,INVALID:()=>A,NEVER:()=>Xp,OK:()=>ue,ParseStatus:()=>ce,Schema:()=>N,ZodAny:()=>kt,ZodArray:()=>ot,ZodBigInt:()=>Gt,ZodBoolean:()=>zt,ZodBranded:()=>nr,ZodCatch:()=>on,ZodDate:()=>Wt,ZodDefault:()=>rn,ZodDiscriminatedUnion:()=>no,ZodEffects:()=>Ae,ZodEnum:()=>tn,ZodError:()=>_e,ZodFirstPartyTypeKind:()=>R,ZodFunction:()=>oo,ZodIntersection:()=>Xt,ZodIssueCode:()=>y,ZodLazy:()=>Qt,ZodLiteral:()=>en,ZodMap:()=>kn,ZodNaN:()=>En,ZodNativeEnum:()=>nn,ZodNever:()=>Ie,ZodNull:()=>Yt,ZodNullable:()=>Ve,ZodNumber:()=>Kt,ZodObject:()=>ve,ZodOptional:()=>Te,ZodParsedType:()=>b,ZodPipeline:()=>rr,ZodPromise:()=>Tt,ZodReadonly:()=>sn,ZodRecord:()=>ro,ZodSchema:()=>N,ZodSet:()=>Tn,ZodString:()=>Ct,ZodSymbol:()=>xn,ZodTransformer:()=>Ae,ZodTuple:()=>Fe,ZodType:()=>N,ZodUndefined:()=>Jt,ZodUnion:()=>Zt,ZodUnknown:()=>rt,ZodVoid:()=>Cn,addIssueToContext:()=>v,any:()=>xp,array:()=>Ep,bigint:()=>_p,boolean:()=>Rc,coerce:()=>Zp,custom:()=>Tc,date:()=>vp,datetimeRegex:()=>Cc,defaultErrorMap:()=>tt,discriminatedUnion:()=>$p,effect:()=>Hp,enum:()=>Fp,function:()=>Dp,getErrorMap:()=>bn,getParsedType:()=>je,instanceof:()=>hp,intersection:()=>Pp,isAborted:()=>eo,isAsync:()=>Sn,isDirty:()=>to,isValid:()=>xt,late:()=>gp,lazy:()=>Up,literal:()=>jp,makeIssue:()=>tr,map:()=>Np,nan:()=>yp,nativeEnum:()=>Vp,never:()=>kp,null:()=>wp,nullable:()=>Kp,number:()=>Ac,object:()=>Ap,objectUtil:()=>$s,oboolean:()=>Yp,onumber:()=>Jp,optional:()=>Bp,ostring:()=>Wp,pipeline:()=>zp,preprocess:()=>Gp,promise:()=>qp,quotelessJson:()=>Hm,record:()=>Op,set:()=>Lp,setErrorMap:()=>Km,strictObject:()=>Rp,string:()=>Ec,symbol:()=>bp,transformer:()=>Hp,tuple:()=>Mp,undefined:()=>Sp,union:()=>Ip,unknown:()=>Cp,util:()=>L,void:()=>Tp});var L;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},e.getValidEnumValues=o=>{let s=e.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return e.objectValues(i)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},e.find=(o,s)=>{for(let i of o)if(s(i))return i},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(L||(L={}));var $s;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})($s||($s={}));var b=L.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),je=e=>{switch(typeof e){case"undefined":return b.undefined;case"string":return b.string;case"number":return Number.isNaN(e)?b.nan:b.number;case"boolean":return b.boolean;case"function":return b.function;case"bigint":return b.bigint;case"symbol":return b.symbol;case"object":return Array.isArray(e)?b.array:e===null?b.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?b.promise:typeof Map<"u"&&e instanceof Map?b.map:typeof Set<"u"&&e instanceof Set?b.set:typeof Date<"u"&&e instanceof Date?b.date:b.object;default:return b.unknown}};var y=L.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"]),Hm=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),_e=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,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 o(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,L.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];n[s]=n[s]||[],n[s].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};_e.create=e=>new _e(e);var Bm=(e,t)=>{let n;switch(e.code){case y.invalid_type:e.received===b.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case y.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,L.jsonStringifyReplacer)}`;break;case y.unrecognized_keys:n=`Unrecognized key(s) in object: ${L.joinValues(e.keys,", ")}`;break;case y.invalid_union:n="Invalid input";break;case y.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${L.joinValues(e.options)}`;break;case y.invalid_enum_value:n=`Invalid enum value. Expected ${L.joinValues(e.options)}, received '${e.received}'`;break;case y.invalid_arguments:n="Invalid function arguments";break;case y.invalid_return_type:n="Invalid function return type";break;case y.invalid_date:n="Invalid date";break;case y.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}"`:L.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case y.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 y.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 y.custom:n="Invalid input";break;case y.invalid_intersection_types:n="Intersection results could not be merged";break;case y.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case y.not_finite:n="Number must be finite";break;default:n=t.defaultError,L.assertNever(e)}return{message:n}},tt=Bm;var vc=tt;function Km(e){vc=e}function bn(){return vc}var tr=e=>{let{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)a=c(i,{data:t,defaultError:a}).message;return{...o,path:s,message:a}},Gm=[];function v(e,t){let n=bn(),r=tr({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===tt?void 0:tt].filter(o=>!!o)});e.common.issues.push(r)}var ce=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let o of n){if(o.status==="aborted")return A;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let o of n){let s=await o.key,i=await o.value;r.push({key:s,value:i})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let o of n){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return A;s.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:t.value,value:r}}},A=Object.freeze({status:"aborted"}),Bt=e=>({status:"dirty",value:e}),ue=e=>({status:"valid",value:e}),eo=e=>e.status==="aborted",to=e=>e.status==="dirty",xt=e=>e.status==="valid",Sn=e=>typeof Promise<"u"&&e instanceof Promise;var w;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(w||(w={}));var Ee=class{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},bc=(e,t)=>{if(xt(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 _e(e.common.issues);return this._error=n,this._error}}};function M(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(i,a)=>{let{message: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:o}}var N=class{get description(){return this._def.description}_getType(t){return je(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:je(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ce,ctx:{common:t.parent.common,data:t.data,parsedType:je(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Sn(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:je(t)},o=this._parseSync({data:t,path:r.path,parent:r});return bc(r,o)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:je(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return xt(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=>xt(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:je(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(Sn(o)?o:Promise.resolve(o));return bc(r,s)}refine(t,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{let i=t(o),a=()=>s.addIssue({code:y.custom,...r(o)});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,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Ae({schema:this,typeName:R.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 Te.create(this,this._def)}nullable(){return Ve.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ot.create(this)}promise(){return Tt.create(this,this._def)}or(t){return Zt.create([this,t],this._def)}and(t){return Xt.create(this,t,this._def)}transform(t){return new Ae({...M(this._def),schema:this,typeName:R.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new rn({...M(this._def),innerType:this,defaultValue:n,typeName:R.ZodDefault})}brand(){return new nr({typeName:R.ZodBranded,type:this,...M(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new on({...M(this._def),innerType:this,catchValue:n,typeName:R.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return rr.create(this,t)}readonly(){return sn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},zm=/^c[^\s-]{8,}$/i,Wm=/^[0-9a-z]+$/,Jm=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ym=/^[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,Zm=/^[a-z0-9_-]{21}$/i,Xm=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Qm=/^[-+]?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)?)??$/,ep=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,tp="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ps,np=/^(?:(?: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])$/,rp=/^(?:(?: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])$/,op=/^(([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]))$/,sp=/^(([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])$/,ip=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ap=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,wc="((\\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])))",cp=new RegExp(`^${wc}$`);function xc(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 lp(e){return new RegExp(`^${xc(e)}$`)}function Cc(e){let t=`${wc}T${xc(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 up(e,t){return!!((t==="v4"||!t)&&np.test(e)||(t==="v6"||!t)&&op.test(e))}function dp(e,t){if(!Xm.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function mp(e,t){return!!((t==="v4"||!t)&&rp.test(e)||(t==="v6"||!t)&&sp.test(e))}var Ct=class e extends N{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==b.string){let s=this._getOrReturnCtx(t);return v(s,{code:y.invalid_type,expected:b.string,received:s.parsedType}),A}let r=new ce,o;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),v(o,{code:y.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),v(o,{code:y.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let i=t.data.length>s.value,a=t.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(t,o),i?v(o,{code:y.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&v(o,{code:y.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")ep.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"email",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Ps||(Ps=new RegExp(tp,"u")),Ps.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"emoji",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")Ym.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"uuid",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")Zm.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"nanoid",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")zm.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"cuid",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")Wm.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"cuid2",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")Jm.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"ulid",code:y.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),v(o,{validation:"url",code:y.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"regex",code:y.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),v(o,{code:y.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),v(o,{code:y.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),v(o,{code:y.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?Cc(s).test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{code:y.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?cp.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{code:y.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?lp(s).test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{code:y.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?Qm.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"duration",code:y.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?up(t.data,s.version)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"ip",code:y.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?dp(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"jwt",code:y.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?mp(t.data,s.version)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"cidr",code:y.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?ip.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"base64",code:y.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?ap.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"base64url",code:y.invalid_string,message:s.message}),r.dirty()):L.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:y.invalid_string,...w.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...w.errToObj(t)})}url(t){return this._addCheck({kind:"url",...w.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...w.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...w.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...w.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...w.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...w.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...w.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...w.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...w.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...w.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...w.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...w.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,...w.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,...w.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...w.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...w.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...w.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...w.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...w.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...w.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...w.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...w.errToObj(n)})}nonempty(t){return this.min(1,w.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}};Ct.create=e=>new Ct({checks:[],typeName:R.ZodString,coerce:e?.coerce??!1,...M(e)});function pp(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/10**o}var Kt=class e extends N{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)!==b.number){let s=this._getOrReturnCtx(t);return v(s,{code:y.invalid_type,expected:b.number,received:s.parsedType}),A}let r,o=new ce;for(let s of this._def.checks)s.kind==="int"?L.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),v(r,{code:y.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),v(r,{code:y.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),v(r,{code:y.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?pp(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),v(r,{code:y.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),v(r,{code:y.not_finite,message:s.message}),o.dirty()):L.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,w.toString(n))}gt(t,n){return this.setLimit("min",t,!1,w.toString(n))}lte(t,n){return this.setLimit("max",t,!0,w.toString(n))}lt(t,n){return this.setLimit("max",t,!1,w.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:w.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:w.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:w.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:w.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:w.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:w.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:w.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:w.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:w.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:w.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"&&L.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:R.ZodNumber,coerce:e?.coerce||!1,...M(e)});var Gt=class e extends N{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)!==b.bigint)return this._getInvalidInput(t);let r,o=new ce;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),v(r,{code:y.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),v(r,{code:y.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),v(r,{code:y.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):L.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return v(n,{code:y.invalid_type,expected:b.bigint,received:n.parsedType}),A}gte(t,n){return this.setLimit("min",t,!0,w.toString(n))}gt(t,n){return this.setLimit("min",t,!1,w.toString(n))}lte(t,n){return this.setLimit("max",t,!0,w.toString(n))}lt(t,n){return this.setLimit("max",t,!1,w.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:w.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:w.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:w.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:w.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:w.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:w.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}};Gt.create=e=>new Gt({checks:[],typeName:R.ZodBigInt,coerce:e?.coerce??!1,...M(e)});var zt=class extends N{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==b.boolean){let r=this._getOrReturnCtx(t);return v(r,{code:y.invalid_type,expected:b.boolean,received:r.parsedType}),A}return ue(t.data)}};zt.create=e=>new zt({typeName:R.ZodBoolean,coerce:e?.coerce||!1,...M(e)});var Wt=class e extends N{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==b.date){let s=this._getOrReturnCtx(t);return v(s,{code:y.invalid_type,expected:b.date,received:s.parsedType}),A}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return v(s,{code:y.invalid_date}),A}let r=new ce,o;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),v(o,{code:y.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),v(o,{code:y.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):L.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:w.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:w.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}};Wt.create=e=>new Wt({checks:[],coerce:e?.coerce||!1,typeName:R.ZodDate,...M(e)});var xn=class extends N{_parse(t){if(this._getType(t)!==b.symbol){let r=this._getOrReturnCtx(t);return v(r,{code:y.invalid_type,expected:b.symbol,received:r.parsedType}),A}return ue(t.data)}};xn.create=e=>new xn({typeName:R.ZodSymbol,...M(e)});var Jt=class extends N{_parse(t){if(this._getType(t)!==b.undefined){let r=this._getOrReturnCtx(t);return v(r,{code:y.invalid_type,expected:b.undefined,received:r.parsedType}),A}return ue(t.data)}};Jt.create=e=>new Jt({typeName:R.ZodUndefined,...M(e)});var Yt=class extends N{_parse(t){if(this._getType(t)!==b.null){let r=this._getOrReturnCtx(t);return v(r,{code:y.invalid_type,expected:b.null,received:r.parsedType}),A}return ue(t.data)}};Yt.create=e=>new Yt({typeName:R.ZodNull,...M(e)});var kt=class extends N{constructor(){super(...arguments),this._any=!0}_parse(t){return ue(t.data)}};kt.create=e=>new kt({typeName:R.ZodAny,...M(e)});var rt=class extends N{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ue(t.data)}};rt.create=e=>new rt({typeName:R.ZodUnknown,...M(e)});var Ie=class extends N{_parse(t){let n=this._getOrReturnCtx(t);return v(n,{code:y.invalid_type,expected:b.never,received:n.parsedType}),A}};Ie.create=e=>new Ie({typeName:R.ZodNever,...M(e)});var Cn=class extends N{_parse(t){if(this._getType(t)!==b.undefined){let r=this._getOrReturnCtx(t);return v(r,{code:y.invalid_type,expected:b.void,received:r.parsedType}),A}return ue(t.data)}};Cn.create=e=>new Cn({typeName:R.ZodVoid,...M(e)});var ot=class e extends N{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==b.array)return v(n,{code:y.invalid_type,expected:b.array,received:n.parsedType}),A;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(v(n,{code:i?y.too_big:y.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(v(n,{code:y.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(v(n,{code:y.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>o.type._parseAsync(new Ee(n,i,n.path,a)))).then(i=>ce.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new Ee(n,i,n.path,a)));return ce.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:w.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:w.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:w.toString(n)}})}nonempty(t){return this.min(1,t)}};ot.create=(e,t)=>new ot({type:e,minLength:null,maxLength:null,exactLength:null,typeName:R.ZodArray,...M(t)});function wn(e){if(e instanceof ve){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Te.create(wn(r))}return new ve({...e._def,shape:()=>t})}else return e instanceof ot?new ot({...e._def,type:wn(e.element)}):e instanceof Te?Te.create(wn(e.unwrap())):e instanceof Ve?Ve.create(wn(e.unwrap())):e instanceof Fe?Fe.create(e.items.map(t=>wn(t))):e}var ve=class e extends N{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=L.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==b.object){let c=this._getOrReturnCtx(t);return v(c,{code:y.invalid_type,expected:b.object,received:c.parsedType}),A}let{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ie&&this._def.unknownKeys==="strip"))for(let c in o.data)i.includes(c)||a.push(c);let l=[];for(let c of i){let u=s[c],d=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Ee(o,d,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Ie){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")a.length>0&&(v(o,{code:y.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 d=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Ee(o,d,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of l){let d=await u.key,f=await u.value;c.push({key:d,value:f,alwaysSet:u.alwaysSet})}return c}).then(c=>ce.mergeObjectSync(r,c)):ce.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return w.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:w.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:R.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 L.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 L.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return wn(this)}partial(t){let n={};for(let r of L.objectKeys(this.shape)){let o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let r of L.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Te;)s=s._def.innerType;n[r]=s}return new e({...this._def,shape:()=>n})}keyof(){return kc(L.objectKeys(this.shape))}};ve.create=(e,t)=>new ve({shape:()=>e,unknownKeys:"strip",catchall:Ie.create(),typeName:R.ZodObject,...M(t)});ve.strictCreate=(e,t)=>new ve({shape:()=>e,unknownKeys:"strict",catchall:Ie.create(),typeName:R.ZodObject,...M(t)});ve.lazycreate=(e,t)=>new ve({shape:e,unknownKeys:"strip",catchall:Ie.create(),typeName:R.ZodObject,...M(t)});var Zt=class extends N{_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new _e(a.ctx.common.issues));return v(n,{code:y.invalid_union,unionErrors:i}),A}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let 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"&&!s&&(s={result:u,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(l=>new _e(l));return v(n,{code:y.invalid_union,unionErrors:a}),A}}get options(){return this._def.options}};Zt.create=(e,t)=>new Zt({options:e,typeName:R.ZodUnion,...M(t)});var nt=e=>e instanceof Qt?nt(e.schema):e instanceof Ae?nt(e.innerType()):e instanceof en?[e.value]:e instanceof tn?e.options:e instanceof nn?L.objectValues(e.enum):e instanceof rn?nt(e._def.innerType):e instanceof Jt?[void 0]:e instanceof Yt?[null]:e instanceof Te?[void 0,...nt(e.unwrap())]:e instanceof Ve?[null,...nt(e.unwrap())]:e instanceof nr||e instanceof sn?nt(e.unwrap()):e instanceof on?nt(e._def.innerType):[],no=class e extends N{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.object)return v(n,{code:y.invalid_type,expected:b.object,received:n.parsedType}),A;let r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(v(n,{code:y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),A)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let o=new Map;for(let s of n){let i=nt(s.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);o.set(a,s)}}return new e({typeName:R.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...M(r)})}};function Ms(e,t){let n=je(e),r=je(t);if(e===t)return{valid:!0,data:e};if(n===b.object&&r===b.object){let o=L.objectKeys(t),s=L.objectKeys(e).filter(a=>o.indexOf(a)!==-1),i={...e,...t};for(let a of s){let l=Ms(e[a],t[a]);if(!l.valid)return{valid:!1};i[a]=l.data}return{valid:!0,data:i}}else if(n===b.array&&r===b.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let s=0;s<e.length;s++){let i=e[s],a=t[s],l=Ms(i,a);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===b.date&&r===b.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Xt=class extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=(s,i)=>{if(eo(s)||eo(i))return A;let a=Ms(s.value,i.value);return a.valid?((to(s)||to(i))&&n.dirty(),{status:n.value,value:a.data}):(v(r,{code:y.invalid_intersection_types}),A)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Xt.create=(e,t,n)=>new Xt({left:e,right:t,typeName:R.ZodIntersection,...M(n)});var Fe=class e extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.array)return v(r,{code:y.invalid_type,expected:b.array,received:r.parsedType}),A;if(r.data.length<this._def.items.length)return v(r,{code:y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),A;!this._def.rest&&r.data.length>this._def.items.length&&(v(r,{code:y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Ee(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>ce.mergeArray(n,i)):ce.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Fe.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Fe({items:e,typeName:R.ZodTuple,rest:null,...M(t)})};var ro=class e extends N{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!==b.object)return v(r,{code:y.invalid_type,expected:b.object,received:r.parsedType}),A;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new Ee(r,a,r.path,a)),value:i._parse(new Ee(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?ce.mergeObjectAsync(n,o):ce.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof N?new e({keyType:t,valueType:n,typeName:R.ZodRecord,...M(r)}):new e({keyType:Ct.create(),valueType:t,typeName:R.ZodRecord,...M(n)})}},kn=class extends N{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!==b.map)return v(r,{code:y.invalid_type,expected:b.map,received:r.parsedType}),A;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,l],c)=>({key:o._parse(new Ee(r,a,r.path,[c,"key"])),value:s._parse(new Ee(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 A;(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 A;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}}}};kn.create=(e,t,n)=>new kn({valueType:t,keyType:e,typeName:R.ZodMap,...M(n)});var Tn=class e extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.set)return v(r,{code:y.invalid_type,expected:b.set,received:r.parsedType}),A;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(v(r,{code:y.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(v(r,{code:y.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(l){let c=new Set;for(let u of l){if(u.status==="aborted")return A;u.status==="dirty"&&n.dirty(),c.add(u.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((l,c)=>s._parse(new Ee(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:w.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:w.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};Tn.create=(e,t)=>new Tn({valueType:e,minSize:null,maxSize:null,typeName:R.ZodSet,...M(t)});var oo=class e extends N{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.function)return v(n,{code:y.invalid_type,expected:b.function,received:n.parsedType}),A;function r(a,l){return tr({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,bn(),tt].filter(c=>!!c),issueData:{code:y.invalid_arguments,argumentsError:l}})}function o(a,l){return tr({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,bn(),tt].filter(c=>!!c),issueData:{code:y.invalid_return_type,returnTypeError:l}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof Tt){let a=this;return ue(async function(...l){let c=new _e([]),u=await a._def.args.parseAsync(l,s).catch(p=>{throw c.addIssue(r(l,p)),c}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,s).catch(p=>{throw c.addIssue(o(d,p)),c})})}else{let a=this;return ue(function(...l){let c=a._def.args.safeParse(l,s);if(!c.success)throw new _e([r(l,c.error)]);let u=Reflect.apply(i,this,c.data),d=a._def.returns.safeParse(u,s);if(!d.success)throw new _e([o(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Fe.create(t).rest(rt.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||Fe.create([]).rest(rt.create()),returns:n||rt.create(),typeName:R.ZodFunction,...M(r)})}},Qt=class extends N{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})}};Qt.create=(e,t)=>new Qt({getter:e,typeName:R.ZodLazy,...M(t)});var en=class extends N{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return v(n,{received:n.data,code:y.invalid_literal,expected:this._def.value}),A}return{status:"valid",value:t.data}}get value(){return this._def.value}};en.create=(e,t)=>new en({value:e,typeName:R.ZodLiteral,...M(t)});function kc(e,t){return new tn({values:e,typeName:R.ZodEnum,...M(t)})}var tn=class e extends N{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return v(n,{expected:L.joinValues(r),received:n.parsedType,code:y.invalid_type}),A}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 v(n,{received:n.data,code:y.invalid_enum_value,options:r}),A}return ue(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})}};tn.create=kc;var nn=class extends N{_parse(t){let n=L.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==b.string&&r.parsedType!==b.number){let o=L.objectValues(n);return v(r,{expected:L.joinValues(o),received:r.parsedType,code:y.invalid_type}),A}if(this._cache||(this._cache=new Set(L.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let o=L.objectValues(n);return v(r,{received:r.data,code:y.invalid_enum_value,options:o}),A}return ue(t.data)}get enum(){return this._def.values}};nn.create=(e,t)=>new nn({values:e,typeName:R.ZodNativeEnum,...M(t)});var Tt=class extends N{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.promise&&n.common.async===!1)return v(n,{code:y.invalid_type,expected:b.promise,received:n.parsedType}),A;let r=n.parsedType===b.promise?n.data:Promise.resolve(n.data);return ue(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Tt.create=(e,t)=>new Tt({type:e,typeName:R.ZodPromise,...M(t)});var Ae=class extends N{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===R.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:i=>{v(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return A;let l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?A:l.status==="dirty"?Bt(l.value):n.value==="dirty"?Bt(l.value):l});{if(n.value==="aborted")return A;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?A:a.status==="dirty"?Bt(a.value):n.value==="dirty"?Bt(a.value):a}}if(o.type==="refinement"){let i=a=>{let l=o.refinement(a,s);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"?A:(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"?A:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!xt(i))return A;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>xt(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):A);L.assertNever(o)}};Ae.create=(e,t,n)=>new Ae({schema:e,typeName:R.ZodEffects,effect:t,...M(n)});Ae.createWithPreprocess=(e,t,n)=>new Ae({schema:t,effect:{type:"preprocess",transform:e},typeName:R.ZodEffects,...M(n)});var Te=class extends N{_parse(t){return this._getType(t)===b.undefined?ue(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Te.create=(e,t)=>new Te({innerType:e,typeName:R.ZodOptional,...M(t)});var Ve=class extends N{_parse(t){return this._getType(t)===b.null?ue(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ve.create=(e,t)=>new Ve({innerType:e,typeName:R.ZodNullable,...M(t)});var rn=class extends N{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===b.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};rn.create=(e,t)=>new rn({innerType:e,typeName:R.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...M(t)});var on=class extends N{_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Sn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new _e(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new _e(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};on.create=(e,t)=>new on({innerType:e,typeName:R.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...M(t)});var En=class extends N{_parse(t){if(this._getType(t)!==b.nan){let r=this._getOrReturnCtx(t);return v(r,{code:y.invalid_type,expected:b.nan,received:r.parsedType}),A}return{status:"valid",value:t.data}}};En.create=e=>new En({typeName:R.ZodNaN,...M(e)});var fp=Symbol("zod_brand"),nr=class extends N{_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}},rr=class e extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?A:s.status==="dirty"?(n.dirty(),Bt(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?A:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:R.ZodPipeline})}},sn=class extends N{_parse(t){let n=this._def.innerType._parse(t),r=o=>(xt(o)&&(o.value=Object.freeze(o.value)),o);return Sn(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};sn.create=(e,t)=>new sn({innerType:e,typeName:R.ZodReadonly,...M(t)});function Sc(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Tc(e,t={},n){return e?kt.create().superRefine((r,o)=>{let s=e(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Sc(t,r),l=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:l})}});if(!s){let i=Sc(t,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):kt.create()}var gp={object:ve.lazycreate},R;(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"})(R||(R={}));var hp=(e,t={message:`Input not instance of ${e.name}`})=>Tc(n=>n instanceof e,t),Ec=Ct.create,Ac=Kt.create,yp=En.create,_p=Gt.create,Rc=zt.create,vp=Wt.create,bp=xn.create,Sp=Jt.create,wp=Yt.create,xp=kt.create,Cp=rt.create,kp=Ie.create,Tp=Cn.create,Ep=ot.create,Ap=ve.create,Rp=ve.strictCreate,Ip=Zt.create,$p=no.create,Pp=Xt.create,Mp=Fe.create,Op=ro.create,Np=kn.create,Lp=Tn.create,Dp=oo.create,Up=Qt.create,jp=en.create,Fp=tn.create,Vp=nn.create,qp=Tt.create,Hp=Ae.create,Bp=Te.create,Kp=Ve.create,Gp=Ae.createWithPreprocess,zp=rr.create,Wp=()=>Ec().optional(),Jp=()=>Ac().optional(),Yp=()=>Rc().optional(),Zp={string:(e=>Ct.create({...e,coerce:!0})),number:(e=>Kt.create({...e,coerce:!0})),boolean:(e=>zt.create({...e,coerce:!0})),bigint:(e=>Gt.create({...e,coerce:!0})),date:(e=>Wt.create({...e,coerce:!0}))};var Xp=A;var Ic=["tempo","mpp_self","merchant_self"];var Ns=g.object({inputPerMillion:g.number().positive(),outputPerMillion:g.number().positive(),contextWindow:g.number().int().positive().optional(),maxOutput:g.number().int().positive().optional(),perRequestFeeCents:g.number().nonnegative().optional()}),Qp=g.object({strategy:g.enum(["flat","token","band"]).optional(),pricingModel:g.enum(["per-call","per-token","band"]).optional(),priceCents:g.number().nonnegative().optional(),currency:g.string().optional(),display:g.string().optional(),estimate:g.boolean().optional(),source:g.string().optional(),priceBand:g.record(g.unknown()).optional(),tokenPricing:Ns.optional()}).passthrough(),Ls=g.discriminatedUnion("type",[g.object({type:g.literal("shortcut"),routedPath:g.string().min(1).startsWith("/")}),g.object({type:g.literal("custom"),merchantSlug:g.string().min(1),subPath:g.string().optional()}),g.object({type:g.literal("local"),fn:g.string().min(1)}),g.object({type:g.literal("read")})]),Ds=g.object({amount:g.number().nonnegative(),currency:g.string().length(3).optional(),display:g.string().optional(),free:g.boolean().optional(),batchDiscount:g.number().min(0).max(100).optional()}),$c=g.object({attestation:g.boolean().optional(),rateLimitMs:g.number().positive().optional()}),Pc=g.object({displayName:g.string().optional(),feedbackEligible:g.boolean().optional(),suggestionEligible:g.boolean().optional(),batchable:g.boolean().optional()}),ef=g.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),tf=120,nf=120,rf=1200,of=/^[^\u0000-\u001F\u007F]+$/;function Os(e,t){return g.string().min(1).max(e).regex(of,`${t} must not contain control characters`)}var Us={id:g.string().min(1),name:Os(tf,"name"),description:Os(rf,"description"),provider:g.string().min(1),model:g.string().min(1),category:ef,priceCents:g.number().nonnegative(),inputSchema:g.record(g.unknown()),gatewayUrl:g.string().min(1),merchantName:Os(nf,"merchantName"),isAsync:g.boolean().optional(),pollUrl:g.string().optional(),pollInterval:g.number().positive().optional(),pollTimeout:g.number().positive().optional(),tags:g.array(g.string()).optional(),tokenPricing:Ns.optional(),priceDisplay:g.string().optional(),pricingModel:g.enum(["per-call","per-token","band"]).optional(),pricingInfo:Qp.optional(),status:g.enum(["available","unavailable"]).optional(),handler:Ls.optional(),pricing:Ds.optional(),security:$c.optional(),engagement:Pc.optional(),enabled:g.boolean().optional(),beta:g.boolean().optional(),deprecated:g.boolean().optional(),replacementTool:g.string().optional(),minCliVersion:g.string().optional(),sunsetAt:g.string().optional(),rail:g.enum(Ic).optional(),pricingStrategy:g.enum(["flat","token","band"]).optional()},Mc=g.object({...Us,dispatch:g.literal("routed"),routedPath:g.string().min(1).startsWith("/")}).strict(),Oc=g.object({...Us,dispatch:g.literal("enveloped")}).strict(),Nc=g.object({...Us,handler:Ls,pricing:Ds}).strict(),Lc=g.union([g.discriminatedUnion("dispatch",[Mc,Oc]),Nc]);var js=/^[a-z0-9][a-z0-9_-]*$/;var af="https://fal.run",Fc="https://openrouter.mpp.tempo.xyz";function cf(e){let{attestation:t,tool_id:n,...r}=e;return r}var Dc={"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 so(e){let{attestation:t,tool_id:n,aspect_ratio:r,image_size:o,...s}=e,i={...s};return typeof o=="string"&&o.length>0?(i.image_size=o,i):(typeof r=="string"&&Dc[r]&&(i.image_size=Dc[r]),i)}function Uc(e){let t={chain:e.chain,token_address:e.token_address};if(e.start_timestamp){let n=e.end_timestamp||new Date().toISOString(),r=e.time_granularity;if(!r){let o=new Date(e.start_timestamp).getTime();(new Date(n).getTime()-o)/(1e3*60*60*24)<=2?r="1h":r="1d"}return{addresses:[t],start_timestamp:e.start_timestamp,end_timestamp:n,time_granularity:r}}return[t]}function lf(e,t,n,r,o,s,i,a,l){return{id:e,name:t,description:n,provider:r,model:o.replace(/^\//,""),category:s,gatewayUrl:`https://${r}${o}`,merchantName:t,inputSchema:a,handler:{type:"custom",merchantSlug:r,subPath:o},pricing:{amount:i,currency:"USD",display:`$${(i/100).toFixed(2)}`},priceCents:i,tags:[],...l}}function uf(e,t,n,r,o,s,i,a){return lf(e,t,n,"suno-ai",r,o,s,i,{merchantName:"Suno AI",...a})}function X(e,t,n,r,o,s,i,a){return{dispatch:"routed",id:e,name:t,description:n,provider:"fal",model:r,category:o,priceCents:s,inputSchema:i,routedPath:`/api/v1/fal/${r}`,gatewayUrl:`${af}/${r}`,merchantName:"fal.ai",buildBody:cf,tags:[],...a}}function df(e){return t=>{let{attestation:n,tool_id:r,prompt:o,system_prompt:s,max_tokens:i,temperature:a,...l}=t;return{model:e,messages:[...s?[{role:"system",content:s}]:[],{role:"user",content:o}],max_tokens:i??1024,temperature:a??.7,...l}}}function mf(e){return t=>{let{attestation:n,tool_id:r,prompt:o,image_url:s,aspect_ratio:i,max_tokens:a,temperature:l,...c}=t,u=[{type:"text",text:o}];return typeof s=="string"&&s.length>0&&u.push({type:"image_url",image_url:{url:s}}),{model:e,messages:[{role:"user",content:u}],max_tokens:a??1024,temperature:l??.7,...typeof i=="string"&&i.length>0?{image_config:{aspect_ratio:i}}:{},...c}}}function te(e,t,n,r,o,s,i){let a=i?.perRequestFeeCents??0,l=500/1e6*o*100,c=500/1e6*s*100,u=Math.max(1,Math.ceil(l+c+a)),{perRequestFeeCents:d,...f}=i??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"llm",priceCents:u,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:`${Fc}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:df(r),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:o,outputPerMillion:s,...a>0?{perRequestFeeCents:a}:{}},...f}}function Fs(e,t,n,r,o,s){return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"image",priceCents:o,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate or edit"},image_url:{type:"string",description:"Optional source image URL for edits"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"1:1"},max_tokens:{type:"integer",description:"Maximum text tokens in response metadata (default: 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:`${Fc}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:mf(r),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...s}}var Vs=[X("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"]}),X("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:so}),X("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:so}),X("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:so}),X("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"]}),Fs("or-gemini-nano-banana","Nano Banana","Google Gemini 2.5 Flash Image via OpenRouter for image generation and edits.","google/gemini-2.5-flash-image",4),Fs("or-gemini-nano-banana-2","Nano Banana 2","Google Gemini 3.1 Flash Image Preview via OpenRouter for fast image generation and edits.","google/gemini-3.1-flash-image-preview",5,{tags:["image","gemini","google","nano-banana","edit","fast"],tokenPricing:{inputPerMillion:.5,outputPerMillion:3}}),Fs("or-gemini-nano-banana-pro","Nano Banana Pro","Google Gemini 3 Pro Image Preview via OpenRouter for professional image generation, edits, and text rendering.","google/gemini-3-pro-image-preview",8,{tags:["image","gemini","google","nano-banana","pro","text-rendering"],tokenPricing:{inputPerMillion:2,outputPerMillion:12}}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("fal-stable-audio","Stable Audio","Generate sound effects and ambient audio from text descriptions.","fal-ai/stable-audio","audio",4,{type:"object",properties:{prompt:{type:"string",description:"Description of the audio to generate"},seconds_total:{type:"number",description:"Duration in seconds (max 47)",default:30}},required:["prompt"]},{tags:["audio","sound-effects","ambient"]}),X("fal-ace-step-music","ACE-Step Music","Generate full music tracks from a prompt, with optional vocals or instrumentals.","fal-ai/ace-step/prompt-to-audio","audio",2,{type:"object",properties:{prompt:{type:"string",description:"Description of the song, genre, mood, instruments, and lyrics direction"},instrumental:{type:"boolean",description:"Generate instrumental music without vocals",default:!1},duration:{type:"number",description:"Duration in seconds",default:60}},required:["prompt"]},{tags:["music","song","vocals","instrumental","ace-step"]}),uf("suno-music","Suno Music","AI music generation. Create full songs with vocals or instrumentals.","/suno/generate-music","audio",10,{type:"object",properties:{prompt:{type:"string",description:"Description of the song (genre, mood, instruments)"},instrumental:{type:"boolean",description:"Instrumental only, no vocals",default:!1}},required:["prompt"]},{isAsync:!0,pollUrl:"https://api.sunoapi.org/suno/get-music-status",deprecated:!0,tags:["music","song","vocals","instrumental"],buildBody:e=>{let{attestation:t,tool_id:n,prompt:r,instrumental:o,...s}=e;return{prompt:r,customMode:!1,instrumental:typeof o=="boolean"?o:!1,model:"V4",...s}}}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),te("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"]}),te("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"]}),te("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"]}),te("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"]}),te("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"]}),te("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"]}),te("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"]}),te("or-gemini-3-flash","Gemini 3 Flash","Google's high-speed thinking model for agentic workflows, coding, and multimodal tasks.","google/gemini-3-flash-preview",.5,3,{tags:["llm","gemini","google","agentic","coding","fast"]}),te("or-gemini-3-pro","Gemini 3 Pro","Google's flagship frontier model for deep reasoning, multimodal analysis, and agentic coding.","google/gemini-3-pro-preview",2,12,{tags:["llm","gemini","google","reasoning","coding","multimodal"]}),te("or-gemini-3-lite","Gemini 3.1 Flash Lite","Google's efficient multimodal model optimized for low-latency, high-volume agent workloads.","google/gemini-3.1-flash-lite",.25,1.5,{tags:["llm","gemini","google","fast","cheap","multimodal"]}),te("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"]}),te("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"]}),te("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"]}),te("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"]}),te("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"]}),te("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"]}),te("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"]}),te("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"]}),te("or-perplexity-sonar","Perplexity Sonar","Search-augmented LLM. Answers with real-time web sources and citations.","perplexity/sonar",1,1,{perRequestFeeCents:.5,tags:["llm","perplexity","search","web","citations","real-time"]}),{dispatch:"enveloped",id:"query_onchain_prices",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly and daily granularity.",provider:"allium",model:"allium-prices",category:"onchain",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly) or '1d' (daily). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:Uc,tags:["onchain","prices","allium","crypto"]},{dispatch:"enveloped",id:"generate_image_card",name:"Generate Image (Ultra)",description:"Generate a high-quality AI image (FLUX Pro Ultra, 2K, ~$0.06).",provider:"fal",model:"fal-ai/flux-pro/v1.1-ultra",category:"image",priceCents:6,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1-ultra",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro-ultra",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),t},tags:["image","flux","ultra","legacy"]},{dispatch:"enveloped",id:"generate_image_fast_card",name:"Generate Image (Fast)",description:"Generate an AI image (FLUX Pro v1.1, 1K, ~$0.04).",provider:"fal",model:"fal-ai/flux-pro/v1.1",category:"image",priceCents:4,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro",buildBody:e=>so({prompt:e.prompt,aspect_ratio:e.aspect_ratio}),tags:["image","flux","legacy"]},{dispatch:"enveloped",id:"generate_image_schnell_card",name:"Generate Image (Cheap)",description:"Cheap, fast FLUX image generation (~$0.01).",provider:"fal",model:"fal-ai/flux/schnell",category:"image",priceCents:1,inputSchema:{type:"object",properties:{prompt:{type:"string"},image_size:{type:"string"},num_inference_steps:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux/schnell",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-schnell",buildBody:e=>{let t={prompt:e.prompt};return e.image_size&&(t.image_size=e.image_size),e.num_inference_steps!==void 0&&(t.num_inference_steps=e.num_inference_steps),e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","flux","schnell","legacy"]},{dispatch:"enveloped",id:"generate_image_recraft_card",name:"Generate Image (Recraft)",description:"Recraft V3 image generation with style control.",provider:"fal",model:"fal-ai/recraft-v3",category:"image",priceCents:5,inputSchema:{type:"object",properties:{prompt:{type:"string"},style:{type:"string"},image_size:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/recraft-v3",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-recraft-v3",buildBody:e=>{let t={prompt:e.prompt};return e.style&&(t.style=e.style),e.image_size&&(t.image_size=e.image_size),t},tags:["image","recraft","legacy"]},{dispatch:"enveloped",id:"generate_image_ideogram_card",name:"Generate Image (Ideogram)",description:"Ideogram V2 image generation, strong with text rendering.",provider:"fal",model:"fal-ai/ideogram/v2",category:"image",priceCents:8,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},style_type:{type:"string"},negative_prompt:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/ideogram/v2",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-ideogram-v2",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.style_type&&(t.style_type=e.style_type),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),t},tags:["image","ideogram","text","legacy"]},X("upscale_image_card","Upscale Image","Upscale an image using ESRGAN.","fal-ai/esrgan","upscale",2,{type:"object",properties:{image_url:{type:"string"},scale:{type:"number"}},required:["image_url"]},{buildBody:e=>{let t={image_url:e.image_url};return e.scale!==void 0&&(t.scale=e.scale),t},tags:["upscale","esrgan"],deprecated:!0,replacementTool:"fal-aura-sr"}),X("edit_image_seed_card","Edit Image (SeedEdit)","Inpaint/edit an image with a prompt using SeedEdit.","fal-ai/bytedance/seededit","image",5,{type:"object",properties:{image_url:{type:"string"},prompt:{type:"string"},seed:{type:"number"}},required:["image_url","prompt"]},{buildBody:e=>{let t={image_url:e.image_url,prompt:e.prompt};return e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","edit","inpaint","seededit"],deprecated:!0,replacementTool:"or-gemini-nano-banana"}),{dispatch:"enveloped",id:"generate_video_tempo_card",name:"Generate Video (Grok)",description:"Generate a video from a text prompt using Grok Imagine Video.",provider:"fal",model:"xai/grok-imagine-video/text-to-video",category:"video",priceCents:30,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/xai/grok-imagine-video/text-to-video",merchantName:"Grok Video via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),t},tags:["video","grok","legacy"]},{dispatch:"enveloped",id:"generate_video_kling_card",name:"Generate Video (Kling)",description:"Generate a video using Kling v1.6 (async, ~$0.40).",provider:"fal",model:"fal-ai/kling-video/v1.6/standard/text-to-video",category:"video",priceCents:40,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/kling-video/v1.6/standard/text-to-video",merchantName:"Kling via fal.ai",deprecated:!0,replacementTool:"fal-kling-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","kling","legacy"]},{dispatch:"enveloped",id:"generate_video_wan_card",name:"Generate Video (Wan)",description:"Generate a video using Wan T2V (async, ~$0.25).",provider:"fal",model:"fal-ai/wan/t2v-1.3b",category:"video",priceCents:25,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/wan/t2v-1.3b",merchantName:"Wan T2V via fal.ai",deprecated:!0,replacementTool:"fal-wan-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","wan","legacy"]},{dispatch:"enveloped",id:"generate_video_minimax_card",name:"Generate Video (MiniMax)",description:"Generate a video using MiniMax (async, ~$0.35).",provider:"fal",model:"fal-ai/minimax/video-01",category:"video",priceCents:35,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/minimax/video-01",merchantName:"MiniMax via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","minimax","legacy"]},{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",deprecated:!0,replacementTool:"fal-trellis-3d",buildBody:e=>{let t={object_prompt:e.object_prompt};return e.style_prompt&&(t.style_prompt=e.style_prompt),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.art_style&&(t.art_style=e.art_style),e.seed!==void 0&&(t.seed=e.seed),t},tags:["3d","mesh","meshy","legacy"]},{dispatch:"enveloped",id:"generate_speech_card",name:"Generate Speech",description:"Text-to-speech using F5-TTS with optional voice cloning.",provider:"fal",model:"fal-ai/f5-tts",category:"tts",priceCents:3,inputSchema:{type:"object",properties:{gen_text:{type:"string",description:"Text to synthesize"},ref_audio_url:{type:"string",description:"Reference audio URL (for voice cloning)"},ref_text:{type:"string",description:"Transcription of ref audio"},remove_silence:{type:"boolean"}},required:["gen_text"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/f5-tts",merchantName:"fal.ai",buildBody:e=>{let t={gen_text:e.gen_text};return e.ref_audio_url&&(t.ref_audio_url=e.ref_audio_url),e.ref_text&&(t.ref_text=e.ref_text),e.remove_silence!==void 0&&(t.remove_silence=e.remove_silence),t},deprecated:!0,replacementTool:"fal-metavoice",tags:["tts","speech","f5-tts","legacy"]},{dispatch:"enveloped",id:"generate_music_tempo_card",name:"Generate Music (Suno)",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,deprecated:!0,replacementTool:"fal-ace-step-music",tags:["music","audio","suno","async","legacy"]},{dispatch:"enveloped",id:"check_music_status_tempo_card",name:"Check Music Status",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}),deprecated:!0,tags:["music","status","suno","legacy"]},{dispatch:"enveloped",id:"query_onchain_prices_card",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly, daily, and weekly granularity.",provider:"allium",model:"allium-prices",category:"llm",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly), '1d' (daily), or '1w' (weekly). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",deprecated:!0,replacementTool:"query_onchain_prices",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:Uc,tags:["onchain","prices","allium","crypto","legacy"]}];function or(e){return Vs.find(t=>t.id===e)}var Vc=1,qc=["pick_one","fan_out"],Hc=["concat","dedupe_by_url","top_k_by_score"],gf=8,hf=g.object({type:g.string().min(1),description:g.string().min(1),enum:g.array(g.string()).optional(),default:g.unknown().optional(),minimum:g.number().optional(),maximum:g.number().optional()}),yf=g.object({toolId:g.string().min(1),notes:g.string().min(1)}),_f=g.string().regex(/^[a-z0-9_-]{1,32}$/,"tier key must be 1-32 chars [a-z0-9_-]"),vf=g.object({providers:g.array(g.string().min(1)).min(1).max(gf),merge:g.enum(Hc),maxResults:g.number().int().positive().optional()}),Bc=g.object({mode:g.enum(qc).default("pick_one"),intro:g.string().min(1),defaultTier:g.string().min(1),tiers:g.record(_f,yf).refine(e=>Object.keys(e).length>0,{message:"must have at least one tier"}),fanOut:vf.optional(),guidance:g.string().min(1),inputProperties:g.record(g.string(),hf),required:g.array(g.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"]}),bf=g.object({version:g.literal(Vc),generatedAt:g.string().datetime(),tools:g.record(g.string().regex(js,"tool name must match MCP naming rules"),Bc).refine(e=>Object.keys(e).length>0,{message:"manifest must have at least one tool"})});var co=require("child_process"),Jc=require("util"),Yc=E(require("crypto")),de=E(require("fs")),Zc=E(require("os")),qe=E(require("path"));var An=(0,Jc.promisify)(co.execFile),lo=qe.join(Zc.homedir(),".visa-mcp","bin"),an=qe.join(lo,"Visa CLI"),xf=qe.join(__dirname,"..","native"),Kc="6",Gc=qe.join(lo,"visa-keychain.version"),zc=qe.join(lo,"visa-keychain.sha256");function Wc(e){let t=de.readFileSync(e);return Yc.createHash("sha256").update(t).digest("hex")}async function Hs(){try{if(de.readFileSync(Gc,"utf-8").trim()===Kc&&de.existsSync(an)){let r=de.readFileSync(zc,"utf-8").trim();if(Wc(an)!==r)m.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),de.unlinkSync(an);else return an}}catch{}let e=qe.join(xf,"visa-keychain.m");if(de.existsSync(e)||(e=qe.resolve(__dirname,"..","..","native","visa-keychain.m")),de.existsSync(e)||(e=qe.resolve(__dirname,"..","native","visa-keychain.m")),!de.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");de.mkdirSync(lo,{recursive:!0,mode:448});try{await An("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",an,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=Wc(an);return de.writeFileSync(zc,t,{mode:384}),de.writeFileSync(Gc,Kc,{mode:384}),an}async function Xc(e){let t=await Hs(),n;try{n=(await An(t,e,{timeout:6e4})).stdout}catch(s){n=s.stdout||"";let i=n.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(s.stderr?.trim()||s.message||"Unknown error")}let r=n.trim();if(r.startsWith("OK:"))return r.slice(3);if(r==="OK")return;let o=r.startsWith("ERROR:")?r.slice(6):"Unknown error";throw new Error(o)}var qs=null;function se(){return fn()?!0:process.platform!=="darwin"?!1:qs!==null?qs:(qs=!0,!0)}var io="visa-cli",ao="attestation-key";async function Cf(e){try{await An("security",["delete-generic-password","-s",io,"-a",ao],{timeout:5e3})}catch{}await An("security",["add-generic-password","-s",io,"-a",ao,"-w",e],{timeout:5e3})}async function Bs(){try{let{stdout:e}=await An("security",["find-generic-password","-s",io,"-a",ao,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function uo(){let e=await Xc(["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 Cf(n),r}async function Qc(){return await Bs()!==null}async function el(){if(fn())return"mock-public-key-spki";let e=await Bs();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await Hs();return new Promise((n,r)=>{let o=(0,co.execFile)(t,["public-key"],{timeout:6e4},(s,i)=>{let a=(i||"").trim();if(s){a.startsWith("ERROR:")?r(new Error(a.slice(6))):r(new Error(s.stderr?.trim()||s.message||"Unknown error"));return}a.startsWith("OK:")?n(a.slice(3)):r(new Error(a.startsWith("ERROR:")?a.slice(6):"Unknown error"))});o.stdin.write(e),o.stdin.end()})}async function Rn(e,t){if(fn())return Promise.resolve(Zi());let n=await Bs();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await Hs(),o=["sign",e];return t&&o.push(t),new Promise((s,i)=>{let a=(0,co.execFile)(r,o,{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:")?s(u.slice(3)):i(new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error"))});a.stdin.write(n),a.stdin.end()})}async function mo(){try{await An("security",["delete-generic-password","-s",io,"-a",ao],{timeout:5e3})}catch{}try{await Xc(["delete-key"])}catch{}}var kf=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],Tf=[...kf.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 Gs(e,t=Tf){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=Ks(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(Ks(r.match.provider)))&&r.match.keywords.every(o=>n.includes(Ks(o))))return r.targetToolId;return null}function Ks(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}var sr={generate_image:{intro:'Generate an AI image from a text prompt \u2014 useful for hero shots, marketing assets, social posts, blog covers, app mockups, or any time the user asks for art, a logo, an icon, a thumbnail, or "a picture of \u2026". From $0.01 (fast) to $0.06 (pro), returns a hosted PNG/JPG URL. Default tier: balanced ($0.04, 1K, ~10s).',tiers:{balanced:{toolId:"fal-flux-pro",notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",notes:"Recraft V3 \u2014 vector/flat/illustration styles"}},guidance:"If the user didn't specify a tier, pick 'balanced' unless the prompt clearly signals otherwise (text \u2192 text_heavy, logo/icon \u2192 vector, quick test \u2192 fast, hero/print \u2192 pro).",inputProperties:{prompt:{type:"string",description:"Text description of the image to generate."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9", "1:1", "9:16".',default:"16:9"}},required:["prompt"]},generate_video:{intro:'Generate a short AI video from a text prompt \u2014 useful for product demos, social clips, mood reels, ad concepts, or any "make me a video of \u2026" request. $0.10\u2013$0.40 per ~6s clip depending on tier. Async: returns a request_id; use execute_tool with tool_id "check_fal_status_card" to resolve it (60\u2013180s).',tiers:{balanced:{toolId:"fal-minimax-video",notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",notes:"Kling \u2014 highest quality, cinematic"}},guidance:'Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate and are processed asynchronously. The response includes a request_id and model_path. Poll with execute_tool using tool_id "check_fal_status_card" and params {request_id, model_path}. Do not poll more than once per 30 seconds.',inputProperties:{prompt:{type:"string",description:"Text description of the video scene."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9" or "9:16".',default:"16:9"}},required:["prompt"]},generate_music:{intro:'Generate an original music track from a prompt via ACE-Step. ~$0.02 for the default 60s track. Use for songs, backing tracks, jingles, vocal music, instrumental music, or any "make a song/music/track" request. Takes ~60-90s and may return a request_id to poll with check_fal_status_card. For SFX, chimes, ambient beds, or TTS, use generate_audio instead.',tiers:{ace_step:{toolId:"fal-ace-step-music",notes:"ACE-Step \u2014 prompt-to-music with vocals or instrumentals"}},guidance:"Use for songs and music tracks. Takes ~60-90s and may return a request_id to poll with check_fal_status_card. For sound effects, chimes, ambient beds, or TTS, use generate_audio instead.",inputProperties:{prompt:{type:"string",description:"Musical style, mood, instruments, subject, and lyrics direction."},instrumental:{type:"boolean",description:"True for instrumental music with no vocals; false for vocal tracks.",default:!1},duration:{type:"number",description:"Duration in seconds.",default:60}},required:["prompt"]},generate_audio:{intro:'Generate sound effects from a text prompt (sfx tier \u2014 default), or voice-cloned speech from text + a reference audio URL (tts tier). $0.03\u2013$0.04. Use for SFX, chimes, UI sounds, ambient audio (default sfx), or voice cloning when a reference audio URL is available (pass tier:"tts"). Default tier is sfx; pass tier:"tts" for voice cloning.',tiers:{sfx:{toolId:"fal-stable-audio",notes:"Stable Audio \u2014 sound effects and ambient from a prompt"},tts:{toolId:"fal-metavoice",notes:"MetaVoice \u2014 voice cloning TTS (requires a voice sample URL)"}},guidance:'Default tier is sfx: pass prompt describing the sound. For tts (voice cloning): pass tier:"tts" + text + audio_url.',inputProperties:{prompt:{type:"string",description:"Description of sound to generate (sfx tier, default)."},text:{type:"string",description:"Text to speak aloud (tts tier)."},audio_url:{type:"string",description:"URL of a voice sample to clone (tts tier, required for voice cloning)."}},required:[]},generate_3d:{intro:"Generate a 3D mesh (GLB) from an image URL via Trellis. ~$0.08, ~30\u201360s. Use when the user shares an image and asks for a 3D model, asset, AR-ready mesh, or game-ready GLB.",tiers:{trellis:{toolId:"fal-trellis-3d",notes:"Trellis \u2014 image-to-3D, returns a GLB mesh URL"}},guidance:"Pass an image URL. Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{image_url:{type:"string",description:"URL of the image to convert to a 3D model."}},required:["image_url"]},upscale_image:{intro:'Upscale an image to 4\xD7 resolution via Aura SR (preserves detail without hallucination). ~$0.03. Use whenever the user shares a low-res image and asks to "upscale", "make this higher resolution", "4x this", "enhance", or to print/export at larger size.',tiers:{aura:{toolId:"fal-aura-sr",notes:"Aura SR \u2014 default; preserves detail without hallucination"}},guidance:"Pass the existing image URL. Returns an upscaled version.",inputProperties:{image_url:{type:"string",description:"URL of the image to upscale."}},required:["image_url"]},transcribe_audio:{intro:'Transcribe speech in an audio or video file (URL) to text via OpenAI Whisper. ~$0.02 per file, multilingual, handles long files. Use whenever the user asks to "transcribe this", "what does this audio say", "make subtitles", "convert this to text", or shares an audio/video URL with no other clear intent.',tiers:{whisper:{toolId:"fal-whisper",notes:"OpenAI Whisper \u2014 fast, multilingual"}},guidance:"Pass the URL. Returns the transcript text.",inputProperties:{audio_url:{type:"string",description:"URL of the audio or video file to transcribe."}},required:["audio_url"]},run_llm:{intro:"Run a text prompt through a different LLM (GPT-4o-mini, Claude Sonnet, DeepSeek R1/V3, Perplexity Sonar with web search, or Llama 70B). Token-metered, typically ~$0.01\u2013$0.10 per call. Use for: web-grounded answers (search tier), second-opinion reasoning (reasoning tier), code generation in a different family (coding tier), deep math/logic (deep_reasoning tier), or fast cheap text cleanup (fast tier). Pair with batch for multi-model councils.",tiers:{fast:{toolId:"or-gpt-4o-mini",notes:"GPT-4o Mini. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",notes:"Claude Sonnet. Strong reasoning, long-context. Warn user it is materially pricier than `fast`."},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 cn(e,t,n){if(!nl(e))return If(e,n);let r=tl[e];if(!r)return e;let o=Object.keys(r.tiers),s=t||o[0],i=$f(e,s,n);return i||Pf(e,r,s,o)}function If(e,t){return Gs({requestedTool:e,intentText:t})??e}function $f(e,t,n){return Gs({requestedTool:e,metaTool:e,tier:t,intentText:n})}function Pf(e,t,n,r){let o=t.tiers[n];if(!o)throw new Error(`Unknown tier '${n}' for ${e}. Valid tiers: ${r.join(", ")}`);return o.toolId}var tl=sr;function nl(e){return e in tl}var ir=Object.keys(sr);function zs(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function rl(e=process.env){return zs(e)!==null}var Fl=require("child_process"),me=E(require("crypto")),Me=E(require("fs")),dr=E(require("os")),To=E(require("path"));var ol=!1;async function ar(e,t,n){try{return await t()}catch(r){if(!(r.message==="Invalid signature"||r.code==="ATTESTATION_KEY_DRIFT"||r.error_code==="ATTESTATION_KEY_DRIFT"||r.name==="AttestationDriftError")||!se())throw r;if(m.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(ol)throw m.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;ol=!0,m.info("attestation:starting-browser-recovery");try{let s=await n();if(!s.success)throw m.error("attestation:browser-recovery-failed",{message:s.message}),r;let i=await uo();return await e.registerAttestationKey(i),await e.setBiometricPreference({required:!0}),m.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),m.info("attestation:key-reregistered-after-recovery"),await t()}catch(s){throw m.error("attestation:recovery-failure",{error:s.message}),r}}throw r}}var sl="2.3.0-rc.1";function Ws(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function fo(e,t,n){let r=process.env[e];if(r!==void 0)return{value:n==="opt-in"?r==="true":r!=="false",source:{kind:"env",var:e}};let o=Zr(t);return o!==void 0?{value:o,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function we(e){return e==null?"\u2014":e?"yes":"no"}function go(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function Mf(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function Of(){let e=process.env.VISA_CREDIT_SESSION_CAP_CENTS;if(e!==void 0){let n=Number(e);if(Number.isFinite(n)&&n>=10&&n<=1e4)return{value:Math.floor(n),source:{kind:"env",var:"VISA_CREDIT_SESSION_CAP_CENTS"}}}let t=Is("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:As,source:{kind:"default"}}}async function cr(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(B){n=B?.message||"unknown error"}let r=[],o=process.env.VISA_AUTH_URL,s=Rs("auth.serverUrl"),i=ye(),a=o!==void 0&&o!==""?{kind:"env",var:"VISA_AUTH_URL"}:s!==void 0?{kind:"settings"}:{kind:"default"};r.push({key:"auth.serverUrl",value:i,formatted:i,source:a,hint:a.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),r.push({key:"account.enrolled",value:t?.enrolled??null,formatted:we(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:we(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:we(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:se(),formatted:we(se()),source:{kind:"device"}});let c=t?.spendingControls,u=c?c.max_transaction_amount??c.maxTransactionAmount??null:null,d=c?c.daily_limit??c.dailyLimit??null:null;r.push({key:"spending.maxPerTxn",value:u,formatted:go(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:go(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:go(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:go(t?.dailyRemaining),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"cards.count",value:t?.cardCount??null,formatted:t?.cardCount!=null?String(t.cardCount):"\u2014",source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}});let f=t?.cards?.find(B=>B.isDefault)??t?.cards?.[0];f&&r.push({key:"cards.default",value:{brand:f.brand??null,last4:f.last4},formatted:`${f.brand||"card"} \u2022\u2022\u2022\u2022 ${f.last4}`,source:{kind:"server"}});let p=Of();r.push({key:"credit.sessionCapCents",value:p.value,formatted:Mf(p.value),source:p.source});let _=pc();_.length>0&&r.push({key:"settings.retired",value:_.map(B=>B.key),formatted:_.map(B=>B.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${_.map(B=>`visa-cli config unset ${B.key}`).join(" && ")}`});let h=fo("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:h.value,formatted:we(h.value),source:h.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let S=fo("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:S.value,formatted:we(S.value),source:S.source});let I=Ue(),$;process.env.VISA_CLI_NO_UPDATE_CHECK?$={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?$={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?$={kind:"env",var:"NODE_ENV"}:$={kind:"default"},r.push({key:"ui.updateCheck",value:!I,formatted:we(!I),source:$});let C=fo("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:C.value,formatted:we(C.value),source:C.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let k=fo("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:k.value,formatted:we(k.value),source:k.source});let q=process.env.VISA_DRY_RUN,W=rl();if(r.push({key:"tools.dryRun",value:W,formatted:we(W),source:q===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:sl,formatted:sl,source:{kind:"default"}}),e.includeDev){let B=process.env.VISA_MOCK_KEYCHAIN,lt=dt();r.push({key:"dev.mockKeychain",value:lt,formatted:we(lt),source:Ws("VISA_MOCK_KEYCHAIN",!!B),hint:qo()});let re=process.env.VISA_MOCK_TOUCHID,ge=fn();r.push({key:"dev.mockTouchid",value:ge,formatted:we(ge),source:Ws("VISA_MOCK_TOUCHID",!!re),hint:qo()});let ut=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!ut,formatted:we(!!ut),source:Ws("VISA_CLI_DEBUG",!!ut)})}return{entries:r,statusError:n}}function Nf(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 il(e,t={}){if(e.length===0)return"";let n=Math.max(...e.map(s=>s.key.length)),r=Math.max(...e.map(s=>s.formatted.length)),o=[];for(let s of e){let i=s.key.padEnd(n+2),a=s.formatted.padEnd(r+2);o.push(`${i}${a}(${Nf(s.source)})`),t.verbose&&s.hint&&o.push(` ${"\u21B3".padStart(n)} ${s.hint}`)}return o.join(`
123
+ `)}function al(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 cl(e){if(e<=0)return null;let t=(e/100).toFixed(2);return{_credits_prompt:{message:`You've got $${t} in free credits \u2014 enough for about ${Math.floor(e/6)} images. Try something now, or save them for later.`,balanceUsd:t,examples:[{tool:"generate_image",cost:"$0.06",what:"an AI image"},{tool:"run_llm",cost:"token-priced",what:"a quick model call"},{tool:"generate_music",cost:"$0.02",what:"a music track"}]}}}var Et=require("fs"),ul=require("os"),Js=require("path"),Lf=(0,Js.join)((0,ul.homedir)(),".visa-mcp"),ll=(0,Js.join)(Lf,"mcp-session-budget.json");function ho(){try{(0,Et.existsSync)(ll)&&(0,Et.unlinkSync)(ll)}catch{}}var Zs=require("crypto"),Pe=E(lr()),ln=null,xe=0,In=0,be=0,At=null,Xs=null,Qs=null,_o=Promise.resolve();function eg(e){return Number((0,Pe.fromCents)(e))}function pl(e){return(0,Pe.toCents)((0,Pe.micros)(BigInt(e)))}function ml(e){return(0,Pe.toWire)((0,Pe.fromCents)(e))}function Ys(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function yo(e){return typeof e=="string"&&/^\d+$/.test(e)}var tg=43,ng=new RegExp(`^[A-Za-z0-9_-]{${tg}}$`);function rg(e){return typeof e=="string"&&ng.test(e)}function og(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||ln&&e.session_id!==ln||typeof e.nonce!="string"||e.nonce.length===0||!rg(e.server_signature)||!Ys(e.cumulative)||!Ys(e.remaining)||!Ys(e.delta)||e.cumulative<xe||be>0&&e.cumulative>be||be>0&&e.remaining>be||e.cumulative_micros!==void 0&&!yo(e.cumulative_micros)||e.remaining_micros!==void 0&&!yo(e.remaining_micros)||e.delta_micros!==void 0&&!yo(e.delta_micros)||e.reserved_micros!==void 0&&!yo(e.reserved_micros))}function it(e){ln=e,xe=0,In=0,be=0,At=null,Xs=null,Qs=null,_o=Promise.resolve()}function ur(e){be=Math.max(0,Math.floor(e))}function ei(){return ln}function ti(e){if(!ln)return null;let t=xe+In;return be>0&&t>be&&(t=be),{session_budget_id:ln,cumulative_micros:eg(t),nonce:(0,Zs.randomUUID)(),idempotency_key:e||(0,Zs.randomUUID)()}}function ni(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 og(r)?(xe=Math.max(xe,r.cumulative),In=0,At=r,r):null}function fl(){return At}function ri(e){let t=pl(e.cumulative_micros);xe=Math.max(xe,t),In=0;let n={status:"accepted",session_id:e.session_budget_id,cumulative:xe,remaining:Math.max(0,be-xe),delta:0,cumulative_micros:ml(xe),remaining_micros:ml(Math.max(0,be-xe)),delta_micros:"0",nonce:e.nonce};return At=n,n}function oi(e){if(!e||typeof e!="object")return;let t=e.cumulative_micros;if(typeof t!="string"||!/^\d+$/.test(t))return;let n;try{n=BigInt(t)}catch{return}if(n<0n)return;let r=(0,Pe.toCents)((0,Pe.micros)(n));if(!Number.isFinite(r)||r<0)return;Xs=t;let o=e,s=typeof o.session_id=="string"?o.session_id:ln??"";At?(typeof o.remaining_micros=="string"&&/^\d+$/.test(o.remaining_micros)&&(At.remaining_micros=o.remaining_micros),typeof o.charged_micros=="string"&&/^\d+$/.test(o.charged_micros)&&(At.delta_micros=o.charged_micros)):At={session_id:s,cumulative:r,remaining:0,delta:0,nonce:typeof o.transaction_id=="string"?o.transaction_id:"",remaining_micros:typeof o.remaining_micros=="string"&&/^\d+$/.test(o.remaining_micros)?o.remaining_micros:void 0,delta_micros:typeof o.charged_micros=="string"&&/^\d+$/.test(o.charged_micros)?o.charged_micros:void 0}}function gl(e){let t=e.receipt??null;Qs={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:pl(e.voucher.cumulative_micros),estimatedCumulativeCents:vo(),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 hl(){return Qs}function yl(){return xe}function _l(){return Xs}function vo(){let e=xe+In;return be>0&&e>be&&(e=be),e}function vl(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return _o=_o.then(()=>{In+=t}),_o}var sg=10,ig=1,J=null,bl=Promise.resolve();function si(e){let t=bl.catch(()=>{}).then(e);return bl=t.then(()=>{},()=>{}),t}var fe=class extends Error{balanceCents;minRequiredCents;constructor(t,n){super(`Prepaid balance is $${(t/100).toFixed(2)}; at least $${(n/100).toFixed(2)} required to open a credit session. Top up via the buy_credits tool first.`),this.name="InsufficientBalanceError"}};async function ii(e,t,n){return si(()=>Sl(e,t,n))}async function Sl(e,t,n){if(ho(),J&&new Date(J.expiresAt).getTime()>Date.now())return ei()!==J.budgetId&&(it(J.budgetId),ur(J.totalCents)),m.info("mcp-session:active-hit",{budgetId:J.budgetId,tool:n.toolName,remainingEstimatedCents:J.totalCents-vo()}),{budgetId:J.budgetId,isFresh:!1,totalCents:J.totalCents,requestedCapCents:J.totalCents,appliedCapCents:J.totalCents,clampedReason:null};J&&(J=null,it(null));let r=await e.getBalance();if(!r.success)throw new Error(`Could not read balance: ${r.error||"unknown error"}`);let o=n.sessionKind??"explicit",s=o==="one_shot"?ig:sg,i=Math.max(s,Math.ceil(n.minRequiredCents??s));if(r.balanceCents<i)throw new fe(r.balanceCents,i);let a=n.capCentsOverride??hc(),l=Math.min(a,r.balanceCents),c=l<a?"balance":null,u=await t("session_create",l,"Visa CLI Session",`open credit-model session with $${(l/100).toFixed(2)} cap`,n.userContext),d=await e.createSessionBudget({total_cents:l,session_kind:o,...u?{attestation:u}:{}});if(!d.success||!d.budget){let p=d.error||"unknown error";throw new Error(`Failed to open credit session: ${p}`)}let f={budgetId:d.budget.id,expiresAt:d.budget.expiresAt,totalCents:d.budget.totalCents,createdAt:d.budget.createdAt};return J=f,it(f.budgetId),ur(f.totalCents),m.info("mcp-session:opened",{budgetId:f.budgetId,capCents:f.totalCents,requestedCapCents:a,clampedReason:c,sessionKind:o,expiresAt:f.expiresAt,tool:n.toolName}),{budgetId:f.budgetId,isFresh:!0,totalCents:f.totalCents,requestedCapCents:a,appliedCapCents:f.totalCents,clampedReason:c}}async function wl(e,t,n){return si(async()=>{let o=Rt()?await xl(e):null,s=await Sl(e,t,n);return{budgetId:s.budgetId,totalCents:s.totalCents,closedPrevious:o,requestedCapCents:s.requestedCapCents,appliedCapCents:s.appliedCapCents,clampedReason:s.clampedReason}})}async function xl(e){let n=Rt()?.budgetId??ei(),r=!1,o,s;if(n)try{let i=await e.closeSession(n);r=!!i?.success,typeof i?.finalCumulativeCents=="number"&&(o=i.finalCumulativeCents),typeof i?.finalCumulativeMicros=="string"&&(s=i.finalCumulativeMicros)}catch(i){m.warn("mcp-session:close-server-failed",{budgetId:n,error:i?.message||String(i)})}return ho(),J=null,it(null),{closedServerSide:r,budgetId:n,finalCumulativeCents:o,finalCumulativeMicros:s}}async function bo(e){return si(()=>xl(e))}function Rt(){return ho(),J?new Date(J.expiresAt).getTime()<=Date.now()?(J=null,it(null),null):{budgetId:J.budgetId,totalCents:J.totalCents,lastReceiptCumulative:yl(),lastReceiptCumulativeMicros:fl()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:_l(),estimatedCumulative:vo(),lastToolSpend:hl(),expiresAt:J.expiresAt}:null}var kl=E(lr()),Cl=10000n;function ag(e){return e<=0n?0:Number((e+Cl-1n)/Cl)}function Tl(e){return ag((0,kl.fromUsd)(e))}var So="Buying credits currently requires local biometric attestation from a macOS Touch ID-capable CLI/MCP process. This device cannot create the required attestation, so no card charge was attempted. Credits are account-level, so you can top up this account from any interactive Touch ID-capable CLI, then use the balance from this remote server. For unattended workloads, scoped API keys with daily caps are also supported.",El="Tell the user that buying credits requires a local Touch ID-capable CLI/MCP process today. Credits are account-level: suggest topping up the same account from any interactive Touch ID-capable CLI, then continuing on this remote server. For unattended workloads, scoped API keys with daily caps are also supported. Do not retry buy_credits from this process; it cannot produce the required card-charge attestation.";var Al=Promise.resolve(),Rl=!1;function Eo(e){let t=Al.catch(()=>{}).then(e);return Al=t.then(()=>{},()=>{}),t}async function Vl(e){let t=await ii(P,ze,{toolName:e.toolId,userContext:e.userContext}),n=ti(e.idempotencyKey);if(!n)throw new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await fg(),o,s,i=async()=>P.shortcutWithSession(e.toolId,n,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);try{try{({data:o,voucherReceiptHeader:s}=await i())}catch(u){if(u instanceof qt){let d=Math.min(Math.max(u.retryAfterSecs,0),5)*1e3;m.warn("mcp-session:lock-contended-retrying",{tool:e.toolId,retryAfterSecs:u.retryAfterSecs}),await new Promise(f=>setTimeout(f,d)),{data:o,voucherReceiptHeader:s}=await i()}else throw u}}catch(u){if(u instanceof _n){if(m.warn("mcp-session:server-invalidated-budget",{code:u.code,budgetId:u.budgetId??t.budgetId,tool:e.toolId}),await bo(P),process.env.VISA_REQUIRE_EXPLICIT_SESSION==="true")throw new Error(`Your session was closed by another process (${u.code}). Restart MCP or run start_session again.`);return Rl||(Rl=!0,console.error(`[visa-cli] Your session was closed by another process; reopened automatically as pay-as-you-go.
124
+ To require an explicit session approval instead, set VISA_REQUIRE_EXPLICIT_SESSION=true.`)),m.info("mcp-session:falling-back-to-payg",{code:u.code,tool:e.toolId}),ql(e)}throw u instanceof qt?(m.warn("mcp-session:lock-contended-give-up",{tool:e.toolId}),new Error("Another paid call is currently in progress on this session. Wait a moment and try again.")):u}let a=ni(s)??(n?ri(n):null);if(oi(o?.receipt_v2),await vl(e.estimatedAmountCents),gl({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),Bl(o))return o;let l=await Hl();if(e.idempotencyKey&&Kl(o,l,e.idempotencyKey))return o;let c=l?Co(l):null;return Gl(o,r,c)}function Be(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function li(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(li).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${li(r)}`).join(",")}}`}function cg(e,t,n,r){let o=me.createHash("sha256").update(`${n}:${li(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${o}`}function lg(e,t){return`${e}:${t}`}function ug(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 Il(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,o=He(r),s=o!==null?o.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=ug(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),l=i!=null?String(i):a;return{batch_id:e,item_id:lg(e,t),index:t,...l!==void 0?{transaction_id:l}:{},...a!==void 0?{ledger_id:a}:{},...s?{amountMicros:s,amount_micros:s,cost_micros:s}:{}}}async function ql(e){let t=Math.max(1,Math.ceil(e.estimatedAmountCents)),n=await P.getBalance();if(!n.success)throw new Error(`Could not read balance: ${n.error||"unknown error"}`);if(n.balanceCents<t)throw new fe(n.balanceCents,t);let r=t,o=Co(n),s=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(r/100).toFixed(2)})`,i=await ze("session_create",r,"Visa CLI Session",s,e.userContext),a=await P.createSessionBudget({total_cents:r,session_kind:"one_shot",...i?{attestation:i}:{}});if(!a.success||!a.budget)throw new Error(`Failed to open on-demand session: ${a.error||"unknown error"}`);let l=a.budget.id;it(l),ur(a.budget.totalCents),m.info("on-demand-session:opened",{budgetId:l,capCents:a.budget.totalCents,tool:e.toolId});try{let c=ti(e.idempotencyKey);if(!c)throw new Error(`Internal: mintVoucher returned null after on-demand session-open ${l}`);let{data:u,voucherReceiptHeader:d}=await P.shortcutWithSession(e.toolId,c,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(ni(d)||ri(c),oi(u?.receipt_v2),Bl(u))return u;let f=await Hl();if(e.idempotencyKey&&Kl(u,f,e.idempotencyKey))return u;let p=f?Co(f):null;return Gl(u,o,p)}finally{try{await P.closeSession(l)}catch(c){m.warn("on-demand-session:close-failed",{budgetId:l,error:c?.message||String(c)})}it(null),m.info("on-demand-session:closed",{budgetId:l,tool:e.toolId})}}async function $t(e){return Eo(async()=>Rt()?Vl(e):ql(e))}function Ao(){return ye()}var P=new Se(()=>j.getSessionToken());function He(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function Co(e){return He(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function dg(e){if(e<0n&&(e=0n),e>=1000000n){let r=(e+5000n)/10000n,o=r/100n,s=r%100n;return`$${o.toString()}.${s.toString().padStart(2,"0")}`}let t=e%1000000n;return t===0n?"$0.00":`$0.${t.toString().padStart(6,"0").replace(/0+$/,"")}`}function mg(e){let t=He(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=He(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=He(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function wo(e,t="INVALID_TOOL_PARAMS"){return{success:!1,error_code:t,code:t,error:e,message:e}}function pg(e){return{success:!1,error_code:"TOOL_EXECUTION_FAILED",code:"TOOL_EXECUTION_FAILED",error:e.message||"Tool execution failed.",message:e.message||"Tool execution failed.",tool_id:e.toolId,surface:e.surface,merchantName:e.merchantName,amount:e.amount,payment_finalized:!1,charged:!1}}async function fg(){try{let e=await P.getBalance();return e.success?Co(e):null}catch{return null}}async function Hl(){try{let e=await P.getBalance();return e.success?e:null}catch{return null}}function Bl(e){if(!e||e.success===!1)return!1;let t=He(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=He(e.amountMicros??e.amount_micros??e.charged_micros),r=t??n;if(r===null||r<=0n)return!1;let o=r.toString();return e.amountMicros??=o,e.amount_micros??=o,e.charged_micros??=o,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),!0}function Kl(e,t,n){if(!e||e.success===!1||!t||!Array.isArray(t.ledger))return!1;let r=t.ledger.find(a=>a.idempotencyKey===n);if(!r)return!1;let o=He(r.deltaMicros)??BigInt(r.deltaCents)*10000n,s=o<0n?-o:o;if(s<=0n)return!1;let i=s.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(s)/1e6),!0}function Gl(e,t,n){if(!e||e.success===!1||t===null||n===null)return e;let r=t-n;if(r<=0n)return e;let o=r.toString();return e.amountMicros??=o,e.amount_micros??=o,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),e}var gg="2.3.0-rc.1",Xb=["","","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(`
125
+ `);function Ke(e){if(!e||typeof e!="string"||fc())return;let t=Hn(e);if(!t)return;let n=os();if(n.headless){m.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`);return}let r=ma(t,Ao());if(!r){m.info(`Browser auto-open skipped (non-internal host). URL: ${t}`);return}let o=fa(r);if(!o){m.info(`No browser command for platform "${dr.platform()}". URL: ${r}`);return}(0,Fl.execFile)(o.cmd,o.args,s=>{s&&m.warn(`Browser open failed: ${s.message}. URL: ${r}`)})}async function Ce(e){return ar(P,e,Ql)}var zl="get_cards",Wl="set_default_card";function hg(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 '${zl}' to see enrolled cards and '${Wl}' to switch, then retry the original request.`}function yg(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 '${zl}' to see enrolled cards and '${Wl}' to switch. Do not retry automatically.`}function Ge(e,t){let n=e.retryable?hg(e.code,e.retryAfter):yg(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 $n=null,_g=3e4;function Jl(){$n=null}var It=class extends Error{constructor(n){super(`${ko()} attestation is required for this action, but it is not available in this MCP process. `+ui());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function Ro(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. `+ui()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function vg(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:So,agent_guidance:El}}function ko(){return process.platform==="darwin"?"Touch ID":"local biometric"}function ui(){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 Io(e){return typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0}async function bg(e){let t=Date.now();if($n&&$n.expiresAt>t)return{required:$n.required,hasRegisteredKey:$n.hasRegisteredKey};try{let n=await P.getStatus(e),r=n.attestationRequired!==!1,o=Io(n);return $n={required:r,hasRegisteredKey:o,expiresAt:t+_g},{required:r,hasRegisteredKey:o}}catch{return{required:!0,hasRegisteredKey:!0}}}async function ze(e,t,n,r,o,s){if(!s?.forceRequired){let i=await bg(o);if(!i.required){m.info("attestation:skipped-by-server-policy",{context:e});return}if(!i.hasRegisteredKey){m.info("attestation:skipped-no-registered-key",{context:e});return}}if(!se())throw m.warn("attestation:unavailable",{context:e}),new It(e);m.info("attestation:attempt",{context:e,amount:t,merchant:n});try{let{nonce:i}=await P.getAttestationChallenge(),a=Buffer.from(JSON.stringify({nonce:i,amount:t,merchant:n,context:e})).toString("base64");m.info("touchid:prompt",{context:e,amount:t,merchant:n});let l=await Rn(a,r);return m.info("attestation:success",{context:e,amount:t,merchant:n}),{signature:l,nonce:i,amount:t,merchant:n}}catch(i){throw m.error("attestation:failure",{context:e,amount:t,merchant:n,error:i.message}),i}}var $l="[dry-run] https://placeholder.visa-cli.dev/image.png",Sg=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"]),wg=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 xg(e,t){return t==="run_llm"||e.startsWith("or-")?"llm":t==="generate_image"||Sg.has(e)?"image":t==="generate_video"||wg.has(e)?"video":null}function Cg(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function kg(e){return e==="llm"?"OpenRouter":"fal.ai"}function Pn(e,t,n,r){let o={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:kg(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${Cg(n)}`;return{...o,content:i,data:{content:i,model:t,dry_run:!0}}}return{...o,urls:[$l],data:{[e==="video"?"videoUrl":"imageUrl"]:$l,metadata:{dry_run:!0}}}}async function ai(e){let t=e.mode??"mock",n=t==="preflight"?"/v1/telemetry/preflight":"/v1/telemetry/dry-run",r=t==="preflight"?"preflight":null;try{await P.emitTelemetry([{id:me.randomUUID(),timestamp:new Date().toISOString(),tool_name:e.toolName,user_prompt:e.userContext??"",tool_params:JSON.stringify(e.toolParams),result_success:!0,result_error:null,result_json:JSON.stringify(e.result),payment_rail:r,payment_amount:0,payment_currency:"USD",merchant_name:e.result.merchantName,transaction_id:e.result.transactionId,tx_hash:null,protocol:null,http_status:200,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",event_kind:"mcp_tool",endpoint:n,resolved_model:e.resolvedModel,session_budget_id:null}])}catch(o){m.warn("dry_run:telemetry_failed",{tool:e.toolName,error:o?.message||String(o),mode:t})}}var Tg="https://openrouter.ai/api/v1/chat/completions",Eg="openrouter/free",Ag=50,Rg=15e3;function Ig(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 $g(e,t,n){let r=process.env.OPENROUTER_API_KEY;if(!r)return m.warn("preflight:no_openrouter_key_falling_back_to_mock",{tool:e}),{result:Pn("llm",e,t,n),degraded:!0,resolvedModel:null};let o=Ig(t),s;try{s=await Ft(Tg,{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:Eg,messages:[{role:"user",content:o}],max_tokens:Ag}),timeoutMs:Rg})}catch(u){return m.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:Pn("llm",e,t,n),degraded:!0,resolvedModel:null}}if(!s.ok){let u=await s.text().catch(()=>"");return m.warn("preflight:openrouter_http_error_falling_back_to_mock",{tool:e,status:s.status,bodyExcerpt:u.slice(0,200)}),{result:Pn("llm",e,t,n),degraded:!0,resolvedModel:null}}let i;try{i=await s.json()}catch(u){return m.warn("preflight:openrouter_invalid_json_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:Pn("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 $o(e,t,n,r){let o=zs();if(!o)return null;let s=xg(e,r);if(!s)return null;let i=Date.now();if(o==="mock"){let c=Pn(s,e,t,r);return await ai({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:c,userContext:n,startedAt:i,mode:"mock"}),m.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:s,mode:o}),c}if(s!=="llm"){m.warn("preflight:not_supported_for_kind_falling_back_to_mock",{tool:e,kind:s});let c=Pn(s,e,t,r);return await ai({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 $g(e,t,r);return await ai({toolName:r??e,resolvedModel:l??(r&&r!==e?e:null),toolParams:t,result:a,userContext:n,startedAt:i,mode:"preflight"}),m.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:s,mode:o}),a}async function at(e,t,n){let r=await P.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 ct(e){return Tl(e.amount)}function Pg(){return To.join(dr.homedir(),".visa-mcp","allium-results")}var Qb=16*1024,eS=50*1024*1024;function Mg(){let e=Pg();try{if(!Me.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=Me.readdirSync(e),n=0,r=0;for(let o of t)try{let s=Me.statSync(To.join(e,o));s.isFile()&&(n+=s.size,r++)}catch{}return{file_count:r,size_bytes:n,path:e}}catch(t){return m.warn("allium:disk_usage_error",{error:t.message}),{file_count:0,size_bytes:0,path:e}}}var Pl=3600*1e3,ci=0;function Og(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function mr(e){if(!gc()&&!(Date.now()<ci))try{if(!await j.getSessionToken())return;await P.feedSubmit({prompt:e.prompt,tool:e.tool,media_url:e.mediaUrl,media_type:e.mediaType,cost:e.cost,transaction_id:e.transactionId,auto:!0,...e.userContext&&{user_context:e.userContext}}),m.info("feed:submitted",{tool:e.tool,mediaType:e.mediaType,transactionId:e.transactionId})}catch(t){if(Og(t)){let n=ci===0;ci=Date.now()+Pl,n&&m.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:Pl});return}m.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function Ng(e,t){let n=(e.state||"").trim().toUpperCase(),r=(e.county||"").trim(),o=(e.start_date||"").trim(),s=(e.end_date||o).trim();if(!/^[A-Z]{2}$/.test(n))throw new Error('state must be a 2-letter US state code (e.g. "VA").');if(!r)throw new Error("county is required.");if(!/^\d{4}-\d{2}$/.test(o))throw new Error('start_date must be YYYY-MM (e.g. "2025-08").');if(s&&!/^\d{4}-\d{2}$/.test(s))throw new Error("end_date must be YYYY-MM.");let i="Visa SMI",a=.1,l=`Pay $0.10 to ${i} for SMI data (${n} / ${r})`;m.info("payment:attempt",{tool:"get_visa_smi",amount:a,merchant:i});try{return await Ce(async()=>{let c=await ze("get_visa_smi",a,i,l),u=await P.getVisaSmi({state:n,county:r,start_date:o,end_date:s,attestation:c,idempotencyKey:me.randomUUID()},t);return u.success?m.info("payment:success",{tool:"get_visa_smi",merchant:i,charged_cents:u.charged_cents}):m.warn("payment:declined",{tool:"get_visa_smi",merchant:i,message:u.error}),u})}catch(c){if(c instanceof le)return m.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:c.code,retryable:c.retryable}),Ge(c,{amount:a,merchantName:i,description:"Visa SMI data"});throw m.error("payment:failure",{tool:"get_visa_smi",merchant:i,error:c.message}),c}}async function Lg(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await $o("generate_image_card",e,t);if(n)return n;let r=await at("generate_image_card",void 0,t),o=me.randomUUID();m.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await Ce(async()=>{let s;try{s=await $t({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:ct(r),userContext:t,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof fe)return Be(i);throw i}return m.info("payment:success",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Ke(i)),mr({prompt:e.prompt,tool:"generate_image_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):m.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof le)return m.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Ge(s,r);throw m.error("payment:failure",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function Dg(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await $o("generate_image_fast_card",e,t);if(n)return n;let r=await at("generate_image_fast_card",void 0,t),o=me.randomUUID();m.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await Ce(async()=>{let s;try{s=await $t({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:ct(r),userContext:t,timeoutMs:6e4,idempotencyKey:o})}catch(i){if(i instanceof fe)return Be(i);throw i}return m.info("payment:success",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Ke(i)),mr({prompt:e.prompt,tool:"generate_image_fast_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):m.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof le)return m.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Ge(s,r);throw m.error("payment:failure",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function Ug(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let n=await $o("generate_video_tempo_card",e,t);if(n)return n;let r=await at("generate_video_tempo_card",void 0,t),o=me.randomUUID();m.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await Ce(async()=>{let s;try{s=await $t({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:ct(r),userContext:t,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof fe)return Be(i);throw i}return m.info("payment:success",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Ke(i)),mr({prompt:e.prompt,tool:"generate_video_tempo_card",mediaUrl:s.urls[0],mediaType:"video",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):m.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof le)return m.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Ge(s,r);throw m.error("payment:failure",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function jg(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 at("generate_music_tempo_card",void 0,t),r=me.randomUUID();m.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await Ce(async()=>{let o;try{o=await $t({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:ct(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(s){if(s instanceof fe)return Be(s);throw s}return m.info("payment:success",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),o.urls?.length&&o.status!=="processing"?(o.urls.forEach(s=>Ke(s)),mr({prompt:e.prompt,tool:"generate_music_tempo_card",mediaUrl:o.urls[0],mediaType:"audio",cost:o.amount??n.amount,transactionId:o.transactionId,userContext:t})):o.urls?.length&&o.status==="processing"?(o._preliminary_urls=o.urls,delete o.urls,m.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):m.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof le)return m.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Ge(o,n);throw m.error("payment:failure",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}async function Fg(e,t){let n=await at("check_music_status_tempo_card",void 0,t),r=me.randomUUID();m.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await Ce(async()=>{let o;try{o=await $t({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:ct(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof fe)return Be(s);throw s}return m.info("payment:success",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),o.urls?.length&&o.urls.forEach(s=>Ke(s)),o})}catch(o){if(o instanceof le)return m.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Ge(o,n);throw m.error("payment:failure",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}async function Vg(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 at("query_onchain_prices",void 0,t),r=me.randomUUID();m.info("payment:attempt",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName});try{return await Ce(async()=>{let o;try{o=await $t({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:ct(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof fe)return Be(s);throw s}if(m.info("payment:success",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,mode:"session"}),Array.isArray(o?.data))o.data=o.data.map(s=>{if("mint"in s&&!("address"in s)){let{mint:i,...a}=s;return{address:i,...a}}return s});else if(o&&"mint"in o&&!("address"in o)){let{mint:s,...i}=o;return{address:s,...i}}return o})}catch(o){if(o instanceof le)return m.warn("payment:declined",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Ge(o,n);throw m.error("payment:failure",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}var qg=["generate_music_tempo_card"],Ml=10,Ol=5,Nl=new Map;function Ll(e){let t=Nl.get(e);if(t!==void 0)return t;let r=or(e)?.isAsync===!0||qg.includes(e);return Nl.set(e,r),r}var Hg=36e4,Bg=18e4,Kg=15e3,Gg=12e4,zg=2e3;function Dl(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}async function Wg(e,t){let n;if(e.requests?.some(C=>C.tool||C.tool_id)&&e.requests)n=e.requests.map(C=>{let k=C.tool||C.tool_id||e.tool;if(!k)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let q=cn(k,C.tier||e.tier,C.prompt??t),{tool:W,tool_id:B,tier:lt,params:re,...ge}=C,ut=re&&typeof re=="object"?{...re,...ge}:ge;return{resolvedTool:q,params:ut}});else if(e.tool){let C=cn(e.tool,e.tier,e.params?.prompt??t);n=(e.requests||(e.count&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(q=>({resolvedTool:C,params:q}))}else return Dl("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return Dl("BATCH_EMPTY","Batch requires at least one item.");if(n.length>Ml)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${Ml} items. Please split into smaller batches.`};if([...new Set(n.map(C=>C.resolvedTool))].some(Ll)&&n.length>Ol)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${Ol} items. Please use multiple batches for more.`};let i=[...new Set(n.map(C=>C.resolvedTool))],a=i.length===1,l={};for(let C of i)l[C]=await at(C,void 0,t);let c=0;for(let C of n)c+=l[C.resolvedTool].amount;let u=[...new Set(Object.values(l).map(C=>C.merchantName))].join(", "),d=a?i[0]:"mixed";m.info("payment:attempt",{tool:"batch",batchTool:d,count:n.length,totalAmount:c,merchant:u,heterogeneous:!a});let f=n.some(C=>Ll(C.resolvedTool)),p=n.some(C=>C.resolvedTool.startsWith("or-")||C.resolvedTool==="run_llm"||C.resolvedTool==="execute_tool"),_=f?Hg:p?Bg+n.length*Kg:Gg+n.length*zg,h=me.randomUUID(),S=[],I=0,$=0n;return Eo(async()=>{let C=!Rt();if(C)try{let k=Math.max(1,Math.ceil(c*100));await ii(P,ze,{toolName:"batch",userContext:t,sessionKind:"one_shot",minRequiredCents:k,capCentsOverride:k})}catch(k){return k instanceof fe?Be(k):(m.warn("payment:batch-prewarm-failed",{batchTool:d,count:n.length,error:k?.message||String(k)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:k?.message||"Failed to authenticate batch session",tool:d,count:n.length,failedCount:n.length,results:[]})}try{for(let re=0;re<n.length;re+=1){let ge=n[re],ut=l[ge.resolvedTool];try{let ae=await Vl({toolId:ge.resolvedTool,toolParams:ge.params,estimatedAmountCents:ct(ut),userContext:t,metaTool:"batch",timeoutMs:_,idempotencyKey:cg(h,re,ge.resolvedTool,ge.params)});if(S.push({success:ae?.success!==!1,tool:ge.resolvedTool,...ae,...Il(h,re,ae)}),ae?.success!==!1){let Un=He(ae?.amountMicros??ae?.amount_micros),Fi=typeof ae?.amount=="number"?ae.amount:ut.amount;Un!==null&&Un>0n?$+=Un:$+=BigInt(Math.round(Fi*1e6)),I+=Fi}ae?.urls&&ae.urls.forEach(Un=>Ke(Un))}catch(ae){if(ae instanceof fe&&S.length===0)return Be(ae);m.warn("payment:batch-item-failed",{tool:ge.resolvedTool,index:re,error:ae?.message||String(ae)}),S.push({success:!1,tool:ge.resolvedTool,...Il(h,re),error:ae?.message||String(ae)})}}let k=S.filter(re=>re?.success===!1).length,q=S.length-k,W=S.flatMap(re=>Array.isArray(re?.urls)?re.urls:[]),B=$>0n?Number($)/1e6:Math.round((I+Number.EPSILON)*100)/100,lt=q===0?"failure":k===0?"success":"partial";return m.info("payment:success",{tool:"batch",batchTool:d,count:n.length,totalAmount:c,totalCharged:B,merchant:u,successCount:q,failedCount:k,outcome:lt,mode:"session",batchId:h}),{success:q>0,outcome:lt,batch_id:h,tool:a?i[0]:d,count:n.length,successCount:q,failedCount:k,totalCharged:B,...$>0n?{totalChargedMicros:$.toString(),amountMicros:$.toString(),amount_micros:$.toString()}:{},merchantName:u,results:S,...W.length?{urls:W}:{}}}catch(k){if(k instanceof le)return m.warn("payment:declined",{tool:"batch",batchTool:d,count:n.length,totalAmount:c,merchant:u,code:k.code,retryable:k.retryable}),Ge(k,{amount:c,merchantName:u});throw m.error("payment:failure",{tool:"batch",batchTool:d,count:n.length,totalAmount:c,merchant:u,error:k.message}),k}finally{if(C){let k=await bo(P);m.info("batch-session:closed",{budgetId:k.budgetId,closedServerSide:k.closedServerSide})}}})}function Jg(){let e=!1,t;try{let r=To.join(dr.homedir(),".claude","settings.json");if(Me.existsSync(r)){let o=JSON.parse(Me.readFileSync(r,"utf-8")),s=typeof o.statusLine=="object"?o.statusLine.command:"";e=vt(s)}}catch{}let n=Lr();return n||(t="visa-cli config hud enable"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function Yg(e){let[t,n]=await Promise.all([P.getStatus(e),P.getBalance().catch(s=>(m.warn("get_status:balance_fetch_failed",{error:s?.message||String(s)}),null))]);typeof t?.dailyRemaining=="number"&&(t.dailyRemaining=Math.round(t.dailyRemaining*100)/100);let r=Mg();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=Jg(),t.version=gg,Array.isArray(t.cards)&&(t.cards=t.cards.map(s=>({...s,displayName:di(s)})),t.cardIdGuidance="cardId values are opaque tool parameters only; refer to cards by brand and last four digits."),n&&n.success&&(t.balanceCents=n.balanceCents,t.amountUsd=n.amountUsd);let o=Rt();if(t.sessionMode=!!o,o){let s=Math.max(0,o.totalCents-o.estimatedCumulative);t.activeSession={budgetId:o.budgetId,capCents:o.totalCents,capUsd:o.totalCents/100,lastReceiptCumulativeCents:o.lastReceiptCumulative,estimatedCumulativeCents:o.estimatedCumulative,spentCents:o.estimatedCumulative,spentUsd:o.estimatedCumulative/100,estimatedRemainingCents:s,estimatedRemainingUsd:s/100,...o.lastToolSpend?{lastToolSpend:{toolName:o.lastToolSpend.toolName,resolvedToolId:o.lastToolSpend.resolvedToolId,estimatedAmountCents:o.lastToolSpend.estimatedAmountCents,estimatedAmountUsd:o.lastToolSpend.estimatedAmountCents/100,voucherCumulativeCents:o.lastToolSpend.voucherCumulativeCents,estimatedCumulativeCents:o.lastToolSpend.estimatedCumulativeCents,receiptDeltaCents:o.lastToolSpend.receiptDeltaCents,receiptCumulativeCents:o.lastToolSpend.receiptCumulativeCents,receiptRemainingCents:o.lastToolSpend.receiptRemainingCents,recordedAt:o.lastToolSpend.recordedAt}}:{},expiresAt:o.expiresAt}}return t}function di(e){let t=typeof e.brand=="string"&&e.brand.trim().length>0?e.brand.trim():"card",n=t.charAt(0).toUpperCase()+t.slice(1).toLowerCase(),r=typeof e.last4=="string"&&e.last4.trim().length>0?e.last4.trim():"unknown",o=e.isDefault===!0?" (default)":"";return`${n} ending in ${r}${o}`}async function Yl(e,t){try{let r=((await P.getStatus(t)).cards||[]).find(o=>o?.id===e);if(r)return di(r)}catch(n){m.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function Zg(e){let n=(await P.getStatus(e)).cards||[];return n.length===0?{cards:[],message:"No cards enrolled. Use the add_card tool to add a payment card."}:n.some(o=>!Number.isInteger(o?.id)||o.id<=0)?{success:!1,cards:[],message:"Card action handles are unavailable right now, so remove_card and set_default_card are temporarily disabled."}:{cards:n.map(o=>({...o,displayName:di(o)})),message:"Use cardId only as an opaque tool parameter. When speaking to the user, refer to cards by brand and last four digits, not by card id."}}async function Xg(e,t){return await P.getTransactions({limit:e.limit,offset:e.offset},t)}async function Qg(e,t){return await P.feedback(e.message,e.transaction_id,t)}var eh=100;async function th(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return un("MISSING_CONFIRMATION","Please confirm by setting confirm: true to charge your enrolled card for credits.");if(!e.amount||!Number.isFinite(e.amount)||e.amount<=0)return{success:!1,error:"amount must be a positive number in USD (e.g. 5.00)"};let n=Math.round(e.amount*100);if(n<eh)return{success:!1,error:"Minimum top-up is $1.00"};let r=me.randomUUID();m.info("buy_credits:attempt",{amountCents:n});try{return await Ce(async()=>{let o=await ze("balance-topup",e.amount,"Visa CLI Balance",`top up balance with $${e.amount.toFixed(2)}`,t,{forceRequired:!0}),s=await P.topupBalance({amount_cents:n,idempotency_key:r,attestation:o});if(s.success){m.info("buy_credits:success",{amountCents:n,balanceCents:s.balanceCents});let i=((s.balanceCents??0)/100).toFixed(2),a=(n/100).toFixed(2);return{...s,amount:n/100,amountMicros:String(n*1e4),merchantName:"Visa CLI Balance",message:`Added $${a} \u2014 balance is now $${i}`}}return m.warn("buy_credits:failed",{amountCents:n,error:s.error}),s})}catch(o){if(o instanceof It)return vg();throw m.error("buy_credits:failure",{amountCents:n,error:o.message}),o}}function un(e,t){return{success:!1,error:t,code:e,message:t}}async function nh(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return un("MISSING_CONFIRMATION","Please confirm by setting confirm: true to update spending controls.");if(e.maxTransactionAmount!==void 0&&(typeof e.maxTransactionAmount!="number"||!Number.isFinite(e.maxTransactionAmount)||e.maxTransactionAmount<.01||e.maxTransactionAmount>100))return un("INVALID_VALUE","maxTransactionAmount must be between $0.01 and $100");if(e.dailyLimit!==void 0&&(typeof e.dailyLimit!="number"||!Number.isFinite(e.dailyLimit)||e.dailyLimit<1||e.dailyLimit>100))return un("INVALID_VALUE","dailyLimit must be between $1 and $100");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return un("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");m.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await Ce(async()=>{let n=await ze("spending-controls",0,"","update spending controls"),r=await P.updateSpendingControls({maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit,confirm:!0,attestation:n},t);return m.info("spending_controls:success",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit}),r})}catch(n){if(m.error("spending_controls:failure",{error:n.message}),n instanceof It)return Ro(n,"update_spending_controls");if(String(n?.message||n).includes("Attestation required"))return un("ATTESTATION_REQUIRED","Changing spending controls requires local attestation, even when payment biometric prompts are disabled.");throw n}}async function rh(e){let t=await cr({api:P,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 oh(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."};m.info("config:set",{key:e.key});try{let t=Xr(e.key,e.value);return m.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 Qe?"UNKNOWN_KEY":t instanceof et?"SERVER_CONTROLLED":t instanceof bt?"RETIRED_KEY":"INVALID_VALUE";return m.warn("config:set:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(wt).sort()}}}async function sh(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."};m.info("config:unset",{key:e.key});try{let t=Qr(e.key);return m.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 Qe?"UNKNOWN_KEY":t instanceof et?"SERVER_CONTROLLED":t instanceof bt?"RETIRED_KEY":"INVALID_VALUE";return m.warn("config:unset:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(wt).sort()}}}async function ih(e){let t=await P.getStatus(e),n=t.attestationRequired!==!1,r=Io(t),o=se(),s=n?r?o?`${ko()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${ko()} is not available in this process. ${ui()}`:"Biometric attestation is enabled on the account, but no attestation key is registered. Payments on this device proceed without a biometric signature; processor declines such as INVALID_OR_MISSING_CONFIG are card/account configuration issues, not something biometric setup fixes.":"Biometric attestation is NOT required for payments. Payments will proceed without biometric confirmation.";return{required:n,hasAttestationKey:!!t.hasAttestationKey,hasTelegramAttestationKey:!!t.hasTelegramAttestationKey,hasAnyAttestationKey:r,touchIdAvailable:o,platform:process.platform,effectiveRequiredOnThisDevice:n&&r&&o,canDisableFromThisDevice:!n||!r||o,message:s}}async function ah(e){m.info("biometric:on");let t=await P.setBiometricPreference({required:!0},e);return t.success?(Jl(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:t.error||"unknown error"}}async function ch(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return un("MISSING_CONFIRMATION","Please confirm by setting confirm: true. Disabling Touch ID is a security downgrade \u2014 the user will be prompted for one final Touch ID confirmation before the change takes effect.");m.info("biometric:off");try{return await Ce(async()=>{let n=await P.getStatus(t),r;if(Io(n)&&(r=await ze("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${ko()} confirmation required to disable \u2014 not available on this device.`);let o=await P.setBiometricPreference({required:!1,attestation:r},t);if(!o.success)throw new Error(o.error||"unknown error");return Jl(),{success:!0,required:!1,message:"Touch ID is no longer required for payments."}})}catch(n){if(m.error("biometric:off:failure",{error:n.message}),n instanceof It)return Ro(n,"biometric_off");throw n}}var Ul=3e4,lh=3e5;async function Zl(e,t,n="login"){let r=me.randomUUID(),o=`${e}${e.includes("?")?"&":"?"}state=${r}`;return Ke(o),Xl(r,t,n)}async function Xl(e,t,n="login"){let r=Date.now()+lh;for(;Date.now()<r;)try{let s=await fetch(`${Ao()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:Ul,...t&&{user_context:t}}),signal:AbortSignal.timeout(Ul+5e3)});if(!s.ok){await ht(s,a=>{m.warn("auth_status:retry_after_http_error",{status:s.status,delayMs:a})});continue}let i=await s.json();if(i.status==="pending")continue;if(i.status==="expired")return{success:!1,message:"Session expired. Please try again."};if(i.status==="error")return{success:!1,message:i.error||"Authentication failed. Please try again."};if(i.status==="complete"){if(n==="attestation-recovery"||i.attestationCleared)return m.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=cl(a);if(i.sessionToken){await j.saveSessionToken(i.sessionToken);let u=i.user||"",d=i.last4||"****";return m.info("auth:login_complete",{user:u,last4:d,bonusCents:a}),{success:!0,message:`Signed in as ${u}. Card ending in ${d} enrolled and ready for payments.`,...l||{}}}let c=i.last4||"****";return m.info("auth:card_added",{last4:c,bonusCents:a}),{success:!0,message:`Card ending in ${c} enrolled and ready for payments.`,...l||{}}}}catch{await ht(void 0,s=>{m.warn("auth_status:retry_after_network_error",{delayMs:s})})}return{success:!1,message:n==="enrollment"?"Card enrollment timed out. Please try again.":n==="attestation-recovery"?"Biometric reset timed out. Please try reset again.":"Login timed out. Please try again."}}async function Ql(e){let t=me.randomUUID(),n;try{n=await P.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."}:(Ke(n.recoveryUrl),Xl(t,e,"attestation-recovery"))}async function uh(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to remove this card."};let n=e.cardId;if(!Number.isInteger(n)||n<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to get the opaque cardId for the card you want to remove."};m.info("cards:remove_attempt",{cardId:n});let r=`remove-card:${n}`,o=`remove ${await Yl(n,t)}`;try{return await Ce(async()=>{let s=await ze(r,0,"",o,t,{forceRequired:!0}),i=await P.removeCard(n,{attestation:s},t);return m.info("cards:remove_success",{cardId:n,promotedId:i?.promotedId??null}),i})}catch(s){if(m.error("cards:remove_failure",{cardId:n,error:s.message}),s instanceof It)return Ro(s,"remove_card");throw s}}async function dh(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."};m.info("cards:set_default_attempt",{cardId:n});let r=`set-default-card:${n}`,o=`set ${await Yl(n,t)} as default`;try{return await Ce(async()=>{let s=await ze(r,0,"",o,t,{forceRequired:!0}),i=await P.setDefaultCard(n,{attestation:s},t);return m.info("cards:set_default_success",{cardId:n}),i})}catch(s){if(m.error("cards:set_default_failure",{cardId:n,error:s.message}),s instanceof It)return Ro(s,"set_default_card");throw s}}async function mh(e){return m.info("auth:login_attempt"),Zl(`${Ao()}/login`,e)}function ph(e){if(e.capCents!==void 0){let t=Number(e.capCents);if(!Number.isFinite(t)||t<10||t>1e4)throw new Error("capCents must be between 10 ($0.10) and 10000 ($100)");return Math.floor(t)}if(e.capUsd!==void 0){let t=Number(e.capUsd);if(!Number.isFinite(t)||t<.1||t>100)throw new Error("capUsd must be between 0.10 and 100");return Math.floor(t*100)}}async function fh(e={},t){let n;try{n=ph(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return Eo(async()=>{let r=await wl(P,ze,{toolName:"start_session",userContext:t,capCentsOverride:n});m.info("session:started",{budgetId:r.budgetId,totalCents:r.totalCents,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious});let o=(r.appliedCapCents/100).toFixed(2),s=(r.requestedCapCents/100).toFixed(2),i=`Session started with a $${o} cap. Paid calls will use this approval window until you close it, it expires, or this MCP process restarts.`,a=r.clampedReason==="balance"?`${i} Note: requested cap of $${s} was clamped to your prepaid balance of $${o}. Run buy_credits to top up if you need a larger session.`:i;return{success:!0,budgetId:r.budgetId,totalCents:r.totalCents,amountUsd:r.totalCents/100,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious,message:a}})}async function gh(){let e=Rt();if(!e)return{success:!0,active:!1,message:"No active explicit approval window. Paid calls use a one-shot session in pay-as-you-go mode; see transaction_history for records."};let t=Math.max(0,e.totalCents-e.estimatedCumulative);return{success:!0,active:!0,budgetId:e.budgetId,totalCents:e.totalCents,estimatedCumulativeCents:e.estimatedCumulative,estimatedRemainingCents:t,expiresAt:e.expiresAt,lastToolSpend:e.lastToolSpend,message:`Active explicit approval window: about $${(t/100).toFixed(2)} remaining of $${(e.totalCents/100).toFixed(2)}.`}}async function hh(){return Eo(async()=>{let e=Rt();if(!e)return{success:!0,message:"No active explicit approval window to close. Paid calls remain pay-as-you-go.",closed:!1};let t=await bo(P);m.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=mg(e),r=He(t.finalCumulativeMicros),o=r??(typeof t.finalCumulativeCents=="number"?BigInt(Math.max(0,t.finalCumulativeCents))*10000n:n.micros),s=Number(o/10000n);return m.info("session:closed:final-spend",{budgetId:t.budgetId,closedServerSide:t.closedServerSide,finalSpendMicros:o.toString(),finalSpendCents:s,finalSpendSource:r!==null?"server.finalCumulativeMicros":typeof t.finalCumulativeCents=="number"?"server.finalCumulativeCents":n.source,totalCents:e.totalCents}),{success:!0,closed:!0,closedServerSide:t.closedServerSide,budgetId:t.budgetId,finalEstimatedCumulativeCents:s,finalEstimatedCumulativeMicros:o.toString(),totalCents:e.totalCents,message:t.closedServerSide?`Explicit approval window closed. Spent ${dg(o)} of $${(e.totalCents/100).toFixed(2)} cap. Future paid calls are pay-as-you-go until you start a new explicit approval window.`:"Explicit approval window cleared locally; server-side close call did not succeed (likely already closed). Future paid calls are pay-as-you-go until you start a new explicit approval window."}})}async function yh(e){if(m.info("auth:add_card_attempt"),!await j.getSessionToken())return{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."};let{code:n}=await P.createEnrollCode();return Zl(`${Ao()}/enroll-card?code=${encodeURIComponent(n)}`,e,"enrollment")}async function _h(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};m.info("reset:attempt");let n=!1;try{let r=await P.getStatus(t);if(r&&Io(r)){let o=await Ql(t);if(!o.success)return o;n=!0}}catch(r){let o=r?.message||"unknown error";if(!/not logged in|session.*expired|no local credentials/i.test(o))return{success:!1,message:`Could not check server biometric state: ${o}`};m.warn("reset:server_attestation_status_unavailable",{error:o})}try{await P.logout(void 0,t)}catch{}if(await j.clearAll(),se())try{await mo()}catch{}return m.info("reset:success"),{success:!0,message:n?"Device reset. Server-side biometric state and local credentials have been cleared. Use the login tool or visa-cli setup to re-enroll.":"Device reset. Local credentials and keys have been removed. Use the login tool or visa-cli setup to re-enroll."}}async function vh(e){let t=e.query?.trim()||void 0,n=e.category?.trim()||void 0,r=!t&&!n;m.info("catalog:discover",{query:t,category:n,browseAll:r});try{let s=(await P.catalogSearch(t,n)).tools||[];if(s.length===0)return{content:[{type:"text",text:r?"The tool catalog is currently empty.":`No tools found for "${t||n}". Try a different search term.`}]};if(r){let a={};for(let c of s){let u=c.category||"other";(a[u]??=[]).push(c)}let l=Object.keys(a).sort().map(c=>{let u=a[c].map((f,p)=>`${p+1}. **${f.name}** (${f.id})
126
+ ${f.description}
127
+ Provider: ${f.provider} | Price: ${jl(f)}
128
+ Params: ${Object.keys(f.inputSchema?.properties||f.inputSchema||{}).join(", ")||"none"}`).join(`
128
129
 
129
130
  `);return`## ${c.length<=3?c.toUpperCase():c.charAt(0).toUpperCase()+c.slice(1)}
130
131
 
@@ -136,48 +137,48 @@ ${l}
136
137
 
137
138
  Use execute_tool with the tool id and required params to run any of these.`}],_tools:s}}let i=s.map((a,l)=>`${l+1}. **${a.name}** (${a.id})
138
139
  ${a.description}
139
- Provider: ${a.provider} | Category: ${a.category} | Price: ${Nl(a)}
140
+ Provider: ${a.provider} | Category: ${a.category} | Price: ${jl(a)}
140
141
  Params: ${Object.keys(a.inputSchema?.properties||a.inputSchema||{}).join(", ")||"none"}`).join(`
141
142
 
142
143
  `);return m.info("catalog:discovered",{count:s.length}),{content:[{type:"text",text:`Found ${s.length} tool(s):
143
144
 
144
145
  ${i}
145
146
 
146
- Use execute_tool with the tool id and required params to run any of these.`}],_tools:s}}catch(o){throw m.error("catalog:discover:error",{error:o.message}),new Error(`Failed to search tool catalog: ${o.message}`)}}function Nl(e){return e.priceDisplay??`$${(e.priceCents/100).toFixed(2)}`}function mh(e,t){return t==="image"||t==="video"||t==="audio"?t:e?.match(/\.(mp4|webm|mov)/)?"video":"image"}function _o(e,t){return Array.isArray(e.type)?e.type.includes(t):e.type===t}function ph(e,t,n){let r=e.inputSchema;if(!r||r.type!=="object")return null;let o=r.properties??{},s=n??e.id;for(let a of Object.keys(t))if(!Object.prototype.hasOwnProperty.call(o,a)){let l=Object.keys(o),c=l.length>0?` Expected: ${l.join(", ")}.`:"";return`Unknown parameter "${a}" for ${s}.${c}`}let i=(r.required??[]).filter(a=>!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0);if(i.length>1)return`${i.join(", ")} are required for ${s}.`;for(let a of r.required??[]){if(!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0)return`${a} is required for ${s}.`;if(t[a]===null)return`${a} cannot be null.`;if(typeof t[a]=="string"&&t[a].trim()==="")return`${a} cannot be empty.`}for(let[a,l]of Object.entries(t)){let c=o[a];if(!(!c||l===void 0||l===null)){if(c.enum&&!c.enum.includes(l))return`${a} must be one of: ${c.enum.map(String).join(", ")}.`;if(_o(c,"integer")){if(typeof l!="number"||!Number.isInteger(l))return`${a} must be an integer.`}else if(_o(c,"number")){if(typeof l!="number"||!Number.isFinite(l))return`${a} must be a number.`}else if(_o(c,"string")){if(typeof l!="string")return`${a} must be a string.`;if(l.trim()==="")return`${a} cannot be empty.`;if(c.minLength!==void 0&&l.length<c.minLength)return`${a} is too short.`;if(c.maxLength!==void 0&&l.length>c.maxLength)return`${a} is too long.`}else if(_o(c,"boolean")&&typeof l!="boolean")return`${a} must be a boolean.`;if(typeof l=="number"){if(c.minimum!==void 0&&l<c.minimum)return`${a} must be at least ${c.minimum}.`;if(c.maximum!==void 0&&l>c.maximum)return`${a} must be at most ${c.maximum}.`}}}return null}async function fh(e){let t=or(e);if(t)return t;try{return await P.catalogTool(e)}catch(n){return m.warn("catalog:resolve:error",{tool:e,error:n?.message||String(n)}),null}}async function gh(e,t,n="execute_tool"){let{tool_id:r,params:o,...s}=e,i=o||s;if(!r)return yo("tool_id is required. Use discover_tools first to find available tools.","MISSING_TOOL_ID");m.info("catalog:execute",{tool:r,metaTool:n});let a=await fh(r);if(!a)return yo(`Unknown tool: '${r}'. Use discover_tools first to find available tools.`,"UNKNOWN_TOOL");if(a.deprecated){let p=a.replacementTool?` Use '${a.replacementTool}' instead.`:"";return yo(`Tool '${r}' is deprecated and is no longer available for new paid calls.${p}`,"DEPRECATED_TOOL")}let c=ph(a,i,n&&n!=="execute_tool"?n:void 0);if(c)return m.info("catalog:execute:validation_failed",{tool:r,metaTool:n,error:c}),yo(c);let u=await To(r,i,t,n);if(u)return u;if(a.executionMode==="free_authenticated"||a.accessMode==="free"){m.info("catalog:execute:free",{tool:r,metaTool:n});let p=await P.shortcut(r,i,6e4,t,n);return p&&typeof p=="object"&&!Array.isArray(p)&&p.merchantName==null&&(p.merchantName=a.name??r),p}let d=await it(r,void 0,t),g=de.randomUUID();m.info("payment:attempt",{tool:r,amount:d.amount,merchant:d.merchantName});try{return await Ce(async()=>{let p;try{p=await It({toolId:r,toolParams:i,estimatedAmountCents:at(d),userContext:t,metaTool:n,timeoutMs:12e4,idempotencyKey:g})}catch(_){if(_ instanceof me)return Be(_);throw _}if(m.info("payment:success",{tool:r,amount:d.amount,merchant:d.merchantName,mode:"session"}),p&&typeof p=="object"&&!Array.isArray(p)&&p.merchantName==null&&(p.merchantName=a?.name??r),p.urls?.length){p.urls.forEach(h=>Ke(h));let _=mh(p.urls[0],p.mediaType);mr({prompt:i.prompt||`${r} execution`,tool:r,mediaUrl:p.urls[0],mediaType:_,cost:p.amount??d.amount,transactionId:p.transactionId,userContext:t})}return p})}catch(p){return p instanceof ce?(m.warn("payment:declined",{tool:r,amount:d.amount,merchant:d.merchantName,code:p.code,retryable:p.retryable}),Ge(p,d)):(m.error("payment:failure",{tool:r,amount:d.amount,merchant:d.merchantName,error:p.message}),sg({toolId:r,surface:n,merchantName:d.merchantName,amount:d.amount,message:p?.message||"Tool execution failed."}))}}var $e=class{static async getStatus(t){return qg(t)}static async getVisaSmi(t,n){return Eg(t,n)}static async getCards(t){return Hg(t)}static async transactionHistory(t,n){return Bg(t||{},n)}static async feedback(t,n){return Kg(t,n)}static async updateSpendingControls(t,n){return Wg(t,n)}static async configList(t){return Jg(t||{})}static async configSet(t){return Yg(t||{})}static async configUnset(t){return Zg(t||{})}static async biometricStatus(t){return Xg(t)}static async biometricOn(t){return Qg(t)}static async biometricOff(t,n){return eh(t,n)}static async reset(t,n){return uh(t,n)}static async login(t){return oh(t)}static async closeSession(t){return ch()}static async startSession(t,n){return ih(t||{},n)}static async getSessionStatus(t){return ah()}static async addCard(t){return lh(t)}static async removeCard(t,n){return nh(t,n)}static async setDefaultCard(t,n){return rh(t,n)}static async buyCredits(t,n){return zg(t,n)}static async batch(t,n){return Fg(t,n)}static async discoverTools(t){return dh(t)}static async executeTool(t,n,r="execute_tool"){return gh(t,n,r)}static async shortcut(t,n,r){switch(t){case"generate_image_card":return Ag(n,r);case"generate_image_fast_card":return Rg(n,r);case"generate_video_tempo_card":return Ig(n,r);case"generate_music_tempo_card":return $g(n,r);case"check_music_status_tempo_card":return Pg(n,r);case"query_onchain_prices_card":return Mg(n,r);default:{let o=await it(t,void 0,r);m.info("payment:attempt",{tool:t});try{let s=await It({toolId:t,toolParams:n,estimatedAmountCents:at(o),userContext:r,timeoutMs:6e4});return m.info("payment:success",{tool:t,mode:"session"}),s.urls?.length&&s.urls.forEach(i=>Ke(i)),s}catch(s){if(s instanceof me)return Be(s);if(s instanceof ce)return m.warn("payment:declined",{tool:t,code:s.code,retryable:s.retryable}),Ge(s,o);throw m.error("payment:failure",{tool:t,error:s.message}),s}}}}static async submitFeedback(t,n,r){m.info("feedback:submit",{length:t.length,transactionId:n,hasContext:!!r});try{let o=await P.submitFeedback(t,n,r);return m.info("feedback:submitted",{transactionId:n}),o}catch(o){let s=o instanceof Error?o.message:"Unknown error";throw m.error("feedback:error",{error:s,transactionId:n}),o}}static async getFeedback(t,n){m.info("feedback:list",{limit:t||20});try{let r=await P.getFeedback(t,n);return m.info("feedback:listed",{count:r?.feedback?.length||0}),r}catch(r){let o=r instanceof Error?r.message:"Unknown error";throw m.error("feedback:error",{error:o}),r}}};function Yl(e,t=process.stderr){if(Ue()||!e?.updateAvailable)return!1;let{latestVersion:n}=e.updateAvailable;if(!n)return!1;let r=`Update available: v${n}. Run: visa-cli update`;return t.write(`
147
+ Use execute_tool with the tool id and required params to run any of these.`}],_tools:s}}catch(o){throw m.error("catalog:discover:error",{error:o.message}),new Error(`Failed to search tool catalog: ${o.message}`)}}function jl(e){return e.priceDisplay??`$${(e.priceCents/100).toFixed(2)}`}function bh(e,t){return t==="image"||t==="video"||t==="audio"?t:e?.match(/\.(mp4|webm|mov)/)?"video":"image"}function xo(e,t){return Array.isArray(e.type)?e.type.includes(t):e.type===t}function Sh(e,t,n){let r=e.inputSchema;if(!r||r.type!=="object")return null;let o=r.properties??{},s=n??e.id;for(let a of Object.keys(t))if(!Object.prototype.hasOwnProperty.call(o,a)){let l=Object.keys(o),c=l.length>0?` Expected: ${l.join(", ")}.`:"";return`Unknown parameter "${a}" for ${s}.${c}`}let i=(r.required??[]).filter(a=>!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0);if(i.length>1)return`${i.join(", ")} are required for ${s}.`;for(let a of r.required??[]){if(!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0)return`${a} is required for ${s}.`;if(t[a]===null)return`${a} cannot be null.`;if(typeof t[a]=="string"&&t[a].trim()==="")return`${a} cannot be empty.`}for(let[a,l]of Object.entries(t)){let c=o[a];if(!(!c||l===void 0||l===null)){if(c.enum&&!c.enum.includes(l))return`${a} must be one of: ${c.enum.map(String).join(", ")}.`;if(xo(c,"integer")){if(typeof l!="number"||!Number.isInteger(l))return`${a} must be an integer.`}else if(xo(c,"number")){if(typeof l!="number"||!Number.isFinite(l))return`${a} must be a number.`}else if(xo(c,"string")){if(typeof l!="string")return`${a} must be a string.`;if(l.trim()==="")return`${a} cannot be empty.`;if(c.minLength!==void 0&&l.length<c.minLength)return`${a} is too short.`;if(c.maxLength!==void 0&&l.length>c.maxLength)return`${a} is too long.`}else if(xo(c,"boolean")&&typeof l!="boolean")return`${a} must be a boolean.`;if(typeof l=="number"){if(c.minimum!==void 0&&l<c.minimum)return`${a} must be at least ${c.minimum}.`;if(c.maximum!==void 0&&l>c.maximum)return`${a} must be at most ${c.maximum}.`}}}return null}async function wh(e){let t=or(e);if(t)return t;try{return await P.catalogTool(e)}catch(n){return m.warn("catalog:resolve:error",{tool:e,error:n?.message||String(n)}),null}}async function xh(e,t,n="execute_tool"){let{tool_id:r,params:o,...s}=e,i=o||s;if(!r)return wo("tool_id is required. Use discover_tools first to find available tools.","MISSING_TOOL_ID");m.info("catalog:execute",{tool:r,metaTool:n});let a=await wh(r);if(!a)return wo(`Unknown tool: '${r}'. Use discover_tools first to find available tools.`,"UNKNOWN_TOOL");if(a.deprecated){let p=a.replacementTool?` Use '${a.replacementTool}' instead.`:"";return wo(`Tool '${r}' is deprecated and is no longer available for new paid calls.${p}`,"DEPRECATED_TOOL")}let c=Sh(a,i,n&&n!=="execute_tool"?n:void 0);if(c)return m.info("catalog:execute:validation_failed",{tool:r,metaTool:n,error:c}),wo(c);let u=await $o(r,i,t,n);if(u)return u;if(a.executionMode==="free_authenticated"||a.accessMode==="free"){m.info("catalog:execute:free",{tool:r,metaTool:n});let p=await P.shortcut(r,i,6e4,t,n);return p&&typeof p=="object"&&!Array.isArray(p)&&p.merchantName==null&&(p.merchantName=a.name??r),p}let d=await at(r,void 0,t),f=me.randomUUID();m.info("payment:attempt",{tool:r,amount:d.amount,merchant:d.merchantName});try{return await Ce(async()=>{let p;try{p=await $t({toolId:r,toolParams:i,estimatedAmountCents:ct(d),userContext:t,metaTool:n,timeoutMs:12e4,idempotencyKey:f})}catch(_){if(_ instanceof fe)return Be(_);throw _}if(m.info("payment:success",{tool:r,amount:d.amount,merchant:d.merchantName,mode:"session"}),p&&typeof p=="object"&&!Array.isArray(p)&&p.merchantName==null&&(p.merchantName=a?.name??r),p.urls?.length){p.urls.forEach(h=>Ke(h));let _=bh(p.urls[0],p.mediaType);mr({prompt:i.prompt||`${r} execution`,tool:r,mediaUrl:p.urls[0],mediaType:_,cost:p.amount??d.amount,transactionId:p.transactionId,userContext:t})}return p})}catch(p){return p instanceof le?(m.warn("payment:declined",{tool:r,amount:d.amount,merchant:d.merchantName,code:p.code,retryable:p.retryable}),Ge(p,d)):(m.error("payment:failure",{tool:r,amount:d.amount,merchant:d.merchantName,error:p.message}),pg({toolId:r,surface:n,merchantName:d.merchantName,amount:d.amount,message:p?.message||"Tool execution failed."}))}}var $e=class{static async getStatus(t){return Yg(t)}static async getVisaSmi(t,n){return Ng(t,n)}static async getCards(t){return Zg(t)}static async transactionHistory(t,n){return Xg(t||{},n)}static async feedback(t,n){return Qg(t,n)}static async updateSpendingControls(t,n){return nh(t,n)}static async configList(t){return rh(t||{})}static async configSet(t){return oh(t||{})}static async configUnset(t){return sh(t||{})}static async biometricStatus(t){return ih(t)}static async biometricOn(t){return ah(t)}static async biometricOff(t,n){return ch(t,n)}static async reset(t,n){return _h(t,n)}static async login(t){return mh(t)}static async closeSession(t){return hh()}static async startSession(t,n){return fh(t||{},n)}static async getSessionStatus(t){return gh()}static async addCard(t){return yh(t)}static async removeCard(t,n){return uh(t,n)}static async setDefaultCard(t,n){return dh(t,n)}static async buyCredits(t,n){return th(t,n)}static async batch(t,n){return Wg(t,n)}static async discoverTools(t){return vh(t)}static async executeTool(t,n,r="execute_tool"){return xh(t,n,r)}static async shortcut(t,n,r){switch(t){case"generate_image_card":return Lg(n,r);case"generate_image_fast_card":return Dg(n,r);case"generate_video_tempo_card":return Ug(n,r);case"generate_music_tempo_card":return jg(n,r);case"check_music_status_tempo_card":return Fg(n,r);case"query_onchain_prices_card":return Vg(n,r);default:{let o=await at(t,void 0,r);m.info("payment:attempt",{tool:t});try{let s=await $t({toolId:t,toolParams:n,estimatedAmountCents:ct(o),userContext:r,timeoutMs:6e4});return m.info("payment:success",{tool:t,mode:"session"}),s.urls?.length&&s.urls.forEach(i=>Ke(i)),s}catch(s){if(s instanceof fe)return Be(s);if(s instanceof le)return m.warn("payment:declined",{tool:t,code:s.code,retryable:s.retryable}),Ge(s,o);throw m.error("payment:failure",{tool:t,error:s.message}),s}}}}static async submitFeedback(t,n,r){m.info("feedback:submit",{length:t.length,transactionId:n,hasContext:!!r});try{let o=await P.submitFeedback(t,n,r);return m.info("feedback:submitted",{transactionId:n}),o}catch(o){let s=o instanceof Error?o.message:"Unknown error";throw m.error("feedback:error",{error:s,transactionId:n}),o}}static async getFeedback(t,n){m.info("feedback:list",{limit:t||20});try{let r=await P.getFeedback(t,n);return m.info("feedback:listed",{count:r?.feedback?.length||0}),r}catch(r){let o=r instanceof Error?r.message:"Unknown error";throw m.error("feedback:error",{error:o}),r}}};function eu(e,t=process.stderr){if(Ue()||!e?.updateAvailable)return!1;let{latestVersion:n}=e.updateAvailable;if(!n)return!1;let r=`Update available: v${n}. Run: visa-cli update`;return t.write(`
147
148
  \x1B[33m\u2191 ${r}\x1B[0m
148
- `),!0}function Zl(e){let t=Array.isArray(e.inputSchema?.required)?e.inputSchema.required.filter(o=>typeof o=="string"):[],n=e.inputSchema?.properties&&typeof e.inputSchema.properties=="object"?e.inputSchema.properties:{};if(t.length===0)return{prompt:"a lobster"};let r={};for(let o of t)r[o]=hh(o,n[o]?.description);return r}function hh(e,t){let n=e.toLowerCase();return n==="prompt"?"a lobster":n==="text"?"Hello from Visa CLI.":n.endsWith("image_url")||n==="image_url"?"https://example.com/sample.jpg":n.endsWith("audio_url")||n==="audio_url"?"https://example.com/sample.wav":n.endsWith("video_url")||n==="video_url"?"https://example.com/sample.mp4":n==="taskid"||n==="task_id"?"task_abc123":n==="request_id"||n==="requestid"?"req_abc123":n==="model_path"||n==="model"?"fal-ai/flux/schnell":n==="language"?"en":t&&/\bUR?L\b|https?:\/\//i.test(t)?"https://example.com/sample":"example"}function Ql(e,t,n,r){let o=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=xh(e.spendingControls).dailyLimit,a=Math.max(0,pr(e.dailySpent)),l=i>0?Math.min(i,Math.max(0,pr(e.dailyRemaining??i-a))):0,c=i>0?Math.min(1,a/i):0,d=(Array.isArray(t)?t:[]).filter(vh),g=d.slice(0,3),p=bh(d,3),_=(e.cards??[]).slice(0,3),h=r.latestVersion?un(r.latestVersion):"",S=r.updateCheckDisabled?"update checks disabled":h?`update ready: v${h}`:"up to date",I=Math.round(c*100),$=$t(e.status,e.enrolled?"approved":"not enrolled"),k=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${$} | touch id: ${n?"ready":"unavailable"}`,`Version: v${o} | ${S}`,`Spend meter: ${Xl(c)} ${String(I).padStart(3," ")}% | remaining ${Mn(l)}/day | daily cap ${Mn(i)}`,"","Spend",` Remaining ${Mn(l)} / ${Mn(i)}`,` Usage ${Xl(c)} ${I}%`,` Spent today ${Mn(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",..._.length>0?_.map(q=>` ${wh(q)}`):[" No cards enrolled"],"","Last 3 services",...p.length>0?p.map((q,W)=>` ${W+1}. ${q}`):[" No paid services yet"],"","Recent receipts",...g.length>0?g.map(q=>` ${Sh(q)}`):[" No receipts yet"]];return h&&!r.updateCheckDisabled?(k.push("",`Update: v${h} ready \u2014 run \`visa-cli update\``),r.updateMessage&&k.push(` ${un(r.updateMessage)}`)):r.updateMessage&&k.push("",`Update: ${un(r.updateMessage)}`),`${k.join(`
149
+ `),!0}function tu(e){let t=Array.isArray(e.inputSchema?.required)?e.inputSchema.required.filter(o=>typeof o=="string"):[],n=e.inputSchema?.properties&&typeof e.inputSchema.properties=="object"?e.inputSchema.properties:{};if(t.length===0)return{prompt:"a lobster"};let r={};for(let o of t)r[o]=Ch(o,n[o]?.description);return r}function Ch(e,t){let n=e.toLowerCase();return n==="prompt"?"a lobster":n==="text"?"Hello from Visa CLI.":n.endsWith("image_url")||n==="image_url"?"https://example.com/sample.jpg":n.endsWith("audio_url")||n==="audio_url"?"https://example.com/sample.wav":n.endsWith("video_url")||n==="video_url"?"https://example.com/sample.mp4":n==="taskid"||n==="task_id"?"task_abc123":n==="request_id"||n==="requestid"?"req_abc123":n==="model_path"||n==="model"?"fal-ai/flux/schnell":n==="language"?"en":t&&/\bUR?L\b|https?:\/\//i.test(t)?"https://example.com/sample":"example"}function ru(e,t,n,r){let o=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=$h(e.spendingControls).dailyLimit,a=Math.max(0,pr(e.dailySpent)),l=i>0?Math.min(i,Math.max(0,pr(e.dailyRemaining??i-a))):0,c=i>0?Math.min(1,a/i):0,d=(Array.isArray(t)?t:[]).filter(Eh),f=d.slice(0,3),p=Ah(d,3),_=(e.cards??[]).slice(0,3),h=r.latestVersion?dn(r.latestVersion):"",S=r.updateCheckDisabled?"update checks disabled":h?`update ready: v${h}`:"up to date",I=Math.round(c*100),$=Pt(e.status,e.enrolled?"approved":"not enrolled"),k=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${$} | touch id: ${n?"ready":"unavailable"}`,`Version: v${o} | ${S}`,`Spend meter: ${nu(c)} ${String(I).padStart(3," ")}% | remaining ${Mn(l)}/day | daily cap ${Mn(i)}`,"","Spend",` Remaining ${Mn(l)} / ${Mn(i)}`,` Usage ${nu(c)} ${I}%`,` Spent today ${Mn(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",..._.length>0?_.map(q=>` ${Ih(q)}`):[" No cards enrolled"],"","Last 3 services",...p.length>0?p.map((q,W)=>` ${W+1}. ${q}`):[" No paid services yet"],"","Recent receipts",...f.length>0?f.map(q=>` ${Rh(q)}`):[" No receipts yet"]];return h&&!r.updateCheckDisabled?(k.push("",`Update: v${h} ready \u2014 run \`visa-cli update\``),r.updateMessage&&k.push(` ${dn(r.updateMessage)}`)):r.updateMessage&&k.push("",`Update: ${dn(r.updateMessage)}`),`${k.join(`
149
150
  `)}
150
- `}function yh(e){return e.tool_name!=null}function _h(e){return pr(e.amount)===0&&e.status==="failed"}function vh(e){return yh(e)&&!_h(e)}function bh(e,t=1/0){let n=new Set,r=[];for(let o of e){if(r.length>=t)break;let s=$t(o.merchant_name,"Unknown merchant"),i=$t(o.tool_name,"unknown_tool"),a=`${s} :: ${i}`;n.has(a)||(n.add(a),r.push(`${s} [${i}]`))}return r}function Sh(e){let t=$t(e.merchant_name,"Unknown merchant"),n=$t(e.tool_name,"unknown_tool"),r=Mn(pr(e.amount)),o=$t(e.status,"unknown"),s=Ch(e.created_at);return`${r} ${o.padEnd(9)} ${t} [${n}] ${s}`}function wh(e){let t=$t(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function xh(e){return{dailyLimit:pr(e?.daily_limit??e?.dailyLimit??0)}}function pr(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function Mn(e){return`$${e.toFixed(2)}`}function Xl(e,t=20){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=un(e??"").trim();return n.length>0?n:t}function Ch(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 un(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 kh=/^[1-9]\d{0,9}$/;function ai(e){if(!kh.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 eu(e){let t=un(e.brand||"Visa"),n=un(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 We=E(require("fs")),Q=E(require("path")),Th=["npm","pnpm","yarn","bun"],Eh=/\s+/,Ah=process.platform==="win32"?"visa-cli.cmd":"visa-cli",ci=["node_modules","@visa","cli"];function Rh(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(Eh)[0]??"",r=n.indexOf("/"),o=r===-1?n:n.slice(0,r);return Th.includes(o)?o:void 0}function li(e){if(!e)return;let t=e;try{t=We.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 Ih(e=process.argv[1]){return Rh()??li(process.env.npm_execpath)??li(process.env.npm_node_execpath)??li(e)}function $h(e=process.env.PATH??""){let t=[];for(let n of e.split(Q.delimiter))n&&t.push(n);return t}function Ph(e=process.env.PATH??""){let t=new Set,n=[];for(let r of $h(e))try{let o=Q.join(r,Ah);We.accessSync(o,We.constants.X_OK);let s=Q.resolve(o);t.has(s)||(t.add(s),n.push(o))}catch{}return n}function tu(e){try{let t=We.readFileSync(Q.join(e,"package.json"),"utf-8"),n=JSON.parse(t);if(n.name==="@visa/cli"&&typeof n.version=="string")return n.version}catch{}}function Mh(e){let t=Q.resolve(e).split(Q.sep);for(let n=t.length-ci.length;n>=0;n--)if(ci.every((r,o)=>t[n+o]===r)){let r=t.slice(0,n+ci.length).join(Q.sep)||Q.sep;if(tu(r))return r}}function Oh(e){if(!e)return;let t=Q.normalize(e),n=t.split(Q.sep),r=s=>s.every((a,l)=>n[n.length-s.length+l]===a)?n.slice(0,-s.length).join(Q.sep)||Q.parse(t).root:void 0,o=r(["lib","node_modules","@visa","cli"]);if(o)return o;if(process.platform==="win32")return r(["node_modules","@visa","cli"])}function Nh(e,t){let n=Q.resolve(e);try{n=We.realpathSync(e)}catch{}let r=Mh(n);return{binPath:e,realPath:n,packageRoot:r,version:r?tu(r):void 0,prefix:Oh(r),isActive:n===t}}function Dh(e,t=process.env.PATH??""){let n=e??process.argv[1],r=n?Q.resolve(n):"";try{n&&(r=We.realpathSync(n))}catch{}let o=e?[e]:[n,...Ph(t)].filter(Boolean),s=new Map;for(let d of o){let g=Nh(d,r),p=s.get(g.realPath);s.set(g.realPath,p?{...g,binPath:p.binPath}:g)}let i=[...s.values()],a=i.find(d=>d.isActive);!a&&i.length>0&&!e&&(a={...i[0],isActive:!0},i[0]=a);let l=new Set(i.map(d=>d.packageRoot).filter(Boolean)),c=!!a?.packageRoot&&l.size>1,u=a?.prefix;return{active:a,installs:i,hasConflictingInstalls:c,recommendedPrefix:u}}function Lh(e,t=process.platform){return/^[A-Za-z0-9_./:@+-]+$/.test(e)?e:t==="win32"?`"${e.replace(/"/g,'""')}"`:`'${e.replace(/'/g,"'\\''")}'`}function ui(e,t,n,r={}){let o=t??Ih(n)??"npm",s=r.withDiagnostics?Dh(n):void 0,a=`@visa/cli@${e??"latest"}`;switch(o){case"npm":if(s?.hasConflictingInstalls&&s.recommendedPrefix){let l=s.recommendedPrefix;return{packageManager:o,command:"npm",args:["install","-g","--prefix",l,a],display:`npm install -g --prefix ${Lh(l)} ${a}`,diagnostics:s}}return{packageManager:o,command:"npm",args:["install","-g",a],display:`npm install -g ${a}`,diagnostics:s};case"pnpm":return{packageManager:o,command:"pnpm",args:["add","-g",a],display:`pnpm add -g ${a}`,diagnostics:s};case"yarn":return{packageManager:o,command:"yarn",args:["global","add",a],display:`yarn global add ${a}`,diagnostics:s};case"bun":return{packageManager:o,command:"bun",args:["add","-g",a],display:`bun add -g ${a}`,diagnostics:s}}}function Uh(e){let t=e.isActive?" (active)":"",n=e.version?` v${e.version}`:" version unknown",r=e.prefix?` via ${e.prefix}`:"";return` - ${e.binPath}${t}: ${n}${r}`}function di(e,t){if(!e.hasConflictingInstalls)return null;let n=["Multiple Visa CLI installs detected.",...e.installs.map(Uh)];return t&&(e.recommendedPrefix?n.push("The update command below targets the active install so your shell actually picks up the new version."):n.push("The update command is shown below; remove duplicate installs if your shell still picks up an older version."),n.push(` ${t}`)),n.join(`
151
- `)}var Po=E(lr());var jh=["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 Fh(){let e=new Set;for(let t of jh)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of ir)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var uS=Fh();var mi=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 gS=new Set(ir),hS=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...mi,...ir]);var Pt=E(lr()),Vh=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;function nu(e,t,n){if(typeof e!="string"||!Vh.test(e))return{ok:!1,error:"amount must be a USD amount with at most two decimal places"};let[r,o=""]=e.split("."),s=BigInt(r)*100n+BigInt(o.padEnd(2,"0"));if(s>BigInt(Number.MAX_SAFE_INTEGER))return{ok:!1,error:"amount is too large"};let i=Number(s);return i<t?{ok:!1,error:`minimum top-up is ${(0,Pt.toDisplay)((0,Pt.fromCents)(t))}`}:i>n?{ok:!1,error:`maximum top-up is ${(0,Pt.toDisplay)((0,Pt.fromCents)(n))}`}:{ok:!0,cents:i,displayUsd:(0,Pt.toDisplay)((0,Pt.fromCents)(i),{symbol:""})}}var L=E(require("fs")),O=E(require("path")),ru=E(require("os")),Y=ru.homedir(),qh=["Claude_","Anthropic.ClaudeDesktop_"],On=class extends Error{constructor(n,r,o){super(Bh(n,r,o));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function ou(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
152
- `)}function Hh(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=ou(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function Bh(e,t,n){let r=t.replace(Y,"~"),o=ou(n).split(`
153
- `).find(Boolean),s=o?` (${o})`:"";return e.id==="codex"?`Could not update Codex MCP config at ${r}: filesystem access was denied${s}. In Codex, rerun with elevated filesystem access or run \`visa-cli install codex\` outside the sandbox.`:`Could not update ${e.displayName} MCP config at ${r}: filesystem access was denied${s}.`}function fr(){return process.env.APPDATA||O.join(Y,"AppData","Roaming")}function Kh(){return process.env.LOCALAPPDATA||O.join(Y,"AppData","Local")}function pi(e){return process.platform==="win32"?e.win32:e.posix}function su(){if(process.platform!=="win32")return;let e=O.join(Kh(),"Packages");if(L.existsSync(e))try{let t=L.readdirSync(e,"utf-8");for(let n of qh){let r=t.filter(o=>o.startsWith(n)).sort()[0];if(r)return O.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function iu(){if(process.platform==="win32"){let e=su();return e?O.join(e,"claude_desktop_config.json"):O.join(fr(),"Claude","claude_desktop_config.json")}return O.join(Y,"Library","Application Support","Claude","claude_desktop_config.json")}function au(){if(process.platform!=="win32")return[O.join(Y,"Library","Application Support","Claude")];let e=[O.join(fr(),"Claude")],t=su();return t&&e.push(t),e}function Eo(e){return e.id==="claude-desktop"?iu():e.globalConfigPath}function Gh(e){return e.id==="claude-desktop"?au():e.detectPaths}var Oe=[{id:"claude",displayName:"Claude Code",globalConfigPath:O.join(Y,".claude.json"),configKey:"mcpServers",detectPaths:[O.join(Y,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:iu(),configKey:"mcpServers",detectPaths:au(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:O.join(Y,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[O.join(Y,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:O.join(Y,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[O.join(Y,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:O.join(Y,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[O.join(Y,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:pi({win32:O.join(fr(),"Roo","mcp_settings.json"),posix:O.join(Y,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[O.join(Y,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:O.join(Y,".vscode","mcp.json"),configKey:"servers",detectPaths:[O.join(Y,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:pi({win32:O.join(fr(),"Zed","settings.json"),posix:O.join(Y,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:pi({win32:[O.join(fr(),"Zed")],posix:[O.join(Y,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:O.join(Y,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[O.join(Y,".codex")],postInstallHint:"Restart Codex to connect."}];function fi(e){return Oe.find(t=>t.id===e)}function gr(e){return Gh(e).some(t=>{if(t.includes("*")){let n=O.dirname(t),r=O.basename(t).replaceAll("*","");if(!L.existsSync(n))return!1;try{return L.readdirSync(n).some(o=>o.startsWith(r))}catch{return!1}}return L.existsSync(t)})}function cu(){return{command:"node",args:[O.resolve(__dirname,"mcp-server/index.js")]}}function gi(e,t){return t==="project"?"json":e.configFormat??"json"}function zh(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 hi(e,t){let n=`[mcp_servers.${t}]`,r=e.findIndex(s=>s.trim()===n);if(r===-1)return;let o=r+1;for(;o<e.length&&!e[o].trim().startsWith("[");)o++;return{start:r,end:o}}function yi(e,t){let n=e.split(`
154
- `),r=hi(n,t);if(!r)return;let o={};for(let s=r.start+1;s<r.end;s++){let i=n[s].trim().match(/^(\w+)\s*=\s*(.+)$/);i&&(o[i[1]]=zh(i[2]))}return Object.keys(o).length>0?o:void 0}function Wh(e,t,n){let r=`[${n.args.map(l=>`"${l}"`).join(", ")}]`,o=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],s=e.split(`
155
- `),i=hi(s,t);if(i){s.splice(i.start,i.end-i.start,...o);let l=s.join(`
151
+ `}function kh(e){return e.tool_name!=null}function Th(e){return pr(e.amount)===0&&e.status==="failed"}function Eh(e){return kh(e)&&!Th(e)}function Ah(e,t=1/0){let n=new Set,r=[];for(let o of e){if(r.length>=t)break;let s=Pt(o.merchant_name,"Unknown merchant"),i=Pt(o.tool_name,"unknown_tool"),a=`${s} :: ${i}`;n.has(a)||(n.add(a),r.push(`${s} [${i}]`))}return r}function Rh(e){let t=Pt(e.merchant_name,"Unknown merchant"),n=Pt(e.tool_name,"unknown_tool"),r=Mn(pr(e.amount)),o=Pt(e.status,"unknown"),s=Ph(e.created_at);return`${r} ${o.padEnd(9)} ${t} [${n}] ${s}`}function Ih(e){let t=Pt(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function $h(e){return{dailyLimit:pr(e?.daily_limit??e?.dailyLimit??0)}}function pr(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function Mn(e){return`$${e.toFixed(2)}`}function nu(e,t=20){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function Pt(e,t){let n=dn(e??"").trim();return n.length>0?n:t}function Ph(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?Pt(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function dn(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ")}var Mh=/^[1-9]\d{0,9}$/;function mi(e){if(!Mh.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 ou(e){let t=dn(e.brand||"Visa"),n=dn(e.last4||"unknown");return{id:Number.isInteger(e.id)?String(e.id):"-",brand:t.charAt(0).toUpperCase()+t.slice(1).toLowerCase(),card:`****${n}`,default:e.isDefault?"yes":""}}var We=E(require("fs")),Q=E(require("path")),Oh=["npm","pnpm","yarn","bun"],Nh=/\s+/,Lh=process.platform==="win32"?"visa-cli.cmd":"visa-cli",pi=["node_modules","@visa","cli"];function Dh(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(Nh)[0]??"",r=n.indexOf("/"),o=r===-1?n:n.slice(0,r);return Oh.includes(o)?o:void 0}function fi(e){if(!e)return;let t=e;try{t=We.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 Uh(e=process.argv[1]){return Dh()??fi(process.env.npm_execpath)??fi(process.env.npm_node_execpath)??fi(e)}function jh(e=process.env.PATH??""){let t=[];for(let n of e.split(Q.delimiter))n&&t.push(n);return t}function Fh(e=process.env.PATH??""){let t=new Set,n=[];for(let r of jh(e))try{let o=Q.join(r,Lh);We.accessSync(o,We.constants.X_OK);let s=Q.resolve(o);t.has(s)||(t.add(s),n.push(o))}catch{}return n}function su(e){try{let t=We.readFileSync(Q.join(e,"package.json"),"utf-8"),n=JSON.parse(t);if(n.name==="@visa/cli"&&typeof n.version=="string")return n.version}catch{}}function Vh(e){let t=Q.resolve(e).split(Q.sep);for(let n=t.length-pi.length;n>=0;n--)if(pi.every((r,o)=>t[n+o]===r)){let r=t.slice(0,n+pi.length).join(Q.sep)||Q.sep;if(su(r))return r}}function qh(e){if(!e)return;let t=Q.normalize(e),n=t.split(Q.sep),r=s=>s.every((a,l)=>n[n.length-s.length+l]===a)?n.slice(0,-s.length).join(Q.sep)||Q.parse(t).root:void 0,o=r(["lib","node_modules","@visa","cli"]);if(o)return o;if(process.platform==="win32")return r(["node_modules","@visa","cli"])}function Hh(e,t){let n=Q.resolve(e);try{n=We.realpathSync(e)}catch{}let r=Vh(n);return{binPath:e,realPath:n,packageRoot:r,version:r?su(r):void 0,prefix:qh(r),isActive:n===t}}function Bh(e,t=process.env.PATH??""){let n=e??process.argv[1],r=n?Q.resolve(n):"";try{n&&(r=We.realpathSync(n))}catch{}let o=e?[e]:[n,...Fh(t)].filter(Boolean),s=new Map;for(let d of o){let f=Hh(d,r),p=s.get(f.realPath);s.set(f.realPath,p?{...f,binPath:p.binPath}:f)}let i=[...s.values()],a=i.find(d=>d.isActive);!a&&i.length>0&&!e&&(a={...i[0],isActive:!0},i[0]=a);let l=new Set(i.map(d=>d.packageRoot).filter(Boolean)),c=!!a?.packageRoot&&l.size>1,u=a?.prefix;return{active:a,installs:i,hasConflictingInstalls:c,recommendedPrefix:u}}function Kh(e,t=process.platform){return/^[A-Za-z0-9_./:@+-]+$/.test(e)?e:t==="win32"?`"${e.replace(/"/g,'""')}"`:`'${e.replace(/'/g,"'\\''")}'`}function gi(e,t,n,r={}){let o=t??Uh(n)??"npm",s=r.withDiagnostics?Bh(n):void 0,a=`@visa/cli@${e??"latest"}`;switch(o){case"npm":if(s?.hasConflictingInstalls&&s.recommendedPrefix){let l=s.recommendedPrefix;return{packageManager:o,command:"npm",args:["install","-g","--prefix",l,a],display:`npm install -g --prefix ${Kh(l)} ${a}`,diagnostics:s}}return{packageManager:o,command:"npm",args:["install","-g",a],display:`npm install -g ${a}`,diagnostics:s};case"pnpm":return{packageManager:o,command:"pnpm",args:["add","-g",a],display:`pnpm add -g ${a}`,diagnostics:s};case"yarn":return{packageManager:o,command:"yarn",args:["global","add",a],display:`yarn global add ${a}`,diagnostics:s};case"bun":return{packageManager:o,command:"bun",args:["add","-g",a],display:`bun add -g ${a}`,diagnostics:s}}}function Gh(e){let t=e.isActive?" (active)":"",n=e.version?` v${e.version}`:" version unknown",r=e.prefix?` via ${e.prefix}`:"";return` - ${e.binPath}${t}: ${n}${r}`}function hi(e,t){if(!e.hasConflictingInstalls)return null;let n=["Multiple Visa CLI installs detected.",...e.installs.map(Gh)];return t&&(e.recommendedPrefix?n.push("The update command below targets the active install so your shell actually picks up the new version."):n.push("The update command is shown below; remove duplicate installs if your shell still picks up an older version."),n.push(` ${t}`)),n.join(`
152
+ `)}var Do=E(lr());var zh=["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 Wh(){let e=new Set;for(let t of zh)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of ir)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var _S=Wh();var yi=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 xS=new Set(ir),CS=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...yi,...ir]);var Mt=E(lr()),Jh=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;function iu(e,t,n){if(typeof e!="string"||!Jh.test(e))return{ok:!1,error:"amount must be a USD amount with at most two decimal places"};let[r,o=""]=e.split("."),s=BigInt(r)*100n+BigInt(o.padEnd(2,"0"));if(s>BigInt(Number.MAX_SAFE_INTEGER))return{ok:!1,error:"amount is too large"};let i=Number(s);return i<t?{ok:!1,error:`minimum top-up is ${(0,Mt.toDisplay)((0,Mt.fromCents)(t))}`}:i>n?{ok:!1,error:`maximum top-up is ${(0,Mt.toDisplay)((0,Mt.fromCents)(n))}`}:{ok:!0,cents:i,displayUsd:(0,Mt.toDisplay)((0,Mt.fromCents)(i),{symbol:""})}}var U=E(require("fs")),O=E(require("path")),au=E(require("os")),Y=au.homedir(),Yh=["Claude_","Anthropic.ClaudeDesktop_"],On=class extends Error{constructor(n,r,o){super(Xh(n,r,o));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function cu(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
153
+ `)}function Zh(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=cu(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function Xh(e,t,n){let r=t.replace(Y,"~"),o=cu(n).split(`
154
+ `).find(Boolean),s=o?` (${o})`:"";return e.id==="codex"?`Could not update Codex MCP config at ${r}: filesystem access was denied${s}. In Codex, rerun with elevated filesystem access or run \`visa-cli install codex\` outside the sandbox.`:`Could not update ${e.displayName} MCP config at ${r}: filesystem access was denied${s}.`}function fr(){return process.env.APPDATA||O.join(Y,"AppData","Roaming")}function Qh(){return process.env.LOCALAPPDATA||O.join(Y,"AppData","Local")}function _i(e){return process.platform==="win32"?e.win32:e.posix}function lu(){if(process.platform!=="win32")return;let e=O.join(Qh(),"Packages");if(U.existsSync(e))try{let t=U.readdirSync(e,"utf-8");for(let n of Yh){let r=t.filter(o=>o.startsWith(n)).sort()[0];if(r)return O.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function uu(){if(process.platform==="win32"){let e=lu();return e?O.join(e,"claude_desktop_config.json"):O.join(fr(),"Claude","claude_desktop_config.json")}return O.join(Y,"Library","Application Support","Claude","claude_desktop_config.json")}function du(){if(process.platform!=="win32")return[O.join(Y,"Library","Application Support","Claude")];let e=[O.join(fr(),"Claude")],t=lu();return t&&e.push(t),e}function Po(e){return e.id==="claude-desktop"?uu():e.globalConfigPath}function ey(e){return e.id==="claude-desktop"?du():e.detectPaths}var Oe=[{id:"claude",displayName:"Claude Code",globalConfigPath:O.join(Y,".claude.json"),configKey:"mcpServers",detectPaths:[O.join(Y,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:uu(),configKey:"mcpServers",detectPaths:du(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:O.join(Y,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[O.join(Y,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:O.join(Y,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[O.join(Y,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:O.join(Y,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[O.join(Y,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:_i({win32:O.join(fr(),"Roo","mcp_settings.json"),posix:O.join(Y,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[O.join(Y,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:O.join(Y,".vscode","mcp.json"),configKey:"servers",detectPaths:[O.join(Y,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:_i({win32:O.join(fr(),"Zed","settings.json"),posix:O.join(Y,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:_i({win32:[O.join(fr(),"Zed")],posix:[O.join(Y,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:O.join(Y,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[O.join(Y,".codex")],postInstallHint:"Restart Codex to connect."}];function vi(e){return Oe.find(t=>t.id===e)}function gr(e){return ey(e).some(t=>{if(t.includes("*")){let n=O.dirname(t),r=O.basename(t).replaceAll("*","");if(!U.existsSync(n))return!1;try{return U.readdirSync(n).some(o=>o.startsWith(r))}catch{return!1}}return U.existsSync(t)})}function mu(){return{command:"node",args:[O.resolve(__dirname,"mcp-server/index.js")]}}function bi(e,t){return t==="project"?"json":e.configFormat??"json"}function ty(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 Si(e,t){let n=`[mcp_servers.${t}]`,r=e.findIndex(s=>s.trim()===n);if(r===-1)return;let o=r+1;for(;o<e.length&&!e[o].trim().startsWith("[");)o++;return{start:r,end:o}}function wi(e,t){let n=e.split(`
155
+ `),r=Si(n,t);if(!r)return;let o={};for(let s=r.start+1;s<r.end;s++){let i=n[s].trim().match(/^(\w+)\s*=\s*(.+)$/);i&&(o[i[1]]=ty(i[2]))}return Object.keys(o).length>0?o:void 0}function ny(e,t,n){let r=`[${n.args.map(l=>`"${l}"`).join(", ")}]`,o=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],s=e.split(`
156
+ `),i=Si(s,t);if(i){s.splice(i.start,i.end-i.start,...o);let l=s.join(`
156
157
  `);return l.endsWith(`
157
158
  `)?l:l+`
158
159
  `}let a=e.trimEnd();return a+(a.length>0?`
159
160
 
160
161
  `:"")+o.join(`
161
162
  `)+`
162
- `}function Jh(e,t){let n=e.split(`
163
- `),r=hi(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
163
+ `}function ry(e,t){let n=e.split(`
164
+ `),r=Si(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
164
165
  `).replace(/\n{3,}/g,`
165
166
 
166
- `)):e}function hr(e,t="global"){let n=t==="project"?O.join(process.cwd(),".mcp.json"):Eo(e);try{let r=O.dirname(n);L.existsSync(r)||L.mkdirSync(r,{recursive:!0});let o=gi(e,t),s=cu();if(o==="toml"){let i=L.existsSync(n)?L.readFileSync(n,"utf-8"):"",a=Wh(i,"visa-cli",s);L.writeFileSync(n,a)}else{let i={};if(L.existsSync(n))try{i=JSON.parse(L.readFileSync(n,"utf-8"))}catch{i={}}i[e.configKey]=i[e.configKey]||{},i[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(s):s,L.writeFileSync(n,JSON.stringify(i,null,2)+`
167
- `)}}catch(r){throw Hh(r)?new On(e,n,r):r}return{installed:!0,configPath:n,message:e.postInstallHint}}function _i(e,t="global"){let n=t==="project"?O.join(process.cwd(),".mcp.json"):Eo(e);if(!L.existsSync(n))return{removed:!1,configPath:n};if(gi(e,t)==="toml"){let i=L.readFileSync(n,"utf-8");return yi(i,"visa-cli")?(L.writeFileSync(n,Jh(i,"visa-cli")),{removed:!0,configPath:n}):{removed:!1,configPath:n}}let o;try{o=JSON.parse(L.readFileSync(n,"utf-8"))}catch{return{removed:!1,configPath:n}}let s=o[e.configKey];return!s||!s["visa-cli"]?{removed:!1,configPath:n}:(delete s["visa-cli"],L.writeFileSync(n,JSON.stringify(o,null,2)+`
168
- `),{removed:!0,configPath:n})}function lu(e,t="global"){let n=t==="project"?O.join(process.cwd(),".mcp.json"):Eo(e);if(!L.existsSync(n))return!1;if(gi(e,t)==="toml")try{let o=L.readFileSync(n,"utf-8");return!!yi(o,"visa-cli")}catch{return!1}try{return!!JSON.parse(L.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function Yh(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 Zh(e,t){if(e===t)return!0;let n=O.resolve(e),r=O.resolve(t);if(n===r)return!0;try{let o=L.realpathSync(n),s=L.realpathSync(r);return o===s}catch{return!1}}function yr(){let e=cu(),t=e.args[e.args.length-1],n=[];for(let r of Oe){let o=Eo(r);if(!L.existsSync(o))continue;let s=r.configFormat??"json",i;if(s==="toml")try{let c=L.readFileSync(o,"utf-8");i=yi(c,"visa-cli")}catch{continue}else{let c;try{c=JSON.parse(L.readFileSync(o,"utf-8"))}catch{continue}i=c?.[r.configKey]?.["visa-cli"]}if(!i)continue;let a=Yh(i);if(!a||Zh(a,t))continue;let l=L.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:o,currentPath:a,expectedPath:t,staleReason:l})}return n}function vi(e){return{configPath:hr(e.client,"global").configPath}}var xi=(0,vu.promisify)(yu.execFile);process.stdout.on("error",e=>{throw e.code==="EPIPE"&&process.exit(0),e});process.stderr.on("error",e=>{throw e.code==="EPIPE"&&process.exit(0),e});function ty(e){let t=F.homedir(),n=o=>o.replace(t,"~"),r=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
169
- ${r}: ${n(e.currentPath)}`}function bu(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(ty(n))}function uu(e){console.log(` ! ${e.client.displayName} skipped: ${e.message}`)}function Ne(){this.help({error:!1})}var G=new hu.Command,ny=new Set(["pay",...mi]),Io=null,_r=!1;function se(){return Io=new Se(()=>U.getSessionToken()),Io}function Su(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function du(e){if(e instanceof Ft)return!0;let t=e instanceof Error?e.message:"";return/attestation required|invalid signature|rotate biometric key|biometric key/i.test(t)}var mu=0,pu="",ry="attestation-key-rotation";async function oy(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:mu,merchant:pu,context:ry})).toString("base64");return{signature:await Rn(n,"verify Visa CLI Touch ID setup"),nonce:t,amount:mu,merchant:pu}}async function sy(e){let t=await Yc(),n=await oy(e);await e.registerAttestationKey(t,n)}async function wu(e,t,n=!1){let r=await so();console.log(" Attestation key generated."),await e.registerAttestationKey(r),console.log(" Attestation key registered with server."),t&&(await e.setBiometricPreference({required:!0}),n&&m.info("attestation:requirement-restored-after-recovery",{surface:"setup"}),console.log(n?" Touch ID requirement re-enabled after biometric recovery.":" Touch ID requirement enabled."))}async function bi(e){if(!await ki(e))throw new Error("Could not clear stale server biometric state. Run `visa-cli config reset`, then `visa-cli setup`.");await wu(e,!0,!0)}function xu(e){return async()=>{let t=await ki(e);return{success:t,...t?{}:{message:"Biometric recovery was not completed."}}}}async function iy(e){let r=Date.now()+3e5;for(;Date.now()<r;)try{let o=await globalThis.fetch(`${he()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:3e4}),signal:AbortSignal.timeout(35e3)});if(!o.ok){await gt(o,i=>{m.warn("auth_status:retry_after_http_error",{status:o.status,delayMs:i})});continue}let s=await o.json();if(s.status==="pending")continue;if(s.status==="complete"&&s.attestationCleared)return;if(s.status==="expired")throw new Error("Biometric reset session expired. Please run visa-cli config reset again.");if(s.status==="error")throw new Error(s.error||"Biometric reset failed. Please try again.")}catch(o){if(o?.message&&!/fetch failed|network|abort/i.test(o.message))throw o;await gt(void 0,s=>{m.warn("auth_status:retry_after_network_error",{delayMs:s})})}throw new Error("Biometric reset timed out after 5 minutes. Please run visa-cli config reset again.")}async function ki(e){let t;try{t=await e.getStatus()}catch(o){let s=o?.message||"";if(/not logged in|session.*expired|no local credentials/i.test(s))return!1;throw new Error(`Could not check server biometric state: ${s||"unknown error"}`)}if(!Su(t))return!1;let n=$o.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 es(r.recoveryUrl),await iy(n),console.log(" Server biometric state cleared."),!0}function vr(e){return`$${(e/100).toFixed(2)}`}function Ci(e,t,n=!1){if(!e){let i=vr(t);return n&&t>=0?`+${i}`:i}let r=(0,Po.fromWire)(e),o=r%10000n===0n?2:6,s=(0,Po.toDisplay)(r,{decimals:o});return n&&r>=0n?`+${s}`:s}function ay(e){return Ci(e,0)}function cy(e){let t=`visa-cli-${F.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 ly(e){if(!e)return;let t=e.split(",").map(s=>s.trim()).filter(Boolean),n=Array.from(new Set(t)),r=n.find(s=>s.length>64);if(r)throw new Error(`Tool id is too long: ${r}`);let o=n.find(s=>ny.has(s));if(o)throw new Error(`Tool id "${o}" is retired for direct API-key access. Use category meta-tools or discover/execute instead.`);return n}function uy(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 Cu(e){return e&&e.length>0?e.join(", "):"all tools"}function Ti(e,t){return t||(typeof e!="number"||!Number.isFinite(e)?"price unknown":`$${(e/100).toFixed(2)}`)}function dy(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 ku(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 Si(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function my(e){let t=new Map;for(let n of e){let r=n.category||"other",o=t.get(r)??[];o.push(n),t.set(r,o)}return new Map([...t.entries()].sort(([n],[r])=>n.localeCompare(r)))}function py(e){let t=Math.max(4,Math.min(28,e.reduce((i,a)=>Math.max(i,a.id.length),0))),n=7,r=Math.max(8,Math.min(12,e.reduce((i,a)=>Math.max(i,(a.category||"").length),0))),o=typeof process.stdout.columns=="number"&&process.stdout.columns>0?process.stdout.columns:100,s=Math.max(40,o-(t+n+r+10));console.log(`
167
+ `)):e}function hr(e,t="global"){let n=t==="project"?O.join(process.cwd(),".mcp.json"):Po(e);try{let r=O.dirname(n);U.existsSync(r)||U.mkdirSync(r,{recursive:!0});let o=bi(e,t),s=mu();if(o==="toml"){let i=U.existsSync(n)?U.readFileSync(n,"utf-8"):"",a=ny(i,"visa-cli",s);U.writeFileSync(n,a)}else{let i={};if(U.existsSync(n))try{i=JSON.parse(U.readFileSync(n,"utf-8"))}catch{i={}}i[e.configKey]=i[e.configKey]||{},i[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(s):s,U.writeFileSync(n,JSON.stringify(i,null,2)+`
168
+ `)}}catch(r){throw Zh(r)?new On(e,n,r):r}return{installed:!0,configPath:n,message:e.postInstallHint}}function xi(e,t="global"){let n=t==="project"?O.join(process.cwd(),".mcp.json"):Po(e);if(!U.existsSync(n))return{removed:!1,configPath:n};if(bi(e,t)==="toml"){let i=U.readFileSync(n,"utf-8");return wi(i,"visa-cli")?(U.writeFileSync(n,ry(i,"visa-cli")),{removed:!0,configPath:n}):{removed:!1,configPath:n}}let o;try{o=JSON.parse(U.readFileSync(n,"utf-8"))}catch{return{removed:!1,configPath:n}}let s=o[e.configKey];return!s||!s["visa-cli"]?{removed:!1,configPath:n}:(delete s["visa-cli"],U.writeFileSync(n,JSON.stringify(o,null,2)+`
169
+ `),{removed:!0,configPath:n})}function pu(e,t="global"){let n=t==="project"?O.join(process.cwd(),".mcp.json"):Po(e);if(!U.existsSync(n))return!1;if(bi(e,t)==="toml")try{let o=U.readFileSync(n,"utf-8");return!!wi(o,"visa-cli")}catch{return!1}try{return!!JSON.parse(U.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function oy(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 sy(e,t){if(e===t)return!0;let n=O.resolve(e),r=O.resolve(t);if(n===r)return!0;try{let o=U.realpathSync(n),s=U.realpathSync(r);return o===s}catch{return!1}}function yr(){let e=mu(),t=e.args[e.args.length-1],n=[];for(let r of Oe){let o=Po(r);if(!U.existsSync(o))continue;let s=r.configFormat??"json",i;if(s==="toml")try{let c=U.readFileSync(o,"utf-8");i=wi(c,"visa-cli")}catch{continue}else{let c;try{c=JSON.parse(U.readFileSync(o,"utf-8"))}catch{continue}i=c?.[r.configKey]?.["visa-cli"]}if(!i)continue;let a=oy(i);if(!a||sy(a,t))continue;let l=U.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:o,currentPath:a,expectedPath:t,staleReason:l})}return n}function Ci(e){return{configPath:hr(e.client,"global").configPath}}var Ri=(0,xu.promisify)(Su.execFile);function ki(){let e=ee.join(D.homedir(),".claude","settings.json");setImmediate(()=>{fs(e,{getCommand:()=>qr(process.execPath,process.argv[1])})})}process.stdout.on("error",e=>{throw e.code==="EPIPE"&&process.exit(0),e});process.stderr.on("error",e=>{throw e.code==="EPIPE"&&process.exit(0),e});function ly(e){let t=D.homedir(),n=o=>o.replace(t,"~"),r=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
170
+ ${r}: ${n(e.currentPath)}`}function Cu(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(ly(n))}function fu(e){console.log(` ! ${e.client.displayName} skipped: ${e.message}`)}function Ne(){this.help({error:!1})}var G=new bu.Command,uy=new Set(["pay",...yi]),No=null,_r=!1;function ie(){return No=new Se(()=>j.getSessionToken()),No}function ku(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function gu(e){if(e instanceof Vt)return!0;let t=e instanceof Error?e.message:"";return/attestation required|invalid signature|rotate biometric key|biometric key/i.test(t)}var hu=0,yu="",dy="attestation-key-rotation";async function my(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:hu,merchant:yu,context:dy})).toString("base64");return{signature:await Rn(n,"verify Visa CLI Touch ID setup"),nonce:t,amount:hu,merchant:yu}}async function py(e){let t=await el(),n=await my(e);await e.registerAttestationKey(t,n)}async function Tu(e,t,n=!1){let r=await uo();console.log(" Attestation key generated."),await e.registerAttestationKey(r),console.log(" Attestation key registered with server."),t&&(await e.setBiometricPreference({required:!0}),n&&m.info("attestation:requirement-restored-after-recovery",{surface:"setup"}),console.log(n?" Touch ID requirement re-enabled after biometric recovery.":" Touch ID requirement enabled."))}async function Ti(e){if(!await $i(e))throw new Error("Could not clear stale server biometric state. Run `visa-cli config reset`, then `visa-cli setup`.");await Tu(e,!0,!0)}function Eu(e){return async()=>{let t=await $i(e);return{success:t,...t?{}:{message:"Biometric recovery was not completed."}}}}async function fy(e){let r=Date.now()+3e5;for(;Date.now()<r;)try{let o=await globalThis.fetch(`${ye()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:3e4}),signal:AbortSignal.timeout(35e3)});if(!o.ok){await ht(o,i=>{m.warn("auth_status:retry_after_http_error",{status:o.status,delayMs:i})});continue}let s=await o.json();if(s.status==="pending")continue;if(s.status==="complete"&&s.attestationCleared)return;if(s.status==="expired")throw new Error("Biometric reset session expired. Please run visa-cli config reset again.");if(s.status==="error")throw new Error(s.error||"Biometric reset failed. Please try again.")}catch(o){if(o?.message&&!/fetch failed|network|abort/i.test(o.message))throw o;await ht(void 0,s=>{m.warn("auth_status:retry_after_network_error",{delayMs:s})})}throw new Error("Biometric reset timed out after 5 minutes. Please run visa-cli config reset again.")}async function $i(e){let t;try{t=await e.getStatus()}catch(o){let s=o?.message||"";if(/not logged in|session.*expired|no local credentials/i.test(s))return!1;throw new Error(`Could not check server biometric state: ${s||"unknown error"}`)}if(!ku(t))return!1;let n=Lo.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 ss(r.recoveryUrl),await fy(n),console.log(" Server biometric state cleared."),!0}function vr(e){return`$${(e/100).toFixed(2)}`}function Ii(e,t,n=!1){if(!e){let i=vr(t);return n&&t>=0?`+${i}`:i}let r=(0,Do.fromWire)(e),o=r%10000n===0n?2:6,s=(0,Do.toDisplay)(r,{decimals:o});return n&&r>=0n?`+${s}`:s}function gy(e){return Ii(e,0)}function hy(e){let t=`visa-cli-${D.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 yy(e){if(!e)return;let t=e.split(",").map(s=>s.trim()).filter(Boolean),n=Array.from(new Set(t)),r=n.find(s=>s.length>64);if(r)throw new Error(`Tool id is too long: ${r}`);let o=n.find(s=>uy.has(s));if(o)throw new Error(`Tool id "${o}" is retired for direct API-key access. Use category meta-tools or discover/execute instead.`);return n}function _y(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 Au(e){return e&&e.length>0?e.join(", "):"all tools"}function Pi(e,t){return t||(typeof e!="number"||!Number.isFinite(e)?"price unknown":`$${(e/100).toFixed(2)}`)}function vy(e,t){if(!e)return{};try{let n=JSON.parse(e);if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`${t} must be a JSON object.`);return n}catch(n){throw new Error(`${t} must be valid JSON: ${n.message}`)}}function Ru(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 Ei(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function by(e){let t=new Map;for(let n of e){let r=n.category||"other",o=t.get(r)??[];o.push(n),t.set(r,o)}return new Map([...t.entries()].sort(([n],[r])=>n.localeCompare(r)))}function Sy(e){let t=Math.max(4,Math.min(28,e.reduce((i,a)=>Math.max(i,a.id.length),0))),n=7,r=Math.max(8,Math.min(12,e.reduce((i,a)=>Math.max(i,(a.category||"").length),0))),o=typeof process.stdout.columns=="number"&&process.stdout.columns>0?process.stdout.columns:100,s=Math.max(40,o-(t+n+r+10));console.log(`
170
171
  Merchant tools
171
- `),console.log(` ${"Tool".padEnd(t)} ${"Price".padEnd(n)} ${"Category".padEnd(r)} Params`),console.log(` ${"\u2500".repeat(t)} ${"\u2500".repeat(n)} ${"\u2500".repeat(r)} ${"\u2500".repeat(Math.min(s,32))}`);for(let i of e)console.log(` ${Si(i.id,t).padEnd(t)} ${Ti(i.priceCents,i.priceDisplay).padEnd(n)} ${Si(i.category||"other",r).padEnd(r)} ${Si(ku(i),s)}`);console.log("\nUse `visa-cli merchants describe <tool>` for full details (incl. parameter types)."),console.log('Shortcut: `visa-cli generate image "a lobster"`\n')}function fy(e){console.log(`
172
+ `),console.log(` ${"Tool".padEnd(t)} ${"Price".padEnd(n)} ${"Category".padEnd(r)} Params`),console.log(` ${"\u2500".repeat(t)} ${"\u2500".repeat(n)} ${"\u2500".repeat(r)} ${"\u2500".repeat(Math.min(s,32))}`);for(let i of e)console.log(` ${Ei(i.id,t).padEnd(t)} ${Pi(i.priceCents,i.priceDisplay).padEnd(n)} ${Ei(i.category||"other",r).padEnd(r)} ${Ei(Ru(i),s)}`);console.log("\nUse `visa-cli merchants describe <tool>` for full details (incl. parameter types)."),console.log('Shortcut: `visa-cli generate image "a lobster"`\n')}function wy(e){console.log(`
172
173
  Merchant tools
173
- `);for(let[t,n]of my(e)){console.log(t[0]?.toUpperCase()+t.slice(1));for(let r of n)console.log(` ${r.id.padEnd(28)} ${Ti(r.priceCents,r.priceDisplay).padEnd(8)} ${r.description}`),console.log(` Params: ${ku(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"
174
- `)}function Ei(e,t={}){let n=t.format&&Mr(t.format)?t.format:void 0;if(t.json||n!==void 0){let i=t.command??"tool.run",a=n??"json",l,c=e?.content?.[0]?.text;typeof c=="string"&&(l=c);let u=Array.isArray(e?.urls)&&typeof e.urls[0]=="string"?e.urls[0]:void 0;if(!l&&u&&u.startsWith("data:")&&(l=u),l)try{let d=Go(l);if(d){let g=typeof e?.merchantName=="string"?e.merchantName:"media",p=typeof e?.transactionId=="string"?`${g}-${e.transactionId}`:g,_=zo(d,{tag:p}),h=Wo(i,e);h.success&&(h.filePath=_.filePath,h.mime=_.mime,h.bytes=_.bytes,u&&u.startsWith("data:")&&(h.urls=void 0)),qn(h,a);return}}catch(d){qn(Fn(i,`Failed to save inline media: ${d instanceof Error?d.message:String(d)}`),a),process.exitCode=Eu;return}qn(Wo(i,e),a);return}if(e?.content?.[0]?.text&&typeof e.content[0].text=="string"){try{let i=Go(e.content[0].text);if(i){let a=typeof e?.merchantName=="string"?e.merchantName:"media",l=typeof e?.transactionId=="string"?`${a}-${e.transactionId}`:a,c=zo(i,{tag:l});console.log("Saved inline image to file:"),console.log(` ${c.filePath}`),console.log(` (${c.mime}, ${(c.bytes/1024).toFixed(1)} KB)`),console.log(` Open with: open "${c.filePath}"`);return}}catch(i){console.error(`(warning: could not save inline image to disk: ${i instanceof Error?i.message:String(i)})`)}console.log(e.content[0].text);return}let o=Array.isArray(e?.urls)?e.urls:Array.isArray(e?.receipt?.urls)?e.receipt.urls:[];if(e?.success===!1){let i=JSON.stringify(e,null,2);console.log("Result:"),console.log(i);return}if(console.log("Done"),typeof e?.merchantName=="string"&&console.log(`Merchant: ${e.merchantName}`),typeof e?.amount=="number"&&console.log(`Cost: $${e.amount.toFixed(2)}`),typeof e?.transactionId=="string"&&console.log(`Transaction: ${e.transactionId}`),o.length>0){console.log(`
174
+ `);for(let[t,n]of by(e)){console.log(t[0]?.toUpperCase()+t.slice(1));for(let r of n)console.log(` ${r.id.padEnd(28)} ${Pi(r.priceCents,r.priceDisplay).padEnd(8)} ${r.description}`),console.log(` Params: ${Ru(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"
175
+ `)}function Mi(e,t={}){let n=t.format&&Mr(t.format)?t.format:void 0;if(t.json||n!==void 0){let i=t.command??"tool.run",a=n??"json",l,c=e?.content?.[0]?.text;typeof c=="string"&&(l=c);let u=Array.isArray(e?.urls)&&typeof e.urls[0]=="string"?e.urls[0]:void 0;if(!l&&u&&u.startsWith("data:")&&(l=u),l)try{let d=Zo(l);if(d){let f=typeof e?.merchantName=="string"?e.merchantName:"media",p=typeof e?.transactionId=="string"?`${f}-${e.transactionId}`:f,_=Xo(d,{tag:p}),h=Qo(i,e);h.success&&(h.filePath=_.filePath,h.mime=_.mime,h.bytes=_.bytes,u&&u.startsWith("data:")&&(h.urls=void 0)),qn(h,a);return}}catch(d){qn(Fn(i,`Failed to save inline media: ${d instanceof Error?d.message:String(d)}`),a),process.exitCode=$u;return}qn(Qo(i,e),a);return}if(e?.content?.[0]?.text&&typeof e.content[0].text=="string"){try{let i=Zo(e.content[0].text);if(i){let a=typeof e?.merchantName=="string"?e.merchantName:"media",l=typeof e?.transactionId=="string"?`${a}-${e.transactionId}`:a,c=Xo(i,{tag:l});console.log("Saved inline image to file:"),console.log(` ${c.filePath}`),console.log(` (${c.mime}, ${(c.bytes/1024).toFixed(1)} KB)`),console.log(` Open with: open "${c.filePath}"`);return}}catch(i){console.error(`(warning: could not save inline image to disk: ${i instanceof Error?i.message:String(i)})`)}console.log(e.content[0].text);return}let o=Array.isArray(e?.urls)?e.urls:Array.isArray(e?.receipt?.urls)?e.receipt.urls:[];if(e?.success===!1){let i=JSON.stringify(e,null,2);console.log("Result:"),console.log(i);return}if(console.log("Done"),typeof e?.merchantName=="string"&&console.log(`Merchant: ${e.merchantName}`),typeof e?.amount=="number"&&console.log(`Cost: $${e.amount.toFixed(2)}`),typeof e?.transactionId=="string"&&console.log(`Transaction: ${e.transactionId}`),o.length>0){console.log(`
175
176
  Result URLs:`);for(let i of o)console.log(` ${i}`);return}let s=JSON.stringify(e,null,2);s&&s!=="{}"&&(console.log(`
176
- Result:`),console.log(s))}var gy=new Set(["INVALID_TOOL_PARAMS","MISSING_TOOL_ID","UNKNOWN_TOOL"]),Tu=0,Eu=1,hy=2;function yy(e){if(e?.success!==!1)return Tu;let n=(typeof e?.error_code=="string"?e.error_code:typeof e?.code=="string"?e.code:"").toUpperCase();return gy.has(n)?hy:Eu}function Ai(e){let t=yy(e);t!==Tu&&(process.exitCode=t)}function Nn(e,t,n={}){let r=typeof n=="boolean"?{json:n}:n,o=t instanceof Error?t.message:String(t),s=r.format&&Mr(r.format)?r.format:void 0;if(r.json||s!==void 0){let i=s??"json";qn(Fn(e,o),i)}else console.error("Error:",o);process.exit(1)}async function _y(e,t={}){let n=await e.catalogSearch(t.query,t.category,"discover_tools",{limit:t.limit,offset:t.offset});return Array.isArray(n.tools)?n.tools:[]}var Au=100,Ru=200;function fu(e){let t=Number.parseInt(e,10);return Number.isNaN(t)?Number.NaN:t}function vy(e){let t=typeof e.limit=="number"&&Number.isInteger(e.limit)?Math.max(1,Math.min(e.limit,Ru)):Au,n=typeof e.offset=="number"&&Number.isInteger(e.offset)?Math.max(0,e.offset):0;return{limit:t,offset:n}}function by(e){let t=`
177
+ Result:`),console.log(s))}var xy=new Set(["INVALID_TOOL_PARAMS","MISSING_TOOL_ID","UNKNOWN_TOOL"]),Iu=0,$u=1,Cy=2;function ky(e){if(e?.success!==!1)return Iu;let n=(typeof e?.error_code=="string"?e.error_code:typeof e?.code=="string"?e.code:"").toUpperCase();return xy.has(n)?Cy:$u}function Oi(e){let t=ky(e);t!==Iu&&(process.exitCode=t)}function Nn(e,t,n={}){let r=typeof n=="boolean"?{json:n}:n,o=t instanceof Error?t.message:String(t),s=r.format&&Mr(r.format)?r.format:void 0;if(r.json||s!==void 0){let i=s??"json";qn(Fn(e,o),i)}else console.error("Error:",o);process.exit(1)}async function Ty(e,t={}){let n=await e.catalogSearch(t.query,t.category,"discover_tools",{limit:t.limit,offset:t.offset});return Array.isArray(n.tools)?n.tools:[]}var Pu=100,Mu=200;function _u(e){let t=Number.parseInt(e,10);return Number.isNaN(t)?Number.NaN:t}function Ey(e){let t=typeof e.limit=="number"&&Number.isInteger(e.limit)?Math.max(1,Math.min(e.limit,Mu)):Pu,n=typeof e.offset=="number"&&Number.isInteger(e.offset)?Math.max(0,e.offset):0;return{limit:t,offset:n}}function Ay(e){let t=`
177
178
  Options:
178
179
  `,n=`
179
180
  Commands:
180
- `,r=e.indexOf(t),o=e.indexOf(n);if(r===-1||o===-1||r>o)return e;let s=g=>{let _=e.slice(g+1).search(/\n[A-Z][A-Za-z ]+:\n/);return _===-1?e.length:g+1+_},i=s(r),a=s(o),l=e.slice(0,r),c=e.slice(r,i),u=e.slice(o,a),d=e.slice(a);return`${l}${u}${c}${d}`}function Sy(e){if(!e.startsWith("Usage: "))return e;let t=e.indexOf(`
181
+ `,r=e.indexOf(t),o=e.indexOf(n);if(r===-1||o===-1||r>o)return e;let s=f=>{let _=e.slice(f+1).search(/\n[A-Z][A-Za-z ]+:\n/);return _===-1?e.length:f+1+_},i=s(r),a=s(o),l=e.slice(0,r),c=e.slice(r,i),u=e.slice(o,a),d=e.slice(a);return`${l}${u}${c}${d}`}function Ry(e){if(!e.startsWith("Usage: "))return e;let t=e.indexOf(`
181
182
 
182
183
  `);if(t===-1)return e;let n=e.slice(0,t),r=e.slice(t+2),o=r.indexOf(`
183
184
 
@@ -185,14 +186,14 @@ Commands:
185
186
 
186
187
  ${n}
187
188
 
188
- ${i}`:e}function wy(e){return e.replace(/(^|\n)(Commands:\n)([\s\S]*?)(?=\n[A-Z][A-Za-z ]+:\n|$)/g,(t,n,r,o)=>{let s=o.split(`
189
- `).map(xy).join(`
190
- `);return`${n}${r}${s}`})}function xy(e){if(!e.startsWith(" "))return e;let n=2,r=n;for(;r<e.length&&e[r]!==" "&&e[r]!==" ";)r+=1;if(r===n)return e;let o=-1;for(let l=r;l<e.length-1;l+=1){if(e[l]!==" "||e[l+1]!==" ")continue;let c=l+2;for(;c<e.length&&e[c]===" ";)c+=1;if(c<e.length){o=c;break}}if(o===-1)return e;let s=e.slice(n,r),i=e.slice(o),a=Math.max(2,o-2-s.length);return` ${s}${" ".repeat(a)}${i}`}function Cy(e){return e.replace(/^(Usage: .+?) \[options\](?= |$)/gm,"$1")}function ky(e){return e.replace(/^Options:$/gm,"Flags:")}function Iu(e){let t=e.helpInformation.bind(e);e.helpInformation=()=>ky(Cy(wy(by(Sy(t())))));for(let n of e.commands)Iu(n)}function Ty(e){let t=new Map(e.map((r,o)=>[r,o]));G.commands.sort((r,o)=>{let s=t.get(r.name())??Number.MAX_SAFE_INTEGER,i=t.get(o.name())??Number.MAX_SAFE_INTEGER;return s-i})}G.name("visa-cli").description("Visa CLI - set up MCP payments, manage credentials, and monitor AI spend").version(Er().version).addHelpCommand(!1).action(Ne);G.hook("preAction",async()=>{await Yi()});G.command("setup").description("Register MCP server, authenticate, and generate attestation key").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--yes","Accept setup prompts without asking \u2014 for CI/agent use").option("--hud","Also enable the Visa HUD (Claude Code statusLine)").option("--no-hud","Do not install the Visa HUD during setup (default)").action(async e=>{try{if(e.check){let h=yr();bu(h,"MCP config check:"),h.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=yr(),n=new Map(t.map(h=>[h.client.id,h])),r=new Set,o=new Set,s=new Set;for(let h of Oe)if(gr(h)){let S;try{S=hr(h)}catch(C){if(C instanceof On){uu(C),o.add(h.displayName),s.add(h.id);continue}throw C}let I=n.get(h.id),$=I?` \u2014 repaired stale ${I.staleReason} entry`:"";console.log(` \u2713 ${h.displayName} (${S.configPath.replace(F.homedir(),"~")})${$}`),I&&r.add(h.id)}let i=t.filter(h=>!r.has(h.client.id)&&!s.has(h.client.id)),a=0;for(let h of i){try{vi(h)}catch(S){if(S instanceof On){uu(S),o.add(h.client.displayName),s.add(h.client.id);continue}throw S}console.log(` \u2713 ${h.client.displayName} (${h.configPath.replace(F.homedir(),"~")}) \u2014 repaired stale ${h.staleReason} entry`),a++}let l=r.size+a;l===0&&o.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"}.`),o.size>0&&console.log(` ! Skipped MCP registration for: ${Array.from(o).join(", ")}. Rerun with access to those config files to complete registration.`),console.log(`
191
- Step 2: Checking authentication...`);let c=await U.getSessionToken();if(c)try{await new Se(()=>Promise.resolve(c)).getStatus(),console.log(" Already authenticated.")}catch(h){let S=h instanceof Error?h.message:"";S.includes("session has expired")||S.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await U.clearAll(),c=null):console.log(` Couldn't verify session (${S||"unknown error"}) \u2014 continuing with existing token.`)}if(!c){let h=null;try{let{stdout:S}=await xi("gh",["auth","token"],{timeout:5e3});h=S.trim()}catch{}if(h||(h=process.env.GITHUB_TOKEN||null),h)try{console.log(" Found GitHub token \u2014 attempting headless login...");let S=await globalThis.fetch(`${he()}/v1/auth/token-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({github_token:h}),signal:AbortSignal.timeout(1e4)});if(S.ok){let I=await S.json();if(I.success&&I.sessionToken){let $=I.sessionToken;c=$,await U.saveSessionToken($),console.log(` Signed in as ${I.user} (headless).`)}}else(await S.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(h,S)=>{let I=$o.randomUUID(),$=`${he()}/login?state=${I}`;await es($);let C=3e4,k=300*1e3,q=Date.now()+k;for(;Date.now()<q;)try{let W=await globalThis.fetch(`${he()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:I,timeout:C}),signal:AbortSignal.timeout(C+5e3)});if(!W.ok){await gt(W,ct=>{m.warn("auth_status:retry_after_http_error",{status:W.status,delayMs:ct})});continue}let B=await W.json();if(B.status==="pending")continue;if(B.status==="expired"){S(new Error("Session expired. Please run setup again."));return}if(B.status==="complete"&&B.sessionToken){console.log(` Signed in as ${B.user}.`),h(B.sessionToken);return}}catch{await gt(void 0,W=>{m.warn("auth_status:retry_after_network_error",{delayMs:W})})}S(new Error("Login timed out after 5 minutes. Please run setup again."))}),await U.saveSessionToken(c),console.log(" Session token saved.")),console.log(`
192
- Step 3: Setting up authentication...`),!re())console.log(" Not macOS \u2014 skipping biometric setup.");else{try{await xi("clang",["--version"])}catch{console.error(" Xcode Command Line Tools are required for payment authentication."),console.error(" Install them by running: xcode-select --install"),console.error(" Then re-run: visa-cli setup"),process.exit(1)}let h=se();try{let S=await h.getStatus(),I=!0;if(Su(S))if(await Jc())try{await sy(h),console.log(" Attestation key already registered with server."),console.log(" Existing local Touch ID key verified and preserved."),I=!1}catch($){if(!du($))throw $;console.log(" Existing local Touch ID key does not match server biometric state."),await bi(h),I=!1}else console.log(" Server already has a biometric key, but this device has no local key."),await bi(h),I=!1;I&&await wu(h,S.attestationRequired===!1)}catch(S){let I=S?.message||"unknown error";if(du(S)){console.log(" Server already has a biometric key for this account, but this device cannot prove access to it.");let $=!1;try{await bi(h),$=!0}catch(C){console.error(` Biometric recovery failed: ${C?.message||"unknown error"}`)}if(!$){let C=S instanceof Ft&&S.hint?S.hint:"Run `visa-cli config reset` to clear server-side biometric state through GitHub, then run `visa-cli setup` again.";console.error(` ${C}`),process.exit(1)}}else console.error(` Biometric setup failed: ${I}`),process.exit(1)}}let u=oe.join(F.homedir(),".claude","settings.json"),d=z.existsSync(oe.join(F.homedir(),".claude.json"));if(e.hud===!0)if(!d)console.log(`
189
+ ${i}`:e}function Iy(e){return e.replace(/(^|\n)(Commands:\n)([\s\S]*?)(?=\n[A-Z][A-Za-z ]+:\n|$)/g,(t,n,r,o)=>{let s=o.split(`
190
+ `).map($y).join(`
191
+ `);return`${n}${r}${s}`})}function $y(e){if(!e.startsWith(" "))return e;let n=2,r=n;for(;r<e.length&&e[r]!==" "&&e[r]!==" ";)r+=1;if(r===n)return e;let o=-1;for(let l=r;l<e.length-1;l+=1){if(e[l]!==" "||e[l+1]!==" ")continue;let c=l+2;for(;c<e.length&&e[c]===" ";)c+=1;if(c<e.length){o=c;break}}if(o===-1)return e;let s=e.slice(n,r),i=e.slice(o),a=Math.max(2,o-2-s.length);return` ${s}${" ".repeat(a)}${i}`}function Py(e){return e.replace(/^(Usage: .+?) \[options\](?= |$)/gm,"$1")}function My(e){return e.replace(/^Options:$/gm,"Flags:")}function Ou(e){let t=e.helpInformation.bind(e);e.helpInformation=()=>My(Py(Iy(Ay(Ry(t())))));for(let n of e.commands)Ou(n)}function Oy(e){let t=new Map(e.map((r,o)=>[r,o]));G.commands.sort((r,o)=>{let s=t.get(r.name())??Number.MAX_SAFE_INTEGER,i=t.get(o.name())??Number.MAX_SAFE_INTEGER;return s-i})}G.name("visa-cli").description("Visa CLI - set up MCP payments, manage credentials, and monitor AI spend").version(Er().version).addHelpCommand(!1).action(Ne);G.hook("preAction",async()=>{await na()});G.command("setup").description("Register MCP server, authenticate, and generate attestation key").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--yes","Accept setup prompts without asking \u2014 for CI/agent use").option("--hud","Also enable the Visa HUD (Claude Code statusLine)").option("--no-hud","Do not install the Visa HUD during setup (default)").action(async e=>{try{if(e.check){let h=yr();Cu(h,"MCP config check:"),h.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=yr(),n=new Map(t.map(h=>[h.client.id,h])),r=new Set,o=new Set,s=new Set;for(let h of Oe)if(gr(h)){let S;try{S=hr(h)}catch(C){if(C instanceof On){fu(C),o.add(h.displayName),s.add(h.id);continue}throw C}let I=n.get(h.id),$=I?` \u2014 repaired stale ${I.staleReason} entry`:"";console.log(` \u2713 ${h.displayName} (${S.configPath.replace(D.homedir(),"~")})${$}`),I&&r.add(h.id)}let i=t.filter(h=>!r.has(h.client.id)&&!s.has(h.client.id)),a=0;for(let h of i){try{Ci(h)}catch(S){if(S instanceof On){fu(S),o.add(h.client.displayName),s.add(h.client.id);continue}throw S}console.log(` \u2713 ${h.client.displayName} (${h.configPath.replace(D.homedir(),"~")}) \u2014 repaired stale ${h.staleReason} entry`),a++}let l=r.size+a;l===0&&o.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"}.`),o.size>0&&console.log(` ! Skipped MCP registration for: ${Array.from(o).join(", ")}. Rerun with access to those config files to complete registration.`),console.log(`
192
+ Step 2: Checking authentication...`);let c=await j.getSessionToken();if(c)try{await new Se(()=>Promise.resolve(c)).getStatus(),console.log(" Already authenticated.")}catch(h){let S=h instanceof Error?h.message:"";S.includes("session has expired")||S.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await j.clearAll(),c=null):console.log(` Couldn't verify session (${S||"unknown error"}) \u2014 continuing with existing token.`)}if(!c){let h=null;try{let{stdout:S}=await Ri("gh",["auth","token"],{timeout:5e3});h=S.trim()}catch{}if(h||(h=process.env.GITHUB_TOKEN||null),h)try{console.log(" Found GitHub token \u2014 attempting headless login...");let S=await globalThis.fetch(`${ye()}/v1/auth/token-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({github_token:h}),signal:AbortSignal.timeout(1e4)});if(S.ok){let I=await S.json();if(I.success&&I.sessionToken){let $=I.sessionToken;c=$,await j.saveSessionToken($),console.log(` Signed in as ${I.user} (headless).`)}}else(await S.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(h,S)=>{let I=Lo.randomUUID(),$=`${ye()}/login?state=${I}`;await ss($);let C=3e4,k=300*1e3,q=Date.now()+k;for(;Date.now()<q;)try{let W=await globalThis.fetch(`${ye()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:I,timeout:C}),signal:AbortSignal.timeout(C+5e3)});if(!W.ok){await ht(W,lt=>{m.warn("auth_status:retry_after_http_error",{status:W.status,delayMs:lt})});continue}let B=await W.json();if(B.status==="pending")continue;if(B.status==="expired"){S(new Error("Session expired. Please run setup again."));return}if(B.status==="complete"&&B.sessionToken){console.log(` Signed in as ${B.user}.`),h(B.sessionToken);return}}catch{await ht(void 0,W=>{m.warn("auth_status:retry_after_network_error",{delayMs:W})})}S(new Error("Login timed out after 5 minutes. Please run setup again."))}),await j.saveSessionToken(c),console.log(" Session token saved.")),console.log(`
193
+ Step 3: Setting up authentication...`),!se())console.log(" Not macOS \u2014 skipping biometric setup.");else{try{await Ri("clang",["--version"])}catch{console.error(" Xcode Command Line Tools are required for payment authentication."),console.error(" Install them by running: xcode-select --install"),console.error(" Then re-run: visa-cli setup"),process.exit(1)}let h=ie();try{let S=await h.getStatus(),I=!0;if(ku(S))if(await Qc())try{await py(h),console.log(" Attestation key already registered with server."),console.log(" Existing local Touch ID key verified and preserved."),I=!1}catch($){if(!gu($))throw $;console.log(" Existing local Touch ID key does not match server biometric state."),await Ti(h),I=!1}else console.log(" Server already has a biometric key, but this device has no local key."),await Ti(h),I=!1;I&&await Tu(h,S.attestationRequired===!1)}catch(S){let I=S?.message||"unknown error";if(gu(S)){console.log(" Server already has a biometric key for this account, but this device cannot prove access to it.");let $=!1;try{await Ti(h),$=!0}catch(C){console.error(` Biometric recovery failed: ${C?.message||"unknown error"}`)}if(!$){let C=S instanceof Vt&&S.hint?S.hint:"Run `visa-cli config reset` to clear server-side biometric state through GitHub, then run `visa-cli setup` again.";console.error(` ${C}`),process.exit(1)}}else console.error(` Biometric setup failed: ${I}`),process.exit(1)}}let u=ee.join(D.homedir(),".claude","settings.json"),d=z.existsSync(ee.join(D.homedir(),".claude.json"));if(e.hud===!0)if(!d)console.log(`
193
194
  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(`
194
- Step 4: Enabling the Visa spend HUD...`);let h=Wn(u),S=h.installed==="new"||h.installed==="already-visa"||h.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${S}${h.message}`);try{let I=se(),$=await I.getStatus(),C={currentVersion:I.getClientVersion(),latestVersion:I.lastSignals?.updateAvailable?.latestVersion,updateCheckDisabled:Ue()},k=os($,C);ss(k,$),console.log(` Preview: ${k.split(`
195
- `)[0]}`)}catch{}}let g="\x1B[1m",p="\x1B[2m",_="\x1B[0m";console.log(`
195
+ Step 4: Enabling the Visa spend HUD...`);let h=Wn(u),S=h.installed==="new"||h.installed==="already-visa"||h.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${S}${h.message}`);try{let I=ie(),$=await I.getStatus(),C={currentVersion:I.getClientVersion(),latestVersion:I.lastSignals?.updateAvailable?.latestVersion,updateCheckDisabled:Ue()},k=ls($,C);us(k,$),console.log(` Preview: ${k.split(`
196
+ `)[0]}`)}catch{}}let f="\x1B[1m",p="\x1B[2m",_="\x1B[0m";console.log(`
196
197
  \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
197
198
  \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
198
199
  \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
@@ -200,15 +201,15 @@ Step 4: Enabling the Visa spend HUD...`);let h=Wn(u),S=h.installed==="new"||h.in
200
201
  \u255A\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551
201
202
  \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u2588 CLI
202
203
 
203
- ${g}Setup complete.${_} Restart Claude Code or run /mcp to connect.
204
+ ${f}Setup complete.${_} Restart Claude Code or run /mcp to connect.
204
205
 
205
- ${g}Try it out:${_}
206
+ ${f}Try it out:${_}
206
207
  \u2022 Ask Claude: "Generate an image of a neon cityscape"
207
208
  \u2022 Ask Claude: "What's the price of ETH on Base?"
208
209
  \u2022 Check balance: visa-cli balance show
209
210
 
210
211
  \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510
211
- \u2502 ${g}Recommended: enable the spend HUD${_} \u2502
212
+ \u2502 ${f}Recommended: enable the spend HUD${_} \u2502
212
213
  \u2502 \u2502
213
214
  \u2502 Keep an eye on what your agents are spending. \u2502
214
215
  \u2502 Shows your balance, active card, and recent tool usage \u2502
@@ -218,63 +219,63 @@ Step 4: Enabling the Visa spend HUD...`);let h=Wn(u),S=h.installed==="new"||h.in
218
219
  \u2502 \u2502
219
220
  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
220
221
 
221
- ${g}Verify:${_} visa-cli status
222
- ${g}Docs:${_} https://visacli.sh
223
- `)}catch(t){console.error("Error:",t.message),process.exit(1)}});G.command("install [client]",{hidden:!0}).description("Register MCP server with an AI client (claude, cursor, windsurf, cline, zed, ...)").option("--all","Install for all detected clients").option("--list","Show supported clients and install status").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--repair","Repair stale MCP client configs without re-running the full setup flow").option("--scope <scope>","Install scope: global or project","global").action(async(e,t)=>{try{if(t.check){let s=yr();bu(s,"MCP config check:"),s.length>0&&process.exit(1);return}if(t.repair){let s=yr();if(s.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of s)vi(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(F.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
222
+ ${f}Verify:${_} visa-cli status
223
+ ${f}Docs:${_} https://visacli.sh
224
+ `)}catch(t){console.error("Error:",t.message),process.exit(1)}});G.command("install [client]",{hidden:!0}).description("Register MCP server with an AI client (claude, cursor, windsurf, cline, zed, ...)").option("--all","Install for all detected clients").option("--list","Show supported clients and install status").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--repair","Repair stale MCP client configs without re-running the full setup flow").option("--scope <scope>","Install scope: global or project","global").action(async(e,t)=>{try{if(t.check){let s=yr();Cu(s,"MCP config check:"),s.length>0&&process.exit(1);return}if(t.repair){let s=yr();if(s.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of s)Ci(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(D.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
224
225
  Repaired ${s.length} stale MCP config ${s.length===1?"entry":"entries"}.`);return}if(t.list){console.log(`
225
226
  \x1B[1mSupported MCP Clients\x1B[0m
226
- `),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 Oe){let l=gr(a),c=lu(a),u=l?"Yes":"No",d=c?"Yes":"No",g=a.globalConfigPath.replace(F.homedir(),"~");console.log(` ${a.displayName.padEnd(18)} ${u.padEnd(10)} ${d.padEnd(11)} ${g}`)}console.log("");return}let n=t.scope==="project"?"project":"global";if(t.all){let s=[],i=[];for(let a of Oe){if(!gr(a)){i.push(a.displayName);continue}hr(a,n),s.push(a.displayName)}s.length>0&&console.log(`Installed for: ${s.join(", ")}.`),i.length>0&&console.log(`Skipped: ${i.map(a=>`${a} (not detected)`).join(", ")}.`),s.length===0&&i.length===0&&console.log("No supported clients found.");return}e||(console.error("Usage: visa-cli install <client>"),console.error(" visa-cli install --all"),console.error(" visa-cli install --list"),console.error(`
227
- Supported clients: ${Oe.map(s=>s.id).join(", ")}`),process.exit(1));let r=fi(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${Oe.map(s=>s.id).join(", ")}`),process.exit(1)),n==="global"&&!gr(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let o=hr(r,n);console.log(`Registered visa-cli MCP server in ${o.configPath}`),console.log(o.message)}catch(n){console.error("Error:",n.message),process.exit(1)}});G.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{_r=!1;try{let e=se(),[t,n]=await Promise.all([e.getStatus(),e.getTransactions().catch(o=>{if(process.env.VISA_CLI_DEBUG){let s=o instanceof Error?o.message:String(o);process.stderr.write(`[visa-cli] getTransactions failed (HUD will omit): ${s}
228
- `)}return{transactions:[]}})]),r={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:Ue()};process.stdout.write(Ql(t,Array.isArray(n?.transactions)?n.transactions:[],re(),r)),_r=!0}catch(e){_r=!1,console.error("Error:",e.message),process.exit(1)}});function Ey(e){let t=e.map(eu),n=Math.max(2,...t.map(i=>i.id.length)),r=Math.max(5,...t.map(i=>i.brand.length)),o=Math.max(4,...t.map(i=>i.card.length)),s=7;console.log(`
227
+ `),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 Oe){let l=gr(a),c=pu(a),u=l?"Yes":"No",d=c?"Yes":"No",f=a.globalConfigPath.replace(D.homedir(),"~");console.log(` ${a.displayName.padEnd(18)} ${u.padEnd(10)} ${d.padEnd(11)} ${f}`)}console.log("");return}let n=t.scope==="project"?"project":"global";if(t.all){let s=[],i=[];for(let a of Oe){if(!gr(a)){i.push(a.displayName);continue}hr(a,n),s.push(a.displayName)}s.length>0&&console.log(`Installed for: ${s.join(", ")}.`),i.length>0&&console.log(`Skipped: ${i.map(a=>`${a} (not detected)`).join(", ")}.`),s.length===0&&i.length===0&&console.log("No supported clients found.");return}e||(console.error("Usage: visa-cli install <client>"),console.error(" visa-cli install --all"),console.error(" visa-cli install --list"),console.error(`
228
+ Supported clients: ${Oe.map(s=>s.id).join(", ")}`),process.exit(1));let r=vi(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${Oe.map(s=>s.id).join(", ")}`),process.exit(1)),n==="global"&&!gr(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let o=hr(r,n);console.log(`Registered visa-cli MCP server in ${o.configPath}`),console.log(o.message)}catch(n){console.error("Error:",n.message),process.exit(1)}});G.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{_r=!1;try{let e=ie(),[t,n]=await Promise.all([e.getStatus(),e.getTransactions().catch(o=>{if(process.env.VISA_CLI_DEBUG){let s=o instanceof Error?o.message:String(o);process.stderr.write(`[visa-cli] getTransactions failed (HUD will omit): ${s}
229
+ `)}return{transactions:[]}})]),r={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:Ue()};process.stdout.write(ru(t,Array.isArray(n?.transactions)?n.transactions:[],se(),r)),_r=!0}catch(e){_r=!1,console.error("Error:",e.message),process.exit(1)}});function Ny(e){let t=e.map(ou),n=Math.max(2,...t.map(i=>i.id.length)),r=Math.max(5,...t.map(i=>i.brand.length)),o=Math.max(4,...t.map(i=>i.card.length)),s=7;console.log(`
229
230
  Cards
230
231
  `),console.log(` ${"ID".padEnd(n)} ${"Brand".padEnd(r)} ${"Card".padEnd(o)} Default`),console.log(` ${"\u2500".repeat(n)} ${"\u2500".repeat(r)} ${"\u2500".repeat(o)} ${"\u2500".repeat(s)}`);for(let i of t)console.log(` ${i.id.padEnd(n)} ${i.brand.padEnd(r)} ${i.card.padEnd(o)} ${i.default}`);console.log(`
231
232
  Use:`),console.log(" visa-cli cards default <id>"),console.log(` visa-cli cards remove <id>
232
- `)}async function $u(e,t){if(t.yes)return"confirmed";if(!process.stdin.isTTY)return"refused-non-tty";let n=_u.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 Mo=G.command("cards").description("Manage enrolled payment cards").addHelpCommand(!1).action(Ne);Mo.command("list").description("List enrolled payment cards").action(async()=>{try{let e=await $e.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}Ey(t)}catch(e){console.error("Error:",e.message),process.exit(1)}});Mo.command("add").description("Add a new Visa card").action(async()=>{try{let e=await $e.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)}});Mo.command("remove <card-id>").description("Remove an enrolled card").option("-y, --yes","Skip the interactive confirmation prompt").action(async(e,t)=>{try{let n=ai(e),r=await $u(`Remove card ${n}? This cannot be undone.`,t);if(r==="refused-non-tty"&&(console.error("Refusing to remove card without --yes in a non-interactive shell."),process.exit(1)),r==="declined"){console.log("Aborted.");return}let o=await $e.removeCard({cardId:n,confirm:!0},"visa-cli cards remove");o?.success===!1&&(console.error(o.error||o.message||"Failed to remove card."),process.exit(1)),console.log(o?.message||`Removed card ${n}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});Mo.command("default <card-id>").alias("set-default").description("Set the default payment card").action(async e=>{try{let t=ai(e),n=await $e.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 Ri=G.command("tokens").description("Create and manage API tokens for apps and agents").addHelpCommand(!1).action(Ne);function Ii(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)}Ri.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 se().createAppApiKey({label:cy(e),allowed_tools:ly(t.tools),daily_cap_cents:uy(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: ${Cu(r.allowed_tools)}`),console.log(`Daily cap: ${vr(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("Biometric (Touch ID) is currently ON for this account."),console.log("This API token can still be used headlessly. Per-call Touch ID is"),console.log("not required; spending is bounded by the token daily cap and tools."),console.log("---------------------------------------------------------------"),console.log("")):r.biometric_warning&&(console.log("Note: API tokens bypass per-call biometric verification."),console.log("Keep daily caps and allowed tools scoped for headless use."),console.log("")),console.log("Prepaid session-budget flow:"),console.log(` curl -X POST ${he()}/v1/api/session-budget/create \\`),console.log(` -H "X-Api-Key: ${r.key}" \\`),console.log(' -H "Content-Type: application/json" \\'),console.log(` -d '{"total_cents":500}'`),console.log(""),console.log("Then execute a tool with the returned budget.id:"),console.log(` curl -X POST ${he()}/v1/api/session-budget/stream/or-gpt-4o-mini \\`),console.log(` -H "X-Api-Key: ${r.key}" \\`),console.log(' -H "Content-Type: application/json" \\'),console.log(` -d '{"session_budget_id":"sb_...","cumulative_cents":0,"nonce":"nonce-at-least-16","idempotency_key":"idem-at-least-16","prompt":"Say hello in one sentence."}'`)}catch(n){Ii(n)}});Ri.command("list").description("List API tokens for the authenticated user").option("--json","Output raw JSON").action(async e=>{try{let n=await se().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 o of r)console.log(`${o.id}. ${o.label} (${o.key_prefix})`),console.log(` Status: ${o.status}`),console.log(` Owner: ${o.owner}`),console.log(` Allowed tools: ${Cu(o.allowed_tools)}`),console.log(` Daily cap: ${vr(o.daily_cap_cents)}/day`),console.log(` Last used: ${o.last_used_at||"never"}`)}catch(t){Ii(t)}});Ri.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 se().revokeAppApiKey(t);console.log(`Revoked API token ${r.revoked}.`)}catch(t){Ii(t)}});async function Pu(){try{console.log(`Resetting Visa CLI...
233
- `);let e=se();await ki(e);try{await e.logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}if(await U.clearAll(),console.log(" Keychain credentials cleared."),re())try{await io(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}console.log(`
234
- Reset complete.`)}catch(e){console.error("Error:",e.message),process.exit(1)}}G.command("reset",{hidden:!0}).description("Deprecated alias for `config reset`").action(Pu);var Ay=100,Ry=1e4,$i=G.command("balance").description("Manage prepaid balance").addHelpCommand(!1).action(Ne);$i.command("show").description("Show prepaid balance + recent ledger entries").action(async()=>{try{let t=await new Se(()=>U.getSessionToken()).getBalance();if(console.log(`
235
- Balance: ${Ci(t.balanceMicros,t.balanceCents)}
233
+ `)}async function Nu(e,t){if(t.yes)return"confirmed";if(!process.stdin.isTTY)return"refused-non-tty";let n=wu.createInterface({input:process.stdin,output:process.stdout});try{let r=(await n.question(`${e} [y/N] `)).trim();return/^y(es)?$/i.test(r)?"confirmed":"declined"}finally{n.close()}}var Uo=G.command("cards").description("Manage enrolled payment cards").addHelpCommand(!1).action(Ne);Uo.command("list").description("List enrolled payment cards").action(async()=>{try{let e=await $e.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}Ny(t)}catch(e){console.error("Error:",e.message),process.exit(1)}});Uo.command("add").description("Add a new Visa card").action(async()=>{try{let e=await $e.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)}});Uo.command("remove <card-id>").description("Remove an enrolled card").option("-y, --yes","Skip the interactive confirmation prompt").action(async(e,t)=>{try{let n=mi(e),r=await Nu(`Remove card ${n}? This cannot be undone.`,t);if(r==="refused-non-tty"&&(console.error("Refusing to remove card without --yes in a non-interactive shell."),process.exit(1)),r==="declined"){console.log("Aborted.");return}let o=await $e.removeCard({cardId:n,confirm:!0},"visa-cli cards remove");o?.success===!1&&(console.error(o.error||o.message||"Failed to remove card."),process.exit(1)),console.log(o?.message||`Removed card ${n}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});Uo.command("default <card-id>").alias("set-default").description("Set the default payment card").action(async e=>{try{let t=mi(e),n=await $e.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 Ni=G.command("tokens").description("Create and manage API tokens for apps and agents").addHelpCommand(!1).action(Ne);function Li(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)}Ni.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 ie().createAppApiKey({label:hy(e),allowed_tools:yy(t.tools),daily_cap_cents:_y(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: ${Au(r.allowed_tools)}`),console.log(`Daily cap: ${vr(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("Biometric (Touch ID) is currently ON for this account."),console.log("This API token can still be used headlessly. Per-call Touch ID is"),console.log("not required; spending is bounded by the token daily cap and tools."),console.log("---------------------------------------------------------------"),console.log("")):r.biometric_warning&&(console.log("Note: API tokens bypass per-call biometric verification."),console.log("Keep daily caps and allowed tools scoped for headless use."),console.log("")),console.log("Prepaid session-budget flow:"),console.log(` curl -X POST ${ye()}/v1/api/session-budget/create \\`),console.log(` -H "X-Api-Key: ${r.key}" \\`),console.log(' -H "Content-Type: application/json" \\'),console.log(` -d '{"total_cents":500}'`),console.log(""),console.log("Then execute a tool with the returned budget.id:"),console.log(` curl -X POST ${ye()}/v1/api/session-budget/stream/or-gpt-4o-mini \\`),console.log(` -H "X-Api-Key: ${r.key}" \\`),console.log(' -H "Content-Type: application/json" \\'),console.log(` -d '{"session_budget_id":"sb_...","cumulative_cents":0,"nonce":"nonce-at-least-16","idempotency_key":"idem-at-least-16","prompt":"Say hello in one sentence."}'`)}catch(n){Li(n)}});Ni.command("list").description("List API tokens for the authenticated user").option("--json","Output raw JSON").action(async e=>{try{let n=await ie().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 o of r)console.log(`${o.id}. ${o.label} (${o.key_prefix})`),console.log(` Status: ${o.status}`),console.log(` Owner: ${o.owner}`),console.log(` Allowed tools: ${Au(o.allowed_tools)}`),console.log(` Daily cap: ${vr(o.daily_cap_cents)}/day`),console.log(` Last used: ${o.last_used_at||"never"}`)}catch(t){Li(t)}});Ni.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 ie().revokeAppApiKey(t);console.log(`Revoked API token ${r.revoked}.`)}catch(t){Li(t)}});async function Lu(){try{console.log(`Resetting Visa CLI...
234
+ `);let e=ie();await $i(e);try{await e.logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}if(await j.clearAll(),console.log(" Keychain credentials cleared."),se())try{await mo(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}console.log(`
235
+ Reset complete.`)}catch(e){console.error("Error:",e.message),process.exit(1)}}G.command("reset",{hidden:!0}).description("Deprecated alias for `config reset`").action(Lu);var Ly=100,Dy=1e4,Di=G.command("balance").description("Manage prepaid balance").addHelpCommand(!1).action(Ne);Di.command("show").description("Show prepaid balance + recent ledger entries").action(async()=>{try{let t=await new Se(()=>j.getSessionToken()).getBalance();if(console.log(`
236
+ Balance: ${Ii(t.balanceMicros,t.balanceCents)}
236
237
  `),t.ledger.length===0){console.log(` (no ledger entries \u2014 top up to begin: visa-cli balance topup --amount 5)
237
- `);return}let n=t.ledger.slice(0,20),r=[],o=t.balanceCents,s=t.balanceMicros?BigInt(t.balanceMicros):null;for(let u of n)r.push(s!=null?s.toString():String(o*1e4)),s!=null&&u.deltaMicros?s-=BigInt(u.deltaMicros):(s=null,o-=u.deltaCents);let i=19,a=11,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,d)=>{let g=(u.createdAt||"").slice(0,19),p=Ci(u.deltaMicros,u.deltaCents,!0),_=ay(r[d]),h=(u.reason??"").slice(0,c),S=u.toolName??"";console.log(` ${g.padEnd(i)} ${p.padStart(a)} ${_.padStart(l)} ${h.padEnd(c)} ${S}`)}),console.log()}catch(e){console.error("Error:",e.message),process.exit(1)}});$i.command("topup").description("Top up prepaid balance from your default card (same path as MCP buy_credits; Touch ID required)").requiredOption("-a, --amount <usd>","Amount in USD (e.g. 5 or 1.50)").action(async e=>{try{let t=nu(e.amount,Ay,Ry);if(!t.ok)throw new Error(t.error);let n=t.cents,r=n/100,o=new Se(()=>U.getSessionToken());if(!re())throw new Error(ho);let s=$o.randomUUID(),i=await ar(o,async()=>{let a;if(re()){let{nonce:l}=await o.getAttestationChallenge(),c=Buffer.from(JSON.stringify({nonce:l,amount:r,merchant:"Visa CLI Balance",context:"balance-topup"})).toString("base64");a={signature:await Rn(c,`top up balance with $${t.displayUsd}`),nonce:l,amount:r,merchant:"Visa CLI Balance"}}return o.topupBalance({amount_cents:n,idempotency_key:s,attestation:a})},xu(o));if(i.success)console.log(`Top-up complete: +$${(n/100).toFixed(2)} \u2192 balance now $${((i.balanceCents??0)/100).toFixed(2)}`),i.transactionId&&console.log(`Transaction: ${i.transactionId}`),wa();else{let a=i.error_code?` [${i.error_code}]`:"";console.error(`Top-up failed${a}: ${i.error||"Unknown error"}`),process.exit(1)}}catch(t){console.error("Error:",t.message),process.exit(1)}});var Mu=$i.command("auto-topup").description("Show or disable automatic balance top-ups (read/disable only \u2014 re-enabling is retired pending mandate model)").addHelpCommand(!1).action(Ne);Mu.command("show").description("Show current auto-topup configuration").action(async()=>{try{let t=await new Se(()=>U.getSessionToken()).getAutoTopup();if(t.targetCents==null||t.targetCents===0){console.log(`
238
+ `);return}let n=t.ledger.slice(0,20),r=[],o=t.balanceCents,s=t.balanceMicros?BigInt(t.balanceMicros):null;for(let u of n)r.push(s!=null?s.toString():String(o*1e4)),s!=null&&u.deltaMicros?s-=BigInt(u.deltaMicros):(s=null,o-=u.deltaCents);let i=19,a=11,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,d)=>{let f=(u.createdAt||"").slice(0,19),p=Ii(u.deltaMicros,u.deltaCents,!0),_=gy(r[d]),h=(u.reason??"").slice(0,c),S=u.toolName??"";console.log(` ${f.padEnd(i)} ${p.padStart(a)} ${_.padStart(l)} ${h.padEnd(c)} ${S}`)}),console.log()}catch(e){console.error("Error:",e.message),process.exit(1)}});Di.command("topup").description("Top up prepaid balance from your default card (same path as MCP buy_credits; Touch ID required)").requiredOption("-a, --amount <usd>","Amount in USD (e.g. 5 or 1.50)").action(async e=>{try{let t=iu(e.amount,Ly,Dy);if(!t.ok)throw new Error(t.error);let n=t.cents,r=n/100,o=new Se(()=>j.getSessionToken());if(!se())throw new Error(So);let s=Lo.randomUUID(),i=await ar(o,async()=>{let a;if(se()){let{nonce:l}=await o.getAttestationChallenge(),c=Buffer.from(JSON.stringify({nonce:l,amount:r,merchant:"Visa CLI Balance",context:"balance-topup"})).toString("base64");a={signature:await Rn(c,`top up balance with $${t.displayUsd}`),nonce:l,amount:r,merchant:"Visa CLI Balance"}}return o.topupBalance({amount_cents:n,idempotency_key:s,attestation:a})},Eu(o));if(i.success)console.log(`Top-up complete: +$${(n/100).toFixed(2)} \u2192 balance now $${((i.balanceCents??0)/100).toFixed(2)}`),i.transactionId&&console.log(`Transaction: ${i.transactionId}`),Aa();else{let a=i.error_code?` [${i.error_code}]`:"";console.error(`Top-up failed${a}: ${i.error||"Unknown error"}`),process.exit(1)}}catch(t){console.error("Error:",t.message),process.exit(1)}});var Du=Di.command("auto-topup").description("Show or disable automatic balance top-ups (read/disable only \u2014 re-enabling is retired pending mandate model)").addHelpCommand(!1).action(Ne);Du.command("show").description("Show current auto-topup configuration").action(async()=>{try{let t=await new Se(()=>j.getSessionToken()).getAutoTopup();if(t.targetCents==null||t.targetCents===0){console.log(`
238
239
  Auto-topup: disabled
239
- `);return}let n=vr(t.targetCents),r=vr(t.thresholdCents),o=12,s=13;console.log(),console.log(` ${"STATE".padEnd(o)} enabled`),console.log(` ${"TARGET".padEnd(o)} ${n.padStart(s)} (refill balance to this amount)`),console.log(` ${"THRESHOLD".padEnd(o)} ${r.padStart(s)} (trigger refill when balance drops below this)`),console.log(),console.log(" Disable with: visa-cli balance auto-topup disable"),console.log()}catch(e){console.error("Error:",e.message),process.exit(1)}});Mu.command("disable").description("Disable auto-topup").action(async()=>{try{let t=await new Se(()=>U.getSessionToken()).disableAutoTopup();t.success||(console.error(`Auto-topup disable failed: ${t.error||"Unknown error"}`),process.exit(1)),console.log("Auto-topup disabled. Your balance will no longer refill automatically.")}catch(e){console.error("Error:",e.message),process.exit(1)}});var Iy=G.command("session",{hidden:!0}).description("Inspect session budgets");Iy.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 Se(()=>U.getSessionToken()),[n,r]=await Promise.allSettled([t.getSessionBudget(e),t.getSessionLedger(e)]),o=n.status==="fulfilled"?n.value.budget:void 0,s=r.status==="fulfilled"?r.value:void 0;if(!o&&!s?.ledger?.length&&(console.error(`Session not found: ${e}`),process.exit(1)),console.log(`
240
+ `);return}let n=vr(t.targetCents),r=vr(t.thresholdCents),o=12,s=13;console.log(),console.log(` ${"STATE".padEnd(o)} enabled`),console.log(` ${"TARGET".padEnd(o)} ${n.padStart(s)} (refill balance to this amount)`),console.log(` ${"THRESHOLD".padEnd(o)} ${r.padStart(s)} (trigger refill when balance drops below this)`),console.log(),console.log(" Disable with: visa-cli balance auto-topup disable"),console.log()}catch(e){console.error("Error:",e.message),process.exit(1)}});Du.command("disable").description("Disable auto-topup").action(async()=>{try{let t=await new Se(()=>j.getSessionToken()).disableAutoTopup();t.success||(console.error(`Auto-topup disable failed: ${t.error||"Unknown error"}`),process.exit(1)),console.log("Auto-topup disabled. Your balance will no longer refill automatically.")}catch(e){console.error("Error:",e.message),process.exit(1)}});var Uy=G.command("session",{hidden:!0}).description("Inspect session budgets");Uy.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 Se(()=>j.getSessionToken()),[n,r]=await Promise.allSettled([t.getSessionBudget(e),t.getSessionLedger(e)]),o=n.status==="fulfilled"?n.value.budget:void 0,s=r.status==="fulfilled"?r.value:void 0;if(!o&&!s?.ledger?.length&&(console.error(`Session not found: ${e}`),process.exit(1)),console.log(`
240
241
  Session: ${e}`),o){let i=(o.totalCents/100).toFixed(2),a=(o.cumulativeCents/100).toFixed(2),l=(o.remainingCents/100).toFixed(2);console.log(` Status: ${o.status}${o.expired?" (expired)":""}`),console.log(` Budget: $${i} \xB7 spent $${a} \xB7 remaining $${l}`),console.log(` Created: ${o.createdAt}`),console.log(` Expires: ${o.expiresAt}`)}if(s?.ledger?.length){console.log(`
241
242
  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 s.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 o&&console.log(`
242
- (no PSP references yet \u2014 no holds placed)`);console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});async function Ou(e){(!e||e.trim().length===0)&&(console.log('Usage: visa-cli feedback "your message"'),process.exit(1));try{await U.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await se().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}}G.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action(Ou);G.command("update").description("Update Visa CLI to the latest stable version").action(async()=>{let e=ui(void 0,void 0,void 0,{withDiagnostics:!0}),t=e.diagnostics?di(e.diagnostics,e.display):null;try{t&&console.warn(`Warning: ${t}`),console.log(`Updating Visa CLI with ${e.packageManager}: ${e.display}`);let{stdout:n,stderr:r}=await xi(e.command,e.args,{timeout:5*6e4,maxBuffer:10*1024*1024});n.trim()&&process.stdout.write(n),r.trim()&&process.stderr.write(r),console.log("Visa CLI update complete. Restart any running MCP clients to use the new version.")}catch(n){console.error(`Update failed while running: ${e.display}`),console.error(n?.message??String(n)),process.exit(1)}});var Je=G.command("config").description("Manage CLI configuration and local integrations").addHelpCommand(!1).action(Ne);function Nu(e){return[oe.join(e,".zshrc"),oe.join(e,".bashrc"),oe.join(e,".bash_profile"),oe.join(e,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),oe.join(e,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),oe.join(e,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),oe.join(e,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),oe.join(e,".config","powershell","Microsoft.PowerShell_profile.ps1")]}function $y(e){let t=new Map;for(let n of Nu(e))try{z.existsSync(n)&&t.set(n,z.readFileSync(n,"utf-8"))}catch{}return t}function Py(e){let t=[];for(let[n,r]of e)try{(z.existsSync(n)?z.readFileSync(n,"utf-8"):"")!==r&&t.push(n)}catch{}return t}function My(e){let t=[];for(let n of Nu(e))try{if(!z.existsSync(n))continue;let r=z.readFileSync(n,"utf-8");Gn(r)!==r.trimEnd()&&t.push(n)}catch{}return t}Je.command("feedback",{hidden:!0}).description("Deprecated alias for `feedback`").argument("[message]","Your feedback message").action(Ou);Je.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=se(),n=await cr({api:t,includeDev:!!e.dev});if(e.json){console.log(rl(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(nl(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});Je.command("get <key>").description("Print the resolved value of a single config key (pipe-friendly)").option("--raw","Print the underlying value as JSON instead of the formatted display string").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").action(async(e,t)=>{try{let n=se(),o=(await cr({api:n,includeDev:!!t.dev})).entries.find(s=>s.key===e);o||(console.error(`Error: unknown config key '${e}'. Run 'visa-cli config list' to see available keys.`),process.exit(1)),t.raw?console.log(JSON.stringify(o.value)):console.log(o.formatted)}catch(n){console.error("Error:",n.message),process.exit(1)}});function Oy(){return Object.entries(St).map(([e,t])=>` ${e.padEnd(22)} (${t.type}) ${t.description}`).join(`
243
+ (no PSP references yet \u2014 no holds placed)`);console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});async function Uu(e){(!e||e.trim().length===0)&&(console.log('Usage: visa-cli feedback "your message"'),process.exit(1));try{await j.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await ie().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}}G.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action(Uu);G.command("update").description("Update Visa CLI to the latest stable version").action(async()=>{let e=gi(void 0,void 0,void 0,{withDiagnostics:!0}),t=e.diagnostics?hi(e.diagnostics,e.display):null;try{t&&console.warn(`Warning: ${t}`),console.log(`Updating Visa CLI with ${e.packageManager}: ${e.display}`);let{stdout:n,stderr:r}=await Ri(e.command,e.args,{timeout:5*6e4,maxBuffer:10*1024*1024});n.trim()&&process.stdout.write(n),r.trim()&&process.stderr.write(r);let o=fs(ee.join(D.homedir(),".claude","settings.json"),{force:!0});for(let s of o.messages)console.log(s);console.log("Visa CLI update complete. Restart any running MCP clients to use the new version.")}catch(n){console.error(`Update failed while running: ${e.display}`),console.error(n?.message??String(n)),process.exit(1)}});var Je=G.command("config").description("Manage CLI configuration and local integrations").addHelpCommand(!1).action(Ne);function ju(e){return[ee.join(e,".zshrc"),ee.join(e,".bashrc"),ee.join(e,".bash_profile"),ee.join(e,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),ee.join(e,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),ee.join(e,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),ee.join(e,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),ee.join(e,".config","powershell","Microsoft.PowerShell_profile.ps1")]}function jy(e){let t=new Map;for(let n of ju(e))try{z.existsSync(n)&&t.set(n,z.readFileSync(n,"utf-8"))}catch{}return t}function Fy(e){let t=[];for(let[n,r]of e)try{(z.existsSync(n)?z.readFileSync(n,"utf-8"):"")!==r&&t.push(n)}catch{}return t}function Vy(e){let t=[];for(let n of ju(e))try{if(!z.existsSync(n))continue;let r=z.readFileSync(n,"utf-8");Gn(r)!==r.trimEnd()&&t.push(n)}catch{}return t}Je.command("feedback",{hidden:!0}).description("Deprecated alias for `feedback`").argument("[message]","Your feedback message").action(Uu);Je.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=ie(),n=await cr({api:t,includeDev:!!e.dev});if(e.json){console.log(al(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(il(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});Je.command("get <key>").description("Print the resolved value of a single config key (pipe-friendly)").option("--raw","Print the underlying value as JSON instead of the formatted display string").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").action(async(e,t)=>{try{let n=ie(),o=(await cr({api:n,includeDev:!!t.dev})).entries.find(s=>s.key===e);o||(console.error(`Error: unknown config key '${e}'. Run 'visa-cli config list' to see available keys.`),process.exit(1)),t.raw?console.log(JSON.stringify(o.value)):console.log(o.formatted)}catch(n){console.error("Error:",n.message),process.exit(1)}});function qy(){return Object.entries(wt).map(([e,t])=>` ${e.padEnd(22)} (${t.type}) ${t.description}`).join(`
243
244
  `)}Je.command("set <key> <value>").description("Persist a CLI setting to ~/.visa-mcp/settings.json").addHelpText("after",`
244
245
  Settable keys:
245
- ${Oy()}`).action((e,t)=>{try{let n=zr(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 Xe||n instanceof Qe||n instanceof vt?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});Je.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=Wr(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)}});Je.command("reset").description("Log out and clear all credentials").action(Pu);var Pi=Je.command("biometric").description("Manage Touch ID / biometric attestation enforcement").addHelpCommand(!1).action(Ne);Pi.command("status").description("Show current biometric enforcement state").action(async()=>{try{await U.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let n=await se().getStatus(),r=n.attestationRequired!==!1,o=!!n.hasAttestationKey,s=re();console.log(`Server policy: Touch ID ${r?"REQUIRED":"NOT required"}`),console.log(`Attestation key registered: ${o?"yes":"no"}`),console.log(`Touch ID available on this device: ${s?"yes":"no"}`)}catch(e){console.error("Error:",e.message),process.exit(1)}});Pi.command("on").description("Require Touch ID for payments (security upgrade \u2014 no Touch ID needed)").action(async()=>{try{await U.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=se(),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)}});Pi.command("off").description("Disable Touch ID requirement (security downgrade \u2014 one Touch ID confirmation required)").action(async()=>{try{await U.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=se(),n=await t.getStatus();if(n.attestationRequired===!1){console.log("Touch ID is already disabled.");return}n.hasAttestationKey&&!re()&&(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 ar(t,async()=>{let o;if(n.hasAttestationKey&&re())try{let{nonce:s}=await t.getAttestationChallenge(),i=0,a="",l=Buffer.from(JSON.stringify({nonce:s,amount:i,merchant:a,context:"biometric-preference"})).toString("base64");o={signature:await Rn(l,"disable Touch ID requirement"),nonce:s,amount:i,merchant:a}}catch(s){throw new Error(`Touch ID confirmation failed: ${s?.message||"cancelled"}`)}return t.setBiometricPreference({required:!1,attestation:o})},xu(t));r.success||(console.error(`Failed: ${r.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is no longer required for payments.")}catch(e){console.error("Error:",e.message),process.exit(1)}});var dn=Je.command("shell-hud").description("Manage the shell prompt HUD (opt-in \u2014 prefer: visa-cli config hud enable)").addHelpCommand(!1).action(Ne);function Du(){let e=Lr();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function Lu(e){for(let t of e.messages)console.log(t);for(let t of e.errors)console.error(t);e.ok||process.exit(1)}function Ny(){Lu(fs(void 0,{homeDir:F.homedir(),installVisaStatusLine:Wn,installShellHud:Lr}))}function Uu(){console.log("Note: `config shell-hud enable` now installs the Claude Code statusLine HUD."),console.log(" For the explicit shell-prompt HUD, run: visa-cli config hud enable shell"),Ny()}function Oo(){let e=_t();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}dn.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Du);dn.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(Uu);dn.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Oo);dn.command("disable").description("Disable the persistent shell HUD").action(Oo);dn.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${Ur()}
246
- `)});dn.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,r=(d,g,p)=>{console.log(` ${g?"\u2713":"\u2717"} ${d}: ${p}`),g||(n=!1)};console.log(`Shell HUD Doctor
247
- `);let o=hn();if(r("Shell detected",!!o,o??"none (zsh, bash, or PowerShell required)"),o){let d=Kn(o),g=e(d);if(r("RC file exists",g,d.replace(F.homedir(),"~")),g){let _=t(d,"utf-8").includes("visa-cli shell hud v2");r("HUD block installed",!!_,_?"found in rc file":"missing \u2014 run: visa-cli config hud enable shell")}}let s=ht(),i=e(s);if(r("Cache file",i,i?s.replace(F.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let d=JSON.parse(t(s,"utf-8")),g=Date.now()-(d.renderedAt??0),p=Math.round(g/1e3),_=p<=30;console.log(` ${_?"\u2713":"\u26A0"} Cache freshness: ${p}s old${_?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{r("Cache readable",!1,"corrupt JSON")}let a=Bn(),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 U.getSessionToken()}catch{}if(r("Auth token",u,u?"found in keychain":"missing \u2014 run: visa-cli setup"),u)try{await se().getStatus(),r("API connectivity",!0,"GET /v1/status OK")}catch(d){let g=d instanceof Error?d.message:"unknown error";r("API connectivity",!1,g)}console.log(n?`
246
+ ${qy()}`).action((e,t)=>{try{let n=Xr(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 Qe||n instanceof et||n instanceof bt?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});Je.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=Qr(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)}});Je.command("reset").description("Log out and clear all credentials").action(Lu);var Ui=Je.command("biometric").description("Manage Touch ID / biometric attestation enforcement").addHelpCommand(!1).action(Ne);Ui.command("status").description("Show current biometric enforcement state").action(async()=>{try{await j.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let n=await ie().getStatus(),r=n.attestationRequired!==!1,o=!!n.hasAttestationKey,s=se();console.log(`Server policy: Touch ID ${r?"REQUIRED":"NOT required"}`),console.log(`Attestation key registered: ${o?"yes":"no"}`),console.log(`Touch ID available on this device: ${s?"yes":"no"}`)}catch(e){console.error("Error:",e.message),process.exit(1)}});Ui.command("on").description("Require Touch ID for payments (security upgrade \u2014 no Touch ID needed)").action(async()=>{try{await j.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=ie(),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)}});Ui.command("off").description("Disable Touch ID requirement (security downgrade \u2014 one Touch ID confirmation required)").action(async()=>{try{await j.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=ie(),n=await t.getStatus();if(n.attestationRequired===!1){console.log("Touch ID is already disabled.");return}n.hasAttestationKey&&!se()&&(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 ar(t,async()=>{let o;if(n.hasAttestationKey&&se())try{let{nonce:s}=await t.getAttestationChallenge(),i=0,a="",l=Buffer.from(JSON.stringify({nonce:s,amount:i,merchant:a,context:"biometric-preference"})).toString("base64");o={signature:await Rn(l,"disable Touch ID requirement"),nonce:s,amount:i,merchant:a}}catch(s){throw new Error(`Touch ID confirmation failed: ${s?.message||"cancelled"}`)}return t.setBiometricPreference({required:!1,attestation:o})},Eu(t));r.success||(console.error(`Failed: ${r.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is no longer required for payments.")}catch(e){console.error("Error:",e.message),process.exit(1)}});var mn=Je.command("shell-hud").description("Manage the shell prompt HUD (opt-in \u2014 prefer: visa-cli config hud enable)").addHelpCommand(!1).action(Ne);function Fu(){let e=Dr();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function Vu(e){for(let t of e.messages)console.log(t);for(let t of e.errors)console.error(t);e.ok||process.exit(1)}function Hy(){Vu(vs(void 0,{homeDir:D.homedir(),installVisaStatusLine:Wn,installShellHud:Dr}))}function qu(){console.log("Note: `config shell-hud enable` now installs the Claude Code statusLine HUD."),console.log(" For the explicit shell-prompt HUD, run: visa-cli config hud enable shell"),Hy()}function jo(){let e=Ze();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}mn.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Fu);mn.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(qu);mn.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(jo);mn.command("disable").description("Disable the persistent shell HUD").action(jo);mn.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${Ur()}
247
+ `)});mn.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,r=(d,f,p)=>{console.log(` ${f?"\u2713":"\u2717"} ${d}: ${p}`),f||(n=!1)};console.log(`Shell HUD Doctor
248
+ `);let o=yn();if(r("Shell detected",!!o,o??"none (zsh, bash, or PowerShell required)"),o){let d=Kn(o),f=e(d);if(r("RC file exists",f,d.replace(D.homedir(),"~")),f){let _=t(d,"utf-8").includes("visa-cli shell hud v2");r("HUD block installed",!!_,_?"found in rc file":"missing \u2014 run: visa-cli config hud enable shell")}}let s=yt(),i=e(s);if(r("Cache file",i,i?s.replace(D.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let d=JSON.parse(t(s,"utf-8")),f=Date.now()-(d.renderedAt??0),p=Math.round(f/1e3),_=p<=30;console.log(` ${_?"\u2713":"\u26A0"} Cache freshness: ${p}s old${_?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{r("Cache readable",!1,"corrupt JSON")}let a=Bn(),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 j.getSessionToken()}catch{}if(r("Auth token",u,u?"found in keychain":"missing \u2014 run: visa-cli setup"),u)try{await ie().getStatus(),r("API connectivity",!0,"GET /v1/status OK")}catch(d){let f=d instanceof Error?d.message:"unknown error";r("API connectivity",!1,f)}console.log(n?`
248
249
  All checks passed.`:`
249
- Some checks failed \u2014 see above.`),n||process.exit(1)});async function ju(e){if(!(!e.force&&ba()))try{let t=se(),[n,r,o,s]=await Promise.allSettled([t.getStatus(),t.getBalance(),t.listAppApiKeys(),t.getTransactions({limit:1})]);if(n.status==="rejected")throw n.reason;let i=n.value,a=i.prepaidBalance?.cents;if(typeof a=="number"){i.balanceCents=a;let u=i.prepaidBalance?.amountUsd;i.amountUsd=typeof u=="number"?u:a/100}if(r.status==="fulfilled"&&r.value.success&&(i.balanceCents=r.value.balanceCents,i.amountUsd=r.value.amountUsd),o.status==="fulfilled"&&o.value.success&&(i.apiKeyCount=Array.isArray(o.value.keys)?o.value.keys.length:0),s.status==="fulfilled"){let u=s.value,g=(Array.isArray(u)?u:Array.isArray(u.transactions)?u.transactions:[]).find(p=>p&&typeof p.tool_name=="string"&&p.tool_name.length>0);g&&g.created_at&&(i.lastService={toolName:g.tool_name,createdAt:g.created_at})}let l={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:Ue()},c=os(i,l);ss(c,i)}catch(t){let n=t instanceof Error?t.message:"unknown refresh failure";Sa(n)}finally{Nt()}}dn.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(ju);var mn=G.command("shell-hud",{hidden:!0}).description("Deprecated alias for `config shell-hud`");mn.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Du);mn.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(Uu);mn.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Oo);mn.command("disable").description("Disable the persistent shell HUD").action(Oo);mn.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${Ur()}
250
- `)});mn.command("doctor").description("Show the new shell HUD doctor command").action(()=>{console.log("Run: visa-cli config shell-hud doctor")});mn.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(ju);async function Fu(e){try{let t=await Da(),n=Ur(),r=n,o=n.split(`
251
- `)[0],s=xa();if(!t&&o.includes("loading")){process.stdout.write(`VISA | HUD not initialized \u2014 run: visa-cli config hud enable
252
- `);return}if(e.json){let a=await qa(r,t,s);process.stdout.write(`${JSON.stringify(a,null,2)}
253
- `);return}let i=await ja(r,t,s);process.stdout.write(`${i}
254
- `)}catch(t){let n=t instanceof Error?t.message:"unknown error";console.error(`Failed to render Visa HUD: ${n}`),process.exit(1)}}Je.command("statusline").description("Output the Visa HUD for agent statusline integrations").option("--json","Output structured JSON for clients that render their own HUD").action(Fu);G.command("statusline",{hidden:!0}).description("Deprecated alias for `config statusline`").option("--json","Output structured JSON for clients that render their own HUD").action(Fu);var Dn=Je.command("hud").description("Manage the Visa spend HUD \u2014 one command for all surfaces").addHelpCommand(!1);Dn.description("Show which HUD surfaces are currently enabled").action(()=>{let e="\x1B[1m",t="\x1B[2m",n="\x1B[32m",r="\x1B[33m",o="\x1B[0m";console.log(`
250
+ Some checks failed \u2014 see above.`),n||process.exit(1)});async function Hu(e){if(!(!e.force&&Ta()))try{let t=ie(),[n,r,o,s]=await Promise.allSettled([t.getStatus(),t.getBalance(),t.listAppApiKeys(),t.getTransactions({limit:1})]);if(n.status==="rejected")throw n.reason;let i=n.value,a=i.prepaidBalance?.cents;if(typeof a=="number"){i.balanceCents=a;let u=i.prepaidBalance?.amountUsd;i.amountUsd=typeof u=="number"?u:a/100}if(r.status==="fulfilled"&&r.value.success&&(i.balanceCents=r.value.balanceCents,i.amountUsd=r.value.amountUsd),o.status==="fulfilled"&&o.value.success&&(i.apiKeyCount=Array.isArray(o.value.keys)?o.value.keys.length:0),s.status==="fulfilled"){let u=s.value,f=(Array.isArray(u)?u:Array.isArray(u.transactions)?u.transactions:[]).find(p=>p&&typeof p.tool_name=="string"&&p.tool_name.length>0);f&&f.created_at&&(i.lastService={toolName:f.tool_name,createdAt:f.created_at})}let l={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:Ue()},c=ls(i,l);us(c,i)}catch(t){let n=t instanceof Error?t.message:"unknown refresh failure";Ea(n)}finally{Lt()}}mn.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(Hu);var pn=G.command("shell-hud",{hidden:!0}).description("Deprecated alias for `config shell-hud`");pn.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Fu);pn.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(qu);pn.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(jo);pn.command("disable").description("Disable the persistent shell HUD").action(jo);pn.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${Ur()}
251
+ `)});pn.command("doctor").description("Show the new shell HUD doctor command").action(()=>{console.log("Run: visa-cli config shell-hud doctor")});pn.command("refresh").description("Refresh the shell HUD cache (no-op if cache is fresh unless --force)").option("--force","Bypass the cache freshness gate and always refresh").action(Hu);async function Bu(e){try{let t=await Fa(),n=Ur(),r=n,o=n.split(`
252
+ `)[0],s=Ra();if(!t&&o.includes("loading")){process.stdout.write(`VISA | HUD not initialized \u2014 run: visa-cli config hud enable
253
+ `),ki();return}if(e.json){let a=await Ga(r,t,s);process.stdout.write(`${JSON.stringify(a,null,2)}
254
+ `),ki();return}let i=await Ha(r,t,s);process.stdout.write(`${i}
255
+ `),ki()}catch(t){let n=t instanceof Error?t.message:"unknown error";console.error(`Failed to render Visa HUD: ${n}`),process.exit(1)}}Je.command("statusline").description("Output the Visa HUD for agent statusline integrations").option("--json","Output structured JSON for clients that render their own HUD").action(Bu);G.command("statusline",{hidden:!0}).description("Deprecated alias for `config statusline`").option("--json","Output structured JSON for clients that render their own HUD").action(Bu);var Ln=Je.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",o="\x1B[0m";console.log(`
255
256
  ${e}Visa HUD Status${o}
256
- `);let s=oe.join(F.homedir(),".claude","settings.json"),i=!1,a=!1;try{if(z.existsSync(s)){let _=JSON.parse(z.readFileSync(s,"utf-8")),h=typeof _.statusLine=="object"?_.statusLine.command:"";i=Lt(h),a=!!_.statusLine&&!i}}catch{}let l=i?`${n}\u2713${o}`:`${t}\u2717${o}`,c=i?"registered in ~/.claude/settings.json":a?`${r}another HUD is configured${o} \u2014 edit settings.json to switch`:"not enabled";console.log(` ${l} ${e}Claude Code${o} (statusLine) ${c}`);let u=yn(F.homedir()),d=u.length>0||Dr(),g=d?`${n}\u2713${o}`:`${t}\u2717${o}`,p=d?`installed in shell rc file${u.length>0?` (${u.map(_=>_.replace(F.homedir(),"~")).join(", ")})`:""}`:"not installed (opt-in)";console.log(` ${g} ${e}Shell prompt${o} ${p}`),i&&d&&console.log(` ${r}!${o} ${e}Overlap${o} Claude statusLine and shell prompt HUD are both installed. Remove shell prompt output with: visa-cli config hud disable shell`),console.log(`
257
- ${e}Quick start:${o}`),i||console.log(` visa-cli config hud enable ${t}# Claude Code statusLine (recommended)${o}`),d||console.log(` visa-cli config hud enable shell ${t}# zsh/bash prompt line (opt-in)${o}`),i&&d&&console.log(` ${n}All surfaces enabled.${o}`),(i||d)&&console.log(` visa-cli config hud disable [shell] ${t}# remove a surface${o}`),console.log(` visa-cli config hud doctor ${t}# diagnose connectivity${o}`),console.log()});Dn.command("enable").description("Enable the Visa HUD \u2014 claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{Lu(fs(e,{homeDir:F.homedir(),installVisaStatusLine:Wn,installShellHud:Lr}))});Dn.command("disable").description("Disable the Visa HUD from a surface: claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{let t=e??"claude";if(t==="shell"||t==="prompt"){let s=_t();s.removed||(console.error(s.message),process.exit(1)),console.log(s.message);return}let n=Vr(t);n||(console.error(`Unknown HUD surface: ${t}`),console.error("Supported: claude (default), shell, all"),process.exit(1));let r=!1,o=!1;if(n==="claude"||n==="claude-code"||n==="all"){let s=oe.join(F.homedir(),".claude","settings.json"),i=us(s);console.log(i.message),i.removed&&(o=!0),!i.removed&&n!=="all"&&(r=!0);let a=i.status==="removed"||i.status==="missing-settings"||i.status==="missing-statusline";if(n!=="all"&&!e&&a&&!ls()&&yn(F.homedir()).length>0){let c=_t();c.removed&&c.rcPaths&&c.rcPaths.length>0&&(console.log(`Also cleaned legacy shell-prompt HUD block from ${c.rcPaths.map(u=>u.replace(F.homedir(),"~")).join(", ")} (was leaking output above every shell prompt). Set VISA_HUD_KEEP_SHELL=1 (or true / yes / on) if you want the shell surface to stay.`),o=!0,(i.status==="missing-settings"||i.status==="missing-statusline")&&(r=!1))}}if(n==="all"){let s=_t();console.log(s.message),s.removed&&(o=!0),!s.removed&&n!=="all"&&(r=!0)}n==="all"&&!o&&(r=!0),r&&process.exit(1)});Dn.command("doctor").description("Diagnose HUD installation and connectivity across all surfaces").option("--fix","Self-heal locally fixable issues (stale cache, legacy placeholder, orphan precmd block)").option("-y, --yes","Allow --fix to remove overlapping shell HUD blocks without an interactive prompt").action(async e=>{let t=!0,n=(p,_,h)=>{console.log(` ${_?"\u2713":"\u2717"} ${p}: ${h}`),_||(t=!1)};console.log(`Visa HUD Doctor
258
- `);let r=[],o=ui(void 0,void 0,void 0,{withDiagnostics:!0}),s=o.diagnostics?di(o.diagnostics,o.display):null;s&&(console.log(`\u26A0 ${s}`),console.log(""));let i=oe.join(F.homedir(),".claude","settings.json"),a=!1;try{if(z.existsSync(i)){let p=JSON.parse(z.readFileSync(i,"utf-8")),_=typeof p.statusLine=="object"?p.statusLine.command:"";a=Lt(_)}}catch{}n("Claude Code statusLine",a,a?"registered":"not registered \u2014 run: visa-cli config hud enable");let l=My(F.homedir()),c=hn();if(n("Shell detected",!!c,c??"none (zsh, bash, or PowerShell required)"),c){let p=Kn(c),_=z.existsSync(p);if(n("RC file exists",_,p.replace(F.homedir(),"~")),_){let S=z.readFileSync(p,"utf-8").includes("visa-cli shell hud v2");console.log(` ${S?"\u2713":"\u2013"} Shell HUD block: ${S?"installed":"not installed (opt-in \u2014 run: visa-cli config hud enable shell)"}`)}}if(l.length>0&&console.log(` \u2713 Shell HUD rc scan: installed in ${l.map(p=>p.replace(F.homedir(),"~")).join(", ")}`),a&&l.length>0&&e.fix){let p=l.map(h=>h.replace(F.homedir(),"~")).join(", "),_=e.yes===!0;if(!_&&process.stdin.isTTY&&(_=await $u(`Remove shell prompt HUD block from ${p}?`,{})==="confirmed"),_){let h=$y(F.homedir());_t();let S=Py(h);if(S.length>0){let I=S.map($=>$.replace(F.homedir(),"~")).join(", ");console.log(` \u2713 --fix: cleaned legacy shell-prompt HUD block from ${I}`),r.push(`removed shell precmd block from ${I}`)}}else console.log(` ! --fix: preserving shell prompt HUD block in ${p}; rerun with --yes or remove it explicitly with: visa-cli config hud disable shell`)}else a&&l.length>0&&console.log(" ! Overlap notice: Claude Code statusLine and shell prompt HUD are both installed. If the prompt output is unintended, run: visa-cli config hud disable shell \u2014 or rerun with: visa-cli config hud doctor --fix --yes");let u=ht(),d=z.existsSync(u);if(n("HUD cache file",d,d?u.replace(F.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),d)try{let p=JSON.parse(z.readFileSync(u,"utf-8")),_=Date.now()-(p.renderedAt??0),h=Math.round(_/1e3),S=h<=30,I=typeof p.line=="string"?p.line:"",$=I.length>0&&jr(I);if(console.log(` ${S?"\u2713":"\u26A0"} Cache freshness: ${h}s old${S?"":" (stale \u2014 will refresh on next prompt)"}`),$&&console.log(' \u26A0 Cache content: legacy placeholder (HUD will display "VISA | HUD not ready" until next successful refresh)'),e.fix&&(!S||$)){let C=!1;try{z.rmSync(u,{force:!0}),C=!0}catch{}try{let k=Bn();z.existsSync(k)&&(z.rmSync(k,{force:!0}),C=!0)}catch{}if(C){let k=$?"cache held legacy placeholder":`cache was ${h}s stale`;console.log(` \u2713 --fix: cleared HUD cache (${k}); next prompt will trigger a fresh refresh`),r.push("cleared HUD cache");let q=oe.join(F.homedir(),".visa-cli","shell-hud.lock");z.existsSync(q)&&(Nt(),console.log(" \u2713 --fix: cleared shell HUD refresh lock"),r.push("cleared shell HUD refresh lock"))}}}catch{if(console.log(" \u2717 Cache readable: corrupt JSON"),e.fix)try{z.rmSync(u,{force:!0}),console.log(" \u2713 --fix: removed corrupt cache file; next prompt will trigger a fresh refresh"),r.push("removed corrupt cache");let p=oe.join(F.homedir(),".visa-cli","shell-hud.lock");z.existsSync(p)&&(Nt(),console.log(" \u2713 --fix: cleared shell HUD refresh lock"),r.push("cleared shell HUD refresh lock"))}catch{t=!1}else t=!1}let g=!1;try{g=!!await U.getSessionToken()}catch{}if(n("Auth token",g,g?"found in keychain":"missing \u2014 run: visa-cli setup"),g)try{await se().getStatus(),n("API connectivity",!0,"GET /v1/status OK")}catch(p){let _=p instanceof Error?p.message:"unknown error";n("API connectivity",!1,_)}e.fix&&(r.length===0?console.log(`
257
+ `);let s=ee.join(D.homedir(),".claude","settings.json"),i=!1,a=!1;try{if(z.existsSync(s)){let _=JSON.parse(z.readFileSync(s,"utf-8")),h=typeof _.statusLine=="object"?_.statusLine.command:"";i=vt(h),a=!!_.statusLine&&!i}}catch{}let l=i?`${n}\u2713${o}`:`${t}\u2717${o}`,c=i?"registered in ~/.claude/settings.json":a?`${r}another HUD is configured${o} \u2014 edit settings.json to switch`:"not enabled";console.log(` ${l} ${e}Claude Code${o} (statusLine) ${c}`);let u=Ut(D.homedir()),d=u.length>0||Lr(),f=d?`${n}\u2713${o}`:`${t}\u2717${o}`,p=d?`installed in shell rc file${u.length>0?` (${u.map(_=>_.replace(D.homedir(),"~")).join(", ")})`:""}`:"not installed (opt-in)";console.log(` ${f} ${e}Shell prompt${o} ${p}`),i&&d&&console.log(` ${r}!${o} ${e}Overlap${o} Claude statusLine and shell prompt HUD are both installed. Remove shell prompt output with: visa-cli config hud disable shell`),console.log(`
258
+ ${e}Quick start:${o}`),i||console.log(` visa-cli config hud enable ${t}# Claude Code statusLine (recommended)${o}`),d||console.log(` visa-cli config hud enable shell ${t}# zsh/bash prompt line (opt-in)${o}`),i&&d&&console.log(` ${n}All surfaces enabled.${o}`),(i||d)&&console.log(` visa-cli config hud disable [shell] ${t}# remove a surface${o}`),console.log(` visa-cli config hud doctor ${t}# diagnose connectivity${o}`),console.log()});Ln.command("enable").description("Enable the Visa HUD \u2014 claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{Vu(vs(e,{homeDir:D.homedir(),installVisaStatusLine:Wn,installShellHud:Dr}))});Ln.command("disable").description("Disable the Visa HUD from a surface: claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{let t=e??"claude";if(t==="shell"||t==="prompt"){let s=Ze();s.removed||(console.error(s.message),process.exit(1)),console.log(s.message);return}let n=Gr(t);n||(console.error(`Unknown HUD surface: ${t}`),console.error("Supported: claude (default), shell, all"),process.exit(1));let r=!1,o=!1;if(n==="claude"||n==="claude-code"||n==="all"){let s=ee.join(D.homedir(),".claude","settings.json"),i=gs(s);console.log(i.message),i.removed&&(o=!0),!i.removed&&n!=="all"&&(r=!0);let a=i.status==="removed"||i.status==="missing-settings"||i.status==="missing-statusline";if(n!=="all"&&!e&&a&&!Br()&&Ut(D.homedir()).length>0){let c=Ze();c.removed&&c.rcPaths&&c.rcPaths.length>0&&(console.log(`Also cleaned legacy shell-prompt HUD block from ${c.rcPaths.map(u=>u.replace(D.homedir(),"~")).join(", ")} (was leaking output above every shell prompt). Set VISA_HUD_KEEP_SHELL=1 (or true / yes / on) if you want the shell surface to stay.`),o=!0,(i.status==="missing-settings"||i.status==="missing-statusline")&&(r=!1))}}if(n==="all"){let s=Ze();console.log(s.message),s.removed&&(o=!0),!s.removed&&n!=="all"&&(r=!0)}n==="all"&&!o&&(r=!0),r&&process.exit(1)});Ln.command("doctor").description("Diagnose HUD installation and connectivity across all surfaces").option("--fix","Self-heal locally fixable issues (stale cache, legacy placeholder, orphan precmd block)").option("-y, --yes","Allow --fix to remove overlapping shell HUD blocks without an interactive prompt").action(async e=>{let t=!0,n=(p,_,h)=>{console.log(` ${_?"\u2713":"\u2717"} ${p}: ${h}`),_||(t=!1)};console.log(`Visa HUD Doctor
259
+ `);let r=[],o=gi(void 0,void 0,void 0,{withDiagnostics:!0}),s=o.diagnostics?hi(o.diagnostics,o.display):null;s&&(console.log(`\u26A0 ${s}`),console.log(""));let i=ee.join(D.homedir(),".claude","settings.json"),a=!1;try{if(z.existsSync(i)){let p=JSON.parse(z.readFileSync(i,"utf-8")),_=typeof p.statusLine=="object"?p.statusLine.command:"";a=vt(_)}}catch{}n("Claude Code statusLine",a,a?"registered":"not registered \u2014 run: visa-cli config hud enable");let l=Vy(D.homedir()),c=yn();if(n("Shell detected",!!c,c??"none (zsh, bash, or PowerShell required)"),c){let p=Kn(c),_=z.existsSync(p);if(n("RC file exists",_,p.replace(D.homedir(),"~")),_){let S=z.readFileSync(p,"utf-8").includes("visa-cli shell hud v2");console.log(` ${S?"\u2713":"\u2013"} Shell HUD block: ${S?"installed":"not installed (opt-in \u2014 run: visa-cli config hud enable shell)"}`)}}if(l.length>0&&console.log(` \u2713 Shell HUD rc scan: installed in ${l.map(p=>p.replace(D.homedir(),"~")).join(", ")}`),a&&l.length>0&&e.fix){let p=l.map(h=>h.replace(D.homedir(),"~")).join(", "),_=e.yes===!0;if(!_&&process.stdin.isTTY&&(_=await Nu(`Remove shell prompt HUD block from ${p}?`,{})==="confirmed"),_){let h=jy(D.homedir());Ze();let S=Fy(h);if(S.length>0){let I=S.map($=>$.replace(D.homedir(),"~")).join(", ");console.log(` \u2713 --fix: cleaned legacy shell-prompt HUD block from ${I}`),r.push(`removed shell precmd block from ${I}`)}}else console.log(` ! --fix: preserving shell prompt HUD block in ${p}; rerun with --yes or remove it explicitly with: visa-cli config hud disable shell`)}else a&&l.length>0&&console.log(" ! Overlap notice: Claude Code statusLine and shell prompt HUD are both installed. If the prompt output is unintended, run: visa-cli config hud disable shell \u2014 or rerun with: visa-cli config hud doctor --fix --yes");let u=yt(),d=z.existsSync(u);if(n("HUD cache file",d,d?u.replace(D.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),d)try{let p=JSON.parse(z.readFileSync(u,"utf-8")),_=Date.now()-(p.renderedAt??0),h=Math.round(_/1e3),S=h<=30,I=typeof p.line=="string"?p.line:"",$=I.length>0&&jr(I);if(console.log(` ${S?"\u2713":"\u26A0"} Cache freshness: ${h}s old${S?"":" (stale \u2014 will refresh on next prompt)"}`),$&&console.log(' \u26A0 Cache content: legacy placeholder (HUD will display "VISA | HUD not ready" until next successful refresh)'),e.fix&&(!S||$)){let C=!1;try{z.rmSync(u,{force:!0}),C=!0}catch{}try{let k=Bn();z.existsSync(k)&&(z.rmSync(k,{force:!0}),C=!0)}catch{}if(C){let k=$?"cache held legacy placeholder":`cache was ${h}s stale`;console.log(` \u2713 --fix: cleared HUD cache (${k}); next prompt will trigger a fresh refresh`),r.push("cleared HUD cache");let q=ee.join(D.homedir(),".visa-cli","shell-hud.lock");z.existsSync(q)&&(Lt(),console.log(" \u2713 --fix: cleared shell HUD refresh lock"),r.push("cleared shell HUD refresh lock"))}}}catch{if(console.log(" \u2717 Cache readable: corrupt JSON"),e.fix)try{z.rmSync(u,{force:!0}),console.log(" \u2713 --fix: removed corrupt cache file; next prompt will trigger a fresh refresh"),r.push("removed corrupt cache");let p=ee.join(D.homedir(),".visa-cli","shell-hud.lock");z.existsSync(p)&&(Lt(),console.log(" \u2713 --fix: cleared shell HUD refresh lock"),r.push("cleared shell HUD refresh lock"))}catch{t=!1}else t=!1}let f=!1;try{f=!!await j.getSessionToken()}catch{}if(n("Auth token",f,f?"found in keychain":"missing \u2014 run: visa-cli setup"),f)try{await ie().getStatus(),n("API connectivity",!0,"GET /v1/status OK")}catch(p){let _=p instanceof Error?p.message:"unknown error";n("API connectivity",!1,_)}e.fix&&(r.length===0?console.log(`
259
260
  --fix: no locally fixable issues found.`):console.log(`
260
261
  --fix: applied ${r.length} change${r.length===1?"":"s"} \u2014 ${r.join("; ")}.`)),console.log(t?`
261
262
  All checks passed.`:`
262
- Some checks failed \u2014 see above.`),t||process.exit(1)});Dn.command("enable-claude").description("Alias for: hud enable claude").action(()=>{let e=oe.join(F.homedir(),".claude","settings.json"),t=Wn(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});Dn.command("disable-claude").description("Alias for: hud disable claude").action(()=>{let e=oe.join(F.homedir(),".claude","settings.json"),t=us(e);console.log(t.message),t.removed||process.exit(1)});var Ln=G.command("merchants").description("List discoverable platform merchants and refresh JIT tools").addHelpCommand(!1).action(Ne);Ln.description("Discover and run paid merchant tools");Ln.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 Se(()=>U.getSessionToken()),n=await t.listPublicMerchants();if(n.length===0){e.json?console.log(JSON.stringify({merchants:[]},null,2)):console.log(`
263
+ Some checks failed \u2014 see above.`),t||process.exit(1)});Ln.command("enable-claude").description("Alias for: hud enable claude").action(()=>{let e=ee.join(D.homedir(),".claude","settings.json"),t=Wn(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=ee.join(D.homedir(),".claude","settings.json"),t=gs(e);console.log(t.message),t.removed||process.exit(1)});var Dn=G.command("merchants").description("List discoverable platform merchants and refresh JIT tools").addHelpCommand(!1).action(Ne);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 Se(()=>j.getSessionToken()),n=await t.listPublicMerchants();if(n.length===0){e.json?console.log(JSON.stringify({merchants:[]},null,2)):console.log(`
263
264
  No live platform merchants on this auth server.
264
265
  `);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 o="\x1B[1m",s="\x1B[2m",i="\x1B[0m";console.log();for(let a of r){let l=a.merchant_of_record!==a.provider?` ${s}(MoR: ${a.merchant_of_record})${i}`:"";if(console.log(` ${o}${a.provider}${i}${l} ${s}\u2014 slug: ${a.slug}${i}`),a.upstream&&console.log(` ${s}upstream: ${a.upstream}${i}`),a.tools.length===0)console.log(` ${s}(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?` ${s}[${c.category}]${i}`:"",d=`$${(c.price_cents/100).toFixed(2)}`;console.log(` ${c.tool_id}${u} ${s}\u2192 Claude: ${c.mcp_name}${i} ${d} ${s}${c.method} ${c.path}${i}`),c.description&&console.log(` ${s}${c.description}${i}`)}console.log()}console.log(` ${s}To enable JIT tools in your MCP server, set: visa-cli config set merchants.discover all (or =<slug,...>)${i}
265
- `)}catch(t){console.error("Error:",t.message),process.exit(1)}});Ln.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").option("--limit <n>",`Maximum tools to return (default ${Au}, max ${Ru})`,fu).option("--offset <n>","Pagination offset (default 0)",fu).action(async e=>{try{let t=se(),{limit:n,offset:r}=vy(e),o=await _y(t,{query:e.query,category:e.category,limit:n,offset:r});if(e.json){console.log(JSON.stringify({tools:o},null,2));return}if(o.length===0){console.log("No merchant tools found. Try: visa-cli merchants tools --category image");return}e.verbose?fy(o):py(o)}catch(t){console.error("Error:",t.message),process.exit(1)}});Ln.command("describe <tool>").description("Show tool schema, price, and examples").action(async e=>{try{let n=await se().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(`
266
+ `)}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").option("--limit <n>",`Maximum tools to return (default ${Pu}, max ${Mu})`,_u).option("--offset <n>","Pagination offset (default 0)",_u).action(async e=>{try{let t=ie(),{limit:n,offset:r}=Ey(e),o=await Ty(t,{query:e.query,category:e.category,limit:n,offset:r});if(e.json){console.log(JSON.stringify({tools:o},null,2));return}if(o.length===0){console.log("No merchant tools found. Try: visa-cli merchants tools --category image");return}e.verbose?wy(o):Sy(o)}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 ie().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(`
266
267
  ${n.id}
267
268
  `),console.log(n.description),console.log(`
268
- Price`),console.log(` ${Ti(n.priceCents,n.priceDisplay)}`),console.log(`
269
+ Price`),console.log(` ${Pi(n.priceCents,n.priceDisplay)}`),console.log(`
269
270
  Provider`),console.log(` ${n.provider} \xB7 ${n.category}`),console.log(`
270
- Inputs`);let r=n.inputSchema?.properties;if(r&&typeof r=="object"&&!Array.isArray(r)){let s=Array.isArray(n.inputSchema.required)?new Set(n.inputSchema.required):new Set,i=Object.entries(r),a=Math.max(12,...i.map(([l])=>l.length));for(let[l,c]of i){let u=s.has(l)?"required":"optional",d=Ya(c),g=d?` ${d.padEnd(8)}`:" ",p=c?.description?` - ${c.description}`:"";console.log(` ${l.padEnd(a)} ${u}${g}${p}`)}}else console.log(" No published schema. Use --json with the request body.");console.log(`
271
- Examples`);let o=Zl(n);console.log(` visa-cli merchants run ${n.id} --json '${JSON.stringify(o)}'`),n.category==="image"&&console.log(' visa-cli generate image "a lobster on a marble counter"'),console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});function Dy(e){return["fal-flux-pro-ultra","fal-flux-pro","fal-flux-schnell","fal-recraft-v3","fal-ideogram-v2","fal-minimax-video","fal-wan-video","fal-kling-video","fal-ace-step-music","check_fal_status_card","query_onchain_prices"].includes(e)}async function Mi(e,t,n){return Dy(e)?$e.shortcut(e,t,n):$e.executeTool({tool_id:e,params:t},n,"execute_tool")}Ln.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=dy(t.json,"--json");t.prompt&&(n.prompt=t.prompt),console.log(`Running ${e}`);let r=await Mi(e,n,`visa-cli merchants run ${e}`);Ei(r),Ai(r)}catch(n){console.error("Error:",n.message),process.exit(1)}});Ln.command("refresh").description("Hint: restart the MCP server (Claude/Cursor) to refresh discovered tools \u2014 discovery is in-process").action(()=>{console.log(`
271
+ Inputs`);let r=n.inputSchema?.properties;if(r&&typeof r=="object"&&!Array.isArray(r)){let s=Array.isArray(n.inputSchema.required)?new Set(n.inputSchema.required):new Set,i=Object.entries(r),a=Math.max(12,...i.map(([l])=>l.length));for(let[l,c]of i){let u=s.has(l)?"required":"optional",d=ec(c),f=d?` ${d.padEnd(8)}`:" ",p=c?.description?` - ${c.description}`:"";console.log(` ${l.padEnd(a)} ${u}${f}${p}`)}}else console.log(" No published schema. Use --json with the request body.");console.log(`
272
+ Examples`);let o=tu(n);console.log(` visa-cli merchants run ${n.id} --json '${JSON.stringify(o)}'`),n.category==="image"&&console.log(' visa-cli generate image "a lobster on a marble counter"'),console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});function By(e){return["fal-flux-pro-ultra","fal-flux-pro","fal-flux-schnell","fal-recraft-v3","fal-ideogram-v2","fal-minimax-video","fal-wan-video","fal-kling-video","fal-ace-step-music","check_fal_status_card","query_onchain_prices"].includes(e)}async function ji(e,t,n){return By(e)?$e.shortcut(e,t,n):$e.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=vy(t.json,"--json");t.prompt&&(n.prompt=t.prompt),console.log(`Running ${e}`);let r=await ji(e,n,`visa-cli merchants run ${e}`);Mi(r),Oi(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(`
272
273
  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.
273
- `)});var br=G.command("generate").description("Generate media with merchant tools").addHelpCommand(!1).action(Ne);async function Sr(e){Zo({yes:e.yes}),e.json||e.format&&Mr(e.format)||(console.log(`
274
+ `)});var br=G.command("generate").description("Generate media with merchant tools").addHelpCommand(!1).action(Ne);async function Sr(e){ns({yes:e.yes}),e.json||e.format&&Mr(e.format)||(console.log(`
274
275
  ${e.kind}
275
276
  `),console.log(`Using: ${e.toolId}`),console.log(`Prompt: ${e.prompt}
276
- `));let n=await Mi(e.toolId,e.params,`visa-cli generate ${e.kind.toLowerCase()}: ${e.prompt}`);Ei(n,{json:e.json,format:e.format,command:e.command??`generate.${e.kind.toLowerCase().replace(/\s+/g,"_")}`}),Ai(n)}var Mt=(e,t)=>n=>(t.includes(n)||G.error(`error: option '${e}' accepts ${t.map(r=>`'${r}'`).join(", ")} (got '${n}')`,{exitCode:2}),n);br.command("image [prompt]").description("Generate an image from a prompt (accepts stdin via `-` or --stdin)").option("--quality <quality>","Image quality: standard or high",Mt("--quality",["standard","high"]),"standard").option("--fast","Use the fast image tool").option("--tool <tool>","Exact tool id override").option("--image-ref <url>","Optional source image URL for edit/style-transfer tools").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Mt("--format",ft)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await Ot(e,t),r=t.tool??(t.fast||t.quality!=="high"?"fal-flux-pro":"fal-flux-pro-ultra"),o={prompt:n};t.imageRef&&(o.image_url=t.imageRef),await Sr({kind:"Image generation",toolId:r,params:o,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.image"})}catch(n){Nn("generate.image",n,{json:t.json,format:t.format})}});br.command("video [prompt]").description("Generate a video from a prompt (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--aspect-ratio <ratio>","Aspect ratio, when supported by the selected tool").option("--duration <seconds>","Duration in seconds, when supported by the selected tool").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Mt("--format",ft)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await Ot(e,t),r={prompt:n};t.aspectRatio&&(r.aspect_ratio=t.aspectRatio),t.duration&&(r.duration=Number(t.duration)),await Sr({kind:"Video generation",toolId:t.tool??"fal-minimax-video",params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.video"})}catch(n){Nn("generate.video",n,{json:t.json,format:t.format})}});br.command("music [prompt]").description("Generate music from a prompt (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--instrumental","Generate instrumental music").option("--duration <seconds>","Duration in seconds, when supported by the selected tool").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Mt("--format",ft)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await Ot(e,t),r={prompt:n};t.instrumental&&(r.instrumental=!0),t.duration&&(r.duration=Number(t.duration)),await Sr({kind:"Music generation",toolId:t.tool??"fal-stable-audio",params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.music"})}catch(n){Nn("generate.music",n,{json:t.json,format:t.format})}});br.command("speech [text]").description("Generate speech from text using a voice sample (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--audio-url <url>","Voice sample audio URL for voice cloning").option("--ref-audio-url <url>","Alias for --audio-url").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Mt("--format",ft)).option("--stdin","Read text from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=t.audioUrl??t.refAudioUrl;n||G.error("error: option '--audio-url <url>' is required for visa-cli generate speech",{exitCode:2});let r=await Ot(e,t),o={text:r,audio_url:n};await Sr({kind:"Speech generation",toolId:t.tool??"fal-metavoice",params:o,prompt:r,json:t.json,format:t.format,yes:t.yes,command:"generate.speech"})}catch(n){Nn("generate.speech",n,{json:t.json,format:t.format})}});br.command("3d [image-url]").alias("model").description("Generate a 3D model from an image URL (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Mt("--format",ft)).option("--stdin","Read image URL from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await Ot(e,t),r={image_url:n};await Sr({kind:"3D generation",toolId:t.tool??an("generate_3d"),params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.3d"})}catch(n){Nn("generate.3d",n,{json:t.json,format:t.format})}});var wi="reasoning",gu=Object.keys(sr.run_llm.tiers);G.command("run-llm [prompt]").description(`Run a chat-completion against an OpenRouter-backed LLM (default tier: ${wi})`).option("--tier <tier>",`LLM tier: ${gu.join(" | ")} (resolves to a catalog tool id via the run_llm meta-tool)`,Mt("--tier",gu),wi).option("--model <id>","Exact catalog tool id (e.g. or-claude-haiku, or-gemini-3-flash). Overrides --tier.").option("--system <prompt>","System prompt (inline string or @./path to a file)").option("--max-tokens <n>","Maximum completion tokens").option("--temperature <n>","Sampling temperature 0-2").option("--image-url <url>","Image URL for vision-capable models (or-gemini-nano-banana-pro, etc.)").option("--from-stdin <field>","Read upstream JSON envelope from stdin and bind .field to a flag value (e.g. --image-url --from-stdin .urls[0])").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Mt("--format",ft)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=t.imageUrl;if(t.fromStdin){let c=await Yo(),u=JSON.parse(c),d=ea(u,t.fromStdin);n=n??d}let r=await Ot(e,{stdin:t.stdin&&!t.fromStdin});Zo({yes:t.yes});let o={prompt:r},s=await na(t.system);s&&(o.system_prompt=s),t.maxTokens&&(o.max_tokens=Number(t.maxTokens)),t.temperature!==void 0&&(o.temperature=Number(t.temperature)),n&&(o.image_url=n);let i=t.tier??wi,a=t.model??an("run_llm",i);if(!t.json){console.log(`
277
+ `));let n=await ji(e.toolId,e.params,`visa-cli generate ${e.kind.toLowerCase()}: ${e.prompt}`);Mi(n,{json:e.json,format:e.format,command:e.command??`generate.${e.kind.toLowerCase().replace(/\s+/g,"_")}`}),Oi(n)}var Ot=(e,t)=>n=>(t.includes(n)||G.error(`error: option '${e}' accepts ${t.map(r=>`'${r}'`).join(", ")} (got '${n}')`,{exitCode:2}),n);br.command("image [prompt]").description("Generate an image from a prompt (accepts stdin via `-` or --stdin)").option("--quality <quality>","Image quality: standard or high",Ot("--quality",["standard","high"]),"standard").option("--fast","Use the fast image tool").option("--tool <tool>","Exact tool id override").option("--image-ref <url>","Optional source image URL for edit/style-transfer tools").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Ot("--format",gt)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await Nt(e,t),r=t.tool??(t.fast||t.quality!=="high"?"fal-flux-pro":"fal-flux-pro-ultra"),o={prompt:n};t.imageRef&&(o.image_url=t.imageRef),await Sr({kind:"Image generation",toolId:r,params:o,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.image"})}catch(n){Nn("generate.image",n,{json:t.json,format:t.format})}});br.command("video [prompt]").description("Generate a video from a prompt (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--aspect-ratio <ratio>","Aspect ratio, when supported by the selected tool").option("--duration <seconds>","Duration in seconds, when supported by the selected tool").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Ot("--format",gt)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await Nt(e,t),r={prompt:n};t.aspectRatio&&(r.aspect_ratio=t.aspectRatio),t.duration&&(r.duration=Number(t.duration)),await Sr({kind:"Video generation",toolId:t.tool??"fal-minimax-video",params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.video"})}catch(n){Nn("generate.video",n,{json:t.json,format:t.format})}});br.command("music [prompt]").description("Generate music from a prompt (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--instrumental","Generate instrumental music").option("--duration <seconds>","Duration in seconds, when supported by the selected tool").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Ot("--format",gt)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await Nt(e,t),r={prompt:n};t.instrumental&&(r.instrumental=!0),t.duration&&(r.duration=Number(t.duration)),await Sr({kind:"Music generation",toolId:t.tool??"fal-stable-audio",params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.music"})}catch(n){Nn("generate.music",n,{json:t.json,format:t.format})}});br.command("speech [text]").description("Generate speech from text using a voice sample (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--audio-url <url>","Voice sample audio URL for voice cloning").option("--ref-audio-url <url>","Alias for --audio-url").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Ot("--format",gt)).option("--stdin","Read text from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=t.audioUrl??t.refAudioUrl;n||G.error("error: option '--audio-url <url>' is required for visa-cli generate speech",{exitCode:2});let r=await Nt(e,t),o={text:r,audio_url:n};await Sr({kind:"Speech generation",toolId:t.tool??"fal-metavoice",params:o,prompt:r,json:t.json,format:t.format,yes:t.yes,command:"generate.speech"})}catch(n){Nn("generate.speech",n,{json:t.json,format:t.format})}});br.command("3d [image-url]").alias("model").description("Generate a 3D model from an image URL (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Ot("--format",gt)).option("--stdin","Read image URL from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await Nt(e,t),r={image_url:n};await Sr({kind:"3D generation",toolId:t.tool??cn("generate_3d"),params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.3d"})}catch(n){Nn("generate.3d",n,{json:t.json,format:t.format})}});var Ai="reasoning",vu=Object.keys(sr.run_llm.tiers);G.command("run-llm [prompt]").description(`Run a chat-completion against an OpenRouter-backed LLM (default tier: ${Ai})`).option("--tier <tier>",`LLM tier: ${vu.join(" | ")} (resolves to a catalog tool id via the run_llm meta-tool)`,Ot("--tier",vu),Ai).option("--model <id>","Exact catalog tool id (e.g. or-claude-haiku, or-gemini-3-flash). Overrides --tier.").option("--system <prompt>","System prompt (inline string or @./path to a file)").option("--max-tokens <n>","Maximum completion tokens").option("--temperature <n>","Sampling temperature 0-2").option("--image-url <url>","Image URL for vision-capable models (or-gemini-nano-banana-pro, etc.)").option("--from-stdin <field>","Read upstream JSON envelope from stdin and bind .field to a flag value (e.g. --image-url --from-stdin .urls[0])").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Ot("--format",gt)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=t.imageUrl;if(t.fromStdin){let c=await ts(),u=JSON.parse(c),d=ia(u,t.fromStdin);n=n??d}let r=await Nt(e,{stdin:t.stdin&&!t.fromStdin});ns({yes:t.yes});let o={prompt:r},s=await ca(t.system);s&&(o.system_prompt=s),t.maxTokens&&(o.max_tokens=Number(t.maxTokens)),t.temperature!==void 0&&(o.temperature=Number(t.temperature)),n&&(o.image_url=n);let i=t.tier??Ai,a=t.model??cn("run_llm",i);if(!t.json){console.log(`
277
278
  LLM completion
278
279
  `),console.log(`Using: ${a}`);let c=r.length>200?`${r.slice(0,200)}\u2026`:r;console.log(`Prompt: ${c}
279
- `)}let l=await Mi(a,o,"visa-cli run-llm");Ei(l,{json:t.json,format:t.format,command:"run-llm"}),Ai(l)}catch(n){Nn("run-llm",n,{json:t.json,format:t.format})}});G.command("uninstall [client]").description("Remove MCP server from an AI client").option("--all","Remove from all clients").option("--scope <scope>","Uninstall scope: global or project","global").action(async(e,t)=>{try{let n=t.scope==="project"?"project":"global";if(t.all){let s=[];for(let i of Oe)_i(i,n).removed&&s.push(i.displayName);s.length>0?console.log(`Removed visa-cli from: ${s.join(", ")}.`):console.log("visa-cli was not installed in any client.");return}e||(console.error("Usage: visa-cli uninstall <client>"),console.error(" visa-cli uninstall --all"),console.error(`
280
- Supported clients: ${Oe.map(s=>s.id).join(", ")}`),process.exit(1));let r=fi(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${Oe.map(s=>s.id).join(", ")}`),process.exit(1));let o=_i(r,n);o.removed?console.log(`Removed visa-cli from ${o.configPath}`):console.log(`visa-cli was not installed for ${r.displayName}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});G.hook("postAction",()=>{if(_r){_r=!1;return}Io&&Yl(Io.lastSignals)});Ty(["setup","install","status","cards","tokens","balance","merchants","generate","config","feedback","update","uninstall"]);Iu(G);G.parseAsync().catch(async e=>{console.error("Error:",e instanceof Error?e.message:String(e));let{reportFatal:t}=await Promise.resolve().then(()=>(Ro(),Ao));await t(e)});process.on("uncaughtException",async e=>{console.error("Uncaught exception:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(Ro(),Ao));await t(e)});process.on("unhandledRejection",async e=>{console.error("Unhandled rejection:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(Ro(),Ao));await t(e)});0&&(module.exports={printGroupHelpAndExit});
280
+ `)}let l=await ji(a,o,"visa-cli run-llm");Mi(l,{json:t.json,format:t.format,command:"run-llm"}),Oi(l)}catch(n){Nn("run-llm",n,{json:t.json,format:t.format})}});G.command("uninstall [client]").description("Remove MCP server from an AI client").option("--all","Remove from all clients").option("--scope <scope>","Uninstall scope: global or project","global").action(async(e,t)=>{try{let n=t.scope==="project"?"project":"global";if(t.all){let s=[];for(let i of Oe)xi(i,n).removed&&s.push(i.displayName);s.length>0?console.log(`Removed visa-cli from: ${s.join(", ")}.`):console.log("visa-cli was not installed in any client.");return}e||(console.error("Usage: visa-cli uninstall <client>"),console.error(" visa-cli uninstall --all"),console.error(`
281
+ Supported clients: ${Oe.map(s=>s.id).join(", ")}`),process.exit(1));let r=vi(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${Oe.map(s=>s.id).join(", ")}`),process.exit(1));let o=xi(r,n);o.removed?console.log(`Removed visa-cli from ${o.configPath}`):console.log(`visa-cli was not installed for ${r.displayName}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});G.hook("postAction",()=>{if(_r){_r=!1;return}No&&eu(No.lastSignals)});Oy(["setup","install","status","cards","tokens","balance","merchants","generate","config","feedback","update","uninstall"]);Ou(G);G.parseAsync().catch(async e=>{console.error("Error:",e instanceof Error?e.message:String(e));let{reportFatal:t}=await Promise.resolve().then(()=>(Oo(),Mo));await t(e)});process.on("uncaughtException",async e=>{console.error("Uncaught exception:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(Oo(),Mo));await t(e)});process.on("unhandledRejection",async e=>{console.error("Unhandled rejection:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(Oo(),Mo));await t(e)});0&&(module.exports={printGroupHelpAndExit});