@visa/cli 2.7.0-rc.4 → 2.7.1-rc.6

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 Kd=Object.create;var Hr=Object.defineProperty;var Gd=Object.getOwnPropertyDescriptor;var Wd=Object.getOwnPropertyNames;var zd=Object.getPrototypeOf,Jd=Object.prototype.hasOwnProperty;var Yd=(e,t)=>()=>(e&&(t=e(e=0)),t);var ha=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ms=(e,t)=>{for(var n in t)Hr(e,n,{get:t[n],enumerable:!0})},ya=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Wd(t))!Jd.call(e,o)&&o!==n&&Hr(e,o,{get:()=>t[o],enumerable:!(r=Gd(t,o))||r.enumerable});return e};var E=(e,t,n)=>(n=e!=null?Kd(zd(e)):{},ya(t||!e||!e.__esModule?Hr(n,"default",{value:e,enumerable:!0}):n,e)),Zd=e=>ya(Hr({},"__esModule",{value:!0}),e);var nr=ha((kv,um)=>{um.exports={name:"@visa/cli",version:"2.7.0-rc.4",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.1","@typescript-eslint/eslint-plugin":"^8.60.0","@typescript-eslint/parser":"^8.60.0","@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.11",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","native/visa-keychain-win.cpp","native/build-win.bat","native/bin/win32-x64/visa-keychain-win.exe","server.json","README.md","LICENSE"]}});var Rr=ha(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.micros=rh;ie.fromCents=oh;ie.fromUsdc=sh;ie.fromUsd=ih;ie.toCents=ah;ie.toCentsForAcquirer=ch;ie.toUsdc=lh;ie.toWire=uh;ie.fromWire=dh;ie.toDisplay=mh;ie.toUsdRounded2dp=ph;ie.add=fh;ie.sub=gh;ie.clampNonNegative=hh;ie.isNonNegative=yh;ie.max=_h;ie.min=vh;var ft=10000n,iu=1000000n;function rh(e){return e}function oh(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*ft}function sh(e){return e}function ih(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function ah(e){if(e>=0n)return Number(e/ft);let t=e/ft,n=e%ft;return Number(n===0n?t:t-1n)}function ch(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/ft)}function lh(e){return e}function uh(e){return e.toString()}function dh(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 mh(e,t={}){let n=t.decimals??2,r=t.symbol??"$",o=e<0n,s=o?-e:e,i=s/iu,a=s%iu,c=o?"-":"";if(n===0)return`${c}${r}${i.toString()}`;let l=a.toString().padStart(6,"0").slice(0,n);return`${c}${r}${i.toString()}.${l}`}function ph(e){let t=e<0n,n=t?-e:e,r=n/ft,s=n%ft*2n,i;s<ft?i=r:s>ft?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function fh(e,t){return e+t}function gh(e,t){return e-t}function hh(e){return e<0n?0n:e}function yh(e){return e>=0n}function _h(e,t){return e>t?e:t}function vh(e,t){return e<t?e:t}});var ss={};ms(ss,{initSentry:()=>I_,isSentryConfigured:()=>R_,reportFatal:()=>$_});function R_(){return!1}async function I_(){return null}async function $_(e,t){process.exit(t?.exitCode??1)}var is=Yd(()=>{});var yv={};ms(yv,{printGroupHelpAndExit:()=>Ve});module.exports=Zd(yv);var Sd=require("commander"),cs=E(require("crypto")),Y=E(require("fs")),z=E(require("os")),Pe=E(require("path")),wd=require("child_process"),ra=require("node:readline/promises"),xd=require("util");var Kr=require("child_process"),Ea=require("util"),bt=E(require("fs")),Gr=E(require("os")),_s=E(require("path"));var Sa=E(require("crypto"));var rt="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";var wa="VISA_ALLOW_INSECURE_MOCKS",_a,va,ba;function ps(e){return`${e}-${Sa.randomBytes(24).toString("base64url")}`}function xa(e=process.env){return e.NODE_ENV==="test"||e[wa]==="true"}function _t(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&xa(e)}function Tn(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&xa(e)}function fs(){return`Set ${wa}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function ka(){return _a??=ps("mock-session"),_a}function Ca(e=process.env){return e.NODE_ENV==="test"?rt:(va??=ps("mock-rc"),va)}function Ta(){return ba??=ps("mock-signature"),ba}var He=(0,Ea.promisify)(Kr.execFile),vs=_s.join(Gr.homedir(),".visa-mcp"),tr=_s.join(vs,"session-token"),Ae="visa-cli",vt="session-token",qr="rc-access",Xd=5e3,Br=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function Qd(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
2
- `)}function Aa(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=Qd(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function em(){try{let{stdout:e}=await He("security",["find-generic-password","-s",Ae,"-a",vt,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(Aa(e))throw new Br("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 tm(e){try{try{await He("security",["delete-generic-password","-s",Ae,"-a",vt],{timeout:5e3})}catch{}return await He("security",["add-generic-password","-s",Ae,"-a",vt,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function nm(){try{await He("security",["delete-generic-password","-s",Ae,"-a",vt],{timeout:5e3})}catch{}}async function rm(){if(!bs())return null;try{let{stdout:e}=await He("secret-tool",["lookup","service",Ae,"account",vt],{timeout:5e3});return e.trim()||null}catch{return null}}async function om(e){if(!bs())return!1;try{let t=(0,Kr.execFile)("secret-tool",["store","--label",`${Ae} ${vt}`,"service",Ae,"account",vt]);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"))},Xd))]),!0):!1}catch{return!1}}async function sm(){if(bs())try{await He("secret-tool",["clear","service",Ae,"account",vt],{timeout:5e3})}catch{}}function bs(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function im(){try{let{stdout:e}=await He("security",["find-generic-password","-s",Ae,"-a",qr,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function am(e){try{try{await He("security",["delete-generic-password","-s",Ae,"-a",qr],{timeout:5e3})}catch{}await He("security",["add-generic-password","-s",Ae,"-a",qr,"-w",e],{timeout:5e3})}catch{}}async function cm(){try{await He("security",["delete-generic-password","-s",Ae,"-a",qr],{timeout:5e3})}catch{}}function hs(){try{return bt.readFileSync(tr,"utf-8").trim()||null}catch(e){if(Aa(e))throw new Br(`Unable to read Visa CLI credentials from ${tr}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function Ra(e){bt.mkdirSync(vs,{recursive:!0,mode:448}),bt.writeFileSync(tr,e,{mode:384}),process.platform==="win32"&&lm(tr)}function ys(){try{bt.unlinkSync(tr)}catch{}}function lm(e){try{let t=Gr.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 gs(){switch(process.platform){case"darwin":return{get:em,store:tm,delete:nm};case"linux":return{get:rm,store:om,delete:sm};default:return{get:async()=>hs(),store:async e=>{try{return Ra(e),!0}catch{return!1}},delete:async()=>ys(),storesInSessionFile:!0}}}var F=class{static async getSessionToken(){if(_t())return Promise.resolve(ka());let t=gs(),n=await t.get();if(n)return n;let r=hs();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(_t())return;let n=gs();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||ys();return}await n.delete()}if(Ra(t),hs()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${vs} is writable.`))}static async getRcAccessToken(){return _t()?Ca():im()}static async saveRcAccessToken(t){_t()||await am(t)}static async deleteSessionToken(){if(_t())return;await gs().delete(),ys()}static async clearAll(){await this.deleteSessionToken(),await cm()}};var Wr=E(require("crypto")),zr=E(require("tty")),Jr=E(require("fs"));function dm(e){return/-rc\.|-beta\./.test(e)}function Ss(e){return Wr.createHash("sha256").update(e.trim()).digest("hex")}function Ia(e){return rt==="SKIP"?!0:Wr.timingSafeEqual(Buffer.from(Ss(e)),Buffer.from(rt))}function mm(){try{let e=Jr.openSync("/dev/tty","r+"),t=new zr.ReadStream(e),n=new zr.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{Jr.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 pm(e){return new Promise((t,n)=>{let r;try{r=mm()}catch(u){n(u);return}let{input:o,output:s,cleanupStreams:i}=r,a=()=>{o.off("data",l);try{o.setRawMode?.(!1)}catch{}i()};s.write(e),o.setRawMode?.(!0),o.resume(),o.setEncoding("utf8");let c="",l=u=>{u==="\r"||u===`
1
+ "use strict";var zd=Object.create;var Hr=Object.defineProperty;var Jd=Object.getOwnPropertyDescriptor;var Yd=Object.getOwnPropertyNames;var Zd=Object.getPrototypeOf,Xd=Object.prototype.hasOwnProperty;var Qd=(e,t)=>()=>(e&&(t=e(e=0)),t);var ha=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ms=(e,t)=>{for(var n in t)Hr(e,n,{get:t[n],enumerable:!0})},ya=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Yd(t))!Xd.call(e,o)&&o!==n&&Hr(e,o,{get:()=>t[o],enumerable:!(r=Jd(t,o))||r.enumerable});return e};var E=(e,t,n)=>(n=e!=null?zd(Zd(e)):{},ya(t||!e||!e.__esModule?Hr(n,"default",{value:e,enumerable:!0}):n,e)),em=e=>ya(Hr({},"__esModule",{value:!0}),e);var nr=ha((Rb,pm)=>{pm.exports={name:"@visa/cli",version:"2.7.1-rc.6",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.1","@typescript-eslint/eslint-plugin":"^8.60.1","@typescript-eslint/parser":"^8.60.0","@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.11",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","native/visa-keychain-win.cpp","native/build-win.bat","native/bin/win32-x64/visa-keychain-win.exe","server.json","README.md","LICENSE"]}});var Rr=ha(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.micros=ah;ie.fromCents=ch;ie.fromUsdc=lh;ie.fromUsd=uh;ie.toCents=dh;ie.toCentsForAcquirer=mh;ie.toUsdc=ph;ie.toWire=fh;ie.fromWire=gh;ie.toDisplay=hh;ie.toUsdRounded2dp=yh;ie.add=_h;ie.sub=bh;ie.clampNonNegative=vh;ie.isNonNegative=Sh;ie.max=wh;ie.min=xh;var gt=10000n,cu=1000000n;function ah(e){return e}function ch(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*gt}function lh(e){return e}function uh(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function dh(e){if(e>=0n)return Number(e/gt);let t=e/gt,n=e%gt;return Number(n===0n?t:t-1n)}function mh(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/gt)}function ph(e){return e}function fh(e){return e.toString()}function gh(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 hh(e,t={}){let n=t.decimals??2,r=t.symbol??"$",o=e<0n,s=o?-e:e,i=s/cu,a=s%cu,c=o?"-":"";if(n===0)return`${c}${r}${i.toString()}`;let l=a.toString().padStart(6,"0").slice(0,n);return`${c}${r}${i.toString()}.${l}`}function yh(e){let t=e<0n,n=t?-e:e,r=n/gt,s=n%gt*2n,i;s<gt?i=r:s>gt?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function _h(e,t){return e+t}function bh(e,t){return e-t}function vh(e){return e<0n?0n:e}function Sh(e){return e>=0n}function wh(e,t){return e>t?e:t}function xh(e,t){return e<t?e:t}});var ss={};ms(ss,{initSentry:()=>N_,isSentryConfigured:()=>M_,reportFatal:()=>L_});function M_(){return!1}async function N_(){return null}async function L_(e,t){process.exit(t?.exitCode??1)}var is=Qd(()=>{});var wb={};ms(wb,{printGroupHelpAndExit:()=>Ve});module.exports=em(wb);var kd=require("commander"),cs=E(require("crypto")),Y=E(require("fs")),z=E(require("os")),Pe=E(require("path")),Cd=require("child_process"),ra=require("node:readline/promises"),Td=require("util");var Kr=require("child_process"),Ea=require("util"),St=E(require("fs")),Gr=E(require("os")),_s=E(require("path"));var Sa=E(require("crypto"));var rt="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";var wa="VISA_ALLOW_INSECURE_MOCKS",_a,ba,va;function ps(e){return`${e}-${Sa.randomBytes(24).toString("base64url")}`}function xa(e=process.env){return e.NODE_ENV==="test"||e[wa]==="true"}function bt(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&xa(e)}function Tn(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&xa(e)}function fs(){return`Set ${wa}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function ka(){return _a??=ps("mock-session"),_a}function Ca(e=process.env){return e.NODE_ENV==="test"?rt:(ba??=ps("mock-rc"),ba)}function Ta(){return va??=ps("mock-signature"),va}var He=(0,Ea.promisify)(Kr.execFile),bs=_s.join(Gr.homedir(),".visa-mcp"),tr=_s.join(bs,"session-token"),Ae="visa-cli",vt="session-token",qr="rc-access",tm=5e3,Br=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function nm(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
2
+ `)}function Aa(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=nm(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function rm(){try{let{stdout:e}=await He("security",["find-generic-password","-s",Ae,"-a",vt,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(Aa(e))throw new Br("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 om(e){try{try{await He("security",["delete-generic-password","-s",Ae,"-a",vt],{timeout:5e3})}catch{}return await He("security",["add-generic-password","-s",Ae,"-a",vt,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function sm(){try{await He("security",["delete-generic-password","-s",Ae,"-a",vt],{timeout:5e3})}catch{}}async function im(){if(!vs())return null;try{let{stdout:e}=await He("secret-tool",["lookup","service",Ae,"account",vt],{timeout:5e3});return e.trim()||null}catch{return null}}async function am(e){if(!vs())return!1;try{let t=(0,Kr.execFile)("secret-tool",["store","--label",`${Ae} ${vt}`,"service",Ae,"account",vt]);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"))},tm))]),!0):!1}catch{return!1}}async function cm(){if(vs())try{await He("secret-tool",["clear","service",Ae,"account",vt],{timeout:5e3})}catch{}}function vs(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function lm(){try{let{stdout:e}=await He("security",["find-generic-password","-s",Ae,"-a",qr,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function um(e){try{try{await He("security",["delete-generic-password","-s",Ae,"-a",qr],{timeout:5e3})}catch{}await He("security",["add-generic-password","-s",Ae,"-a",qr,"-w",e],{timeout:5e3})}catch{}}async function dm(){try{await He("security",["delete-generic-password","-s",Ae,"-a",qr],{timeout:5e3})}catch{}}function hs(){try{return St.readFileSync(tr,"utf-8").trim()||null}catch(e){if(Aa(e))throw new Br(`Unable to read Visa CLI credentials from ${tr}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function Ra(e){St.mkdirSync(bs,{recursive:!0,mode:448}),St.writeFileSync(tr,e,{mode:384}),process.platform==="win32"&&mm(tr)}function ys(){try{St.unlinkSync(tr)}catch{}}function mm(e){try{let t=Gr.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 gs(){switch(process.platform){case"darwin":return{get:rm,store:om,delete:sm};case"linux":return{get:im,store:am,delete:cm};default:return{get:async()=>hs(),store:async e=>{try{return Ra(e),!0}catch{return!1}},delete:async()=>ys(),storesInSessionFile:!0}}}var F=class{static async getSessionToken(){if(bt())return Promise.resolve(ka());let t=gs(),n=await t.get();if(n)return n;let r=hs();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(bt())return;let n=gs();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||ys();return}await n.delete()}if(Ra(t),hs()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${bs} is writable.`))}static async getRcAccessToken(){return bt()?Ca():lm()}static async saveRcAccessToken(t){bt()||await um(t)}static async deleteSessionToken(){if(bt())return;await gs().delete(),ys()}static async clearAll(){await this.deleteSessionToken(),await dm()}};var Wr=E(require("crypto")),zr=E(require("tty")),Jr=E(require("fs"));function fm(e){return/-rc\.|-beta\./.test(e)}function Ss(e){return Wr.createHash("sha256").update(e.trim()).digest("hex")}function Ia(e){return rt==="SKIP"?!0:Wr.timingSafeEqual(Buffer.from(Ss(e)),Buffer.from(rt))}function gm(){try{let e=Jr.openSync("/dev/tty","r+"),t=new zr.ReadStream(e),n=new zr.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{Jr.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 hm(e){return new Promise((t,n)=>{let r;try{r=gm()}catch(u){n(u);return}let{input:o,output:s,cleanupStreams:i}=r,a=()=>{o.off("data",l);try{o.setRawMode?.(!1)}catch{}i()};s.write(e),o.setRawMode?.(!0),o.resume(),o.setEncoding("utf8");let c="",l=u=>{u==="\r"||u===`
3
3
  `?(s.write(`
4
4
  `),a(),t(c)):u===""?(s.write(`
5
- `),a(),n(new Error("Cancelled"))):u==="\x7F"||u==="\b"?c.length>0&&(c=c.slice(0,-1),s.write("\b \b")):(c+=u,s.write("\u2022"))};o.on("data",l)})}var fm=`
5
+ `),a(),n(new Error("Cancelled"))):u==="\x7F"||u==="\b"?c.length>0&&(c=c.slice(0,-1),s.write("\b \b")):(c+=u,s.write("\u2022"))};o.on("data",l)})}var ym=`
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 $a(e={}){let t=e.version??nr().version;if(!dm(t))return;let n=process.env.VISA_RC_CODE;if(n&&Ia(n)){await F.saveRcAccessToken(Ss(n));return}if(e.isMcp??!1){let i=await F.getRcAccessToken();if(i&&(rt==="SKIP"||i===rt))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
15
- `),process.exit(1)}let o=await F.getRcAccessToken();if(o&&(rt==="SKIP"||o===rt))return;console.log(fm);let s=3;for(let i=1;i<=s;i++){let a;try{a=await pm(" Enter RC access code: ")}catch{process.exit(1)}if(Ia(a)){await F.saveRcAccessToken(Ss(a)),console.log(`
14
+ `;async function $a(e={}){let t=e.version??nr().version;if(!fm(t))return;let n=process.env.VISA_RC_CODE;if(n&&Ia(n)){await F.saveRcAccessToken(Ss(n));return}if(e.isMcp??!1){let i=await F.getRcAccessToken();if(i&&(rt==="SKIP"||i===rt))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
15
+ `),process.exit(1)}let o=await F.getRcAccessToken();if(o&&(rt==="SKIP"||o===rt))return;console.log(ym);let s=3;for(let i=1;i<=s;i++){let a;try{a=await hm(" Enter RC access code: ")}catch{process.exit(1)}if(Ia(a)){await F.saveRcAccessToken(Ss(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 Yr=E(require("fs")),Pa=E(require("os")),ws=E(require("path")),gm=[{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"}}],hm=/^data:(image\/(png|jpeg|jpg|gif|webp));base64,([A-Za-z0-9+/=]+)$/;function En(e){if(typeof e!="string"||e.length===0)return null;let t=e.trim(),n=hm.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 gm)if(r.startsWith(o))return{base64:r,sig:s};return null}function rr(e,t={}){let n=t.outputDir??ws.join(Pa.tmpdir(),"visa-cli");Yr.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=ws.join(n,`${r}-${o}.${e.sig.ext}`),i=Buffer.from(e.base64,"base64");return Yr.writeFileSync(s,i,{mode:384}),{filePath:s,bytes:i.length,mime:e.sig.mime}}function ym(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 or(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 xs(e,t){if(!t||typeof t!="object")return or(e,"No result payload from tool");let n=t;if(n.success===!1)return or(e,typeof n.error=="string"?n.error:"Tool execution failed",{error_code:typeof n.error_code=="string"?n.error_code:typeof n.code=="string"?n.code:void 0,transactionId:typeof n.transactionId=="string"?n.transactionId:null});let r=Array.isArray(n.urls)?n.urls.filter(u=>typeof u=="string"):Array.isArray(n.receipt?.urls)?n.receipt.urls.filter(u=>typeof u=="string"):void 0,o=n.data&&typeof n.data=="object"?n.data:void 0,s=n.result&&typeof n.result=="object"?n.result:void 0,i=s&&Array.isArray(s.choices)?s.choices:void 0,a=i&&i[0]&&typeof i[0]=="object"?i[0]:void 0,c=a&&a.message&&typeof a.message=="object"?a.message:void 0,l;if(o&&typeof o.content=="string")l=o.content;else if(o&&typeof o.text=="string")l=o.text;else if(typeof n.content=="string")l=n.content;else if(typeof n.text=="string")l=n.text;else if(c&&typeof c.content=="string")l=c.content;else if(a&&typeof a.text=="string")l=a.text;else if(Array.isArray(n.content)&&n.content[0]&&typeof n.content[0]=="object"){let u=n.content[0].text;typeof u=="string"&&(l=u)}return ym(e,{transactionId:typeof n.transactionId=="string"?n.transactionId:void 0,amount:typeof n.amount=="number"?n.amount:void 0,currency:typeof n.currency=="string"?n.currency:void 0,merchantName:typeof n.merchantName=="string"?n.merchantName:void 0,toolId:typeof n.toolId=="string"?n.toolId:typeof n.tool_id=="string"?n.tool_id:void 0,urls:r,text:l})}var ks=require("process");async function Cs(){let e="";ks.stdin.setEncoding("utf8");for await(let t of ks.stdin)e+=t;return e.endsWith(`
22
- `)?e.slice(0,-1):e}async function Kt(e,t){if(e==="-"||t.stdin===!0&&!e){let o=(await Cs()).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 Zr(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 La=E(require("fs")),Xr=E(require("path"));var St=class extends Error{constructor(t){super(t),this.name="FromStdinFieldError"}},Oa=new Set;function _m(e){Oa.add(e)}function Ma(e){return Oa.has(e)}function Na(e,t){if(!t.startsWith("."))throw new St(`--from-stdin path must start with "." (got: "${t}")`);let n=vm(t),r=e;for(let s of n){if(r==null)throw new St(`--from-stdin path "${t}" failed: hit ${r===null?"null":"undefined"} at segment "${s}"`);if(typeof r!="object")throw new St(`--from-stdin path "${t}" failed: cannot descend into primitive at segment "${s}"`);if(typeof s=="number"){if(!Array.isArray(r))throw new St(`--from-stdin path "${t}" failed: expected array at segment [${s}], got object`);r=r[s]}else r=r[s]}if(r==null)throw new St(`--from-stdin path "${t}" resolved to ${r===null?"null":"undefined"}`);if(typeof r=="object")throw new St(`--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 _m(o),o}function vm(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 Ts=class extends Error{constructor(t){super(t),this.name="FileShorthandStdinSourceError"}};async function Da(e){if(e===void 0)return;if(!e.startsWith("@"))return e;if(Ma(e))throw new Ts("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("~")?Xr.join(process.env.HOME??"",t.slice(1)):Xr.resolve(process.cwd(),t),r=await La.promises.readFile(n,"utf8");return r.endsWith(`
23
- `)?r.slice(0,-1):r}var sr=require("process"),wt=["json","yaml","tsv","table"];function Qr(e){return wt.includes(e)}function ir(e,t){switch(t){case"json":sr.stdout.write(JSON.stringify(e)+`
24
- `);return;case"yaml":sr.stdout.write(bm(e)+`
25
- `);return;case"tsv":sr.stdout.write(Sm(e)+`
26
- `);return;case"table":sr.stdout.write(wm(e)+`
27
- `);return}}function bm(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(` - ${Ua(o)}`)}else r!==null&&typeof r=="object"?t.push(`${n}: ${JSON.stringify(r)}`):t.push(`${n}: ${Ua(r)}`);return t.join(`
28
- `)}function Ua(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 Sm(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 wm(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 Fa=require("child_process");function Es(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 xm(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 ar(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 Va(e,t){let n=ar(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 Ha(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 qa(e,t=process.platform){let n=ar(e);return n?Ha(n,t):null}function ja(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function As(e,t={}){let n=t.log??(l=>console.log(l)),r=t.env??process.env,o=t.platform??process.platform,s=ar(e),i=t.spawn??((l,u,d)=>{(0,Fa.execFile)(l,u,f=>d(f))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let l of xm(s??e).split(`
32
- `))n(` ${l}`);if(n(""),!s){n(" (Auth URL is not a valid absolute http(s) URL \u2014 skipping browser auto-open.)"),n(" Open the URL above manually to continue."),n("");return}let a=Es(r,o);if(a.headless){n(` (${a.reason} \u2014 skipping browser auto-open.)`),n(" Open the URL above on any device with a browser. The CLI will"),n(" continue waiting for you to complete sign-in."),n("");return}let c=Ha(s,o);if(!c){n(` No known browser-open command for platform "${o}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(l=>{let u=d=>{d?ja(n,d):(n(" Opened browser. Waiting for you to sign in..."),n("")),l()};try{i(c.cmd,c.args,u)}catch(d){ja(n,d instanceof Error?d:new Error(String(d))),l()}})}function km(e){return new Promise(t=>setTimeout(t,e))}function Ba(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 Ka(e){return!Number.isFinite(e)||e===null||e<=0?1e3:Math.min(Math.max(Math.ceil(e),1e3),3e4)}async function Cm(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=Ba(e.headers?.get("Retry-After"));if(r!==null)return n(Ka(r));if(typeof e.json=="function")try{let o=await e.json();return n(Ka(Ba(o?.retryAfter)))}catch{return n(1e3)}return n(1e3)}async function xt(e,t){let n=await Cm(e);return t?.(n),await km(n),n}var uc=E(require("crypto")),dc=require("child_process"),ae=E(require("fs")),mc=E(require("os")),he=E(require("path"));var V=E(require("fs")),zt=E(require("os")),q=E(require("path")),Xa=require("child_process"),$s=require("crypto");var Rn=E(require("fs")),eo=E(require("tty"));function Wa(e=process.env){let t=(e.COLORTERM??"").toLowerCase();if(t==="truecolor"||t==="24bit")return!0;let n=(e.TERM??"").toLowerCase();return n.includes("truecolor")||n.includes("24bit")}function za(e,t){let n=(o,s,i)=>`\x1B[38;2;${o};${s};${i}m`,r=o=>`\x1B[38;5;${o}m`;return e==="light"?{reset:"\x1B[0m",visaBlue:t?n(20,52,203):r(26),visaBlueSoft:t?n(11,78,162):r(25),visaGold:t?n(122,82,0):r(94),green:t?n(15,107,47):r(22),muted:t?n(92,100,112):r(241),chrome:t?n(138,138,138):r(245)}:{reset:"\x1B[0m",visaBlue:t?n(168,184,255):r(153),visaBlueSoft:t?n(127,149,242):r(111),visaGold:t?n(255,210,74):r(221),green:t?n(86,211,100):r(77),muted:t?n(199,205,215):r(251),chrome:t?n(110,118,129):r(243)}}function Ja(e){if(!e)return null;let t=e.split(";");if(t.length<2)return null;let n=t[t.length-1].trim();if(n==="0")return"dark";if(n==="7"||n==="15")return"light";let r=Number(n);return Number.isInteger(r)&&r>=0&&r<=255?r<=6||r>=232&&r<=243?"dark":"light":null}function Ga(e){let t=/rgb:([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})/.exec(e);if(!t)return null;let n=i=>{let a=parseInt(i,16),c=(1<<i.length*4)-1;return c>0?a/c:0},r=n(t[1]),o=n(t[2]),s=n(t[3]);return[r,o,s].some(i=>!Number.isFinite(i))?null:.299*r+.587*o+.114*s}var Tm=80,Em="/dev/tty";function Am(e=Em){if(process.platform==="win32")return null;let t,n;try{t=Rn.openSync(e,"r"),n=Rn.openSync(e,"w");let r=new eo.ReadStream(t),o=new eo.WriteStream(n);return{stdin:r,stdout:o,close:()=>{try{r.destroy?.()}catch{}try{o.destroy?.()}catch{}}}}catch{try{t!==void 0&&Rn.closeSync(t)}catch{}try{n!==void 0&&Rn.closeSync(n)}catch{}return null}}function Rm(e){let t={stdin:e.stdin??process.stdin,stdout:e.stdout??process.stdout};if(t.stdout.isTTY&&t.stdin.isTTY&&typeof t.stdin.setRawMode=="function")return t;let n=e.stdin!==void 0||e.stdout!==void 0;if(!(e.allowControllingTerminal??!n))return null;let s=(e.openControllingTerminal??Am)(e.ttyPath);return s?.stdout.isTTY&&s.stdin.isTTY&&typeof s.stdin.setRawMode=="function"?s:(s?.close?.(),null)}async function Im(e={}){let t=Rm(e);if(!t)return null;let{stdin:n,stdout:r}=t,o=e.timeoutMs??Tm,s=e.setTimeoutFn??((a,c)=>setTimeout(a,c)),i=e.clearTimeoutFn??(a=>clearTimeout(a));return new Promise(a=>{let c=!1,l="",u=n.isRaw===!0,d=S=>{l+=typeof S=="string"?S:S.toString("utf-8");let $=Ga(l),H=l.includes("\x07")||l.includes("\x1B\\");$!==null&&H&&m($>.5?"light":"dark")},f=()=>{try{n.removeListener("data",d)}catch{}try{i(y)}catch{}try{!u&&typeof n.setRawMode=="function"&&n.setRawMode(!1)}catch{}try{n.pause?.()}catch{}try{n.unref?.()}catch{}try{t.close?.()}catch{}},m=S=>{c||(c=!0,f(),a(S))},y=s(()=>{let S=Ga(l);m(S!==null?S>.5?"light":"dark":null)},o);try{u||n.setRawMode?.(!0),n.resume?.(),n.on("data",d),r.write("\x1B]11;?\x1B\\")}catch{m(null)}})}var Gt,cr;function $m(e){if((e.NO_COLOR??"")!=="")return"no-color";let t=(e.VISA_CLI_HUD_THEME??"").toLowerCase().trim();if(t==="light")return"light";if(t==="dark")return"dark";let n=Ja(e.COLORFGBG);return n||"dark"}function to(e=process.env){return Gt!==void 0||(Gt=$m(e)),Gt}function de(e=process.env){if(cr!==void 0)return cr;let t=to(e),n=Wa(e);return cr=za(t==="light"?"light":"dark",n),cr}function no(e=process.env){return to(e)==="no-color"}async function Rs(e={}){if(Gt!==void 0)return Gt;let t=e.env??process.env;if((t.NO_COLOR??"")!=="")return An("no-color",t);let n=(t.VISA_CLI_HUD_THEME??"").toLowerCase().trim();if(n==="light")return An("light",t);if(n==="dark")return An("dark",t);let r=Ja(t.COLORFGBG);if(r)return An(r,t);let o=await Im(e);return An(o||"dark",t)}function An(e,t){Gt=e;let n=Wa(t);return cr=za(e==="light"?"light":"dark",n),e}var Pm=2,ro="# >>> visa-cli shell hud v2 >>>",oo="# <<< visa-cli shell hud v2 <<<",Om="# >>> visa-cli shell hud >>>",Mm="# <<< visa-cli shell hud <<<",Qa=3e4,Nm=6e4,Lm="VISA | HUD not ready \u2014 run: visa-cli config hud doctor",Dm={currentVersion:"0.0.0"},Um=15e3;function Ps(){try{return q.join(Ns(),".visa-cli")}catch{return q.join(zt.tmpdir(),".visa-cli")}}function kt(){return q.join(Ps(),"shell-hud.json")}function lr(){return q.join(Ps(),"shell-hud.line")}function ec(){return q.join(Ps(),"shell-hud.lock")}function Pn(e){let t=e??process.env.SHELL;if(!t)return null;let n=q.basename(t.replace(/\\/g,"/")).toLowerCase();return n==="zsh"?"zsh":n==="bash"?"bash":n==="pwsh"||n==="pwsh.exe"||n==="powershell"||n==="powershell.exe"?"powershell":null}function ur(e){let t=Ns();if(e==="zsh")return q.join(t,".zshrc");if(e==="bash")return q.join(t,".bashrc");let n=(process.platform==="win32","PowerShell");return q.join(t,"Documents",n,"Microsoft.PowerShell_profile.ps1")}function tc(e,t){let n=t??Ns(),r=[{shell:"zsh",rcPath:q.join(n,".zshrc")},{shell:"bash",rcPath:q.join(n,".bashrc")},{shell:"bash",rcPath:q.join(n,".bash_profile")},{shell:"powershell",rcPath:q.join(n,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:q.join(n,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:q.join(n,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:q.join(n,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:q.join(n,".config","powershell","Microsoft.PowerShell_profile.ps1")}];if(!e)return r;let o=r.filter(i=>i.shell===e),s=r.filter(i=>i.shell!==e);return[...o,...s]}function jm(e){let t="$HOME/.visa-cli/shell-hud.line",n=rp(e),r=op(e);if(e==="zsh")return`${ro}
21
+ `),process.exit(1)}var Yr=E(require("fs")),Pa=E(require("os")),ws=E(require("path")),_m=[{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"}}],bm=/^data:(image\/(png|jpeg|jpg|gif|webp));base64,([A-Za-z0-9+/=]+)$/;function En(e){if(typeof e!="string"||e.length===0)return null;let t=e.trim(),n=bm.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 _m)if(r.startsWith(o))return{base64:r,sig:s};return null}function rr(e,t={}){let n=t.outputDir??ws.join(Pa.tmpdir(),"visa-cli");Yr.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=ws.join(n,`${r}-${o}.${e.sig.ext}`),i=Buffer.from(e.base64,"base64");return Yr.writeFileSync(s,i,{mode:384}),{filePath:s,bytes:i.length,mime:e.sig.mime}}function vm(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 or(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 xs(e,t){if(!t||typeof t!="object")return or(e,"No result payload from tool");let n=t;if(n.success===!1)return or(e,typeof n.error=="string"?n.error:"Tool execution failed",{error_code:typeof n.error_code=="string"?n.error_code:typeof n.code=="string"?n.code:void 0,transactionId:typeof n.transactionId=="string"?n.transactionId:null});let r=Array.isArray(n.urls)?n.urls.filter(u=>typeof u=="string"):Array.isArray(n.receipt?.urls)?n.receipt.urls.filter(u=>typeof u=="string"):void 0,o=n.data&&typeof n.data=="object"?n.data:void 0,s=n.result&&typeof n.result=="object"?n.result:void 0,i=s&&Array.isArray(s.choices)?s.choices:void 0,a=i&&i[0]&&typeof i[0]=="object"?i[0]:void 0,c=a&&a.message&&typeof a.message=="object"?a.message:void 0,l;if(o&&typeof o.content=="string")l=o.content;else if(o&&typeof o.text=="string")l=o.text;else if(typeof n.content=="string")l=n.content;else if(typeof n.text=="string")l=n.text;else if(c&&typeof c.content=="string")l=c.content;else if(a&&typeof a.text=="string")l=a.text;else if(Array.isArray(n.content)&&n.content[0]&&typeof n.content[0]=="object"){let u=n.content[0].text;typeof u=="string"&&(l=u)}return vm(e,{transactionId:typeof n.transactionId=="string"?n.transactionId:void 0,amount:typeof n.amount=="number"?n.amount:void 0,currency:typeof n.currency=="string"?n.currency:void 0,merchantName:typeof n.merchantName=="string"?n.merchantName:void 0,toolId:typeof n.toolId=="string"?n.toolId:typeof n.tool_id=="string"?n.tool_id:void 0,urls:r,text:l})}var ks=require("process");async function Cs(){let e="";ks.stdin.setEncoding("utf8");for await(let t of ks.stdin)e+=t;return e.endsWith(`
22
+ `)?e.slice(0,-1):e}async function Kt(e,t){if(e==="-"||t.stdin===!0&&!e){let o=(await Cs()).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 Zr(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 La=E(require("fs")),Xr=E(require("path"));var wt=class extends Error{constructor(t){super(t),this.name="FromStdinFieldError"}},Oa=new Set;function Sm(e){Oa.add(e)}function Ma(e){return Oa.has(e)}function Na(e,t){if(!t.startsWith("."))throw new wt(`--from-stdin path must start with "." (got: "${t}")`);let n=wm(t),r=e;for(let s of n){if(r==null)throw new wt(`--from-stdin path "${t}" failed: hit ${r===null?"null":"undefined"} at segment "${s}"`);if(typeof r!="object")throw new wt(`--from-stdin path "${t}" failed: cannot descend into primitive at segment "${s}"`);if(typeof s=="number"){if(!Array.isArray(r))throw new wt(`--from-stdin path "${t}" failed: expected array at segment [${s}], got object`);r=r[s]}else r=r[s]}if(r==null)throw new wt(`--from-stdin path "${t}" resolved to ${r===null?"null":"undefined"}`);if(typeof r=="object")throw new wt(`--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 Sm(o),o}function wm(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 Ts=class extends Error{constructor(t){super(t),this.name="FileShorthandStdinSourceError"}};async function Da(e){if(e===void 0)return;if(!e.startsWith("@"))return e;if(Ma(e))throw new Ts("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("~")?Xr.join(process.env.HOME??"",t.slice(1)):Xr.resolve(process.cwd(),t),r=await La.promises.readFile(n,"utf8");return r.endsWith(`
23
+ `)?r.slice(0,-1):r}var sr=require("process"),xt=["json","yaml","tsv","table"];function Qr(e){return xt.includes(e)}function ir(e,t){switch(t){case"json":sr.stdout.write(JSON.stringify(e)+`
24
+ `);return;case"yaml":sr.stdout.write(xm(e)+`
25
+ `);return;case"tsv":sr.stdout.write(km(e)+`
26
+ `);return;case"table":sr.stdout.write(Cm(e)+`
27
+ `);return}}function xm(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(` - ${Ua(o)}`)}else r!==null&&typeof r=="object"?t.push(`${n}: ${JSON.stringify(r)}`):t.push(`${n}: ${Ua(r)}`);return t.join(`
28
+ `)}function Ua(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 km(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 Cm(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 Fa=require("child_process");function Es(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 Tm(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 ar(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 Va(e,t){let n=ar(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 Ha(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 qa(e,t=process.platform){let n=ar(e);return n?Ha(n,t):null}function ja(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function As(e,t={}){let n=t.log??(l=>console.log(l)),r=t.env??process.env,o=t.platform??process.platform,s=ar(e),i=t.spawn??((l,u,d)=>{(0,Fa.execFile)(l,u,f=>d(f))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let l of Tm(s??e).split(`
32
+ `))n(` ${l}`);if(n(""),!s){n(" (Auth URL is not a valid absolute http(s) URL \u2014 skipping browser auto-open.)"),n(" Open the URL above manually to continue."),n("");return}let a=Es(r,o);if(a.headless){n(` (${a.reason} \u2014 skipping browser auto-open.)`),n(" Open the URL above on any device with a browser. The CLI will"),n(" continue waiting for you to complete sign-in."),n("");return}let c=Ha(s,o);if(!c){n(` No known browser-open command for platform "${o}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(l=>{let u=d=>{d?ja(n,d):(n(" Opened browser. Waiting for you to sign in..."),n("")),l()};try{i(c.cmd,c.args,u)}catch(d){ja(n,d instanceof Error?d:new Error(String(d))),l()}})}function Em(e){return new Promise(t=>setTimeout(t,e))}function Ba(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 Ka(e){return!Number.isFinite(e)||e===null||e<=0?1e3:Math.min(Math.max(Math.ceil(e),1e3),3e4)}async function Am(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=Ba(e.headers?.get("Retry-After"));if(r!==null)return n(Ka(r));if(typeof e.json=="function")try{let o=await e.json();return n(Ka(Ba(o?.retryAfter)))}catch{return n(1e3)}return n(1e3)}async function kt(e,t){let n=await Am(e);return t?.(n),await Em(n),n}var uc=E(require("crypto")),dc=require("child_process"),ce=E(require("fs")),mc=E(require("os")),he=E(require("path"));var V=E(require("fs")),zt=E(require("os")),q=E(require("path")),Xa=require("child_process"),$s=require("crypto");var Rn=E(require("fs")),eo=E(require("tty"));function Wa(e=process.env){let t=(e.COLORTERM??"").toLowerCase();if(t==="truecolor"||t==="24bit")return!0;let n=(e.TERM??"").toLowerCase();return n.includes("truecolor")||n.includes("24bit")}function za(e,t){let n=(o,s,i)=>`\x1B[38;2;${o};${s};${i}m`,r=o=>`\x1B[38;5;${o}m`;return e==="light"?{reset:"\x1B[0m",visaBlue:t?n(20,52,203):r(26),visaBlueSoft:t?n(11,78,162):r(25),visaGold:t?n(122,82,0):r(94),green:t?n(15,107,47):r(22),muted:t?n(92,100,112):r(241),chrome:t?n(138,138,138):r(245)}:{reset:"\x1B[0m",visaBlue:t?n(168,184,255):r(153),visaBlueSoft:t?n(127,149,242):r(111),visaGold:t?n(255,210,74):r(221),green:t?n(86,211,100):r(77),muted:t?n(199,205,215):r(251),chrome:t?n(110,118,129):r(243)}}function Ja(e){if(!e)return null;let t=e.split(";");if(t.length<2)return null;let n=t[t.length-1].trim();if(n==="0")return"dark";if(n==="7"||n==="15")return"light";let r=Number(n);return Number.isInteger(r)&&r>=0&&r<=255?r<=6||r>=232&&r<=243?"dark":"light":null}function Ga(e){let t=/rgb:([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})/.exec(e);if(!t)return null;let n=i=>{let a=parseInt(i,16),c=(1<<i.length*4)-1;return c>0?a/c:0},r=n(t[1]),o=n(t[2]),s=n(t[3]);return[r,o,s].some(i=>!Number.isFinite(i))?null:.299*r+.587*o+.114*s}var Rm=80,Im="/dev/tty";function $m(e=Im){if(process.platform==="win32")return null;let t,n;try{t=Rn.openSync(e,"r"),n=Rn.openSync(e,"w");let r=new eo.ReadStream(t),o=new eo.WriteStream(n);return{stdin:r,stdout:o,close:()=>{try{r.destroy?.()}catch{}try{o.destroy?.()}catch{}}}}catch{try{t!==void 0&&Rn.closeSync(t)}catch{}try{n!==void 0&&Rn.closeSync(n)}catch{}return null}}function Pm(e){let t={stdin:e.stdin??process.stdin,stdout:e.stdout??process.stdout};if(t.stdout.isTTY&&t.stdin.isTTY&&typeof t.stdin.setRawMode=="function")return t;let n=e.stdin!==void 0||e.stdout!==void 0;if(!(e.allowControllingTerminal??!n))return null;let s=(e.openControllingTerminal??$m)(e.ttyPath);return s?.stdout.isTTY&&s.stdin.isTTY&&typeof s.stdin.setRawMode=="function"?s:(s?.close?.(),null)}async function Om(e={}){let t=Pm(e);if(!t)return null;let{stdin:n,stdout:r}=t,o=e.timeoutMs??Rm,s=e.setTimeoutFn??((a,c)=>setTimeout(a,c)),i=e.clearTimeoutFn??(a=>clearTimeout(a));return new Promise(a=>{let c=!1,l="",u=n.isRaw===!0,d=S=>{l+=typeof S=="string"?S:S.toString("utf-8");let $=Ga(l),H=l.includes("\x07")||l.includes("\x1B\\");$!==null&&H&&m($>.5?"light":"dark")},f=()=>{try{n.removeListener("data",d)}catch{}try{i(_)}catch{}try{!u&&typeof n.setRawMode=="function"&&n.setRawMode(!1)}catch{}try{n.pause?.()}catch{}try{n.unref?.()}catch{}try{t.close?.()}catch{}},m=S=>{c||(c=!0,f(),a(S))},_=s(()=>{let S=Ga(l);m(S!==null?S>.5?"light":"dark":null)},o);try{u||n.setRawMode?.(!0),n.resume?.(),n.on("data",d),r.write("\x1B]11;?\x1B\\")}catch{m(null)}})}var Gt,cr;function Mm(e){if((e.NO_COLOR??"")!=="")return"no-color";let t=(e.VISA_CLI_HUD_THEME??"").toLowerCase().trim();if(t==="light")return"light";if(t==="dark")return"dark";let n=Ja(e.COLORFGBG);return n||"dark"}function to(e=process.env){return Gt!==void 0||(Gt=Mm(e)),Gt}function de(e=process.env){if(cr!==void 0)return cr;let t=to(e),n=Wa(e);return cr=za(t==="light"?"light":"dark",n),cr}function no(e=process.env){return to(e)==="no-color"}async function Rs(e={}){if(Gt!==void 0)return Gt;let t=e.env??process.env;if((t.NO_COLOR??"")!=="")return An("no-color",t);let n=(t.VISA_CLI_HUD_THEME??"").toLowerCase().trim();if(n==="light")return An("light",t);if(n==="dark")return An("dark",t);let r=Ja(t.COLORFGBG);if(r)return An(r,t);let o=await Om(e);return An(o||"dark",t)}function An(e,t){Gt=e;let n=Wa(t);return cr=za(e==="light"?"light":"dark",n),e}var Nm=2,ro="# >>> visa-cli shell hud v2 >>>",oo="# <<< visa-cli shell hud v2 <<<",Lm="# >>> visa-cli shell hud >>>",Dm="# <<< visa-cli shell hud <<<",Qa=3e4,Um=6e4,jm="VISA | HUD not ready \u2014 run: visa-cli config hud doctor",Fm={currentVersion:"0.0.0"},Vm=15e3;function Ps(){try{return q.join(Ns(),".visa-cli")}catch{return q.join(zt.tmpdir(),".visa-cli")}}function Ct(){return q.join(Ps(),"shell-hud.json")}function lr(){return q.join(Ps(),"shell-hud.line")}function ec(){return q.join(Ps(),"shell-hud.lock")}function Pn(e){let t=e??process.env.SHELL;if(!t)return null;let n=q.basename(t.replace(/\\/g,"/")).toLowerCase();return n==="zsh"?"zsh":n==="bash"?"bash":n==="pwsh"||n==="pwsh.exe"||n==="powershell"||n==="powershell.exe"?"powershell":null}function ur(e){let t=Ns();if(e==="zsh")return q.join(t,".zshrc");if(e==="bash")return q.join(t,".bashrc");let n=(process.platform==="win32","PowerShell");return q.join(t,"Documents",n,"Microsoft.PowerShell_profile.ps1")}function tc(e,t){let n=t??Ns(),r=[{shell:"zsh",rcPath:q.join(n,".zshrc")},{shell:"bash",rcPath:q.join(n,".bashrc")},{shell:"bash",rcPath:q.join(n,".bash_profile")},{shell:"powershell",rcPath:q.join(n,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:q.join(n,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:q.join(n,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:q.join(n,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:q.join(n,".config","powershell","Microsoft.PowerShell_profile.ps1")}];if(!e)return r;let o=r.filter(i=>i.shell===e),s=r.filter(i=>i.shell!==e);return[...o,...s]}function Hm(e){let t="$HOME/.visa-cli/shell-hud.line",n=ip(e),r=ap(e);if(e==="zsh")return`${ro}
33
33
  _visa_cli_shell_hud_precmd() {
34
34
  setopt localoptions no_bg_nice
35
35
  if [[ -f "${t}" ]]; then
@@ -82,51 +82,51 @@ 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
- ${oo}`}function Fm(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 Vm(e,t,n){let r=new RegExp(`(^|\\n)([ \\t]*${Za(t)}[ \\t]*\\r?\\n)([\\s\\S]*?)(\\r?\\n[ \\t]*${Za(n)}[ \\t]*)(?=\\r?\\n|$)(\\r?\\n)?`,"g");return e.replace(r,(o,s,i,a,c,l,u)=>{if(!Fm(a))return o;let d=u>0?e[u-1]:"";return s===`
85
+ ${oo}`}function qm(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 Bm(e,t,n){let r=new RegExp(`(^|\\n)([ \\t]*${Za(t)}[ \\t]*\\r?\\n)([\\s\\S]*?)(\\r?\\n[ \\t]*${Za(n)}[ \\t]*)(?=\\r?\\n|$)(\\r?\\n)?`,"g");return e.replace(r,(o,s,i,a,c,l,u)=>{if(!qm(a))return o;let d=u>0?e[u-1]:"";return s===`
86
86
  `&&d!==`
87
87
  `?`
88
- `:""})}function dr(e){let t=e;for(let[n,r]of[[ro,oo],[Om,Mm]])t=Vm(t,n,r);return t.trimEnd()}function nc(e){return dr(e)!==e.trimEnd()}function Hm(e,t){let n=dr(e).trimEnd(),r=jm(t);return n.length>0?`${n}
88
+ `:""})}function dr(e){let t=e;for(let[n,r]of[[ro,oo],[Lm,Dm]])t=Bm(t,n,r);return t.trimEnd()}function nc(e){return dr(e)!==e.trimEnd()}function Km(e,t){let n=dr(e).trimEnd(),r=Hm(t);return n.length>0?`${n}
89
89
 
90
90
  ${r}
91
91
  `:`${r}
92
- `}function so(e=Pn()){if(!e)return!1;try{let t=ur(e),n=V.readFileSync(t,"utf-8");return nc(n)}catch{return!1}}function Jt(e=zt.homedir()){let t=[],n=qm(e);for(let r of n)try{if(!V.existsSync(r))continue;let o=V.readFileSync(r,"utf-8");nc(o)&&t.push(r)}catch{}return t}function qm(e){return tc(null,e).map(t=>t.rcPath)}function io(e=Pn()){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=ur(e);let n=V.existsSync(t)?V.readFileSync(t,"utf-8"):"",r=Hm(n,e),o=r!==n;return o&&$n(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}: ${Is(n)}`}}}function ot(e=Pn(),t){let n=[],r=[],o=[];try{for(let s of tc(e,t))if(r.push(s.rcPath),!!V.existsSync(s.rcPath))try{let i=V.readFileSync(s.rcPath,"utf-8"),a=dr(i);if(a===i.trimEnd())continue;$n(s.rcPath,a.length>0?`${a}
93
- `:""),n.push(s.rcPath)}catch(i){o.push(`${s.rcPath}: ${Is(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: ${Is(s)}`}}}function Os(e,t){let n=t??Dm,r=n.currentVersion==="0.0.0"&&e.version?e.version:n.currentVersion,o=Ct(r),s=` ${G("\u2502",B.chrome)} `,i=rc(n),a=zm(n,i),c=n.updateCheckDisabled?"":i,l=Wm(o,c);if(!e.enrolled)return[l,G("setup needed",B.visaGold),a].filter(Boolean).join(s);let u=np(e),d=Gm(e),f=Ct(zt.hostname().split(".")[0]),m=[l,f?G(f,B.muted):"",G(u,B.visaGold),a].filter(Boolean).join(s),y=[d,Bm(e)].filter(Boolean),S=y.length>0?y.join(s):"";return S?`${m}
94
- ${S}`:m}function Bm(e){let t=` ${G("\u2502",B.chrome)} `,n=[],r=e.dailyCardFundedTopupSpent??e.dailySpent;if(typeof r=="number"&&Number.isFinite(r)){let o=Math.max(0,r);n.push(G(`top-ups today ${In(o)}`,B.muted))}if(e.lastService&&typeof e.lastService.toolName=="string"&&e.lastService.toolName.length>0){let o=tp(Ct(e.lastService.toolName)),s=Km(e.lastService.createdAt),i=G(s?`last ${o} ${s}`:`last ${o}`,B.muted);n.push(i)}if(typeof e.apiKeyCount=="number"&&Number.isFinite(e.apiKeyCount)){let o=Math.max(0,Math.floor(e.apiKeyCount)),s=o===1?"VISA Key":"VISA Keys";n.push(G(`${o} ${s}`,B.muted))}else e.apiKeyStatus==="rollout_locked"&&n.push(G("VISA Key \u{1F51C}",B.muted));return n.join(t)}function Km(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 Gm(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 G("balance unknown",B.muted);let r=t/100;if(n){let i=Math.max(0,n.capCents),a=Math.max(0,n.estimatedRemainingCents),c=Math.max(0,i-a),l=i>0?Math.max(0,Math.min(1,c/i)):0;return`${ep(l)} ${G(`${In(a/100)} in session`,B.green)} ${G(`(${In(c/100)}/${In(i/100)} cap)`,B.muted)} ${G("\xB7",B.chrome)} ${G(`${In(r)} balance`,B.muted)}`}let o=10,s=`balance ${In(r)}`;return t>=o?G(s,B.green):G(`${s} \u2014 top up via buy_credits`,B.visaGold)}function Wm(e,t){let n=e,r=`${G("VISA CLI",B.visaBlue)} ${G(`v${n}`,B.visaBlueSoft)}`;if(!t)return r;let o=t;return`${r} ${G("\u2B06 update",B.visaGold)} ${G(`v${o}`,B.visaGold)}`}function zm(e,t){return t&&!e.updateCheckDisabled?G("run: visa-cli update",B.visaGold):t?null:Jm(e)}function rc(e){return e.latestVersion?Ct(e.latestVersion):""}function Jm(e){let t=rc(e);return t?G(`update ready v${t}`,B.visaGold):null}function oc(){let e=mr();return!(!e||Date.now()-e.renderedAt>Qa||e.cwd&&e.cwd!==process.cwd())}function ao(){let e=mr(),t=Date.now();if(e&&t-e.renderedAt<=Qa||(Zm(),e?.line))return Ya(e.line,e,t);try{let n=lr();if(V.existsSync(n)){let r=V.readFileSync(n,"utf-8").trimEnd();if(r&&!co(r))return r}}catch{}return Lm}function Ya(e,t,n){let r=n-t.renderedAt,o=typeof t.refreshFailedAt=="number"&&t.refreshFailedAt>t.renderedAt,s=[];if(r>=Nm&&s.push(`stale ${Ym(r)}`),o&&s.push("\u26A0 refresh failed"),s.length===0)return e;let i=` ${G("\xB7",B.chrome)} ${G(s.join(" \xB7 "),B.visaGold)}`,a=e.split(`
92
+ `}function so(e=Pn()){if(!e)return!1;try{let t=ur(e),n=V.readFileSync(t,"utf-8");return nc(n)}catch{return!1}}function Jt(e=zt.homedir()){let t=[],n=Gm(e);for(let r of n)try{if(!V.existsSync(r))continue;let o=V.readFileSync(r,"utf-8");nc(o)&&t.push(r)}catch{}return t}function Gm(e){return tc(null,e).map(t=>t.rcPath)}function io(e=Pn()){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=ur(e);let n=V.existsSync(t)?V.readFileSync(t,"utf-8"):"",r=Km(n,e),o=r!==n;return o&&$n(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}: ${Is(n)}`}}}function ot(e=Pn(),t){let n=[],r=[],o=[];try{for(let s of tc(e,t))if(r.push(s.rcPath),!!V.existsSync(s.rcPath))try{let i=V.readFileSync(s.rcPath,"utf-8"),a=dr(i);if(a===i.trimEnd())continue;$n(s.rcPath,a.length>0?`${a}
93
+ `:""),n.push(s.rcPath)}catch(i){o.push(`${s.rcPath}: ${Is(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: ${Is(s)}`}}}function Os(e,t){let n=t??Fm,r=n.currentVersion==="0.0.0"&&e.version?e.version:n.currentVersion,o=Tt(r),s=` ${G("\u2502",B.chrome)} `,i=rc(n),a=Zm(n,i),c=n.updateCheckDisabled?"":i,l=Ym(o,c);if(!e.enrolled)return[l,G("setup needed",B.visaGold),a].filter(Boolean).join(s);let u=sp(e),d=Jm(e),f=Tt(zt.hostname().split(".")[0]),m=[l,f?G(f,B.muted):"",G(u,B.visaGold),a].filter(Boolean).join(s),_=[d,Wm(e)].filter(Boolean),S=_.length>0?_.join(s):"";return S?`${m}
94
+ ${S}`:m}function Wm(e){let t=` ${G("\u2502",B.chrome)} `,n=[],r=e.dailyCardFundedTopupSpent??e.dailySpent;if(typeof r=="number"&&Number.isFinite(r)){let o=Math.max(0,r);n.push(G(`top-ups today ${In(o)}`,B.muted))}if(e.lastService&&typeof e.lastService.toolName=="string"&&e.lastService.toolName.length>0){let o=op(Tt(e.lastService.toolName)),s=zm(e.lastService.createdAt),i=G(s?`last ${o} ${s}`:`last ${o}`,B.muted);n.push(i)}if(typeof e.apiKeyCount=="number"&&Number.isFinite(e.apiKeyCount)){let o=Math.max(0,Math.floor(e.apiKeyCount)),s=o===1?"VISA Key":"VISA Keys";n.push(G(`${o} ${s}`,B.muted))}else e.apiKeyStatus==="rollout_locked"&&n.push(G("VISA Key \u{1F51C}",B.muted));return n.join(t)}function zm(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 Jm(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 G("balance unknown",B.muted);let r=t/100;if(n){let i=Math.max(0,n.capCents),a=Math.max(0,n.estimatedRemainingCents),c=Math.max(0,i-a),l=i>0?Math.max(0,Math.min(1,c/i)):0;return`${rp(l)} ${G(`${In(a/100)} in session`,B.green)} ${G(`(${In(c/100)}/${In(i/100)} cap)`,B.muted)} ${G("\xB7",B.chrome)} ${G(`${In(r)} balance`,B.muted)}`}let o=10,s=`balance ${In(r)}`;return t>=o?G(s,B.green):G(`${s} \u2014 top up via buy_credits`,B.visaGold)}function Ym(e,t){let n=e,r=`${G("VISA CLI",B.visaBlue)} ${G(`v${n}`,B.visaBlueSoft)}`;if(!t)return r;let o=t;return`${r} ${G("\u2B06 update",B.visaGold)} ${G(`v${o}`,B.visaGold)}`}function Zm(e,t){return t&&!e.updateCheckDisabled?G("run: visa-cli update",B.visaGold):t?null:Xm(e)}function rc(e){return e.latestVersion?Tt(e.latestVersion):""}function Xm(e){let t=rc(e);return t?G(`update ready v${t}`,B.visaGold):null}function oc(){let e=mr();return!(!e||Date.now()-e.renderedAt>Qa||e.cwd&&e.cwd!==process.cwd())}function ao(){let e=mr(),t=Date.now();if(e&&t-e.renderedAt<=Qa||(ep(),e?.line))return Ya(e.line,e,t);try{let n=lr();if(V.existsSync(n)){let r=V.readFileSync(n,"utf-8").trimEnd();if(r&&!co(r))return r}}catch{}return jm}function Ya(e,t,n){let r=n-t.renderedAt,o=typeof t.refreshFailedAt=="number"&&t.refreshFailedAt>t.renderedAt,s=[];if(r>=Um&&s.push(`stale ${Qm(r)}`),o&&s.push("\u26A0 refresh failed"),s.length===0)return e;let i=` ${G("\xB7",B.chrome)} ${G(s.join(" \xB7 "),B.visaGold)}`,a=e.split(`
95
95
  `);for(let c=a.length-1;c>=0;c--)if(a[c].length>0)return a[c]=`${a[c]}${i}`,a.join(`
96
- `);return`${e}${i}`}function Ym(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 Ms(e,t){try{let n=q.dirname(kt());V.mkdirSync(n,{recursive:!0});let r=e.split(`
97
- `).map(s=>Qm(s)).filter(s=>s.length>0).join(`
98
- `),o={hudVersion:Pm,renderedAt:Date.now(),line:r,cwd:process.cwd(),status:t};$n(kt(),JSON.stringify(o)+`
96
+ `);return`${e}${i}`}function Qm(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 Ms(e,t){try{let n=q.dirname(Ct());V.mkdirSync(n,{recursive:!0});let r=e.split(`
97
+ `).map(s=>np(s)).filter(s=>s.length>0).join(`
98
+ `),o={hudVersion:Nm,renderedAt:Date.now(),line:r,cwd:process.cwd(),status:t};$n(Ct(),JSON.stringify(o)+`
99
99
  `),$n(lr(),r+`
100
- `)}catch{}}function sc(e){try{let t=mr();if(!t)return;let n=Math.max(Date.now(),t.renderedAt+1),r={...t,refreshFailedAt:n,refreshErrorReason:Ct(e).slice(0,200)};$n(kt(),JSON.stringify(r)+`
101
- `)}catch{}}function ic(){try{let e=mr();if(!e)return;let t={...e,renderedAt:0};$n(kt(),JSON.stringify(t)+`
102
- `)}catch{}}function Wt(){try{V.unlinkSync(ec())}catch{}}function mr(){let e=kt();if(!V.existsSync(e))return null;try{let t=JSON.parse(V.readFileSync(e,"utf-8"));return typeof t?.line=="string"&&co(t.line)?null:t}catch{return null}}function co(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 ac(){return mr()?.status??null}function Zm(){if(process.env.JEST_WORKER_ID)return;let e=ec();try{if(V.mkdirSync(q.dirname(e),{recursive:!0}),!sp(e))return;let t=process.argv[1]?q.resolve(process.argv[1]):"";if(!t){Wt();return}let n=to(),r=(process.env.VISA_CLI_HUD_THEME??"").toLowerCase().trim(),o=n==="no-color"||r==="light"||r==="dark"?{}:{VISA_CLI_HUD_THEME:n},s=(0,Xa.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,...o,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});s.once("error",Wt),s.unref()}catch{Wt()}}function Ct(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim()}var Xm=/^\u001B\[(?:0|38;2;\d{1,3};\d{1,3};\d{1,3}|38;5;\d{1,3})m$/;function Qm(e){let t=[],n=`__VISA_CLI_HUD_SGR_${(0,$s.randomBytes)(8).toString("hex")}_`,r=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,s=>{if(!Xm.test(s))return"";let i=`${n}${t.length}__`;return t.push(s),i}),o=new RegExp(`${n}(\\d+)__`,"g");return Ct(r).replace(o,(s,i)=>t[Number(i)]??"")}function ep(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),o="\u2591".repeat(10-n);return`${G(r||"",B.green)}${G(o||"",B.chrome)}`}function In(e){return`$${e.toFixed(2)}`}function tp(e){let t=e;if(t.startsWith("/")&&(t=t.replace(/^\/(?:api\/)?v\d+\/fal\//,""),t=t.replace(/^\/(?:api\/)?v\d+\/(?:shortcuts|openrouter)\//,""),t.startsWith("/"))){let o=t.split("/").filter(Boolean);t=o[o.length-1]||t}return t=t.replace(/^fal-ai\//,""),t=t.replace(/^fal-/,""),t=t.replace(/^or-/,""),t=t.split("/").filter(Boolean).map(o=>o.replace(/^v\d+(?:\.\d+)?-?/,"")||null).filter(o=>o!==null&&o.length>0).join(" "),t=t.replace(/_card$/,""),t.length>28&&(t=t.slice(0,28).trimEnd()),t||e}function np(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=Ct(n.toUpperCase()),s=Ct(r);return`${t.isDefault?"default":"active"} ${o} ****${s}`}var B={get reset(){return de().reset},get visaBlue(){return de().visaBlue},get visaBlueSoft(){return de().visaBlueSoft},get visaGold(){return de().visaGold},get green(){return de().green},get muted(){return de().muted},get chrome(){return de().chrome}};function G(e,t){return e.length===0||process.env.NO_COLOR||no()?e:`${t}${e}${B.reset}`}function Za(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ns(){let e=zt.homedir();if(!e||!q.isAbsolute(e))throw new Error("unable to determine a valid home directory");return q.resolve(e)}function rp(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function op(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function sp(e){for(let t=0;t<2;t+=1){let n;try{return n=V.openSync(e,"wx"),V.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let o=V.statSync(e);if(Date.now()-o.mtimeMs<=Um)return!1;V.unlinkSync(e)}catch{}}finally{n!==void 0&&V.closeSync(n)}}return!1}function Is(e){return e instanceof Error?e.message:"unknown file system error"}function $n(e,t){V.mkdirSync(q.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${(0,$s.randomBytes)(8).toString("hex")}.tmp`;try{V.writeFileSync(n,t),V.renameSync(n,e)}catch(r){try{V.unlinkSync(n)}catch{}throw r}}var ip=1440*60*1e3;function uo(e,t){ae.mkdirSync(he.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${uc.randomBytes(8).toString("hex")}.tmp`;try{ae.writeFileSync(n,JSON.stringify(t,null,2)+`
104
- `),ae.renameSync(n,e)}catch(r){try{ae.unlinkSync(n)}catch{}throw r}}function cc(e){return`'${e.replace(/'/g,"'\\''")}'`}var Ds="# visa-cli-hud-v1";function mo(e,t){if(!e&&!t&&ap())return`visa-cli config statusline ${Ds}`;let n=e??process.execPath,r=t??process.argv[1]??"",o=r?he.resolve(r):"";return`${o?`${cc(n)} ${cc(o)} config statusline`:"visa-cli config statusline"} ${Ds}`}function ap(){try{return(0,dc.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function Tt(e){return typeof e!="string"?!1:e.includes(Ds)?!0:e.includes("visa-cli")&&e.includes("statusline")}function cp(){return"2.7.0-rc.4"}function po(e){let t=he.dirname(he.resolve(e));return he.basename(t)===".claude"?he.dirname(t):mc.homedir()}function lo(e,t){let n=he.relative(t,e);return!n.startsWith("..")&&!he.isAbsolute(n)?`~/${n}`:e}function lp(e){return he.join(po(e),".visa-cli","hud-self-heal.json")}function up(e,t,n,r){try{if(!ae.existsSync(e))return!1;let o=JSON.parse(ae.readFileSync(e,"utf-8"));return o.version===t&&typeof o.checkedAt=="number"&&n-o.checkedAt<r}catch{return!1}}function Ls(e,t,n){try{uo(e,{version:t,checkedAt:n})}catch{}}function dp(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function Us(e,t={}){let n=t.now??Date.now(),r=t.version??cp(),o=t.stampPath??lp(e),s=t.minIntervalMs??ip,i=[],a=!1,c=!1;if(!t.force&&up(o,r,n,s))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:i,skippedReason:"recently checked"};try{if(!ae.existsSync(e))return Ls(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let l=JSON.parse(ae.readFileSync(e,"utf-8")),u=l.statusLine,d=u&&typeof u=="object"&&!Array.isArray(u)?u.command:"";if(!Tt(d))return Ls(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let f=(t.getCommand??mo)();if(d!==f&&(l.statusLine=dp(u,f),uo(e,l),a=!0,i.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!fo()){let m=po(e);if(Jt(m).length>0){let S=ot(null,m);if(S.removed&&S.rcPaths&&S.rcPaths.length>0){let $=S.rcPaths.map(H=>lo(H,m)).join(", ");c=!0,i.push(`Cleaned legacy shell-prompt HUD block from ${$}.`)}}}return Ls(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i}}catch(l){if(t.force){let u=l instanceof Error?l.message:"unknown error";try{process.stderr.write(`visa-cli: HUD self-heal skipped \u2014 ${u}. Run: visa-cli config hud doctor
105
- `)}catch{}}return{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i}}}function mp(e,t){let n=po(t),r=Jt(n);if(r.length===0)return e;let o=r.map(s=>lo(s,n)).join(", ");return`${e}
100
+ `)}catch{}}function sc(e){try{let t=mr();if(!t)return;let n=Math.max(Date.now(),t.renderedAt+1),r={...t,refreshFailedAt:n,refreshErrorReason:Tt(e).slice(0,200)};$n(Ct(),JSON.stringify(r)+`
101
+ `)}catch{}}function ic(){try{let e=mr();if(!e)return;let t={...e,renderedAt:0};$n(Ct(),JSON.stringify(t)+`
102
+ `)}catch{}}function Wt(){try{V.unlinkSync(ec())}catch{}}function mr(){let e=Ct();if(!V.existsSync(e))return null;try{let t=JSON.parse(V.readFileSync(e,"utf-8"));return typeof t?.line=="string"&&co(t.line)?null:t}catch{return null}}function co(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 ac(){return mr()?.status??null}function ep(){if(process.env.JEST_WORKER_ID)return;let e=ec();try{if(V.mkdirSync(q.dirname(e),{recursive:!0}),!cp(e))return;let t=process.argv[1]?q.resolve(process.argv[1]):"";if(!t){Wt();return}let n=to(),r=(process.env.VISA_CLI_HUD_THEME??"").toLowerCase().trim(),o=n==="no-color"||r==="light"||r==="dark"?{}:{VISA_CLI_HUD_THEME:n},s=(0,Xa.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,...o,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});s.once("error",Wt),s.unref()}catch{Wt()}}function Tt(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim()}var tp=/^\u001B\[(?:0|38;2;\d{1,3};\d{1,3};\d{1,3}|38;5;\d{1,3})m$/;function np(e){let t=[],n=`__VISA_CLI_HUD_SGR_${(0,$s.randomBytes)(8).toString("hex")}_`,r=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,s=>{if(!tp.test(s))return"";let i=`${n}${t.length}__`;return t.push(s),i}),o=new RegExp(`${n}(\\d+)__`,"g");return Tt(r).replace(o,(s,i)=>t[Number(i)]??"")}function rp(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),o="\u2591".repeat(10-n);return`${G(r||"",B.green)}${G(o||"",B.chrome)}`}function In(e){return`$${e.toFixed(2)}`}function op(e){let t=e;if(t.startsWith("/")&&(t=t.replace(/^\/(?:api\/)?v\d+\/fal\//,""),t=t.replace(/^\/(?:api\/)?v\d+\/(?:shortcuts|openrouter)\//,""),t.startsWith("/"))){let o=t.split("/").filter(Boolean);t=o[o.length-1]||t}return t=t.replace(/^fal-ai\//,""),t=t.replace(/^fal-/,""),t=t.replace(/^or-/,""),t=t.split("/").filter(Boolean).map(o=>o.replace(/^v\d+(?:\.\d+)?-?/,"")||null).filter(o=>o!==null&&o.length>0).join(" "),t=t.replace(/_card$/,""),t.length>28&&(t=t.slice(0,28).trimEnd()),t||e}function sp(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=Tt(n.toUpperCase()),s=Tt(r);return`${t.isDefault?"default":"active"} ${o} ****${s}`}var B={get reset(){return de().reset},get visaBlue(){return de().visaBlue},get visaBlueSoft(){return de().visaBlueSoft},get visaGold(){return de().visaGold},get green(){return de().green},get muted(){return de().muted},get chrome(){return de().chrome}};function G(e,t){return e.length===0||process.env.NO_COLOR||no()?e:`${t}${e}${B.reset}`}function Za(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ns(){let e=zt.homedir();if(!e||!q.isAbsolute(e))throw new Error("unable to determine a valid home directory");return q.resolve(e)}function ip(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function ap(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function cp(e){for(let t=0;t<2;t+=1){let n;try{return n=V.openSync(e,"wx"),V.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let o=V.statSync(e);if(Date.now()-o.mtimeMs<=Vm)return!1;V.unlinkSync(e)}catch{}}finally{n!==void 0&&V.closeSync(n)}}return!1}function Is(e){return e instanceof Error?e.message:"unknown file system error"}function $n(e,t){V.mkdirSync(q.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${(0,$s.randomBytes)(8).toString("hex")}.tmp`;try{V.writeFileSync(n,t),V.renameSync(n,e)}catch(r){try{V.unlinkSync(n)}catch{}throw r}}var lp=1440*60*1e3;function uo(e,t){ce.mkdirSync(he.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${uc.randomBytes(8).toString("hex")}.tmp`;try{ce.writeFileSync(n,JSON.stringify(t,null,2)+`
104
+ `),ce.renameSync(n,e)}catch(r){try{ce.unlinkSync(n)}catch{}throw r}}function cc(e){return`'${e.replace(/'/g,"'\\''")}'`}var Ds="# visa-cli-hud-v1";function mo(e,t){if(!e&&!t&&up())return`visa-cli config statusline ${Ds}`;let n=e??process.execPath,r=t??process.argv[1]??"",o=r?he.resolve(r):"";return`${o?`${cc(n)} ${cc(o)} config statusline`:"visa-cli config statusline"} ${Ds}`}function up(){try{return(0,dc.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function Et(e){return typeof e!="string"?!1:e.includes(Ds)?!0:e.includes("visa-cli")&&e.includes("statusline")}function dp(){return"2.7.1-rc.6"}function po(e){let t=he.dirname(he.resolve(e));return he.basename(t)===".claude"?he.dirname(t):mc.homedir()}function lo(e,t){let n=he.relative(t,e);return!n.startsWith("..")&&!he.isAbsolute(n)?`~/${n}`:e}function mp(e){return he.join(po(e),".visa-cli","hud-self-heal.json")}function pp(e,t,n,r){try{if(!ce.existsSync(e))return!1;let o=JSON.parse(ce.readFileSync(e,"utf-8"));return o.version===t&&typeof o.checkedAt=="number"&&n-o.checkedAt<r}catch{return!1}}function Ls(e,t,n){try{uo(e,{version:t,checkedAt:n})}catch{}}function fp(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function Us(e,t={}){let n=t.now??Date.now(),r=t.version??dp(),o=t.stampPath??mp(e),s=t.minIntervalMs??lp,i=[],a=!1,c=!1;if(!t.force&&pp(o,r,n,s))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:i,skippedReason:"recently checked"};try{if(!ce.existsSync(e))return Ls(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let l=JSON.parse(ce.readFileSync(e,"utf-8")),u=l.statusLine,d=u&&typeof u=="object"&&!Array.isArray(u)?u.command:"";if(!Et(d))return Ls(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i};let f=(t.getCommand??mo)();if(d!==f&&(l.statusLine=fp(u,f),uo(e,l),a=!0,i.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!fo()){let m=po(e);if(Jt(m).length>0){let S=ot(null,m);if(S.removed&&S.rcPaths&&S.rcPaths.length>0){let $=S.rcPaths.map(H=>lo(H,m)).join(", ");c=!0,i.push(`Cleaned legacy shell-prompt HUD block from ${$}.`)}}}return Ls(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i}}catch(l){if(t.force){let u=l instanceof Error?l.message:"unknown error";try{process.stderr.write(`visa-cli: HUD self-heal skipped \u2014 ${u}. Run: visa-cli config hud doctor
105
+ `)}catch{}}return{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:i}}}function gp(e,t){let n=po(t),r=Jt(n);if(r.length===0)return e;let o=r.map(s=>lo(s,n)).join(", ");return`${e}
106
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 fo(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 lc(e,t){let n=po(t),r=Jt(n);if(r.length===0)return e;let o=r.map(i=>lo(i,n)).join(", ");if(fo())return`${e}
107
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=ot(null,n);if(s.removed&&s.rcPaths&&s.rcPaths.length>0){let i=s.rcPaths.map(a=>lo(a,n)).join(", ");return`${e}
108
108
  Cleaned legacy shell-prompt HUD block from ${i} (was leaking output above every shell prompt). Set VISA_HUD_KEEP_SHELL=true to keep both surfaces (also accepts 1, yes, on).`}return`${e}
109
- Note: a legacy shell-prompt HUD block was detected in ${o} but could not be auto-removed (${s.message}). Remove it manually with: visa-cli config hud disable shell`}function pr(e,t=mo){let n={},r=!1;if(ae.existsSync(e)){r=!0;try{n=JSON.parse(ae.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 Tt(o)?{installed:"already-visa",message:lc("Visa HUD already registered in ~/.claude/settings.json.",e)}:{installed:"other-hud-present",message:mp("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()},uo(e,n),{installed:"new",message:lc(`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 js(e){if(!ae.existsSync(e))return{removed:!1,status:"missing-settings",message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(ae.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(!Tt(n))return{removed:!1,status:"foreign-statusline",message:"statusLine is owned by another tool \u2014 leaving it alone."};delete t.statusLine;try{uo(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 pc=E(require("os")),fc=E(require("path"));function st(e=pc.homedir()){return fc.join(e,".claude","settings.json")}var it=E(require("fs")),qe=E(require("path"));var pp=1,Yt={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},fp=["terminal","claude","claude-code","all"];function ho(e){let t=e.toLowerCase();return fp.includes(t)?t:null}var gp=50,hp=64*1024,gc=10,Fs=80,T={get reset(){return de().reset},get visaBlue(){return de().visaBlue},get visaBlueSoft(){return de().visaBlueSoft},get visaGold(){return de().visaGold},get green(){return de().green},get muted(){return de().muted},get chrome(){return de().chrome}};function A(e,t){return e.length===0||process.env.NO_COLOR||no()?e:`${t}${e}${T.reset}`}function hc(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function bc(e=process.stdin){return e.isTTY?null:new Promise(t=>{let n=[],r=!1,o=()=>{e.removeListener("data",i),e.removeListener("end",a),e.removeListener("error",c),clearTimeout(l)},s=u=>{r||(r=!0,o(),t(u))},i=u=>{n.push(typeof u=="string"?Buffer.from(u):u)},a=()=>{let u=Buffer.concat(n).toString("utf-8").trim();if(!u)return s(null);try{let d=JSON.parse(u);s(d&&typeof d=="object"?d:null)}catch{s(null)}},c=()=>s(null),l=setTimeout(()=>{n.length>0?a():s(null)},gp);e.on("data",i),e.on("end",a),e.on("error",c)})}function fr(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),o="\u2591".repeat(10-n);return`${A(r||"",T.visaBlueSoft)}${A(o||"",T.chrome)}`}function gr(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 yp(e){if(Ic(e))return vp(e);let t=` ${A("\u2502",T.chrome)} `,n=go(e)||"claude",r=e.cwd?te(qe.basename(e.cwd)):"",o=yo(e.workspace),s=r||o,i=o&&o!==s?` ${A(`@${o}`,T.visaBlueSoft)}`:"",a=[A(`[${n}]`,T.visaBlueSoft)];s&&a.push(`${A(s,T.visaGold)}${i}`);let c=te(e.git_branch??e.branch??"");c&&a.push(`${A("git:(",T.muted)}${A(c,T.visaBlueSoft)}${A(")",T.muted)}`);let l=a.join(t),u=Number(e.context_window?.context_window_size??0),d=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,f=e.context_window?.current_usage,m=[f?.input_tokens,f?.output_tokens,f?.cache_creation_input_tokens,f?.cache_read_input_tokens].filter(C=>typeof C=="number"&&Number.isFinite(C)),y=m.length>0?m.reduce((C,L)=>C+L,0):null,S=Number(e.context_window?.total_input_tokens??y??f?.input_tokens??0),$=d!==null?Math.max(0,Math.min(1,d/100)):u>0?Math.max(0,Math.min(1,S/u)):0,H=d!==null&&u>0?Math.round($*u):S,U;if(u>0||d!==null){let C=`${String(Math.round($*100)).padStart(2," ")}%`,L=u>0?` ${A(`(${gr(H)}/${gr(u)})`,T.muted)}`:"";U=`${A("Context",T.muted)} ${fr($)} ${A(C,T.green)}${L}`}else U=`${A("Context",T.muted)} ${A("-",T.muted)}`;let w=Sc(e.rate_limits),x=[U];w&&x.push(w);let _=x.join(t);return`${l}
110
- ${_}`}function _p(e){if(Ic(e))return null;let t=` ${A("\u2502",T.chrome)} `,n=go(e)||"claude",r=e.cwd?te(qe.basename(e.cwd)):"",o=yo(e.workspace),s=r||o,i=o&&o!==s?` ${A(`@${o}`,T.visaBlueSoft)}`:"",a=[A(`[${n}]`,T.visaBlueSoft)];s&&a.push(`${A(s,T.visaGold)}${i}`);let c=te(e.git_branch??e.branch??"");c&&a.push(`${A("git:(",T.muted)}${A(c,T.visaBlueSoft)}${A(")",T.muted)}`);let l=Number(e.context_window?.context_window_size??0),u=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,d=e.context_window?.current_usage,f=[d?.input_tokens,d?.output_tokens,d?.cache_creation_input_tokens,d?.cache_read_input_tokens].filter(x=>typeof x=="number"&&Number.isFinite(x)),m=f.length>0?f.reduce((x,_)=>x+_,0):null,y=Number(e.context_window?.total_input_tokens??m??d?.input_tokens??0),S=u!==null?Math.max(0,Math.min(1,u/100)):l>0?Math.max(0,Math.min(1,y/l)):0,$=u!==null&&l>0?Math.round(S*l):y,H;if(l>0||u!==null){let x=`${String(Math.round(S*100)).padStart(2," ")}%`,_=l>0?` ${A(`(${gr($)}/${gr(l)})`,T.muted)}`:"";H=`${A("Context",T.muted)} ${fr(S)} ${A(x,T.green)}${_}`}else H=`${A("Context",T.muted)} ${A("-",T.muted)}`;let U=Sc(e.rate_limits),w=[H];return U&&w.push(U),{identity:a.join(t),metrics:w.join(t)}}function vp(e){let t=` ${A("\u2502",T.chrome)} `,n=$c(e),r=n.model||"codex",o=[A(`[${r}]`,T.visaBlueSoft)];n.project&&o.push(A(n.project,T.visaGold)),n.gitBranch&&o.push(`${A("git",T.muted)} ${A(n.gitBranch,T.visaGold)}`);let s=o.join(t),i=[];if(typeof n.contextUsedPercent=="number"){let c=Math.max(0,Math.min(1,n.contextUsedPercent/100));i.push(`${A("Context",T.muted)} ${fr(c)} ${A(`${Math.round(n.contextUsedPercent)}%`,T.green)}`)}else if(typeof n.contextRemainingPercent=="number"){let c=100-n.contextRemainingPercent,l=Math.max(0,Math.min(1,c/100));i.push(`${A("Context",T.muted)} ${fr(l)} ${A(`${Math.round(c)}%`,T.green)}`)}typeof n.usedTokens=="number"&&i.push(`${A("Tokens",T.muted)} ${gr(n.usedTokens)}`),n.status&&i.push(`${A("Status",T.muted)} ${A(n.status,T.visaBlueSoft)}`),n.threadTitle&&i.push(`${A("Thread",T.muted)} ${A(n.threadTitle,T.visaBlueSoft)}`);let a=i.length>0?i.join(t):`${A("Context",T.muted)} ${A("-",T.muted)}`;return`${s}
111
- ${a}`}function bp(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 yc(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=fr(r),s=n>=90?"\x1B[38;5;196m":n>=70?T.visaGold:T.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=bp(e.resets_at),c=a?` ${A(`(${a} / ${t})`,T.muted)}`:` ${A(`(${t})`,T.muted)}`;return`${o} ${A(i,s)}${c}`}function Sc(e){if(!e)return null;let t=yc(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?yc(e.seven_day,"7d"):null;if(!t&&!r)return null;let o=` ${A("\u2502",T.chrome)} `,s=[t,r].filter(Boolean);return`${A("Usage",T.muted)} ${s.join(o)}`}function wc(e){let t;try{let n=it.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let o=Math.min(r,hp),s=r-o;t=it.openSync(e,"r");let i=Buffer.alloc(o);it.readSync(t,i,0,o,s);let a=i.toString("utf-8");if(s>0){let c=Buffer.alloc(1);if(it.readSync(t,c,0,1,s-1),c[0]!==10){let l=a.indexOf(`
112
- `);l>=0&&(a=a.slice(l+1))}}return a}catch{return null}finally{if(t!==void 0)try{it.closeSync(t)}catch{}}}function Sp(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=qe.basename(qe.dirname(o)),i=qe.basename(o);return s&&s!=="."&&s!=="/"?`${s}/${i}`:i}return o}}}function wp(e){let t=e.split(`
113
- `),n=[],r=new Set;for(let o=t.length-1;o>=0&&n.length<gc*3;o-=1){let s=t[o].trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{continue}if(!i||typeof i!="object")continue;let c=i.message;if(!c||typeof c!="object")continue;let l=c.content;if(Array.isArray(l))for(let u of l){if(!u||typeof u!="object")continue;let d=u;if(d.type==="tool_result"&&typeof d.tool_use_id=="string")r.add(d.tool_use_id);else if(d.type==="tool_use"&&typeof d.name=="string"){let f=typeof d.id=="string"?d.id:"",m=f.length>0?!r.has(f):!1;n.push({name:d.name,target:Sp(d.input),running:m})}}}return n.reverse(),n.slice(Math.max(0,n.length-gc))}function xp(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 kp(e){let t=e.running?A("\u25D0",T.visaGold):A("\u2713",T.green),n=e.running?T.visaGold:T.visaBlueSoft,r=A(te(e.name),n),o=e.target?te(e.target):"",s=o?`${A(":",T.chrome)} ${A(o,T.muted)}`:"",i=e.count>1?` ${A(`\xD7${e.count}`,T.muted)}`:"";return s?`${t} ${r}${s}${i}`:`${t} ${r}${i}`}function Cp(e){let t=` ${A("\u2502",T.chrome)} `,n=hc(t),r=e.slice();for(;r.length>0;){let c=r.join(t);if(hc(c)<=Fs)return c;r=r.slice(1)}if(e.length===0)return"";let o="\u2026",i=e[e.length-1].replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,""),a=i.length>Fs-n-1?i.slice(0,Fs-n-1)+o:i;return`${A(o,T.muted)}${t}${a}`}async function _c(e){if(!e||typeof e!="string")return null;let t=wc(e);if(!t)return null;let n;try{n=wp(t)}catch{return null}if(n.length===0)return null;let o=xp(n).map(kp);return Cp(o)||null}async function xc(e,t,n){return(await Cc(e,t,n)).join(`
114
- `)}function kc(e,t,n){let r=!!t?.activeSession||e.includes("in session"),o=n?Ep(n):!1;return{isActive:r||o,hasSession:r,hasToolActivity:o}}async function Cc(e,t,n){let{isActive:r}=kc(e,n,t?.transcript_path),o=e.split(`
115
- `).filter(a=>a.length>0),i=t&&!r?o.map(a=>A(Vs(a),T.muted)):[...o];if(t){let a=_p(t);if(a){if(i.push(a.identity),t.transcript_path){let c=await _c(t.transcript_path);c&&i.push(...c.split(`
116
- `))}i.push(a.metrics)}else{let c=yp(t);if(c&&i.push(...c.split(`
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 pr(e,t=mo){let n={},r=!1;if(ce.existsSync(e)){r=!0;try{n=JSON.parse(ce.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 Et(o)?{installed:"already-visa",message:lc("Visa HUD already registered in ~/.claude/settings.json.",e)}:{installed:"other-hud-present",message:gp("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()},uo(e,n),{installed:"new",message:lc(`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 js(e){if(!ce.existsSync(e))return{removed:!1,status:"missing-settings",message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(ce.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(!Et(n))return{removed:!1,status:"foreign-statusline",message:"statusLine is owned by another tool \u2014 leaving it alone."};delete t.statusLine;try{uo(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 pc=E(require("os")),fc=E(require("path"));function st(e=pc.homedir()){return fc.join(e,".claude","settings.json")}var it=E(require("fs")),qe=E(require("path"));var hp=1,Yt={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},yp=["terminal","claude","claude-code","all"];function ho(e){let t=e.toLowerCase();return yp.includes(t)?t:null}var _p=50,bp=64*1024,gc=10,Fs=80,T={get reset(){return de().reset},get visaBlue(){return de().visaBlue},get visaBlueSoft(){return de().visaBlueSoft},get visaGold(){return de().visaGold},get green(){return de().green},get muted(){return de().muted},get chrome(){return de().chrome}};function A(e,t){return e.length===0||process.env.NO_COLOR||no()?e:`${t}${e}${T.reset}`}function hc(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function vc(e=process.stdin){return e.isTTY?null:new Promise(t=>{let n=[],r=!1,o=()=>{e.removeListener("data",i),e.removeListener("end",a),e.removeListener("error",c),clearTimeout(l)},s=u=>{r||(r=!0,o(),t(u))},i=u=>{n.push(typeof u=="string"?Buffer.from(u):u)},a=()=>{let u=Buffer.concat(n).toString("utf-8").trim();if(!u)return s(null);try{let d=JSON.parse(u);s(d&&typeof d=="object"?d:null)}catch{s(null)}},c=()=>s(null),l=setTimeout(()=>{n.length>0?a():s(null)},_p);e.on("data",i),e.on("end",a),e.on("error",c)})}function fr(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),o="\u2591".repeat(10-n);return`${A(r||"",T.visaBlueSoft)}${A(o||"",T.chrome)}`}function gr(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 vp(e){if(Ic(e))return wp(e);let t=` ${A("\u2502",T.chrome)} `,n=go(e)||"claude",r=e.cwd?te(qe.basename(e.cwd)):"",o=yo(e.workspace),s=r||o,i=o&&o!==s?` ${A(`@${o}`,T.visaBlueSoft)}`:"",a=[A(`[${n}]`,T.visaBlueSoft)];s&&a.push(`${A(s,T.visaGold)}${i}`);let c=te(e.git_branch??e.branch??"");c&&a.push(`${A("git:(",T.muted)}${A(c,T.visaBlueSoft)}${A(")",T.muted)}`);let l=a.join(t),u=Number(e.context_window?.context_window_size??0),d=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,f=e.context_window?.current_usage,m=[f?.input_tokens,f?.output_tokens,f?.cache_creation_input_tokens,f?.cache_read_input_tokens].filter(k=>typeof k=="number"&&Number.isFinite(k)),_=m.length>0?m.reduce((k,L)=>k+L,0):null,S=Number(e.context_window?.total_input_tokens??_??f?.input_tokens??0),$=d!==null?Math.max(0,Math.min(1,d/100)):u>0?Math.max(0,Math.min(1,S/u)):0,H=d!==null&&u>0?Math.round($*u):S,U;if(u>0||d!==null){let k=`${String(Math.round($*100)).padStart(2," ")}%`,L=u>0?` ${A(`(${gr(H)}/${gr(u)})`,T.muted)}`:"";U=`${A("Context",T.muted)} ${fr($)} ${A(k,T.green)}${L}`}else U=`${A("Context",T.muted)} ${A("-",T.muted)}`;let w=Sc(e.rate_limits),x=[U];w&&x.push(w);let y=x.join(t);return`${l}
110
+ ${y}`}function Sp(e){if(Ic(e))return null;let t=` ${A("\u2502",T.chrome)} `,n=go(e)||"claude",r=e.cwd?te(qe.basename(e.cwd)):"",o=yo(e.workspace),s=r||o,i=o&&o!==s?` ${A(`@${o}`,T.visaBlueSoft)}`:"",a=[A(`[${n}]`,T.visaBlueSoft)];s&&a.push(`${A(s,T.visaGold)}${i}`);let c=te(e.git_branch??e.branch??"");c&&a.push(`${A("git:(",T.muted)}${A(c,T.visaBlueSoft)}${A(")",T.muted)}`);let l=Number(e.context_window?.context_window_size??0),u=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,d=e.context_window?.current_usage,f=[d?.input_tokens,d?.output_tokens,d?.cache_creation_input_tokens,d?.cache_read_input_tokens].filter(x=>typeof x=="number"&&Number.isFinite(x)),m=f.length>0?f.reduce((x,y)=>x+y,0):null,_=Number(e.context_window?.total_input_tokens??m??d?.input_tokens??0),S=u!==null?Math.max(0,Math.min(1,u/100)):l>0?Math.max(0,Math.min(1,_/l)):0,$=u!==null&&l>0?Math.round(S*l):_,H;if(l>0||u!==null){let x=`${String(Math.round(S*100)).padStart(2," ")}%`,y=l>0?` ${A(`(${gr($)}/${gr(l)})`,T.muted)}`:"";H=`${A("Context",T.muted)} ${fr(S)} ${A(x,T.green)}${y}`}else H=`${A("Context",T.muted)} ${A("-",T.muted)}`;let U=Sc(e.rate_limits),w=[H];return U&&w.push(U),{identity:a.join(t),metrics:w.join(t)}}function wp(e){let t=` ${A("\u2502",T.chrome)} `,n=$c(e),r=n.model||"codex",o=[A(`[${r}]`,T.visaBlueSoft)];n.project&&o.push(A(n.project,T.visaGold)),n.gitBranch&&o.push(`${A("git",T.muted)} ${A(n.gitBranch,T.visaGold)}`);let s=o.join(t),i=[];if(typeof n.contextUsedPercent=="number"){let c=Math.max(0,Math.min(1,n.contextUsedPercent/100));i.push(`${A("Context",T.muted)} ${fr(c)} ${A(`${Math.round(n.contextUsedPercent)}%`,T.green)}`)}else if(typeof n.contextRemainingPercent=="number"){let c=100-n.contextRemainingPercent,l=Math.max(0,Math.min(1,c/100));i.push(`${A("Context",T.muted)} ${fr(l)} ${A(`${Math.round(c)}%`,T.green)}`)}typeof n.usedTokens=="number"&&i.push(`${A("Tokens",T.muted)} ${gr(n.usedTokens)}`),n.status&&i.push(`${A("Status",T.muted)} ${A(n.status,T.visaBlueSoft)}`),n.threadTitle&&i.push(`${A("Thread",T.muted)} ${A(n.threadTitle,T.visaBlueSoft)}`);let a=i.length>0?i.join(t):`${A("Context",T.muted)} ${A("-",T.muted)}`;return`${s}
111
+ ${a}`}function xp(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 yc(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=fr(r),s=n>=90?"\x1B[38;5;196m":n>=70?T.visaGold:T.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=xp(e.resets_at),c=a?` ${A(`(${a} / ${t})`,T.muted)}`:` ${A(`(${t})`,T.muted)}`;return`${o} ${A(i,s)}${c}`}function Sc(e){if(!e)return null;let t=yc(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?yc(e.seven_day,"7d"):null;if(!t&&!r)return null;let o=` ${A("\u2502",T.chrome)} `,s=[t,r].filter(Boolean);return`${A("Usage",T.muted)} ${s.join(o)}`}function wc(e){let t;try{let n=it.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let o=Math.min(r,bp),s=r-o;t=it.openSync(e,"r");let i=Buffer.alloc(o);it.readSync(t,i,0,o,s);let a=i.toString("utf-8");if(s>0){let c=Buffer.alloc(1);if(it.readSync(t,c,0,1,s-1),c[0]!==10){let l=a.indexOf(`
112
+ `);l>=0&&(a=a.slice(l+1))}}return a}catch{return null}finally{if(t!==void 0)try{it.closeSync(t)}catch{}}}function kp(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=qe.basename(qe.dirname(o)),i=qe.basename(o);return s&&s!=="."&&s!=="/"?`${s}/${i}`:i}return o}}}function Cp(e){let t=e.split(`
113
+ `),n=[],r=new Set;for(let o=t.length-1;o>=0&&n.length<gc*3;o-=1){let s=t[o].trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{continue}if(!i||typeof i!="object")continue;let c=i.message;if(!c||typeof c!="object")continue;let l=c.content;if(Array.isArray(l))for(let u of l){if(!u||typeof u!="object")continue;let d=u;if(d.type==="tool_result"&&typeof d.tool_use_id=="string")r.add(d.tool_use_id);else if(d.type==="tool_use"&&typeof d.name=="string"){let f=typeof d.id=="string"?d.id:"",m=f.length>0?!r.has(f):!1;n.push({name:d.name,target:kp(d.input),running:m})}}}return n.reverse(),n.slice(Math.max(0,n.length-gc))}function Tp(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 Ep(e){let t=e.running?A("\u25D0",T.visaGold):A("\u2713",T.green),n=e.running?T.visaGold:T.visaBlueSoft,r=A(te(e.name),n),o=e.target?te(e.target):"",s=o?`${A(":",T.chrome)} ${A(o,T.muted)}`:"",i=e.count>1?` ${A(`\xD7${e.count}`,T.muted)}`:"";return s?`${t} ${r}${s}${i}`:`${t} ${r}${i}`}function Ap(e){let t=` ${A("\u2502",T.chrome)} `,n=hc(t),r=e.slice();for(;r.length>0;){let c=r.join(t);if(hc(c)<=Fs)return c;r=r.slice(1)}if(e.length===0)return"";let o="\u2026",i=e[e.length-1].replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,""),a=i.length>Fs-n-1?i.slice(0,Fs-n-1)+o:i;return`${A(o,T.muted)}${t}${a}`}async function _c(e){if(!e||typeof e!="string")return null;let t=wc(e);if(!t)return null;let n;try{n=Cp(t)}catch{return null}if(n.length===0)return null;let o=Tp(n).map(Ep);return Ap(o)||null}async function xc(e,t,n){return(await Cc(e,t,n)).join(`
114
+ `)}function kc(e,t,n){let r=!!t?.activeSession||e.includes("in session"),o=n?Ip(n):!1;return{isActive:r||o,hasSession:r,hasToolActivity:o}}async function Cc(e,t,n){let{isActive:r}=kc(e,n,t?.transcript_path),o=e.split(`
115
+ `).filter(a=>a.length>0),i=t&&!r?o.map(a=>A(Vs(a),T.muted)):[...o];if(t){let a=Sp(t);if(a){if(i.push(a.identity),t.transcript_path){let c=await _c(t.transcript_path);c&&i.push(...c.split(`
116
+ `))}i.push(a.metrics)}else{let c=vp(t);if(c&&i.push(...c.split(`
117
117
  `)),t.transcript_path){let l=await _c(t.transcript_path);l&&i.push(...l.split(`
118
- `))}}}return i}var Tp=["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 Ep(e){let t=wc(e);if(!t)return!1;let n=t.slice(-16384).toLowerCase();return Tp.some(r=>n.includes(`"${r}"`))}async function Tc(e,t,n){let r=await Cc(e,t,n),o=r.join(`
119
- `),{isActive:s}=kc(e,n,t?.transcript_path);return{schemaVersion:pp,client:t?Rc(t):Yt.UNKNOWN,rendered:o,lines:r.map(Vs),visa:{spendLine:Vs(e),balanceCents:n?.balanceCents,balanceUsd:n?.amountUsd,sessionMode:n?.sessionMode,activeSession:n?.activeSession,isVisaActive:s},context:t?$c(t):{}}}function te(e){return e?e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim():""}function yo(e){if(typeof e=="string")return te(qe.basename(e));if(!e||typeof e!="object")return"";let t=typeof e.current_dir=="string"?e.current_dir:typeof e.path=="string"?e.path:"";return te(t?qe.basename(t):e.name)}function Ec(e){return te(e.app_name??e.appName??e.app??e.client)}function go(e){return te(e.model?.display_name??e.model?.id??e.model_name??e.modelName)}function Ac(e){return te(e.cwd??e.current_dir??e.project_root)}function vc(e){let t=te(e.project);if(t)return t;let n=Ac(e);if(n)return te(qe.basename(n));let r=yo(e.workspace);return r||""}function Me(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function Rc(e){let t=Ec(e).toLowerCase();return t.includes("codex")?Yt.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?Yt.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||Me(e.context_used)!==void 0?Yt.CODEX:Yt.UNKNOWN}function Ic(e){return Rc(e)===Yt.CODEX}function $c(e){let t=Ec(e),n=Ac(e),r=yo(e.workspace),o=Me(e.context_used)??Me(e.context_window?.used_percentage??void 0),s=Me(e.context_remaining)??Me(e.context_window?.remaining_percentage??void 0);return{...t?{app:t}:{},...go(e)?{model:go(e)}:{},...vc(e)?{project:vc(e)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...te(e.git_branch??e.branch)?{gitBranch:te(e.git_branch??e.branch)}:{},...te(e.status??e.run_state??e.runState)?{status:te(e.status??e.run_state??e.runState)}:{},...te(e.thread_title??e.threadTitle)?{threadTitle:te(e.thread_title??e.threadTitle)}:{},...o!==void 0?{contextUsedPercent:o}:{},...s!==void 0?{contextRemainingPercent:s}:{},...Me(e.used_tokens)!==void 0?{usedTokens:Me(e.used_tokens)}:{},...Me(e.total_input_tokens)!==void 0?{totalInputTokens:Me(e.total_input_tokens)}:{},...Me(e.total_output_tokens)!==void 0?{totalOutputTokens:Me(e.total_output_tokens)}:{}}}function Vs(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}var Oc=E(require("path"));function Pc(e){return e instanceof Error?e.message:String(e)}function Hs(e,t){let n=[],r=[],o=e??"claude",s=ho(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: ${Pc(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=Oc.join(t.homeDir,".claude","settings.json");try{let c=t.installVisaStatusLine(a);n.push(c.message),(c.installed==="error"||c.installed==="malformed-json")&&(i=!1)}catch(c){i=!1,r.push(`Failed to install Claude HUD: ${Pc(c)}`)}}return{ok:i,messages:n,errors:r}}function Mc(e){if(!e||typeof e!="object")return"";let t=e;return Array.isArray(t.enum)&&t.enum.length>0?"enum":typeof t.type=="string"?t.type:Array.isArray(t.type)?t.type.filter(n=>typeof n=="string").join("|"):""}var Nc=E(require("os")),Lc=require("node:readline/promises"),hr={card:"default VISA ****7242",balance:"balance $6.38",spentToday:"spent today $0.62",lastActivity:"last Visa tool 38m",model:"Opus 4.6"};async function qs(e,t=!1){if(!process.stdin.isTTY)return t;let n=t?"[Y/n]":"[y/N]",r,o;try{r=(0,Lc.createInterface)({input:process.stdin,output:process.stdout});let s=new AbortController;o=()=>s.abort(),r.once("close",o);let i=(await r.question(`${e} ${n} `,{signal:s.signal})).trim();return i?/^y(es)?$/i.test(i):t}catch{return t}finally{r&&o&&r.off("close",o),r?.close()}}function Ap(e,t){return e.replace(/[\x00-\x1F\x7F\u202A-\u202E\u2066-\u2069]/g,"").trim()||t}function Dc(e=Nc.hostname()){let t=nr().version,n=Ap(e,"this-machine");return[" Preview if installed (sample):",` VISA CLI v${t} | ${n} | ${hr.card}`,` ${hr.balance} | ${hr.spentToday} | ${hr.lastActivity}`,` [${hr.model}] | you`," Activity live"].join(`
120
- `)}async function Zt(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 Xt=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},On=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}},me=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(t,n,r,o,s,i,a,c){super(t),this.name="CardDeclinedError",this.retryable=n,this.code=r,this.reason=o,this.paymentErrorClass=s,this.correlationId=i,this.transactionId=a,this.retryAfter=c}},at=class extends Error{code;transactionId;retryable;reconciliationRequired;constructor(t,n,r={}){super(t),this.name="TopupAmbiguousError",this.code=n,this.transactionId=r.transactionId,this.retryable=r.retryable??!1,this.reconciliationRequired=r.reconciliationRequired??!0}};var Uc={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&&Uc[n]?Uc[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 ve=E(require("fs")),Ws=E(require("path")),jc=E(require("os")),Gs=Ws.join(jc.homedir(),".visa-mcp"),yr=Ws.join(Gs,"mcp-server.log"),Rp=5*1024*1024,Ks=null;function Ip(){ve.existsSync(Gs)||ve.mkdirSync(Gs,{recursive:!0,mode:448})}function $p(){if(!Ks){if(Ip(),ve.existsSync(yr)&&ve.statSync(yr).size>Rp){let t=yr+".1";ve.existsSync(t)&&ve.unlinkSync(t),ve.renameSync(yr,t)}Ks=ve.createWriteStream(yr,{flags:"a"})}return Ks}function Pp(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function _o(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}
121
- `;Pp(e)&&process.stderr.write(o),$p().write(o)}var p={debug:(...e)=>_o("DEBUG",...e),info:(...e)=>_o("INFO",...e),warn:(...e)=>_o("WARN",...e),error:(...e)=>_o("ERROR",...e)};var Op=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Vc(e,t){let n=Fc(e),r=Fc(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:Mp(n.pre,r.pre)>0}function Fc(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(Op);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function Mp(e,t){let n=e.split("."),r=t.split("."),o=Math.max(n.length,r.length);for(let s=0;s<o;s++){if(s>=n.length)return-1;if(s>=r.length)return 1;let i=n[s],a=r[s],c=/^\d+$/.test(i),l=/^\d+$/.test(a);if(c&&l){let u=Number(i)-Number(a);if(u!==0)return u}else{if(c)return-1;if(l)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function Be(){return!!(Hc(process.env.VISA_CLI_NO_UPDATE_CHECK)||Hc(process.env.CI)||process.env.NODE_ENV==="test")}function Hc(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var At=E(require("fs")),Zs=require("node:net"),Gc=E(require("os")),Wc=E(require("path"));var vo=E(require("fs")),qc=E(require("path")),Bc=E(require("os"));var zs=qc.join(Bc.homedir(),".visa-mcp"),_r=class{static ensureConfigDir(){vo.existsSync(zs)||vo.mkdirSync(zs,{recursive:!0,mode:448})}static getConfigDir(){return zs}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 Kc(e){let t=Gc.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}var Np="settings.json",Lp="must use https unless it points at localhost/loopback for local development";function vr(){return Wc.join(_r.getConfigDir(),Np)}function zc(e){if((0,Zs.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function Dp(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 zc(o)}function Up(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,Zs.isIP)(t);return n===4?zc(t):n===6?t==="::1"||Dp(t):!1}function Js(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:"&&Up(n.hostname)))throw new Error(`${t} ${Lp}`)}var Rt={"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");Js(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,bo={"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 en(){let e=vr();if(!At.existsSync(e))return{};try{let t=At.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?(p.warn("settings:corrupt",{path:Kc(e),reason:"not_object"}),{}):n}catch(t){return p.warn("settings:corrupt",{path:Kc(e),error:t?.message||String(t)}),{}}}function Ys(e){_r.ensureConfigDir();let t=vr(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
122
- `;At.writeFileSync(n,r,{mode:384}),At.renameSync(n,t)}function Qs(e){let t=en()[e];return typeof t=="string"?t:void 0}function So(e){let t=en()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function ei(e){let t=en()[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 ct=class extends Error{constructor(t){let n=Object.keys(Rt).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"}},lt=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"}},Et=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+bo[t]),this.name="RetiredSettingKeyError"}},Jc=["biometric.","spending.","account.","cards.","biometric"];function wo(e,t){if(Jc.some(s=>e.startsWith(s)))throw new lt(e);if(e in bo)throw new Et(e);let n=Rt[e];if(!n)throw new ct(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=en();return o[e]=r,Ys(o),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:vr()}}function xo(e){if(Jc.some(s=>e.startsWith(s)))throw new lt(e);let t=Rt[e];if(e in bo){let s=en(),i=e in s;return i&&(delete s[e],Ys(s)),{key:e,removed:i,requiresRestart:!1,path:vr()}}if(!t)throw new ct(e);let r=en(),o=e in r;return o&&(delete r[e],Ys(r)),{key:e,removed:o,requiresRestart:o&&!!t.requiresRestart,path:vr()}}function Yc(){let e=en();return Object.entries(bo).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}var jp="https://auth.visacli.sh",Fp="https://auth-visa-code-preview.up.railway.app";function Vp(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function Hp(){try{let e=nr();return Vp(e.version)}catch{return!1}}function qp(e){return e.envVar!==void 0&&e.envVar!==""?(Js(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(Js(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?Fp:jp}function ke(){return qp({envVar:process.env.VISA_AUTH_URL,settingValue:Qs("auth.serverUrl"),isPrerelease:Hp()})}function Zc(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":So("ui.suppressBrowser")??!1}function Xc(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":So("ui.suppressFeed")??!1}function Qc(){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=ei("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):Xs}var Bp="CARD_REENROLLMENT_REQUIRED",Kp="https://auth.visacli.sh/enroll-card";function Gp(){try{return new URL("/enroll-card",ke()).toString()}catch{return Kp}}function Wp(e){let t=Gp();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 p.warn("card-reenroll:reenroll_url_rejected_fallback",{reason:"untrusted_or_malformed_reenroll_url",fallbackPath:"/enroll-card"}),t}var br="2.7.0-rc.4",zp=/^(?:VisaKey_[A-Za-z0-9_-]{16,128}|visakey_[A-Za-z0-9_-]{16,128}|vk_[A-Za-z0-9_-]{32,128})$/;function Jp(e){if(typeof e!="string")return null;switch(e){case"BUDGET_CLOSED":case"BUDGET_NOT_FOUND":case"BUDGET_EXPIRED":return e;default:return null}}function el(e){return e==="TOPUP_CHARGE_AMBIGUOUS"||e==="TOPUP_RECONCILIATION_REQUIRED"?e:null}var Yp="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function Mn(e){return typeof e=="string"?e.trim():""}function tl(e){let t=e&&typeof e=="object"?e:{},n=Mn(t.error)||Mn(t.message);if(!n)return Yp;let r=Mn(t.error_code),o=[["surface",Mn(t.disabled_surface)],["flag",Mn(t.flag)],["correlation_id",Mn(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 nl(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?zp.test(r)?(n.push("VISA_CLI_API_KEY is set, but MCP bearer tools currently require a local session from visa-cli setup."),n.push("For headless API-key use, call the /v1/api/* HTTP routes with X-Api-Key instead of MCP bearer tools.")):(n.push("VISA_CLI_API_KEY is set but has invalid format (expected VisaKey_<...> or legacy vk_<...>)."),n.push("Create a new 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(`
123
- `)}var Ce=class{constructor(t){this.getSessionToken=t;this.baseUrl=ke()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!Be()){let r=t.headers.get("X-Latest-Version");r&&Vc(r,br)&&(this.lastSignals.updateAvailable={currentVersion:br,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return br}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new Xt(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(tl(n))}async request(t,n,r,o,s,i){let a=await this.getSessionToken();if(!a)throw new Error(nl());let c={Authorization:`Bearer ${a}`};s&&(t==="GET"?c["X-User-Context"]=encodeURIComponent(s.replace(/[\r\n\0]/g," ").slice(0,1e3)):r={...r||{},user_context:s}),i&&(c["X-Visa-Meta-Tool"]=i),r&&(c["Content-Type"]="application/json");let l;try{l=await Zt(`${this.baseUrl}${n}`,{method:t,headers:{...c,"X-Visa-CLI-Version":br,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:o})}catch(d){throw new Error(Bs(d))}if(this.parseServerSignals(l),l.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(l.status===429){let d=l.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${d}s. Tip: use the batch tool to combine multiple requests into one.`)}l.status===503&&await this.throwServerUnavailable(l);let u;try{u=await l.json()}catch{throw l.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${n}. Try again.`)}if(!l.ok){if(l.status===500)throw new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(u),typeof u?.error_code=="string"&&u.error_code===Bp){let f=typeof u?.last4=="string"?u.last4:"",m=typeof u?.brand=="string"?u.brand:"card",y=Wp(u?.reenroll_url),S=f?`${m} ending in ${f}`:"your card";throw new Error(`Please re-add ${S} to keep payments running. Open: ${y}`)}let d=el(u?.error_code);if(d)throw new at(u?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",d,{transactionId:typeof u?.transactionId=="string"?u.transactionId:void 0,retryable:!!u?.retryable,reconciliationRequired:u?.reconciliation_required!==!1});if(u?.declined){let f=Number(u.retryAfter??l.headers.get("Retry-After"));throw new me(u.error||"Your card was declined.",!!u.retryable,u.code,u.reason,u.payment_error_class,u.correlation_id,u.transactionId,Number.isFinite(f)&&f>0?f:void 0)}if(l.status===402){let f=u?.error||"Gateway returned 402",m=typeof u?.error_code=="string"?u.error_code:"";throw m==="SPENDING_LIMIT_EXCEEDED"||m==="DAILY_LIMIT_EXCEEDED"||m==="PER_TXN_LIMIT_EXCEEDED"?new Error(`${f}. Check your limits with get_status or run: visa-cli update-spending-controls`):new Error(f)}throw new Error(u?.error||`Request failed (${l.status}). Try again.`)}return u}async shortcut(t,n,r,o,s){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,o,s)}async shortcutWithSession(t,n,r,o,s,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error(nl());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":br,"X-Source":"cli","Content-Type":"application/json"};i&&(l["X-Visa-Meta-Tool"]=i);let u={...n,...r};s&&(u.user_context=s.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await Zt(`${this.baseUrl}${a}`,{method:"POST",headers:l,body:JSON.stringify(u),timeoutMs:o})}catch(y){throw new Error(Bs(y))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let y=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${y}s. Tip: use the batch tool to combine multiple requests into one.`)}let f=d.headers.get("X-Voucher-Receipt"),m;try{m=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(m),d.status===503){if(m?.error_code==="SESSION_LOCK_CONTENDED"){let $=Number(d.headers.get("Retry-After"))||1;throw new Qt(m?.message||m?.error||"Session budget is being modified by another request. Retry shortly.",$,d.status)}throw new Error(tl(m))}let y=Jp(m?.error_code);if(y||d.status===410){let $=y??"BUDGET_CLOSED";throw new On(m?.message||m?.error||"Your session was invalidated by the server.",$,{budgetId:n.session_budget_id,status:d.status})}if(m?.declined){let $=Number(m.retryAfter??d.headers.get("Retry-After"));throw new me(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite($)&&$>0?$:void 0)}let S=el(m?.error_code);throw S?new at(m?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",S,{transactionId:typeof m?.transactionId=="string"?m.transactionId:void 0,retryable:!!m?.retryable,reconciliationRequired:m?.reconciliation_required!==!1}):new Error(m?.error||`Request failed (${d.status}). Try again.`)}return{data:m,voucherReceiptHeader: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 Zt(`${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 Zt(`${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={};ms(g,{BRAND:()=>xf,DIRTY:()=>tn,EMPTY_PATH:()=>ef,INVALID:()=>R,NEVER:()=>ag,OK:()=>pe,ParseStatus:()=>le,Schema:()=>N,ZodAny:()=>Pt,ZodArray:()=>pt,ZodBigInt:()=>rn,ZodBoolean:()=>on,ZodBranded:()=>wr,ZodCatch:()=>hn,ZodDate:()=>sn,ZodDefault:()=>gn,ZodDiscriminatedUnion:()=>To,ZodEffects:()=>$e,ZodEnum:()=>pn,ZodError:()=>be,ZodFirstPartyTypeKind:()=>I,ZodFunction:()=>Ao,ZodIntersection:()=>un,ZodIssueCode:()=>h,ZodLazy:()=>dn,ZodLiteral:()=>mn,ZodMap:()=>Fn,ZodNaN:()=>Hn,ZodNativeEnum:()=>fn,ZodNever:()=>Ne,ZodNull:()=>cn,ZodNullable:()=>We,ZodNumber:()=>nn,ZodObject:()=>Se,ZodOptional:()=>Re,ZodParsedType:()=>b,ZodPipeline:()=>xr,ZodPromise:()=>Ot,ZodReadonly:()=>yn,ZodRecord:()=>Eo,ZodSchema:()=>N,ZodSet:()=>Vn,ZodString:()=>$t,ZodSymbol:()=>Un,ZodTransformer:()=>$e,ZodTuple:()=>Ge,ZodType:()=>N,ZodUndefined:()=>an,ZodUnion:()=>ln,ZodUnknown:()=>mt,ZodVoid:()=>jn,addIssueToContext:()=>v,any:()=>Pf,array:()=>Lf,bigint:()=>Ef,boolean:()=>pl,coerce:()=>ig,custom:()=>ul,date:()=>Af,datetimeRegex:()=>cl,defaultErrorMap:()=>ut,discriminatedUnion:()=>Ff,effect:()=>Xf,enum:()=>Jf,function:()=>Gf,getErrorMap:()=>Nn,getParsedType:()=>Ke,instanceof:()=>Cf,intersection:()=>Vf,isAborted:()=>ko,isAsync:()=>Ln,isDirty:()=>Co,isValid:()=>It,late:()=>kf,lazy:()=>Wf,literal:()=>zf,makeIssue:()=>Sr,map:()=>Bf,nan:()=>Tf,nativeEnum:()=>Yf,never:()=>Mf,null:()=>$f,nullable:()=>eg,number:()=>ml,object:()=>Df,objectUtil:()=>ti,oboolean:()=>sg,onumber:()=>og,optional:()=>Qf,ostring:()=>rg,pipeline:()=>ng,preprocess:()=>tg,promise:()=>Zf,quotelessJson:()=>Zp,record:()=>qf,set:()=>Kf,setErrorMap:()=>Qp,strictObject:()=>Uf,string:()=>dl,symbol:()=>Rf,transformer:()=>Xf,tuple:()=>Hf,undefined:()=>If,union:()=>jf,unknown:()=>Of,util:()=>D,void:()=>Nf});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 ti;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(ti||(ti={}));var b=D.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ke=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 h=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"]),Zp=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),be=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(n(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,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()}};be.create=e=>new be(e);var Xp=(e,t)=>{let n;switch(e.code){case h.invalid_type:e.received===b.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case h.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,D.jsonStringifyReplacer)}`;break;case h.unrecognized_keys:n=`Unrecognized key(s) in object: ${D.joinValues(e.keys,", ")}`;break;case h.invalid_union:n="Invalid input";break;case h.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${D.joinValues(e.options)}`;break;case h.invalid_enum_value:n=`Invalid enum value. Expected ${D.joinValues(e.options)}, received '${e.received}'`;break;case h.invalid_arguments:n="Invalid function arguments";break;case h.invalid_return_type:n="Invalid function return type";break;case h.invalid_date:n="Invalid date";break;case h.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 h.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 h.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 h.custom:n="Invalid input";break;case h.invalid_intersection_types:n="Intersection results could not be merged";break;case h.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case h.not_finite:n="Number must be finite";break;default:n=t.defaultError,D.assertNever(e)}return{message:n}},ut=Xp;var rl=ut;function Qp(e){rl=e}function Nn(){return rl}var Sr=e=>{let{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=r.filter(l=>!!l).slice().reverse();for(let l of c)a=l(i,{data:t,defaultError:a}).message;return{...o,path:s,message:a}},ef=[];function v(e,t){let n=Nn(),r=Sr({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===ut?void 0:ut].filter(o=>!!o)});e.common.issues.push(r)}var le=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 R;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 R;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}}},R=Object.freeze({status:"aborted"}),tn=e=>({status:"dirty",value:e}),pe=e=>({status:"valid",value:e}),ko=e=>e.status==="aborted",Co=e=>e.status==="dirty",It=e=>e.status==="valid",Ln=e=>typeof Promise<"u"&&e instanceof Promise;var k;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(k||(k={}));var Ie=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}},ol=(e,t)=>{if(It(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new be(e.common.issues);return this._error=n,this._error}}};function O(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(i,a)=>{let{message:c}=e;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??n??a.defaultError}},description:o}}var N=class{get description(){return this._def.description}_getType(t){return Ke(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Ke(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new le,ctx:{common:t.parent.common,data:t.data,parsedType:Ke(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Ln(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:Ke(t)},o=this._parseSync({data:t,path:r.path,parent:r});return ol(r,o)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Ke(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return It(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(r=>It(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(t,n){let r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Ke(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(Ln(o)?o:Promise.resolve(o));return ol(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:h.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new $e({schema:this,typeName:I.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 Re.create(this,this._def)}nullable(){return We.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return pt.create(this)}promise(){return Ot.create(this,this._def)}or(t){return ln.create([this,t],this._def)}and(t){return un.create(this,t,this._def)}transform(t){return new $e({...O(this._def),schema:this,typeName:I.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new gn({...O(this._def),innerType:this,defaultValue:n,typeName:I.ZodDefault})}brand(){return new wr({typeName:I.ZodBranded,type:this,...O(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new hn({...O(this._def),innerType:this,catchValue:n,typeName:I.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return xr.create(this,t)}readonly(){return yn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},tf=/^c[^\s-]{8,}$/i,nf=/^[0-9a-z]+$/,rf=/^[0-9A-HJKMNP-TV-Z]{26}$/i,of=/^[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,sf=/^[a-z0-9_-]{21}$/i,af=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,cf=/^[-+]?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)?)??$/,lf=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,uf="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ni,df=/^(?:(?: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])$/,mf=/^(?:(?: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])$/,pf=/^(([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]))$/,ff=/^(([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])$/,gf=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,hf=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,il="((\\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])))",yf=new RegExp(`^${il}$`);function al(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 _f(e){return new RegExp(`^${al(e)}$`)}function cl(e){let t=`${il}T${al(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 vf(e,t){return!!((t==="v4"||!t)&&df.test(e)||(t==="v6"||!t)&&pf.test(e))}function bf(e,t){if(!af.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 Sf(e,t){return!!((t==="v4"||!t)&&mf.test(e)||(t==="v6"||!t)&&ff.test(e))}var $t=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:h.invalid_type,expected:b.string,received:s.parsedType}),R}let r=new le,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:h.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:h.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:h.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&v(o,{code:h.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")lf.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"email",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")ni||(ni=new RegExp(uf,"u")),ni.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"emoji",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")of.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"uuid",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")sf.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"nanoid",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")tf.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"cuid",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")nf.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"cuid2",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")rf.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"ulid",code:h.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:h.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:h.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:h.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:h.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:h.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?cl(s).test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{code:h.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?yf.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{code:h.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?_f(s).test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{code:h.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?cf.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"duration",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?vf(t.data,s.version)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"ip",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?bf(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"jwt",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?Sf(t.data,s.version)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"cidr",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?gf.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"base64",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?hf.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"base64url",code:h.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:h.invalid_string,...k.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...k.errToObj(t)})}url(t){return this._addCheck({kind:"url",...k.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...k.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...k.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...k.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...k.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...k.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...k.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...k.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...k.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...k.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...k.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...k.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,...k.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,...k.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...k.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...k.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...k.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...k.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...k.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...k.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...k.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...k.errToObj(n)})}nonempty(t){return this.min(1,k.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}};$t.create=e=>new $t({checks:[],typeName:I.ZodString,coerce:e?.coerce??!1,...O(e)});function wf(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 nn=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:h.invalid_type,expected:b.number,received:s.parsedType}),R}let r,o=new le;for(let s of this._def.checks)s.kind==="int"?D.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),v(r,{code:h.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:h.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:h.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?wf(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),v(r,{code:h.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:h.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,k.toString(n))}gt(t,n){return this.setLimit("min",t,!1,k.toString(n))}lte(t,n){return this.setLimit("max",t,!0,k.toString(n))}lt(t,n){return this.setLimit("max",t,!1,k.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:k.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:k.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:k.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:k.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:k.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:k.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:k.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:k.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:k.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:k.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)}};nn.create=e=>new nn({checks:[],typeName:I.ZodNumber,coerce:e?.coerce||!1,...O(e)});var rn=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 le;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:h.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:h.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:h.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:h.invalid_type,expected:b.bigint,received:n.parsedType}),R}gte(t,n){return this.setLimit("min",t,!0,k.toString(n))}gt(t,n){return this.setLimit("min",t,!1,k.toString(n))}lte(t,n){return this.setLimit("max",t,!0,k.toString(n))}lt(t,n){return this.setLimit("max",t,!1,k.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:k.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:k.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:k.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:k.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:k.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:k.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}};rn.create=e=>new rn({checks:[],typeName:I.ZodBigInt,coerce:e?.coerce??!1,...O(e)});var on=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:h.invalid_type,expected:b.boolean,received:r.parsedType}),R}return pe(t.data)}};on.create=e=>new on({typeName:I.ZodBoolean,coerce:e?.coerce||!1,...O(e)});var sn=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:h.invalid_type,expected:b.date,received:s.parsedType}),R}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return v(s,{code:h.invalid_date}),R}let r=new le,o;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),v(o,{code:h.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:h.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:k.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:k.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};sn.create=e=>new sn({checks:[],coerce:e?.coerce||!1,typeName:I.ZodDate,...O(e)});var Un=class extends N{_parse(t){if(this._getType(t)!==b.symbol){let r=this._getOrReturnCtx(t);return v(r,{code:h.invalid_type,expected:b.symbol,received:r.parsedType}),R}return pe(t.data)}};Un.create=e=>new Un({typeName:I.ZodSymbol,...O(e)});var an=class extends N{_parse(t){if(this._getType(t)!==b.undefined){let r=this._getOrReturnCtx(t);return v(r,{code:h.invalid_type,expected:b.undefined,received:r.parsedType}),R}return pe(t.data)}};an.create=e=>new an({typeName:I.ZodUndefined,...O(e)});var cn=class extends N{_parse(t){if(this._getType(t)!==b.null){let r=this._getOrReturnCtx(t);return v(r,{code:h.invalid_type,expected:b.null,received:r.parsedType}),R}return pe(t.data)}};cn.create=e=>new cn({typeName:I.ZodNull,...O(e)});var Pt=class extends N{constructor(){super(...arguments),this._any=!0}_parse(t){return pe(t.data)}};Pt.create=e=>new Pt({typeName:I.ZodAny,...O(e)});var mt=class extends N{constructor(){super(...arguments),this._unknown=!0}_parse(t){return pe(t.data)}};mt.create=e=>new mt({typeName:I.ZodUnknown,...O(e)});var Ne=class extends N{_parse(t){let n=this._getOrReturnCtx(t);return v(n,{code:h.invalid_type,expected:b.never,received:n.parsedType}),R}};Ne.create=e=>new Ne({typeName:I.ZodNever,...O(e)});var jn=class extends N{_parse(t){if(this._getType(t)!==b.undefined){let r=this._getOrReturnCtx(t);return v(r,{code:h.invalid_type,expected:b.void,received:r.parsedType}),R}return pe(t.data)}};jn.create=e=>new jn({typeName:I.ZodVoid,...O(e)});var pt=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:h.invalid_type,expected:b.array,received:n.parsedType}),R;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?h.too_big:h.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:h.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:h.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 Ie(n,i,n.path,a)))).then(i=>le.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new Ie(n,i,n.path,a)));return le.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:k.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:k.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:k.toString(n)}})}nonempty(t){return this.min(1,t)}};pt.create=(e,t)=>new pt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:I.ZodArray,...O(t)});function Dn(e){if(e instanceof Se){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Re.create(Dn(r))}return new Se({...e._def,shape:()=>t})}else return e instanceof pt?new pt({...e._def,type:Dn(e.element)}):e instanceof Re?Re.create(Dn(e.unwrap())):e instanceof We?We.create(Dn(e.unwrap())):e instanceof Ge?Ge.create(e.items.map(t=>Dn(t))):e}var Se=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 l=this._getOrReturnCtx(t);return v(l,{code:h.invalid_type,expected:b.object,received:l.parsedType}),R}let{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ne&&this._def.unknownKeys==="strip"))for(let l in o.data)i.includes(l)||a.push(l);let c=[];for(let l of i){let u=s[l],d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Ie(o,d,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Ne){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(l==="strict")a.length>0&&(v(o,{code:h.unrecognized_keys,keys:a}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Ie(o,d,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,f=await u.value;l.push({key:d,value:f,alwaysSet:u.alwaysSet})}return l}).then(l=>le.mergeObjectSync(r,l)):le.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(t){return k.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:k.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:I.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 Dn(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 Re;)s=s._def.innerType;n[r]=s}return new e({...this._def,shape:()=>n})}keyof(){return ll(D.objectKeys(this.shape))}};Se.create=(e,t)=>new Se({shape:()=>e,unknownKeys:"strip",catchall:Ne.create(),typeName:I.ZodObject,...O(t)});Se.strictCreate=(e,t)=>new Se({shape:()=>e,unknownKeys:"strict",catchall:Ne.create(),typeName:I.ZodObject,...O(t)});Se.lazycreate=(e,t)=>new Se({shape:e,unknownKeys:"strip",catchall:Ne.create(),typeName:I.ZodObject,...O(t)});var ln=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 be(a.ctx.common.issues));return v(n,{code:h.invalid_union,unionErrors:i}),R}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of r){let l={...n,common:{...n.common,issues:[]},parent:null},u=c._parseSync({data:n.data,path:n.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new be(c));return v(n,{code:h.invalid_union,unionErrors:a}),R}}get options(){return this._def.options}};ln.create=(e,t)=>new ln({options:e,typeName:I.ZodUnion,...O(t)});var dt=e=>e instanceof dn?dt(e.schema):e instanceof $e?dt(e.innerType()):e instanceof mn?[e.value]:e instanceof pn?e.options:e instanceof fn?D.objectValues(e.enum):e instanceof gn?dt(e._def.innerType):e instanceof an?[void 0]:e instanceof cn?[null]:e instanceof Re?[void 0,...dt(e.unwrap())]:e instanceof We?[null,...dt(e.unwrap())]:e instanceof wr||e instanceof yn?dt(e.unwrap()):e instanceof hn?dt(e._def.innerType):[],To=class e extends N{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.object)return v(n,{code:h.invalid_type,expected:b.object,received:n.parsedType}),R;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:h.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),R)}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=dt(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:I.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...O(r)})}};function ri(e,t){let n=Ke(e),r=Ke(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 c=ri(e[a],t[a]);if(!c.valid)return{valid:!1};i[a]=c.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],c=ri(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return n===b.date&&r===b.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var un=class extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=(s,i)=>{if(ko(s)||ko(i))return R;let a=ri(s.value,i.value);return a.valid?((Co(s)||Co(i))&&n.dirty(),{status:n.value,value:a.data}):(v(r,{code:h.invalid_intersection_types}),R)};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}))}};un.create=(e,t,n)=>new un({left:e,right:t,typeName:I.ZodIntersection,...O(n)});var Ge=class e extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.array)return v(r,{code:h.invalid_type,expected:b.array,received:r.parsedType}),R;if(r.data.length<this._def.items.length)return v(r,{code:h.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),R;!this._def.rest&&r.data.length>this._def.items.length&&(v(r,{code:h.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Ie(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>le.mergeArray(n,i)):le.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ge.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ge({items:e,typeName:I.ZodTuple,rest:null,...O(t)})};var Eo=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:h.invalid_type,expected:b.object,received:r.parsedType}),R;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new Ie(r,a,r.path,a)),value:i._parse(new Ie(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?le.mergeObjectAsync(n,o):le.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:I.ZodRecord,...O(r)}):new e({keyType:$t.create(),valueType:t,typeName:I.ZodRecord,...O(n)})}},Fn=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:h.invalid_type,expected:b.map,received:r.parsedType}),R;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,c],l)=>({key:o._parse(new Ie(r,a,r.path,[l,"key"])),value:s._parse(new Ie(r,c,r.path,[l,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return R;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let c of i){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return R;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}}}};Fn.create=(e,t,n)=>new Fn({valueType:t,keyType:e,typeName:I.ZodMap,...O(n)});var Vn=class e extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.set)return v(r,{code:h.invalid_type,expected:b.set,received:r.parsedType}),R;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(v(r,{code:h.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:h.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return R;u.status==="dirty"&&n.dirty(),l.add(u.value)}return{status:n.value,value:l}}let a=[...r.data.values()].map((c,l)=>s._parse(new Ie(r,c,r.path,l)));return r.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(t,n){return new e({...this._def,minSize:{value:t,message:k.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:k.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};Vn.create=(e,t)=>new Vn({valueType:e,minSize:null,maxSize:null,typeName:I.ZodSet,...O(t)});var Ao=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:h.invalid_type,expected:b.function,received:n.parsedType}),R;function r(a,c){return Sr({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Nn(),ut].filter(l=>!!l),issueData:{code:h.invalid_arguments,argumentsError:c}})}function o(a,c){return Sr({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Nn(),ut].filter(l=>!!l),issueData:{code:h.invalid_return_type,returnTypeError:c}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof Ot){let a=this;return pe(async function(...c){let l=new be([]),u=await a._def.args.parseAsync(c,s).catch(m=>{throw l.addIssue(r(c,m)),l}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,s).catch(m=>{throw l.addIssue(o(d,m)),l})})}else{let a=this;return pe(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new be([r(c,l.error)]);let u=Reflect.apply(i,this,l.data),d=a._def.returns.safeParse(u,s);if(!d.success)throw new be([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:Ge.create(t).rest(mt.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||Ge.create([]).rest(mt.create()),returns:n||mt.create(),typeName:I.ZodFunction,...O(r)})}},dn=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})}};dn.create=(e,t)=>new dn({getter:e,typeName:I.ZodLazy,...O(t)});var mn=class extends N{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return v(n,{received:n.data,code:h.invalid_literal,expected:this._def.value}),R}return{status:"valid",value:t.data}}get value(){return this._def.value}};mn.create=(e,t)=>new mn({value:e,typeName:I.ZodLiteral,...O(t)});function ll(e,t){return new pn({values:e,typeName:I.ZodEnum,...O(t)})}var pn=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:h.invalid_type}),R}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:h.invalid_enum_value,options:r}),R}return pe(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})}};pn.create=ll;var fn=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:h.invalid_type}),R}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:h.invalid_enum_value,options:o}),R}return pe(t.data)}get enum(){return this._def.values}};fn.create=(e,t)=>new fn({values:e,typeName:I.ZodNativeEnum,...O(t)});var Ot=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:h.invalid_type,expected:b.promise,received:n.parsedType}),R;let r=n.parsedType===b.promise?n.data:Promise.resolve(n.data);return pe(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Ot.create=(e,t)=>new Ot({type:e,typeName:I.ZodPromise,...O(t)});var $e=class extends N{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===I.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 R;let c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?R:c.status==="dirty"?tn(c.value):n.value==="dirty"?tn(c.value):c});{if(n.value==="aborted")return R;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?R:a.status==="dirty"?tn(a.value):n.value==="dirty"?tn(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?R:(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"?R:(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(!It(i))return R;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=>It(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):R);D.assertNever(o)}};$e.create=(e,t,n)=>new $e({schema:e,typeName:I.ZodEffects,effect:t,...O(n)});$e.createWithPreprocess=(e,t,n)=>new $e({schema:t,effect:{type:"preprocess",transform:e},typeName:I.ZodEffects,...O(n)});var Re=class extends N{_parse(t){return this._getType(t)===b.undefined?pe(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Re.create=(e,t)=>new Re({innerType:e,typeName:I.ZodOptional,...O(t)});var We=class extends N{_parse(t){return this._getType(t)===b.null?pe(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};We.create=(e,t)=>new We({innerType:e,typeName:I.ZodNullable,...O(t)});var gn=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}};gn.create=(e,t)=>new gn({innerType:e,typeName:I.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...O(t)});var hn=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 Ln(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new be(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new be(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};hn.create=(e,t)=>new hn({innerType:e,typeName:I.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...O(t)});var Hn=class extends N{_parse(t){if(this._getType(t)!==b.nan){let r=this._getOrReturnCtx(t);return v(r,{code:h.invalid_type,expected:b.nan,received:r.parsedType}),R}return{status:"valid",value:t.data}}};Hn.create=e=>new Hn({typeName:I.ZodNaN,...O(e)});var xf=Symbol("zod_brand"),wr=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}},xr=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"?R:s.status==="dirty"?(n.dirty(),tn(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"?R: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:I.ZodPipeline})}},yn=class extends N{_parse(t){let n=this._def.innerType._parse(t),r=o=>(It(o)&&(o.value=Object.freeze(o.value)),o);return Ln(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};yn.create=(e,t)=>new yn({innerType:e,typeName:I.ZodReadonly,...O(t)});function sl(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function ul(e,t={},n){return e?Pt.create().superRefine((r,o)=>{let s=e(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=sl(t,r),c=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=sl(t,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Pt.create()}var kf={object:Se.lazycreate},I;(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"})(I||(I={}));var Cf=(e,t={message:`Input not instance of ${e.name}`})=>ul(n=>n instanceof e,t),dl=$t.create,ml=nn.create,Tf=Hn.create,Ef=rn.create,pl=on.create,Af=sn.create,Rf=Un.create,If=an.create,$f=cn.create,Pf=Pt.create,Of=mt.create,Mf=Ne.create,Nf=jn.create,Lf=pt.create,Df=Se.create,Uf=Se.strictCreate,jf=ln.create,Ff=To.create,Vf=un.create,Hf=Ge.create,qf=Eo.create,Bf=Fn.create,Kf=Vn.create,Gf=Ao.create,Wf=dn.create,zf=mn.create,Jf=pn.create,Yf=fn.create,Zf=Ot.create,Xf=$e.create,Qf=Re.create,eg=We.create,tg=$e.createWithPreprocess,ng=xr.create,rg=()=>dl().optional(),og=()=>ml().optional(),sg=()=>pl().optional(),ig={string:(e=>$t.create({...e,coerce:!0})),number:(e=>nn.create({...e,coerce:!0})),boolean:(e=>on.create({...e,coerce:!0})),bigint:(e=>rn.create({...e,coerce:!0})),date:(e=>sn.create({...e,coerce:!0}))};var ag=R;var cg=/^[A-Za-z0-9._-]+$/,lg=/^[A-Za-z0-9._-]+(\|[A-Za-z0-9._-]+)*$/,fl=new Set([".",".."]),ye=class extends Error{pattern;constructor(t,n){super(`Invalid freeReadPathPattern ${JSON.stringify(n)}: ${t}`),this.pattern=n,this.name="FreePathPatternError"}};function ug(e,t){if(e==="*")return{raw:e,kind:"single"};if(e==="**")return{raw:e,kind:"multi"};if(e.startsWith("(")){let n=e.endsWith(")?"),r=e.endsWith(")");if(!n&&!r)throw new ye(`malformed alternation segment ${JSON.stringify(e)}`,t);let o=n?e.slice(1,-2):e.slice(1,-1);if(!lg.test(o))throw new ye(`malformed alternation segment ${JSON.stringify(e)}`,t);let s=o.split("|");if(s.some(i=>fl.has(i)))throw new ye(`alternation segment ${JSON.stringify(e)} may not contain '.' or '..'`,t);return{raw:e,kind:n?"alt-optional":"alt",alternatives:s}}if(cg.test(e)){if(fl.has(e))throw new ye(`literal segment ${JSON.stringify(e)} is not permitted`,t);return{raw:e,kind:"literal"}}throw new ye(`segment ${JSON.stringify(e)} must be '*', '**', a [A-Za-z0-9._-]+ literal, or (a|b) alternation`,t)}function dg(e){if(typeof e!="string"||e.length===0)throw new ye("must be a non-empty string",String(e));if(!e.startsWith("/"))throw new ye("must start with '/'",e);if(e.slice(1).includes("//"))throw new ye("empty segments ('//') are not permitted",e);if(e.length>1&&e.endsWith("/"))throw new ye("must not end with '/'",e);let n=e.slice(1).split("/").map(s=>ug(s,e));if(n.filter(s=>s.kind==="multi").length>1)throw new ye("at most one '**' is permitted per pattern",e);if(n[0]?.kind==="multi")throw new ye("'**' may not be the first segment (a literal prefix anchor is required)",e);let o=n.findIndex(s=>s.kind==="alt-optional");if(o!==-1&&o!==n.length-1)throw new ye("optional alternation '(...)?' is only allowed as the final segment",e);return n}function oi(e){dg(e)}var gl=["tempo","mpp_self","merchant_self"],hl=["catalog_static","fal_direct","fal_queue","openrouter_chat","openrouter_image","platform_proxy","tempo_gateway","x402_gateway"],yl=["image","audio","queued_audio","video","queued_video","model_3d","llm","transcription","utility"],_l=["images[0].url","image.url","audio.url","audio_file.url","audio_url","video.url","model_mesh.url","text","choices[0].message.content","choices[0].message.images[0].image_url.url","request_id"];var ii=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()}),mg=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:ii.optional()}).passthrough(),ai=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")})]),ci=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()}),vl=g.object({attestation:g.boolean().optional(),rateLimitMs:g.number().positive().optional()}),bl=g.object({displayName:g.string().optional(),feedbackEligible:g.boolean().optional(),suggestionEligible:g.boolean().optional(),batchable:g.boolean().optional()}),Sl=g.object({enabled:g.boolean().optional(),gatewayPath:g.string().min(1).startsWith("/").optional(),method:g.enum(["GET","POST","PUT","PATCH","DELETE"]).optional(),timeoutMs:g.number().int().positive().max(12e4).optional()}).strict(),pg=g.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),fg=120,gg=120,hg=1200,yg=/^[^\u0000-\u001F\u007F]+$/;function si(e,t){return g.string().min(1).max(e).regex(yg,`${t} must not contain control characters`)}var li={id:g.string().min(1),name:si(fg,"name"),description:si(hg,"description"),provider:g.string().min(1),model:g.string().min(1),category:pg,priceCents:g.number().nonnegative(),inputSchema:g.record(g.unknown()),gatewayUrl:g.string().min(1),merchantName:si(gg,"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:ii.optional(),priceDisplay:g.string().optional(),pricingModel:g.enum(["per-call","per-token","band"]).optional(),pricingInfo:mg.optional(),status:g.enum(["available","unavailable"]).optional(),handler:ai.optional(),pricing:ci.optional(),security:vl.optional(),engagement:bl.optional(),gatewayConfig:Sl.optional(),freeReadPathPattern:g.string().optional().superRefine((e,t)=>{if(e!==void 0)try{oi(e)}catch(n){t.addIssue({code:g.ZodIssueCode.custom,message:n instanceof Error?n.message:String(n)})}}),enabled:g.boolean().optional(),beta:g.boolean().optional(),deprecated:g.boolean().optional(),internal:g.boolean().optional(),replacementTool:g.string().optional(),minCliVersion:g.string().optional(),sunsetAt:g.string().optional(),rail:g.enum(gl).optional(),executionKind:g.enum(hl).optional(),resultKind:g.enum(yl).optional(),extractionMode:g.enum(_l).optional(),pricingStrategy:g.enum(["flat","token","band"]).optional()},wl=g.object({...li,dispatch:g.literal("routed"),routedPath:g.string().min(1).startsWith("/")}).strict(),xl=g.object({...li,dispatch:g.literal("enveloped")}).strict(),kl=g.object({...li,handler:ai,pricing:ci}).strict(),Cl=g.union([g.discriminatedUnion("dispatch",[wl,xl]),kl]);var ui=/^[a-z0-9][a-z0-9_-]*$/;var bg="https://fal.run",Rl="https://openrouter.mpp.tempo.xyz",mi=1024,Io=8192,Sg=4096,wg=10;function xg(e){return e>=wg?Sg:Io}function Il(e,t){let n=typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):mi;return Math.min(n,t)}function kg(e){let{attestation:t,tool_id:n,...r}=e;return r}var Tl={"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 Ro(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"&&Tl[r]&&(i.image_size=Tl[r]),i)}function Cg(e){let{attestation:t,tool_id:n,...r}=e;return r}function El(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 Tg(e,t,n,r,o,s,i,a,c){return{id:e,name:t,description:n,provider:r,model:o.replace(/^\//,""),category:s,gatewayUrl:`https://${r}${o}`,merchantName:t,inputSchema:a,handler:{type:"custom",merchantSlug:r,subPath:o},pricing:{amount:i,currency:"USD",display:`$${(i/100).toFixed(2)}`},priceCents:i,tags:[],...c}}function Eg(e,t,n,r,o,s,i,a){return Tg(e,t,n,"suno-ai",r,o,s,i,{merchantName:"Suno AI",...a})}function ne(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:`${bg}/${r}`,merchantName:"fal.ai",buildBody:kg,tags:[],...a}}function $l(e,t=Io){return n=>{let{attestation:r,tool_id:o,model:s,prompt:i,system_prompt:a,max_tokens:c,max_completion_tokens:l,messages:u,temperature:d,...f}=n;return typeof s=="string"&&s.length>0&&s!==e&&console.warn("[catalog] openrouterBuildBody: caller model override ignored",{catalogModel:e,callerModel:s}),{messages:Array.isArray(u)?u:[...a?[{role:"system",content:a}]:[],{role:"user",content:i}],temperature:d??.7,...f,model:e,max_tokens:Il(c??l,t)}}}function Pl(e,t=Io){return n=>{let{attestation:r,tool_id:o,prompt:s,image_url:i,aspect_ratio:a,max_tokens:c,max_completion_tokens:l,model:u,messages:d,image_config:f,temperature:m,...y}=n,S=[{type:"text",text:s}];return typeof i=="string"&&i.length>0&&S.push({type:"image_url",image_url:{url:i}}),{messages:Array.isArray(d)?d:[{role:"user",content:S}],temperature:m??.7,...y,model:e,...typeof a=="string"&&a.length>0?{image_config:{aspect_ratio:a}}:{},max_tokens:Il(c??l,t)}}}function X(e,t,n,r,o,s,i){let a=i?.maxOutputTokens??xg(s),c=i?.perRequestFeeCents??0,l=500/1e6*o*100,u=500/1e6*s*100,d=Math.max(1,Math.ceil(l+u+c)),{perRequestFeeCents:f,maxOutputTokens:m,...y}=i??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"llm",priceCents:d,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The prompt or question to send to the model"},system_prompt:{type:"string",description:"Optional system prompt to set model behavior"},max_tokens:{type:"integer",description:`Maximum tokens in response (default: ${mi}); values above ${a} are clamped to ${a}`,minimum:1,maximum:a},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${Rl}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:$l(r,a),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:o,outputPerMillion:s,...c>0?{perRequestFeeCents:c}:{}},...y}}function di(e,t,n,r,o,s){let i=s?.maxOutputTokens??Io,{maxOutputTokens:a,...c}=s??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"image",pricingStrategy:"band",priceCents:o,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate or edit"},image_url:{type:"string",description:"Optional source image URL for edits"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"1:1"},max_tokens:{type:"integer",description:`Maximum text tokens in response metadata (default: ${mi}); values above ${i} are clamped to ${i}`,minimum:1,maximum:i},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${Rl}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:Pl(r,i),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...c}}var pi=[ne("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"]}),ne("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:Ro}),ne("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:Ro}),ne("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:Ro}),ne("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"]}),di("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),di("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}}),di("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}}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),Eg("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}}}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),X("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"]}),X("or-gpt-55","GPT-5.5","OpenAI frontier model for complex professional reasoning, coding, and long-context analysis.","openai/gpt-5.5",5,30,{tags:["llm","gpt","openai","frontier","reasoning","coding","long-context"]}),X("or-gpt-55-pro","GPT-5.5 Pro","OpenAI high-capability frontier model optimized for deep reasoning and high-stakes workloads.","openai/gpt-5.5-pro",30,180,{tags:["llm","gpt","openai","frontier","pro","deep-reasoning","coding","long-context"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("or-gemini-35-flash","Gemini 3.5 Flash","Google frontier Flash model for multimodal reasoning, coding, and parallel agentic workflows.","google/gemini-3.5-flash",1.5,9,{tags:["llm","gemini","google","frontier","multimodal","reasoning","coding","fast"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("or-perplexity-sonar","Perplexity Sonar","Search-augmented LLM. Answers with real-time web sources and citations.","perplexity/sonar",1,1,{perRequestFeeCents:.5,tags:["llm","perplexity","search","web","citations","real-time"]}),{dispatch:"enveloped",id:"query_onchain_prices",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly and daily granularity.",provider:"allium",model:"allium-prices",category:"onchain",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly) or '1d' (daily). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",internal:!0,executionKind:"x402_gateway",resultKind:"utility",gatewayConfig:{enabled:!1,gatewayPath:"/gateway",method:"POST",timeoutMs:3e4},buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:El,tags:["onchain","prices","allium","crypto"]},{dispatch:"enveloped",id:"parallel-search-tempo",name:"Parallel Search (Tempo)",description:"Internal Tempo gateway route for Parallel's paid search endpoint.",provider:"parallel",model:"search",category:"utility",priceCents:1,inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query. Mapped by Parallel to objective when provided."},objective:{type:"string",description:"Search objective. Use with search_queries for advanced requests."},search_queries:{type:"array",items:{type:"string"},description:"Optional explicit search query list."},mode:{type:"string",enum:["one-shot","fast"],description:"Parallel search mode.",default:"one-shot"}},anyOf:[{required:["query"]},{required:["objective"]}]},gatewayUrl:"https://parallelmpp.dev/api/search",merchantName:"Parallel",internal:!0,rail:"tempo",executionKind:"tempo_gateway",resultKind:"utility",gatewayConfig:{enabled:!1,gatewayPath:"/gateway",method:"POST",timeoutMs:3e4},buildBody:Cg,tags:["search","parallel","tempo","internal"]},{dispatch:"enveloped",id:"generate_image_card",name:"Generate Image (Ultra)",description:"Generate a high-quality AI image (FLUX Pro Ultra, 2K, ~$0.06).",provider:"fal",model:"fal-ai/flux-pro/v1.1-ultra",category:"image",priceCents:6,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1-ultra",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro-ultra",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),t},tags:["image","flux","ultra","legacy"]},{dispatch:"enveloped",id:"generate_image_fast_card",name:"Generate Image (Fast)",description:"Generate an AI image (FLUX Pro v1.1, 1K, ~$0.04).",provider:"fal",model:"fal-ai/flux-pro/v1.1",category:"image",priceCents:4,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro",buildBody:e=>Ro({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"]},ne("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"}),ne("edit_image_seed_card","Edit Image (SeedEdit)","Inpaint/edit an image with a prompt using SeedEdit.","fal-ai/bytedance/seededit","image",5,{type:"object",properties:{image_url:{type:"string"},prompt:{type:"string"},seed:{type:"number"}},required:["image_url","prompt"]},{buildBody:e=>{let t={image_url:e.image_url,prompt:e.prompt};return e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","edit","inpaint","seededit"],deprecated:!0,replacementTool:"or-gemini-nano-banana"}),{dispatch:"enveloped",id:"generate_video_tempo_card",name:"Generate Video (Grok)",description:"Generate a video from a text prompt using Grok Imagine Video.",provider:"fal",model:"xai/grok-imagine-video/text-to-video",category:"video",priceCents:30,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/xai/grok-imagine-video/text-to-video",merchantName:"Grok Video via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),t},tags:["video","grok","legacy"]},{dispatch:"enveloped",id:"generate_video_kling_card",name:"Generate Video (Kling)",description:"Generate a video using Kling v1.6 (async, ~$0.40).",provider:"fal",model:"fal-ai/kling-video/v1.6/standard/text-to-video",category:"video",priceCents:40,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/kling-video/v1.6/standard/text-to-video",merchantName:"Kling via fal.ai",deprecated:!0,replacementTool:"fal-kling-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","kling","legacy"]},{dispatch:"enveloped",id:"generate_video_wan_card",name:"Generate Video (Wan)",description:"Generate a video using Wan T2V (async, ~$0.25).",provider:"fal",model:"fal-ai/wan/t2v-1.3b",category:"video",priceCents:25,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/wan/t2v-1.3b",merchantName:"Wan T2V via fal.ai",deprecated:!0,replacementTool:"fal-wan-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","wan","legacy"]},{dispatch:"enveloped",id:"generate_video_minimax_card",name:"Generate Video (MiniMax)",description:"Generate a video using MiniMax (async, ~$0.35).",provider:"fal",model:"fal-ai/minimax/video-01",category:"video",priceCents:35,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/minimax/video-01",merchantName:"MiniMax via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","minimax","legacy"]},{id:"check_fal_status",name:"Check fal Async Job Status",description:"Poll an async fal.ai queue job for completion. Free.",provider:"fal",model:"queue-status",category:"image",priceCents:0,inputSchema:{type:"object",properties:{model_path:{type:"string",description:"Model path (e.g. fal-ai/kling-video/v1.6/standard/text-to-video)"},request_id:{type:"string"}},required:["model_path","request_id"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue",merchantName:"fal.ai",handler:{type:"local",fn:"check_fal_status"},pricing:{amount:0,currency:"USD",display:"$0.00",free:!0},freeReadPathPattern:"/api/v1/fal/**/requests/*/(status)?",tags:["status","fal","async"]},{dispatch:"enveloped",id:"generate_3d_card",name:"Generate 3D Model",description:"Generate a 3D mesh from a text prompt using Meshy (async, ~$0.50).",provider:"fal",model:"fal-ai/meshy-ai/text-to-3d",category:"3d",priceCents:50,inputSchema:{type:"object",properties:{object_prompt:{type:"string"},style_prompt:{type:"string"},negative_prompt:{type:"string"},art_style:{type:"string"},seed:{type:"number"}},required:["object_prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/meshy-ai/text-to-3d",merchantName:"Meshy via fal.ai",deprecated:!0,replacementTool:"fal-trellis-3d",buildBody:e=>{let t={object_prompt:e.object_prompt};return e.style_prompt&&(t.style_prompt=e.style_prompt),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.art_style&&(t.art_style=e.art_style),e.seed!==void 0&&(t.seed=e.seed),t},tags:["3d","mesh","meshy","legacy"]},{dispatch:"enveloped",id:"generate_speech_card",name:"Generate Speech",description:"Text-to-speech using F5-TTS with optional voice cloning.",provider:"fal",model:"fal-ai/f5-tts",category:"tts",priceCents:3,inputSchema:{type:"object",properties:{gen_text:{type:"string",description:"Text to synthesize"},ref_audio_url:{type:"string",description:"Reference audio URL (for voice cloning)"},ref_text:{type:"string",description:"Transcription of ref audio"},remove_silence:{type:"boolean"}},required:["gen_text"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/f5-tts",merchantName:"fal.ai",buildBody:e=>{let t={gen_text:e.gen_text};return e.ref_audio_url&&(t.ref_audio_url=e.ref_audio_url),e.ref_text&&(t.ref_text=e.ref_text),e.remove_silence!==void 0&&(t.remove_silence=e.remove_silence),t},deprecated:!0,replacementTool:"fal-metavoice",tags:["tts","speech","f5-tts","legacy"]},{dispatch:"enveloped",id:"generate_music_tempo_card",name:"Generate Music (Suno) \u2014 retired",description:"[Retired] Suno music generation. Use `generate_music` (ACE-Step) instead.",enabled:!1,sunsetAt:"2026-06-25",provider:"suno",model:"suno-v4",category:"audio",priceCents:50,inputSchema:{type:"object",properties:{prompt:{type:"string"},instrumental:{type:"boolean"},model:{type:"string",default:"V4"}},required:["prompt"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/generate-music",merchantName:"Suno via Tempo",buildBody:e=>({prompt:e.prompt,customMode:!1,instrumental:e.instrumental??!1,model:e.model||"V4"}),isAsync:!0,pollUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",pollInterval:15e3,pollTimeout:3e5,deprecated:!0,replacementTool:"fal-ace-step-music",tags:["music","audio","suno","async","legacy"]},{dispatch:"enveloped",id:"check_music_status_tempo_card",name:"Check Music Status (Suno) \u2014 retired",description:"[Retired] Suno status poll. No replacement; ACE-Step jobs poll via `check_fal_status`.",enabled:!1,sunsetAt:"2026-06-25",provider:"suno",model:"suno-status",category:"audio",priceCents:0,inputSchema:{type:"object",properties:{taskId:{type:"string"}},required:["taskId"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",merchantName:"Suno Status",buildBody:e=>({taskId:e.taskId}),deprecated:!0,tags:["music","status","suno","legacy"]},{dispatch:"enveloped",id:"query_onchain_prices_card",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly, daily, and weekly granularity.",provider:"allium",model:"allium-prices",category:"llm",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly), '1d' (daily), or '1w' (weekly). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",deprecated:!0,replacementTool:"query_onchain_prices",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:El,tags:["onchain","prices","allium","crypto","legacy"]}];function kr(e){return pi.find(t=>t.id===e)}var Ol=1,Ml=["pick_one","fan_out"],Nl=["concat","dedupe_by_url","top_k_by_score"],Ig=8,$g=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()}),Pg=g.object({toolId:g.string().min(1),notes:g.string().min(1)}),Og=g.string().regex(/^[a-z0-9_-]{1,32}$/,"tier key must be 1-32 chars [a-z0-9_-]"),Mg=g.object({providers:g.array(g.string().min(1)).min(1).max(Ig),merge:g.enum(Nl),maxResults:g.number().int().positive().optional()}),Ll=g.object({mode:g.enum(Ml).default("pick_one"),intro:g.string().min(1),defaultTier:g.string().min(1),tiers:g.record(Og,Pg).refine(e=>Object.keys(e).length>0,{message:"must have at least one tier"}),fanOut:Mg.optional(),guidance:g.string().min(1),inputProperties:g.record(g.string(),$g),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"]}),Ng=g.object({version:g.literal(Ol),generatedAt:g.string().datetime(),tools:g.record(g.string().regex(ui,"tool name must match MCP naming rules"),Ll).refine(e=>Object.keys(e).length>0,{message:"manifest must have at least one tool"})});var Mo=require("child_process"),ql=require("util"),Bl=E(require("crypto")),W=E(require("fs")),Kl=E(require("os")),fe=E(require("path"));var Le=(0,ql.promisify)(Mo.execFile),Ug=()=>process.platform==="darwin",Nt=()=>process.platform==="win32",Lt=fe.join(Kl.homedir(),".visa-mcp","bin"),_n=fe.join(Lt,"Visa CLI"),Mt=fe.join(Lt,"visa-keychain-win.exe"),Gl=fe.join(__dirname,"..","native"),Dl="6",Ul=fe.join(Lt,"visa-keychain.version"),jl=fe.join(Lt,"visa-keychain.sha256"),Fl="1",Vl=fe.join(Lt,"visa-keychain-win.version"),Hl=fe.join(Lt,"visa-keychain-win.sha256"),jg=[fe.join(Gl,"bin","win32-x64","visa-keychain-win.exe"),fe.resolve(__dirname,"..","..","native","bin","win32-x64","visa-keychain-win.exe"),fe.resolve(__dirname,"..","native","bin","win32-x64","visa-keychain-win.exe")];function $o(e){let t=W.readFileSync(e);return Bl.createHash("sha256").update(t).digest("hex")}function Fg(e){let t=e.trim();if(t.startsWith("OK:"))return t.slice(3);if(t==="OK")return;let n=t.startsWith("ERROR:")?t.slice(6):"Unknown error";throw new Error(n)}async function fi(){try{if(W.readFileSync(Ul,"utf-8").trim()===Dl&&W.existsSync(_n)){let r=W.readFileSync(jl,"utf-8").trim();if($o(_n)!==r)p.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),W.unlinkSync(_n);else return _n}}catch{}let e=fe.join(Gl,"visa-keychain.m");if(W.existsSync(e)||(e=fe.resolve(__dirname,"..","..","native","visa-keychain.m")),W.existsSync(e)||(e=fe.resolve(__dirname,"..","native","visa-keychain.m")),!W.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");W.mkdirSync(Lt,{recursive:!0,mode:448});try{await Le("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",_n,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=$o(_n);return W.writeFileSync(jl,t,{mode:384}),W.writeFileSync(Ul,Dl,{mode:384}),_n}function Wl(){for(let e of jg)if(W.existsSync(e))return e;return null}async function qn(){try{if(W.readFileSync(Vl,"utf-8").trim()===Fl&&W.existsSync(Mt)){let r=W.readFileSync(Hl,"utf-8").trim();if($o(Mt)!==r)p.warn("binary:hash-mismatch:win32",{message:"Windows binary hash mismatch. Redeploying."}),W.unlinkSync(Mt);else return Mt}}catch{}let e=Wl();if(!e)throw new Error(`visa-keychain-win.exe not found in package. Reinstall @visa/cli.
124
- If building from source, run native/build-win.bat first.`);W.mkdirSync(Lt,{recursive:!0}),W.copyFileSync(e,Mt);let t=$o(Mt);return W.writeFileSync(Hl,t,{mode:384}),W.writeFileSync(Vl,Fl,{mode:384}),Mt}async function Vg(){return Nt()?qn():fi()}var Po="visa-cli",Oo="attestation-key";async function Hg(e){try{await Le("security",["delete-generic-password","-s",Po,"-a",Oo],{timeout:5e3})}catch{}await Le("security",["add-generic-password","-s",Po,"-a",Oo,"-w",e],{timeout:5e3})}async function gi(){try{let{stdout:e}=await Le("security",["find-generic-password","-s",Po,"-a",Oo,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function zl(e){let t=await Vg(),n;try{n=(await Le(t,e,{timeout:6e4})).stdout}catch(r){n=r.stdout||"";let o=n.trim();throw o.startsWith("ERROR:")?new Error(o.slice(6)):new Error(r.stderr?.trim()||r.message||"Unknown error")}return Fg(n)}function qg(){if(!Nt())return!1;try{return W.existsSync(Mt)?!0:Wl()!==null}catch{return!1}}function re(){return Tn()||Ug()?!0:Nt()?qg():!1}async function No(){if(Nt()){let o=await qn(),{stdout:s}=await Le(o,["generate-key"],{timeout:3e4}),i=s.trim();if(i.startsWith("OK:"))return i.slice(3);throw new Error(i.startsWith("ERROR:")?i.slice(6):"Key generation failed")}let e=await zl(["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 Hg(n),r}async function Lo(){if(Nt())try{let e=await qn(),{stdout:t}=await Le(e,["public-key"],{timeout:1e4});return t.trim().startsWith("OK:")}catch{return!1}return await gi()!==null}async function Jl(){if(Tn())return"mock-public-key-spki";if(Nt()){let n=await qn(),{stdout:r}=await Le(n,["public-key"],{timeout:6e4}),o=r.trim();if(o.startsWith("OK:"))return o.slice(3);throw new Error(o.startsWith("ERROR:")?o.slice(6):"Attestation key not found. Run setup to generate a new key.")}let e=await gi();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await fi();return new Promise((n,r)=>{let o=(0,Mo.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 vn(e,t){if(Tn())return Promise.resolve(Ta());if(Nt()){let s=await qn(),i=["sign",e];t&&i.push(t);let{stdout:a}=await Le(s,i,{timeout:6e4}),c=a.trim();if(c.startsWith("OK:"))return c.slice(3);throw new Error(c.startsWith("ERROR:")?c.slice(6):"Unknown error")}let n=await gi();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await fi(),o=["sign",e];return t&&o.push(t),new Promise((s,i)=>{let a=(0,Mo.execFile)(r,o,{timeout:6e4},(c,l)=>{let u=(l||"").trim();if(c){u.startsWith("ERROR:")?i(new Error(u.slice(6))):i(new Error(c.stderr?.trim()||c.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 Do(){if(Nt()){try{let e=await qn();await Le(e,["delete-key"],{timeout:1e4})}catch{}return}try{await Le("security",["delete-generic-password","-s",Po,"-a",Oo],{timeout:5e3})}catch{}try{await zl(["delete-key"])}catch{}}var Bg=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],Kg=[...Bg.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 yi(e,t=Kg){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=hi(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(hi(r.match.provider)))&&r.match.keywords.every(o=>n.includes(hi(o))))return r.targetToolId;return null}function hi(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}var Tr={generate_image:{intro:'Generate an AI image from a text prompt \u2014 useful for hero shots, marketing assets, social posts, blog covers, app mockups, or any time the user asks for art, a logo, an icon, a thumbnail, or "a picture of \u2026". From $0.01 (fast) to $0.06 (pro), returns a hosted PNG/JPG URL. Default tier: balanced ($0.04, 1K, ~10s).',tiers:{balanced:{toolId:"fal-flux-pro",notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",notes:"Recraft V3 \u2014 vector/flat/illustration styles"}},guidance:"If the user didn't specify a tier, pick 'balanced' unless the prompt clearly signals otherwise (text \u2192 text_heavy, logo/icon \u2192 vector, quick test \u2192 fast, hero/print \u2192 pro).",inputProperties:{prompt:{type:"string",description:"Text description of the image to generate."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9", "1:1", "9:16".',default:"16:9"}},required:["prompt"]},generate_video:{intro:'Generate a short AI video from a text prompt \u2014 useful for product demos, social clips, mood reels, ad concepts, or any "make me a video of \u2026" request. $0.10\u2013$0.40 per ~6s clip depending on tier. Async: returns a request_id; use execute_tool with tool_id "check_fal_status" to resolve it (60\u2013180s).',tiers:{balanced:{toolId:"fal-minimax-video",notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",notes:"Kling \u2014 highest quality, cinematic"}},guidance:'Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate and are processed asynchronously. The response includes a request_id and model_path. Poll with execute_tool using tool_id "check_fal_status" and the exact request_id/model_path returned by the async response. Do not substitute the catalog model path manually. Do not poll more than once per 30 seconds.',inputProperties:{prompt:{type:"string",description:"Text description of the video scene."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9" or "9:16".',default:"16:9"}},required:["prompt"]},generate_music:{intro:'Generate an original music track from a prompt via ACE-Step. ~$0.02 for the default 60s track. Use for songs, backing tracks, jingles, vocal music, instrumental music, or any "make a song/music/track" request. Takes ~60-90s and may return a request_id to poll with check_fal_status. For SFX, chimes, ambient beds, or TTS, use generate_audio instead.',tiers:{ace_step:{toolId:"fal-ace-step-music",notes:"ACE-Step \u2014 prompt-to-music with vocals or instrumentals"}},guidance:"Use for songs and music tracks. Takes ~60-90s and may return a request_id to poll with check_fal_status. For sound effects, chimes, ambient beds, or TTS, use generate_audio instead.",inputProperties:{prompt:{type:"string",description:"Musical style, mood, instruments, subject, and lyrics direction."},instrumental:{type:"boolean",description:"True for instrumental music with no vocals; false for vocal tracks.",default:!1},duration:{type:"number",description:"Duration in seconds.",default:60}},required:["prompt"]},generate_audio:{intro:'Generate sound effects from a text prompt (sfx tier \u2014 default), or voice-cloned speech from text + a reference audio URL (tts tier). $0.03\u2013$0.04. Use for SFX, chimes, UI sounds, ambient audio (default sfx), or voice cloning when a reference audio URL is available (pass tier:"tts"). Default tier is sfx; pass tier:"tts" for voice cloning.',tiers:{sfx:{toolId:"fal-stable-audio",notes:"Stable Audio \u2014 sound effects and ambient from a prompt"},tts:{toolId:"fal-metavoice",notes:"MetaVoice \u2014 voice cloning TTS (requires a voice sample URL)"}},guidance:'Default tier is sfx: pass prompt describing the sound. For tts (voice cloning): pass tier:"tts" + text + audio_url.',inputProperties:{prompt:{type:"string",description:"Description of sound to generate (sfx tier, default)."},text:{type:"string",description:"Text to speak aloud (tts tier)."},audio_url:{type:"string",description:"URL of a voice sample to clone (tts tier, required for voice cloning)."}},required:[]},generate_3d:{intro:"Generate a 3D mesh (GLB) from an image URL via Trellis. ~$0.08, ~30\u201360s. Use when the user shares an image and asks for a 3D model, asset, AR-ready mesh, or game-ready GLB.",tiers:{trellis:{toolId:"fal-trellis-3d",notes:"Trellis \u2014 image-to-3D, returns a GLB mesh URL"}},guidance:"Pass an image URL. Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{image_url:{type:"string",description:"URL of the image to convert to a 3D model."}},required:["image_url"]},upscale_image:{intro:'Upscale an image to 4\xD7 resolution via Aura SR (preserves detail without hallucination). ~$0.03. Use whenever the user shares a low-res image and asks to "upscale", "make this higher resolution", "4x this", "enhance", or to print/export at larger size.',tiers:{aura:{toolId:"fal-aura-sr",notes:"Aura SR \u2014 default; preserves detail without hallucination"}},guidance:"Pass the existing image URL. Returns an upscaled version.",inputProperties:{image_url:{type:"string",description:"URL of the image to upscale."}},required:["image_url"]},transcribe_audio:{intro:'Transcribe speech in an audio or video file (URL) to text via OpenAI Whisper. ~$0.02 per file, multilingual, handles long files. Use whenever the user asks to "transcribe this", "what does this audio say", "make subtitles", "convert this to text", or shares an audio/video URL with no other clear intent.',tiers:{whisper:{toolId:"fal-whisper",notes:"OpenAI Whisper \u2014 fast, multilingual"}},guidance:"Pass the URL. Returns the transcript text.",inputProperties:{audio_url:{type:"string",description:"URL of the audio or video file to transcribe."}},required:["audio_url"]},run_llm:{intro:"Run a text prompt through a different LLM (GPT-4o-mini, Claude Sonnet, DeepSeek R1/V3, Perplexity Sonar with web search, or Llama 70B). Token-metered, typically ~$0.01\u2013$0.10 per call. Use for: web-grounded answers (search tier), second-opinion reasoning (reasoning tier), code generation in a different family (coding tier), deep math/logic (deep_reasoning tier), or fast cheap text cleanup (fast tier). Pair with batch for multi-model councils.",tiers:{fast:{toolId:"or-gpt-4o-mini",notes:"GPT-4o Mini. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",notes:"Claude Sonnet. Strong reasoning, long-context. Warn user it is materially pricier than `fast`."},frontier_openai:{toolId:"or-gpt-55",notes:"GPT-5.5. OpenAI frontier model for complex professional reasoning."},frontier_openai_pro:{toolId:"or-gpt-55-pro",notes:"GPT-5.5 Pro. Highest-capability OpenAI frontier tier; materially more expensive."},frontier_anthropic:{toolId:"or-claude-opus",notes:"Claude Opus 4.7. Anthropic frontier model for complex tasks."},frontier_google:{toolId:"or-gemini-35-flash",notes:"Gemini 3.5 Flash. Google frontier Flash model for multimodal reasoning and coding."},deep_reasoning:{toolId:"or-deepseek-r1",notes:"DeepSeek R1. Deep chain-of-thought reasoning, mid-range pricing."},search:{toolId:"or-perplexity-sonar",notes:"Perplexity Sonar. Search-augmented, web-grounded with citations."},open_source:{toolId:"or-llama-70b",notes:"Llama 3.3 70B. Open-source large model."},coding:{toolId:"or-deepseek-chat",notes:"DeepSeek Chat V3. Strong at code generation."}},guidance:"Pick based on the user's need: fast (most questions, cheapest), reasoning (complex analysis; warn user it is materially pricier than fast), frontier_* (top-model council / highest quality; warn user these are materially pricier), search (questions about current events), coding (code generation), deep_reasoning (hard math/logic problems).",inputProperties:{prompt:{type:"string",description:"The user query."},system_prompt:{type:"string",description:"Optional system prompt to set model behavior."},max_tokens:{type:"number",description:"Maximum output tokens.",default:1024,minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature \u2014 0 is deterministic, higher is more creative.",default:.7,minimum:0,maximum:2}},required:["prompt"]}};function Dt(e,t,n){if(!Zl(e))return Jg(e,n);let r=Yl[e];if(!r)return e;let o=Object.keys(r.tiers),s=t||o[0],i=Yg(e,s,n);return i||Zg(e,r,s,o)}function Jg(e,t){return yi({requestedTool:e,intentText:t})??e}function Yg(e,t,n){return yi({requestedTool:e,metaTool:e,tier:t,intentText:n})}function Zg(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 Yl=Tr;function Zl(e){return e in Yl}var Er=Object.keys(Tr);function _i(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function Xl(e=process.env){return _i(e)!==null}var Nu=require("child_process"),ge=E(require("crypto")),je=E(require("fs")),$r=E(require("os")),Qo=E(require("path"));function bn(e,t={}){if(!e||typeof e!="object")return e;let n=e,r=t.tag??(typeof n.merchantName=="string"?n.merchantName:"media"),o=n.content?.[0]?.text,s=typeof o=="string"?En(o):null,i=Array.isArray(n.urls)?n.urls[0]:void 0,c=typeof i=="string"&&i.startsWith("data:")?En(i):null;if(!s&&!c)return e;let l=s??c,u=s?"content":"urls",d;try{d=rr(l,{tag:Xg(r,n)})}catch(m){return{...n,_inline_media_warning:`Failed to persist inline media to disk: ${m instanceof Error?m.message:String(m)}`}}let f={...n,filePath:d.filePath,mime:d.mime,bytes:d.bytes};return u==="urls"?f.urls=void 0:(f.content=Array.isArray(n.content)?[...n.content]:[{}],f.content[0]={...f.content[0]??{},text:`[inline media saved to ${d.filePath}]`}),f}function Xg(e,t){let n=typeof t.transactionId=="string"?t.transactionId:typeof t.transaction_id=="string"?t.transaction_id:null;return n?`${e}-${n}`:e}var Ql=!1;async function Bn(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(p.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(Ql)throw p.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;Ql=!0,p.info("attestation:starting-browser-recovery");try{let s=await n();if(!s.success)throw p.error("attestation:browser-recovery-failed",{message:s.message}),r;let i=await No();return await e.registerAttestationKey(i),await e.setBiometricPreference({required:!0}),p.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),p.info("attestation:key-reregistered-after-recovery"),await t()}catch(s){throw p.error("attestation:recovery-failure",{error:s.message}),r}}throw r}}function ze(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}async function Uo(e,t){if(!re())return{ok:!1,code:"TOUCH_ID_UNAVAILABLE",message:"Touch ID is not available in this process. Run `visa-cli setup` from an interactive macOS terminal before enabling Touch ID."};if(!await Lo())return{ok:!1,code:"LOCAL_ATTESTATION_KEY_MISSING",message:"No local attestation key found on this device. Run `visa-cli setup` before enabling Touch ID; otherwise payments and biometric off can require a key this device cannot produce."};let n=await e.getStatus(t);return ze(n)?{ok:!0,status:n}:{ok:!1,code:"SERVER_ATTESTATION_KEY_MISSING",message:"No server attestation key is registered for this account. Run `visa-cli setup` before enabling Touch ID."}}var eu="2.7.0-rc.4";function vi(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function jo(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=So(t);return o!==void 0?{value:o,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function Te(e){return e==null?"\u2014":e?"yes":"no"}function Fo(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function Qg(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function eh(){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=ei("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:Xs,source:{kind:"default"}}}async function Ar(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(L){n=L?.message||"unknown error"}let r=[],o=process.env.VISA_AUTH_URL,s=Qs("auth.serverUrl"),i=ke(),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:Te(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 c=t?t.attestationRequired!==!1:void 0;r.push({key:"biometric.required",value:c,formatted:Te(c),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"},hint:c===!1?"Touch ID prompts are suppressed. Re-enable with `visa-cli config biometric on`.":void 0}),r.push({key:"biometric.keyRegistered",value:t?.hasAttestationKey??null,formatted:Te(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:re(),formatted:Te(re()),source:{kind:"device"}});let l=t?.spendingControls,u=l?l.max_transaction_amount??l.maxTransactionAmount??null:null,d=l?l.daily_limit??l.dailyLimit??null:null;r.push({key:"spending.maxPerTxn",value:u,formatted:Fo(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:Fo(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:Fo(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:Fo(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(L=>L.isDefault)??t?.cards?.[0];f&&r.push({key:"cards.default",value:{brand:f.brand??null,last4:f.last4},formatted:`${f.brand||"card"} \u2022\u2022\u2022\u2022 ${f.last4}`,source:{kind:"server"}});let m=eh();r.push({key:"credit.sessionCapCents",value:m.value,formatted:Qg(m.value),source:m.source});let y=Yc();y.length>0&&r.push({key:"settings.retired",value:y.map(L=>L.key),formatted:y.map(L=>L.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${y.map(L=>`visa-cli config unset ${L.key}`).join(" && ")}`});let S=jo("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:S.value,formatted:Te(S.value),source:S.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let $=jo("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:$.value,formatted:Te($.value),source:$.source});let H=Be(),U;process.env.VISA_CLI_NO_UPDATE_CHECK?U={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?U={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?U={kind:"env",var:"NODE_ENV"}:U={kind:"default"},r.push({key:"ui.updateCheck",value:!H,formatted:Te(!H),source:U});let w=jo("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:w.value,formatted:Te(w.value),source:w.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let x=jo("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:x.value,formatted:Te(x.value),source:x.source});let _=process.env.VISA_DRY_RUN,C=Xl();if(r.push({key:"tools.dryRun",value:C,formatted:Te(C),source:_===void 0?{kind:"default"}:{kind:"env",var:"VISA_DRY_RUN"},hint:"VISA_DRY_RUN=true|1|mock returns deterministic paid-tool fixtures (no card, no upstream). VISA_DRY_RUN=preflight makes a real zero-cost OpenRouter call for LLM tools (image/video still mocked)."}),r.push({key:"client.version",value:eu,formatted:eu,source:{kind:"default"}}),e.includeDev){let L=process.env.VISA_MOCK_KEYCHAIN,Oe=_t();r.push({key:"dev.mockKeychain",value:Oe,formatted:Te(Oe),source:vi("VISA_MOCK_KEYCHAIN",!!L),hint:fs()});let Bt=process.env.VISA_MOCK_TOUCHID,xe=Tn();r.push({key:"dev.mockTouchid",value:xe,formatted:Te(xe),source:vi("VISA_MOCK_TOUCHID",!!Bt),hint:fs()});let K=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!K,formatted:Te(!!K),source:vi("VISA_CLI_DEBUG",!!K)})}return{entries:r,statusError:n}}function th(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 tu(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}(${th(s.source)})`),t.verbose&&s.hint&&o.push(` ${"\u21B3".padStart(n)} ${s.hint}`)}return o.join(`
125
- `)}function nu(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 ru(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 Ut=require("fs"),su=require("os"),bi=require("path"),nh=(0,bi.join)((0,su.homedir)(),".visa-mcp"),ou=(0,bi.join)(nh,"mcp-session-budget.json");function Vo(){try{(0,Ut.existsSync)(ou)&&(0,Ut.unlinkSync)(ou)}catch{}}var wi=require("crypto"),Ue=E(Rr()),Sn=null,Ee=0,Kn=0,we=0,jt=null,xi=null,ki=null,qo=Promise.resolve();function bh(e){return Number((0,Ue.fromCents)(e))}function cu(e){return(0,Ue.toCents)((0,Ue.micros)(BigInt(e)))}function au(e){return(0,Ue.toWire)((0,Ue.fromCents)(e))}function Si(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Ho(e){return typeof e=="string"&&/^\d+$/.test(e)}var Sh=43,wh=new RegExp(`^[A-Za-z0-9_-]{${Sh}}$`);function xh(e){return typeof e=="string"&&wh.test(e)}function kh(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||Sn&&e.session_id!==Sn||typeof e.nonce!="string"||e.nonce.length===0||!xh(e.server_signature)||!Si(e.cumulative)||!Si(e.remaining)||!Si(e.delta)||e.cumulative<Ee||we>0&&e.cumulative>we||we>0&&e.remaining>we||e.cumulative_micros!==void 0&&!Ho(e.cumulative_micros)||e.remaining_micros!==void 0&&!Ho(e.remaining_micros)||e.delta_micros!==void 0&&!Ho(e.delta_micros)||e.reserved_micros!==void 0&&!Ho(e.reserved_micros))}function gt(e){Sn=e,Ee=0,Kn=0,we=0,jt=null,xi=null,ki=null,qo=Promise.resolve()}function Ir(e){we=Math.max(0,Math.floor(e))}function Ci(){return Sn}function Ti(e){if(!Sn)return null;let t=Ee+Kn;return we>0&&t>we&&(t=we),{session_budget_id:Sn,cumulative_micros:bh(t),nonce:(0,wi.randomUUID)(),idempotency_key:e||(0,wi.randomUUID)()}}function Ei(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 kh(r)?(Ee=Math.max(Ee,r.cumulative),Kn=0,jt=r,r):null}function lu(){return jt}function Ai(e){let t=cu(e.cumulative_micros);Ee=Math.max(Ee,t),Kn=0;let n={status:"accepted",session_id:e.session_budget_id,cumulative:Ee,remaining:Math.max(0,we-Ee),delta:0,cumulative_micros:au(Ee),remaining_micros:au(Math.max(0,we-Ee)),delta_micros:"0",nonce:e.nonce};return jt=n,n}function Ri(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,Ue.toCents)((0,Ue.micros)(n));if(!Number.isFinite(r)||r<0)return;xi=t;let o=e,s=typeof o.session_id=="string"?o.session_id:Sn??"";jt?(typeof o.remaining_micros=="string"&&/^\d+$/.test(o.remaining_micros)&&(jt.remaining_micros=o.remaining_micros),typeof o.charged_micros=="string"&&/^\d+$/.test(o.charged_micros)&&(jt.delta_micros=o.charged_micros)):jt={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 uu(e){let t=e.receipt??null;ki={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:cu(e.voucher.cumulative_micros),estimatedCumulativeCents:Bo(),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 du(){return ki}function mu(){return Ee}function pu(){return xi}function Bo(){let e=Ee+Kn;return we>0&&e>we&&(e=we),e}function fu(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return qo=qo.then(()=>{Kn+=t}),qo}var Ch=10,Th=1,Q=null,gu=Promise.resolve();function Ii(e){let t=gu.catch(()=>{}).then(e);return gu=t.then(()=>{},()=>{}),t}var _e=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 $i(e,t,n){return Ii(()=>hu(e,t,n))}async function hu(e,t,n){if(Vo(),Q&&new Date(Q.expiresAt).getTime()>Date.now())return Ci()!==Q.budgetId&&(gt(Q.budgetId),Ir(Q.totalCents)),p.info("mcp-session:active-hit",{budgetId:Q.budgetId,tool:n.toolName,remainingEstimatedCents:Q.totalCents-Bo()}),{budgetId:Q.budgetId,isFresh:!1,totalCents:Q.totalCents,requestedCapCents:Q.totalCents,appliedCapCents:Q.totalCents,clampedReason:null};Q&&(Q=null,gt(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"?Th:Ch,i=Math.max(s,Math.ceil(n.minRequiredCents??s));if(r.balanceCents<i)throw new _e(r.balanceCents,i);let a=n.capCentsOverride??Qc(),c=Math.min(a,r.balanceCents),l=c<a?"balance":null,u=await t("session_create",c,"Visa CLI Session",`open credit-model session with $${(c/100).toFixed(2)} cap`,n.userContext),d=await e.createSessionBudget({total_cents:c,session_kind:o,...u?{attestation:u}:{}});if(!d.success||!d.budget){let m=d.error||"unknown error";throw new Error(`Failed to open credit session: ${m}`)}let f={budgetId:d.budget.id,expiresAt:d.budget.expiresAt,totalCents:d.budget.totalCents,createdAt:d.budget.createdAt};return Q=f,gt(f.budgetId),Ir(f.totalCents),p.info("mcp-session:opened",{budgetId:f.budgetId,capCents:f.totalCents,requestedCapCents:a,clampedReason:l,sessionKind:o,expiresAt:f.expiresAt,tool:n.toolName}),{budgetId:f.budgetId,isFresh:!0,totalCents:f.totalCents,requestedCapCents:a,appliedCapCents:f.totalCents,clampedReason:l}}async function yu(e,t,n){return Ii(async()=>{let o=Ft()?await _u(e):null,s=await hu(e,t,n);return{budgetId:s.budgetId,totalCents:s.totalCents,closedPrevious:o,requestedCapCents:s.requestedCapCents,appliedCapCents:s.appliedCapCents,clampedReason:s.clampedReason}})}async function _u(e){let n=Ft()?.budgetId??Ci(),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){p.warn("mcp-session:close-server-failed",{budgetId:n,error:i?.message||String(i)})}return Vo(),Q=null,gt(null),{closedServerSide:r,budgetId:n,finalCumulativeCents:o,finalCumulativeMicros:s}}async function Ko(e){return Ii(()=>_u(e))}function Ft(){return Vo(),Q?new Date(Q.expiresAt).getTime()<=Date.now()?(Q=null,gt(null),null):{budgetId:Q.budgetId,totalCents:Q.totalCents,lastReceiptCumulative:mu(),lastReceiptCumulativeMicros:lu()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:pu(),estimatedCumulative:Bo(),lastToolSpend:du(),expiresAt:Q.expiresAt}:null}var bu=E(Rr()),vu=10000n;function Eh(e){return e<=0n?0:Number((e+vu-1n)/vu)}function Su(e){return Eh((0,bu.fromUsd)(e))}var Go=E(Rr()),Ah=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;function Wo(e){if(typeof e!="string"||!Ah.test(e))return{ok:!1,error:"amount must be a USD amount with at most two decimal places"};let[t,n=""]=e.split("."),r=BigInt(t)*100n+BigInt(n.padEnd(2,"0"));if(r>BigInt(Number.MAX_SAFE_INTEGER))return{ok:!1,error:"amount is too large"};let o=Number(r);return o<=0?{ok:!1,error:"amount must be greater than $0.00"}:{ok:!0,cents:o,displayUsd:(0,Go.toDisplay)((0,Go.fromCents)(o),{symbol:""})}}var zo="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.",wu="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 xu=Promise.resolve(),ku=!1;function es(e){let t=xu.catch(()=>{}).then(e);return xu=t.then(()=>{},()=>{}),t}async function Lu(e){let t=await ue(()=>$i(P,Qe,{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 Lh(),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;p.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 On){if(p.warn("mcp-session:server-invalidated-budget",{code:u.code,budgetId:u.budgetId??t.budgetId,tool:e.toolId}),await Ko(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 ku||(ku=!0,console.error(`[visa-cli] Your session was closed by another process; reopened automatically as pay-as-you-go.
126
- To require an explicit session approval instead, set VISA_REQUIRE_EXPLICIT_SESSION=true.`)),p.info("mcp-session:falling-back-to-payg",{code:u.code,tool:e.toolId}),Du(e)}throw u instanceof Qt?(p.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=Ei(s)??(n?Ai(n):null);if(Ri(o?.receipt_v2),await fu(e.estimatedAmountCents),uu({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),ju(o))return bn(o);let c=await Uu();if(e.idempotencyKey&&Fu(o,c,e.idempotencyKey))return bn(o);let l=c?Zo(c):null;return bn(Vu(o,r,l))}function Ye(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function Mi(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(Mi).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${Mi(r)}`).join(",")}}`}function Rh(e,t,n,r){let o=ge.createHash("sha256").update(`${n}:${Mi(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${o}`}function Ih(e,t){return`${e}:${t}`}function $h(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 Cu(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,o=Je(r),s=o!==null?o.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=$h(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),c=i!=null?String(i):a;return{batch_id:e,item_id:Ih(e,t),index:t,...c!==void 0?{transaction_id:c}:{},...a!==void 0?{ledger_id:a}:{},...s?{amountMicros:s,amount_micros:s,cost_micros:s}:{}}}async function Du(e){return ue(()=>Ph(e))}async function Ph(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 _e(n.balanceCents,t);let r=t,o=Zo(n),s=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(r/100).toFixed(2)})`,i=await Qe("session_create",r,"Visa CLI Session",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 c=a.budget.id;gt(c),Ir(a.budget.totalCents),p.info("on-demand-session:opened",{budgetId:c,capCents:a.budget.totalCents,tool:e.toolId});try{let l=Ti(e.idempotencyKey);if(!l)throw new Error(`Internal: mintVoucher returned null after on-demand session-open ${c}`);let{data:u,voucherReceiptHeader:d}=await P.shortcutWithSession(e.toolId,l,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(Ei(d)||Ai(l),Ri(u?.receipt_v2),ju(u))return bn(u);let f=await Uu();if(e.idempotencyKey&&Fu(u,f,e.idempotencyKey))return bn(u);let m=f?Zo(f):null;return bn(Vu(u,o,m))}finally{try{await P.closeSession(c)}catch(l){p.warn("on-demand-session:close-failed",{budgetId:c,error:l?.message||String(l)})}gt(null),p.info("on-demand-session:closed",{budgetId:c,tool:e.toolId})}}async function Ht(e){return es(async()=>Ft()?Lu(e):Du(e))}function ts(){return ke()}var P=new Ce(()=>F.getSessionToken());function Je(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function Zo(e){return Je(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function Oh(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 Mh(e){let t=Je(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=Je(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=Je(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function Jo(e,t="INVALID_TOOL_PARAMS"){return{success:!1,error_code:t,code:t,error:e,message:e}}function Nh(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 Lh(){try{let e=await P.getBalance();return e.success?Zo(e):null}catch{return null}}async function Uu(){try{let e=await P.getBalance();return e.success?e:null}catch{return null}}function ju(e){if(!e||e.success===!1)return!1;let t=Je(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=Je(e.amountMicros??e.amount_micros??e.charged_micros),r=t??n;if(r===null||r<=0n)return!1;let o=r.toString();return e.amountMicros??=o,e.amount_micros??=o,e.charged_micros??=o,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),!0}function Fu(e,t,n){if(!e||e.success===!1||!t||!Array.isArray(t.ledger))return!1;let r=t.ledger.find(a=>a.idempotencyKey===n);if(!r)return!1;let o=Je(r.deltaMicros)??BigInt(r.deltaCents)*10000n,s=o<0n?-o:o;if(s<=0n)return!1;let i=s.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(s)/1e6),!0}function Vu(e,t,n){if(!e||e.success===!1||t===null||n===null)return e;let r=t-n;if(r<=0n)return e;let 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 Dh="2.7.0-rc.4",Ww=["","","You're ready to go! Try:","","Core:",'\u2022 "Show my account status" \u2192 get_status','\u2022 "List my enrolled cards" \u2192 get_cards','\u2022 "Show my paid tool use history" \u2192 transaction_history','\u2022 "Set my daily top-up limit to $50" \u2192 update_spending_controls','\u2022 "Generate 3 variations in parallel" \u2192 batch',"","Category tools:",'\u2022 "Generate an image of a sunset over Tokyo" \u2192 generate_image','\u2022 "Make a 4-second video of a penguin juggling" \u2192 generate_video','\u2022 "Make a song about coding late at night" \u2192 generate_music','\u2022 "Create a sound effect for a checkout chime" \u2192 generate_audio','\u2022 "Create a 3D asset from this product sketch" \u2192 generate_3d','\u2022 "Upscale this product image" \u2192 upscale_image','\u2022 "Transcribe this meeting recording" \u2192 transcribe_audio','\u2022 "Run a reasoning model on this prompt" \u2192 run_llm',"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
127
- `);function Ze(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=ar(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(Zc())return{opened:!1,url:t,blockedReason:"suppressed"};let n=Es();if(n.headless)return p.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let r=Va(t,ts());if(!r)return p.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let o=qa(r);return o?((0,Nu.execFile)(o.cmd,o.args,s=>{s&&p.warn(`Browser open failed: ${s.message}. URL: ${r}`)}),{opened:!0,url:r}):(p.info(`No browser command for platform "${$r.platform()}". URL: ${r}`),{opened:!1,url:r,blockedReason:"unsupported_platform"})}async function ue(e){return Bn(P,e,Ju)}var Hu="get_cards",qu="set_default_card";function Uh(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 '${Hu}' to see enrolled cards and '${qu}' to switch, then retry the original request.`}function jh(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 '${Hu}' to see enrolled cards and '${qu}' to switch. Do not retry automatically.`}function Xe(e,t){let n=e.retryable?Uh(e.code,e.retryAfter):jh(e.code,t.merchantName);return{success:!1,declined:!0,retryable:e.retryable,code:e.code,reason:e.reason,payment_error_class:e.paymentErrorClass,correlation_id:e.correlationId,transactionId:e.transactionId,retryAfter:e.retryAfter,merchantName:t.merchantName,amount:t.amount,message:e.message,agent_guidance:n}}function Fh(e){return{success:!1,error:e.message,error_code:e.code,transactionId:e.transactionId,reconciliation_required:e.reconciliationRequired,retryable:e.retryable,agent_guidance:"The top-up charge outcome is ambiguous. Tell the user not to retry with a new idempotency key or start another top-up. They should check transaction_history in a few minutes or contact support with the transactionId."}}var Gn=null,Vh=3e4;function Bu(){Gn=null}var Vt=class extends Error{constructor(n){super(`${Xo()} attestation is required for this action, but it is not available in this MCP process. `+Ni());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function ns(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. `+Ni()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function Hh(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:zo,agent_guidance:wu}}function Xo(){return process.platform==="darwin"?"Touch ID":"local biometric"}function Ni(){return process.platform==="darwin"?"Run the action from an interactive terminal with Touch ID access, or use reset with confirm:true to clear stale server biometric state through GitHub re-authentication.":"This platform cannot create Visa CLI Touch ID attestations. Use reset with confirm:true to clear stale server biometric state through GitHub re-authentication."}async function qh(e){let t=Date.now();if(Gn&&Gn.expiresAt>t)return{required:Gn.required,hasRegisteredKey:Gn.hasRegisteredKey};try{let n=await P.getStatus(e),r=n.attestationRequired!==!1,o=ze(n);return Gn={required:r,hasRegisteredKey:o,expiresAt:t+Vh},{required:r,hasRegisteredKey:o}}catch{return{required:!0,hasRegisteredKey:!0}}}async function Qe(e,t,n,r,o,s){if(!s?.forceRequired){let i=await qh(o);if(!i.required){p.info("attestation:skipped-by-server-policy",{context:e});return}if(!i.hasRegisteredKey){p.info("attestation:skipped-no-registered-key",{context:e});return}}if(!re())throw p.warn("attestation:unavailable",{context:e}),new Vt(e);p.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");p.info("touchid:prompt",{context:e,amount:t,merchant:n});let c=await vn(a,r);return p.info("attestation:success",{context:e,amount:t,merchant:n}),{signature:c,nonce:i,amount:t,merchant:n}}catch(i){throw p.error("attestation:failure",{context:e,amount:t,merchant:n,error:i.message}),i}}var Tu="[dry-run] https://placeholder.visa-cli.dev/image.png",Bh=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"]),Kh=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 Gh(e,t){return t==="run_llm"||e.startsWith("or-")?"llm":t==="generate_image"||Bh.has(e)?"image":t==="generate_video"||Kh.has(e)?"video":null}function Wh(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function zh(e){return e==="llm"?"OpenRouter":"fal.ai"}function Wn(e,t,n,r){let o={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:zh(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${Wh(n)}`;return{...o,content:i,data:{content:i,model:t,dry_run:!0}}}return{...o,urls:[Tu],data:{[e==="video"?"videoUrl":"imageUrl"]:Tu,metadata:{dry_run:!0}}}}async function Pi(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:ge.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){p.warn("dry_run:telemetry_failed",{tool:e.toolName,error:o?.message||String(o),mode:t})}}var Jh="https://openrouter.ai/api/v1/chat/completions",Yh="openrouter/free",Zh=50,Xh=15e3;function Qh(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 ey(e,t,n){let r=process.env.OPENROUTER_API_KEY;if(!r)return p.warn("preflight:no_openrouter_key_falling_back_to_mock",{tool:e}),{result:Wn("llm",e,t,n),degraded:!0,resolvedModel:null};let o=Qh(t),s;try{s=await Zt(Jh,{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:Yh,messages:[{role:"user",content:o}],max_tokens:Zh}),timeoutMs:Xh})}catch(u){return p.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:Wn("llm",e,t,n),degraded:!0,resolvedModel:null}}if(!s.ok){let u=await s.text().catch(()=>"");return p.warn("preflight:openrouter_http_error_falling_back_to_mock",{tool:e,status:s.status,bodyExcerpt:u.slice(0,200)}),{result:Wn("llm",e,t,n),degraded:!0,resolvedModel:null}}let i;try{i=await s.json()}catch(u){return p.warn("preflight:openrouter_invalid_json_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:Wn("llm",e,t,n),degraded:!0,resolvedModel:null}}let a=typeof i?.choices?.[0]?.message?.content=="string"?i.choices[0].message.content:"",c=typeof i?.model=="string"?i.model:null;return{result:{success:!0,transactionId:`preflight:${n??e}`,amount:0,rail:"preflight",merchantName:"OpenRouter",dry_run:!0,preflight:!0,metadata:{dry_run:!0,preflight:!0,model_used:c},content:a,data:{content:a,model:c??e,dry_run:!0,preflight:!0}},degraded:!1,resolvedModel:c}}async function rs(e,t,n,r){let o=_i();if(!o)return null;let s=Gh(e,r);if(!s)return null;let i=Date.now();if(o==="mock"){let l=Wn(s,e,t,r);return await Pi({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:l,userContext:n,startedAt:i,mode:"mock"}),p.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:s,mode:o}),l}if(s!=="llm"){p.warn("preflight:not_supported_for_kind_falling_back_to_mock",{tool:e,kind:s});let l=Wn(s,e,t,r);return await Pi({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:l,userContext:n,startedAt:i,mode:"preflight"}),l}let{result:a,resolvedModel:c}=await ey(e,t,r);return await Pi({toolName:r??e,resolvedModel:c??(r&&r!==e?e:null),toolParams:t,result:a,userContext:n,startedAt:i,mode:"preflight"}),p.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:s,mode:o}),a}async function ht(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 yt(e){return Su(e.amount)}function ty(){return Qo.join($r.homedir(),".visa-mcp","allium-results")}var zw=16*1024,Jw=50*1024*1024;function ny(){let e=ty();try{if(!je.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=je.readdirSync(e),n=0,r=0;for(let o of t)try{let s=je.statSync(Qo.join(e,o));s.isFile()&&(n+=s.size,r++)}catch{}return{file_count:r,size_bytes:n,path:e}}catch(t){return p.warn("allium:disk_usage_error",{error:t.message}),{file_count:0,size_bytes:0,path:e}}}var Eu=3600*1e3,Oi=0;function ry(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function Pr(e){if(!Xc()&&!(Date.now()<Oi))try{if(!await F.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}}),p.info("feed:submitted",{tool:e.tool,mediaType:e.mediaType,transactionId:e.transactionId})}catch(t){if(ry(t)){let n=Oi===0;Oi=Date.now()+Eu,n&&p.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:Eu});return}p.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function oy(e,t){let n=(e.state||"").trim().toUpperCase(),r=(e.county||"").trim(),o=(e.start_date||"").trim(),s=(e.end_date||o).trim();if(!/^[A-Z]{2}$/.test(n))throw new Error('state must be a 2-letter US state code (e.g. "VA").');if(!r)throw new Error("county is required.");if(!/^\d{4}-\d{2}$/.test(o))throw new Error('start_date must be YYYY-MM (e.g. "2025-08").');if(s&&!/^\d{4}-\d{2}$/.test(s))throw new Error("end_date must be YYYY-MM.");let i="Visa SMI",a=.1,c=`Pay $0.10 to ${i} for SMI data (${n} / ${r})`;p.info("payment:attempt",{tool:"get_visa_smi",amount:a,merchant:i});try{return await ue(async()=>{let l=await Qe("get_visa_smi",a,i,c),u=await P.getVisaSmi({state:n,county:r,start_date:o,end_date:s,attestation:l,idempotencyKey:ge.randomUUID()},t);return u.success?p.info("payment:success",{tool:"get_visa_smi",merchant:i,charged_cents:u.charged_cents}):p.warn("payment:declined",{tool:"get_visa_smi",merchant:i,message:u.error}),u})}catch(l){if(l instanceof me)return p.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:l.code,retryable:l.retryable}),Xe(l,{amount:a,merchantName:i,description:"Visa SMI data"});throw p.error("payment:failure",{tool:"get_visa_smi",merchant:i,error:l.message}),l}}async function sy(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 rs("generate_image_card",e,t);if(n)return n;let r=await ht("generate_image_card",void 0,t),o=ge.randomUUID();p.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await ue(async()=>{let s;try{s=await Ht({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:yt(r),userContext:t,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof _e)return Ye(i);throw i}return p.info("payment:success",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Ze(i)),Pr({prompt:e.prompt,tool:"generate_image_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):p.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof me)return p.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Xe(s,r);throw p.error("payment:failure",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function iy(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 rs("generate_image_fast_card",e,t);if(n)return n;let r=await ht("generate_image_fast_card",void 0,t),o=ge.randomUUID();p.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await ue(async()=>{let s;try{s=await Ht({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:yt(r),userContext:t,timeoutMs:6e4,idempotencyKey:o})}catch(i){if(i instanceof _e)return Ye(i);throw i}return p.info("payment:success",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Ze(i)),Pr({prompt:e.prompt,tool:"generate_image_fast_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):p.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof me)return p.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Xe(s,r);throw p.error("payment:failure",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function ay(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 rs("generate_video_tempo_card",e,t);if(n)return n;let r=await ht("generate_video_tempo_card",void 0,t),o=ge.randomUUID();p.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await ue(async()=>{let s;try{s=await Ht({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:yt(r),userContext:t,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof _e)return Ye(i);throw i}return p.info("payment:success",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Ze(i)),Pr({prompt:e.prompt,tool:"generate_video_tempo_card",mediaUrl:s.urls[0],mediaType:"video",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):p.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof me)return p.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Xe(s,r);throw p.error("payment:failure",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function cy(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 ht("generate_music_tempo_card",void 0,t),r=ge.randomUUID();p.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await ue(async()=>{let o;try{o=await Ht({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:yt(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(s){if(s instanceof _e)return Ye(s);throw s}return p.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=>Ze(s)),Pr({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,p.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):p.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof me)return p.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Xe(o,n);throw p.error("payment:failure",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}async function ly(e,t){let n=await ht("check_music_status_tempo_card",void 0,t),r=ge.randomUUID();p.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await ue(async()=>{let o;try{o=await Ht({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:yt(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof _e)return Ye(s);throw s}return p.info("payment:success",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),o.urls?.length&&o.urls.forEach(s=>Ze(s)),o})}catch(o){if(o instanceof me)return p.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Xe(o,n);throw p.error("payment:failure",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}async function uy(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 ht("query_onchain_prices",void 0,t),r=ge.randomUUID();p.info("payment:attempt",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName});try{return await ue(async()=>{let o;try{o=await Ht({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:yt(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof _e)return Ye(s);throw s}if(p.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 me)return p.warn("payment:declined",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Xe(o,n);throw p.error("payment:failure",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}var dy=["generate_music_tempo_card"],Au=10,Ru=5,Iu=new Map;function $u(e){let t=Iu.get(e);if(t!==void 0)return t;let r=kr(e)?.isAsync===!0||dy.includes(e);return Iu.set(e,r),r}var my=36e4,py=18e4,fy=15e3,gy=12e4,hy=2e3;function Pu(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}async function yy(e,t){let n;if(e.requests?.some(_=>_.tool||_.tool_id)&&e.requests)n=e.requests.map(_=>{let C=_.tool||_.tool_id||e.tool;if(!C)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let L=Dt(C,_.tier||e.tier,_.prompt??t),{tool:Oe,tool_id:Bt,tier:xe,params:K,...se}=_,Vr=K&&typeof K=="object"?{...K,...se}:se;return{resolvedTool:L,params:Vr}});else if(e.tool){let _=Dt(e.tool,e.tier,e.params?.prompt??t);n=(e.requests||(e.count&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(L=>({resolvedTool:_,params:L}))}else return Pu("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return Pu("BATCH_EMPTY","Batch requires at least one item.");if(n.length>Au)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${Au} items. Please split into smaller batches.`};if([...new Set(n.map(_=>_.resolvedTool))].some($u)&&n.length>Ru)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${Ru} items. Please use multiple batches for more.`};let i=[...new Set(n.map(_=>_.resolvedTool))],a=i.length===1,c={};for(let _ of i)c[_]=await Yu(_);let l=new Set(i.filter(_=>c[_]&&Zu(c[_]))),u={};for(let _ of i)l.has(_)||(u[_]=await ht(_,void 0,t));let d=0;for(let _ of n)d+=u[_.resolvedTool]?.amount??0;let f=[...new Set([...Object.values(u).map(_=>_.merchantName),...i.filter(_=>l.has(_)).map(_=>c[_]?.name??_)])].join(", "),m=a?i[0]:"mixed";p.info("payment:attempt",{tool:"batch",batchTool:m,count:n.length,totalAmount:d,merchant:f,heterogeneous:!a});let y=n.some(_=>$u(_.resolvedTool)),S=n.some(_=>_.resolvedTool.startsWith("or-")||_.resolvedTool==="run_llm"||_.resolvedTool==="execute_tool"),$=y?my:S?py+n.length*fy:gy+n.length*hy,H=ge.randomUUID(),U=[],w=0,x=0n;return es(async()=>{let _=!Ft();if(_&&d>0)try{let C=Math.max(1,Math.ceil(d*100));await ue(()=>$i(P,Qe,{toolName:"batch",userContext:t,sessionKind:"one_shot",minRequiredCents:C,capCentsOverride:C}))}catch(C){return C instanceof _e?Ye(C):(p.warn("payment:batch-prewarm-failed",{batchTool:m,count:n.length,error:C?.message||String(C)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:C?.message||"Failed to authenticate batch session",tool:m,count:n.length,failedCount:n.length,results:[]})}try{for(let K=0;K<n.length;K+=1){let se=n[K],Vr=u[se.resolvedTool];try{let Z=l.has(se.resolvedTool)?await P.shortcut(se.resolvedTool,se.params,$,t,"batch"):await Lu({toolId:se.resolvedTool,toolParams:se.params,estimatedAmountCents:yt(Vr),userContext:t,metaTool:"batch",timeoutMs:$,idempotencyKey:Rh(H,K,se.resolvedTool,se.params)});if(l.has(se.resolvedTool)&&Z&&typeof Z=="object"&&!Array.isArray(Z)&&Z.merchantName==null&&(Z.merchantName=c[se.resolvedTool]?.name??se.resolvedTool),U.push({success:Z?.success!==!1,tool:se.resolvedTool,...Z,...Cu(H,K,Z)}),Z?.success!==!1){let er=Je(Z?.amountMicros??Z?.amount_micros),ga=typeof Z?.amount=="number"?Z.amount:Vr?.amount??0;er!==null&&er>0n?x+=er:x+=BigInt(Math.round(ga*1e6)),w+=ga}Z?.urls&&Z.urls.forEach(er=>Ze(er))}catch(Z){if(Z instanceof _e&&U.length===0)return Ye(Z);p.warn("payment:batch-item-failed",{tool:se.resolvedTool,index:K,error:Z?.message||String(Z)}),U.push({success:!1,tool:se.resolvedTool,...Cu(H,K),error:Z?.message||String(Z)})}}let C=U.filter(K=>K?.success===!1).length,L=U.length-C,Oe=U.flatMap(K=>Array.isArray(K?.urls)?K.urls:[]),Bt=x>0n?Number(x)/1e6:Math.round((w+Number.EPSILON)*100)/100,xe=L===0?"failure":C===0?"success":"partial";return p.info("payment:success",{tool:"batch",batchTool:m,count:n.length,totalAmount:d,totalCharged:Bt,merchant:f,successCount:L,failedCount:C,outcome:xe,mode:"session",batchId:H}),{success:L>0,outcome:xe,batch_id:H,tool:a?i[0]:m,count:n.length,successCount:L,failedCount:C,totalCharged:Bt,...x>0n?{totalChargedMicros:x.toString(),amountMicros:x.toString(),amount_micros:x.toString()}:{},merchantName:f,results:U,...Oe.length?{urls:Oe}:{}}}catch(C){if(C instanceof me)return p.warn("payment:declined",{tool:"batch",batchTool:m,count:n.length,totalAmount:d,merchant:f,code:C.code,retryable:C.retryable}),Xe(C,{amount:d,merchantName:f});throw p.error("payment:failure",{tool:"batch",batchTool:m,count:n.length,totalAmount:d,merchant:f,error:C.message}),C}finally{if(_){let C=await Ko(P);p.info("batch-session:closed",{budgetId:C.budgetId,closedServerSide:C.closedServerSide})}}})}function _y(){let e=!1,t;try{let r=Qo.join($r.homedir(),".claude","settings.json");if(je.existsSync(r)){let o=JSON.parse(je.readFileSync(r,"utf-8")),s=typeof o.statusLine=="object"?o.statusLine.command:"";e=Tt(s)}}catch{}let n=so();return n||(t="visa-cli config hud enable"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function vy(e){let[t,n]=await Promise.all([P.getStatus(e),P.getBalance().catch(s=>(p.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=ny();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=_y(),t.version=Dh,Array.isArray(t.cards)&&(t.cards=t.cards.map(s=>({...s,displayName:Li(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=Ft();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 Li(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 Ku(e,t){try{let r=((await P.getStatus(t)).cards||[]).find(o=>o?.id===e);if(r)return Li(r)}catch(n){p.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function by(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:Li(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 Sy(e,t){return await P.getTransactions({limit:e.limit,offset:e.offset},t)}async function wy(e,t){return await P.feedback(e.message,e.transaction_id,t)}async function xy(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return wn("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=Wo(String(e.amount));if(n.ok===!1)return{success:!1,error:n.error};let r=n.cents,o=r/100,s=ge.randomUUID();p.info("buy_credits:attempt",{amountCents:r});try{return await ue(async()=>{let i=await Qe("balance-topup",o,"Visa CLI Balance",`top up balance with $${n.displayUsd}`,t,{forceRequired:!0}),a=await P.topupBalance({amount_cents:r,idempotency_key:s,attestation:i});if(a.success){p.info("buy_credits:success",{amountCents:r,balanceCents:a.balanceCents});let c=((a.balanceCents??0)/100).toFixed(2),l=(r/100).toFixed(2);return{...a,amount:r/100,amountMicros:String(r*1e4),merchantName:"Visa CLI Balance",message:`Added $${l} \u2014 balance is now $${c}`}}return p.warn("buy_credits:failed",{amountCents:r,error:a.error}),a})}catch(i){if(i instanceof Vt)return Hh();if(i instanceof at)return p.warn("buy_credits:ambiguous",{amountCents:r,code:i.code,transactionId:i.transactionId}),Fh(i);throw p.error("buy_credits:failure",{amountCents:r,error:i.message}),i}}function wn(e,t){return{success:!1,error:t,code:e,message:t}}async function ky(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return wn("MISSING_CONFIRMATION","Please confirm by setting confirm: true to update spending controls.");if(e.maxTransactionAmount!==void 0&&(typeof e.maxTransactionAmount!="number"||!Number.isFinite(e.maxTransactionAmount)||e.maxTransactionAmount<.01))return wn("INVALID_VALUE","maxTransactionAmount must be at least $0.01");if(e.dailyLimit!==void 0&&(typeof e.dailyLimit!="number"||!Number.isFinite(e.dailyLimit)||e.dailyLimit<1))return wn("INVALID_VALUE","dailyLimit must be at least $1");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return wn("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");p.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await ue(async()=>{let n=await Qe("spending-controls",0,"","update spending controls"),r=await P.updateSpendingControls({maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit,confirm:!0,attestation:n},t);return p.info("spending_controls:success",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit}),r})}catch(n){if(p.error("spending_controls:failure",{error:n.message}),n instanceof Vt)return ns(n,"update_spending_controls");if(String(n?.message||n).includes("Attestation required"))return wn("ATTESTATION_REQUIRED","Changing spending controls requires local attestation, even when payment biometric prompts are disabled.");throw n}}async function Cy(e){let t=await Ar({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 Ty(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."};p.info("config:set",{key:e.key});try{let t=wo(e.key,e.value);return p.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 ct?"UNKNOWN_KEY":t instanceof lt?"SERVER_CONTROLLED":t instanceof Et?"RETIRED_KEY":"INVALID_VALUE";return p.warn("config:set:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(Rt).sort()}}}async function Ey(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."};p.info("config:unset",{key:e.key});try{let t=xo(e.key);return p.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 ct?"UNKNOWN_KEY":t instanceof lt?"SERVER_CONTROLLED":t instanceof Et?"RETIRED_KEY":"INVALID_VALUE";return p.warn("config:unset:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(Rt).sort()}}}async function Ay(e){let t=await P.getStatus(e),n=t.attestationRequired!==!1,r=ze(t),o=re(),s=n?r?o?`${Xo()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${Xo()} is not available in this process. ${Ni()}`:"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 Ry(e){p.info("biometric:on");let t=await Uo(P,e);if(t.ok===!1)return{success:!1,error:t.code,error_code:t.code,message:t.message,agent_guidance:`${t.message} Do not call biometric_on again until the user has completed setup in an interactive terminal.`};let n=await P.setBiometricPreference({required:!0},e);return n.success?(Bu(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:n.error||"unknown error"}}async function Iy(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return wn("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.");p.info("biometric:off");try{return await ue(async()=>{let n=await P.getStatus(t),r;if(ze(n)&&(r=await Qe("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${Xo()} 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 Bu(),{success:!0,required:!1,message:"Touch ID is no longer required for payments."}})}catch(n){if(p.error("biometric:off:failure",{error:n.message}),n instanceof Vt)return ns(n,"biometric_off");throw n}}var Ou=3e4,$y=3e5;async function Gu(e,t,n="login"){let r=ge.randomUUID(),o=`${e}${e.includes("?")?"&":"?"}state=${r}`,s=Ze(o);return!s.opened&&s.blockedReason!=="non_internal_host"&&s.blockedReason!=="invalid_url"?Wu(o,s,n):s.opened?{...await zu(r,t,n),browserUrl:o}:{success:!1,browserUrl:o,message:`Could not open the browser URL safely. Please check the configured auth server and try again. URL: ${o}`}}function Wu(e,t,n){let r=n==="enrollment"?"card enrollment":n==="attestation-recovery"?"biometric reset":"login",o=t.blockedReason==="suppressed"?"browser auto-open is suppressed":t.blockedReason==="headless"?"this process appears to be headless":t.blockedReason==="unsupported_platform"?"this platform has no configured browser opener":"browser auto-open is unavailable";return{success:!1,requiresBrowser:!0,browserUrl:e,message:`Browser auto-open was skipped because ${o}. Open this URL to continue ${r}: ${e}`}}async function zu(e,t,n="login"){let r=Date.now()+$y;for(;Date.now()<r;)try{let s=await fetch(`${ts()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:Ou,...t&&{user_context:t}}),signal:AbortSignal.timeout(Ou+5e3)});if(!s.ok){await xt(s,a=>{p.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 p.info("auth:attestation_recovery_complete",{user:i.user||""}),{success:!0,message:"Server-side biometric state cleared. Run visa-cli setup to register a fresh key before reenabling Touch ID."};let a=i.welcomeBonusCents??0,c=ru(a);if(n!=="enrollment"&&i.sessionToken){await F.saveSessionToken(i.sessionToken);let u=i.user||"",d=i.last4||"****";return p.info("auth:login_complete",{user:u,last4:d,bonusCents:a}),{success:!0,message:`Signed in as ${u}. Card ending in ${d} enrolled and ready for payments.`,...c||{}}}let l=i.last4||"****";return p.info("auth:card_added",{last4:l,bonusCents:a}),{success:!0,message:`Card ending in ${l} enrolled and ready for payments.`,...c||{}}}}catch{await xt(void 0,s=>{p.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 Ju(e){let t=ge.randomUUID(),n;try{n=await P.startAttestationRecovery(t,e)}catch(s){return{success:!1,message:`Could not start biometric reset: ${s?.message||"unknown error"}`}}if(!n.success||!n.recoveryUrl)return{success:!1,message:n.error||"Could not start biometric reset. Please try again."};let r=Ze(n.recoveryUrl);return!r.opened&&r.blockedReason!=="non_internal_host"&&r.blockedReason!=="invalid_url"?Wu(n.recoveryUrl,r,"attestation-recovery"):r.opened?{...await zu(t,e,"attestation-recovery"),browserUrl:n.recoveryUrl}:{success:!1,browserUrl:n.recoveryUrl,message:`Could not open the browser URL safely. Please check the configured auth server and try again. URL: ${n.recoveryUrl}`}}async function Py(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."};p.info("cards:remove_attempt",{cardId:n});let r=`remove-card:${n}`,o=`remove ${await Ku(n,t)}`;try{return await ue(async()=>{let s=await Qe(r,0,"",o,t,{forceRequired:!0}),i=await P.removeCard(n,{attestation:s},t);return p.info("cards:remove_success",{cardId:n,promotedId:i?.promotedId??null}),i})}catch(s){if(p.error("cards:remove_failure",{cardId:n,error:s.message}),s instanceof Vt)return ns(s,"remove_card");throw s}}async function Oy(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."};p.info("cards:set_default_attempt",{cardId:n});let r=`set-default-card:${n}`,o=`set ${await Ku(n,t)} as default`;try{return await ue(async()=>{let s=await Qe(r,0,"",o,t,{forceRequired:!0}),i=await P.setDefaultCard(n,{attestation:s},t);return p.info("cards:set_default_success",{cardId:n}),i})}catch(s){if(p.error("cards:set_default_failure",{cardId:n,error:s.message}),s instanceof Vt)return ns(s,"set_default_card");throw s}}async function My(e){return p.info("auth:login_attempt"),Gu(`${ts()}/login`,e)}function Ny(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 Ly(e={},t){let n;try{n=Ny(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return es(async()=>{let r=await ue(()=>yu(P,Qe,{toolName:"start_session",userContext:t,capCentsOverride:n}));p.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 Dy(){let e=Ft();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 Uy(){return es(async()=>{let e=Ft();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 Ko(P);p.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=Mh(e),r=Je(t.finalCumulativeMicros),o=r??(typeof t.finalCumulativeCents=="number"?BigInt(Math.max(0,t.finalCumulativeCents))*10000n:n.micros),s=Number(o/10000n);return p.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 ${Oh(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 jy(e){if(p.info("auth:add_card_attempt"),!await F.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 Gu(`${ts()}/enroll-card?code=${encodeURIComponent(n)}`,e,"enrollment")}async function Fy(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};p.info("reset:attempt");let n=!1;try{let r=await P.getStatus(t);if(r&&ze(r)){let o=await Ju(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}`};p.warn("reset:server_attestation_status_unavailable",{error:o})}try{await P.logout(void 0,t)}catch{}if(await F.clearAll(),re())try{await Do()}catch{}return p.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 Vy(e){let t=e.query?.trim()||void 0,n=e.category?.trim()||void 0,r=!t&&!n;p.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 l of s){let u=l.category||"other";(a[u]??=[]).push(l)}let c=Object.keys(a).sort().map(l=>{let u=a[l].map((f,m)=>`${m+1}. **${f.name}** (${f.id})
118
+ `))}}}return i}var Rp=["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 Ip(e){let t=wc(e);if(!t)return!1;let n=t.slice(-16384).toLowerCase();return Rp.some(r=>n.includes(`"${r}"`))}async function Tc(e,t,n){let r=await Cc(e,t,n),o=r.join(`
119
+ `),{isActive:s}=kc(e,n,t?.transcript_path);return{schemaVersion:hp,client:t?Rc(t):Yt.UNKNOWN,rendered:o,lines:r.map(Vs),visa:{spendLine:Vs(e),balanceCents:n?.balanceCents,balanceUsd:n?.amountUsd,sessionMode:n?.sessionMode,activeSession:n?.activeSession,isVisaActive:s},context:t?$c(t):{}}}function te(e){return e?e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim():""}function yo(e){if(typeof e=="string")return te(qe.basename(e));if(!e||typeof e!="object")return"";let t=typeof e.current_dir=="string"?e.current_dir:typeof e.path=="string"?e.path:"";return te(t?qe.basename(t):e.name)}function Ec(e){return te(e.app_name??e.appName??e.app??e.client)}function go(e){return te(e.model?.display_name??e.model?.id??e.model_name??e.modelName)}function Ac(e){return te(e.cwd??e.current_dir??e.project_root)}function bc(e){let t=te(e.project);if(t)return t;let n=Ac(e);if(n)return te(qe.basename(n));let r=yo(e.workspace);return r||""}function Me(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function Rc(e){let t=Ec(e).toLowerCase();return t.includes("codex")?Yt.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?Yt.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||Me(e.context_used)!==void 0?Yt.CODEX:Yt.UNKNOWN}function Ic(e){return Rc(e)===Yt.CODEX}function $c(e){let t=Ec(e),n=Ac(e),r=yo(e.workspace),o=Me(e.context_used)??Me(e.context_window?.used_percentage??void 0),s=Me(e.context_remaining)??Me(e.context_window?.remaining_percentage??void 0);return{...t?{app:t}:{},...go(e)?{model:go(e)}:{},...bc(e)?{project:bc(e)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...te(e.git_branch??e.branch)?{gitBranch:te(e.git_branch??e.branch)}:{},...te(e.status??e.run_state??e.runState)?{status:te(e.status??e.run_state??e.runState)}:{},...te(e.thread_title??e.threadTitle)?{threadTitle:te(e.thread_title??e.threadTitle)}:{},...o!==void 0?{contextUsedPercent:o}:{},...s!==void 0?{contextRemainingPercent:s}:{},...Me(e.used_tokens)!==void 0?{usedTokens:Me(e.used_tokens)}:{},...Me(e.total_input_tokens)!==void 0?{totalInputTokens:Me(e.total_input_tokens)}:{},...Me(e.total_output_tokens)!==void 0?{totalOutputTokens:Me(e.total_output_tokens)}:{}}}function Vs(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}var Oc=E(require("path"));function Pc(e){return e instanceof Error?e.message:String(e)}function Hs(e,t){let n=[],r=[],o=e??"claude",s=ho(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: ${Pc(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=Oc.join(t.homeDir,".claude","settings.json");try{let c=t.installVisaStatusLine(a);n.push(c.message),(c.installed==="error"||c.installed==="malformed-json")&&(i=!1)}catch(c){i=!1,r.push(`Failed to install Claude HUD: ${Pc(c)}`)}}return{ok:i,messages:n,errors:r}}function Mc(e){if(!e||typeof e!="object")return"";let t=e;return Array.isArray(t.enum)&&t.enum.length>0?"enum":typeof t.type=="string"?t.type:Array.isArray(t.type)?t.type.filter(n=>typeof n=="string").join("|"):""}var Nc=E(require("os")),Lc=require("node:readline/promises"),hr={card:"default VISA ****7242",balance:"balance $6.38",spentToday:"spent today $0.62",lastActivity:"last Visa tool 38m",model:"Opus 4.6"};async function qs(e,t=!1){if(!process.stdin.isTTY)return t;let n=t?"[Y/n]":"[y/N]",r,o;try{r=(0,Lc.createInterface)({input:process.stdin,output:process.stdout});let s=new AbortController;o=()=>s.abort(),r.once("close",o);let i=(await r.question(`${e} ${n} `,{signal:s.signal})).trim();return i?/^y(es)?$/i.test(i):t}catch{return t}finally{r&&o&&r.off("close",o),r?.close()}}function $p(e,t){return e.replace(/[\x00-\x1F\x7F\u202A-\u202E\u2066-\u2069]/g,"").trim()||t}function Dc(e=Nc.hostname()){let t=nr().version,n=$p(e,"this-machine");return[" Preview if installed (sample):",` VISA CLI v${t} | ${n} | ${hr.card}`,` ${hr.balance} | ${hr.spentToday} | ${hr.lastActivity}`,` [${hr.model}] | you`," Activity live"].join(`
120
+ `)}async function Zt(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 Xt=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},On=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}},me=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(t,n,r,o,s,i,a,c){super(t),this.name="CardDeclinedError",this.retryable=n,this.code=r,this.reason=o,this.paymentErrorClass=s,this.correlationId=i,this.transactionId=a,this.retryAfter=c}},at=class extends Error{code;transactionId;retryable;reconciliationRequired;constructor(t,n,r={}){super(t),this.name="TopupAmbiguousError",this.code=n,this.transactionId=r.transactionId,this.retryable=r.retryable??!1,this.reconciliationRequired=r.reconciliationRequired??!0}};var Uc={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&&Uc[n]?Uc[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 be=E(require("fs")),Ws=E(require("path")),jc=E(require("os")),Gs=Ws.join(jc.homedir(),".visa-mcp"),yr=Ws.join(Gs,"mcp-server.log"),Pp=5*1024*1024,Ks=null;function Op(){be.existsSync(Gs)||be.mkdirSync(Gs,{recursive:!0,mode:448})}function Mp(){if(!Ks){if(Op(),be.existsSync(yr)&&be.statSync(yr).size>Pp){let t=yr+".1";be.existsSync(t)&&be.unlinkSync(t),be.renameSync(yr,t)}Ks=be.createWriteStream(yr,{flags:"a"})}return Ks}function Np(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function _o(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}
121
+ `;Np(e)&&process.stderr.write(o),Mp().write(o)}var p={debug:(...e)=>_o("DEBUG",...e),info:(...e)=>_o("INFO",...e),warn:(...e)=>_o("WARN",...e),error:(...e)=>_o("ERROR",...e)};var Lp=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Vc(e,t){let n=Fc(e),r=Fc(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:Dp(n.pre,r.pre)>0}function Fc(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(Lp);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function Dp(e,t){let n=e.split("."),r=t.split("."),o=Math.max(n.length,r.length);for(let s=0;s<o;s++){if(s>=n.length)return-1;if(s>=r.length)return 1;let i=n[s],a=r[s],c=/^\d+$/.test(i),l=/^\d+$/.test(a);if(c&&l){let u=Number(i)-Number(a);if(u!==0)return u}else{if(c)return-1;if(l)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function Be(){return!!(Hc(process.env.VISA_CLI_NO_UPDATE_CHECK)||Hc(process.env.CI)||process.env.NODE_ENV==="test")}function Hc(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var Rt=E(require("fs")),Zs=require("node:net"),Gc=E(require("os")),Wc=E(require("path"));var bo=E(require("fs")),qc=E(require("path")),Bc=E(require("os"));var zs=qc.join(Bc.homedir(),".visa-mcp"),_r=class{static ensureConfigDir(){bo.existsSync(zs)||bo.mkdirSync(zs,{recursive:!0,mode:448})}static getConfigDir(){return zs}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 Kc(e){let t=Gc.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}var Up="settings.json",jp="must use https unless it points at localhost/loopback for local development";function br(){return Wc.join(_r.getConfigDir(),Up)}function zc(e){if((0,Zs.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function Fp(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 zc(o)}function Vp(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,Zs.isIP)(t);return n===4?zc(t):n===6?t==="::1"||Fp(t):!1}function Js(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:"&&Vp(n.hostname)))throw new Error(`${t} ${jp}`)}var It={"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");Js(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,vo={"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 en(){let e=br();if(!Rt.existsSync(e))return{};try{let t=Rt.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?(p.warn("settings:corrupt",{path:Kc(e),reason:"not_object"}),{}):n}catch(t){return p.warn("settings:corrupt",{path:Kc(e),error:t?.message||String(t)}),{}}}function Ys(e){_r.ensureConfigDir();let t=br(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
122
+ `;Rt.writeFileSync(n,r,{mode:384}),Rt.renameSync(n,t)}function Qs(e){let t=en()[e];return typeof t=="string"?t:void 0}function So(e){let t=en()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function ei(e){let t=en()[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 ct=class extends Error{constructor(t){let n=Object.keys(It).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"}},lt=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"}},At=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+vo[t]),this.name="RetiredSettingKeyError"}},Jc=["biometric.","spending.","account.","cards.","biometric"];function wo(e,t){if(Jc.some(s=>e.startsWith(s)))throw new lt(e);if(e in vo)throw new At(e);let n=It[e];if(!n)throw new ct(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=en();return o[e]=r,Ys(o),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:br()}}function xo(e){if(Jc.some(s=>e.startsWith(s)))throw new lt(e);let t=It[e];if(e in vo){let s=en(),i=e in s;return i&&(delete s[e],Ys(s)),{key:e,removed:i,requiresRestart:!1,path:br()}}if(!t)throw new ct(e);let r=en(),o=e in r;return o&&(delete r[e],Ys(r)),{key:e,removed:o,requiresRestart:o&&!!t.requiresRestart,path:br()}}function Yc(){let e=en();return Object.entries(vo).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}var Hp="https://auth.visacli.sh",qp="https://auth-visa-code-preview.up.railway.app";function Bp(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function Kp(){try{let e=nr();return Bp(e.version)}catch{return!1}}function Gp(e){return e.envVar!==void 0&&e.envVar!==""?(Js(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(Js(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?qp:Hp}function ke(){return Gp({envVar:process.env.VISA_AUTH_URL,settingValue:Qs("auth.serverUrl"),isPrerelease:Kp()})}function Zc(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":So("ui.suppressBrowser")??!1}function Xc(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":So("ui.suppressFeed")??!1}function Qc(){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=ei("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):Xs}var Wp="CARD_REENROLLMENT_REQUIRED",zp="https://auth.visacli.sh/enroll-card";function Jp(){try{return new URL("/enroll-card",ke()).toString()}catch{return zp}}function Yp(e){let t=Jp();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 p.warn("card-reenroll:reenroll_url_rejected_fallback",{reason:"untrusted_or_malformed_reenroll_url",fallbackPath:"/enroll-card"}),t}var vr="2.7.1-rc.6",Zp=/^(?:VisaKey_[A-Za-z0-9_-]{16,128}|visakey_[A-Za-z0-9_-]{16,128}|vk_[A-Za-z0-9_-]{32,128})$/;function Xp(e){if(typeof e!="string")return null;switch(e){case"BUDGET_CLOSED":case"BUDGET_NOT_FOUND":case"BUDGET_EXPIRED":return e;default:return null}}function el(e){return e==="TOPUP_CHARGE_AMBIGUOUS"||e==="TOPUP_RECONCILIATION_REQUIRED"?e:null}var Qp="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function Mn(e){return typeof e=="string"?e.trim():""}function tl(e){let t=e&&typeof e=="object"?e:{},n=Mn(t.error)||Mn(t.message);if(!n)return Qp;let r=Mn(t.error_code),o=[["surface",Mn(t.disabled_surface)],["flag",Mn(t.flag)],["correlation_id",Mn(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 nl(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?Zp.test(r)?(n.push("VISA_CLI_API_KEY is set, but MCP bearer tools currently require a local session from visa-cli setup."),n.push("For headless API-key use, call the /v1/api/* HTTP routes with X-Api-Key instead of MCP bearer tools.")):(n.push("VISA_CLI_API_KEY is set but has invalid format (expected VisaKey_<...> or legacy vk_<...>)."),n.push("Create a new 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(`
123
+ `)}var Ce=class{constructor(t){this.getSessionToken=t;this.baseUrl=ke()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!Be()){let r=t.headers.get("X-Latest-Version");r&&Vc(r,vr)&&(this.lastSignals.updateAvailable={currentVersion:vr,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return vr}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new Xt(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(tl(n))}async request(t,n,r,o,s,i){let a=await this.getSessionToken();if(!a)throw new Error(nl());let c={Authorization:`Bearer ${a}`};s&&(t==="GET"?c["X-User-Context"]=encodeURIComponent(s.replace(/[\r\n\0]/g," ").slice(0,1e3)):r={...r||{},user_context:s}),i&&(c["X-Visa-Meta-Tool"]=i),r&&(c["Content-Type"]="application/json");let l;try{l=await Zt(`${this.baseUrl}${n}`,{method:t,headers:{...c,"X-Visa-CLI-Version":vr,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:o})}catch(d){throw new Error(Bs(d))}if(this.parseServerSignals(l),l.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(l.status===429){let d=l.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${d}s. Tip: use the batch tool to combine multiple requests into one.`)}l.status===503&&await this.throwServerUnavailable(l);let u;try{u=await l.json()}catch{throw l.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${n}. Try again.`)}if(!l.ok){if(l.status===500)throw new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(u),typeof u?.error_code=="string"&&u.error_code===Wp){let f=typeof u?.last4=="string"?u.last4:"",m=typeof u?.brand=="string"?u.brand:"card",_=Yp(u?.reenroll_url),S=f?`${m} ending in ${f}`:"your card";throw new Error(`Please re-add ${S} to keep payments running. Open: ${_}`)}let d=el(u?.error_code);if(d)throw new at(u?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",d,{transactionId:typeof u?.transactionId=="string"?u.transactionId:void 0,retryable:!!u?.retryable,reconciliationRequired:u?.reconciliation_required!==!1});if(u?.declined){let f=Number(u.retryAfter??l.headers.get("Retry-After"));throw new me(u.error||"Your card was declined.",!!u.retryable,u.code,u.reason,u.payment_error_class,u.correlation_id,u.transactionId,Number.isFinite(f)&&f>0?f:void 0)}if(l.status===402){let f=u?.error||"Gateway returned 402",m=typeof u?.error_code=="string"?u.error_code:"";throw m==="SPENDING_LIMIT_EXCEEDED"||m==="DAILY_LIMIT_EXCEEDED"||m==="PER_TXN_LIMIT_EXCEEDED"?new Error(`${f}. Check your limits with get_status or run: visa-cli update-spending-controls`):new Error(f)}throw new Error(u?.error||`Request failed (${l.status}). Try again.`)}return u}async shortcut(t,n,r,o,s){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,o,s)}async shortcutWithSession(t,n,r,o,s,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error(nl());let l={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":vr,"X-Source":"cli","Content-Type":"application/json"};i&&(l["X-Visa-Meta-Tool"]=i);let u={...n,...r};s&&(u.user_context=s.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await Zt(`${this.baseUrl}${a}`,{method:"POST",headers:l,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"),m;try{m=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(m),d.status===503){if(m?.error_code==="SESSION_LOCK_CONTENDED"){let $=Number(d.headers.get("Retry-After"))||1;throw new Qt(m?.message||m?.error||"Session budget is being modified by another request. Retry shortly.",$,d.status)}throw new Error(tl(m))}let _=Xp(m?.error_code);if(_||d.status===410){let $=_??"BUDGET_CLOSED";throw new On(m?.message||m?.error||"Your session was invalidated by the server.",$,{budgetId:n.session_budget_id,status:d.status})}if(m?.declined){let $=Number(m.retryAfter??d.headers.get("Retry-After"));throw new me(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite($)&&$>0?$:void 0)}let S=el(m?.error_code);throw S?new at(m?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",S,{transactionId:typeof m?.transactionId=="string"?m.transactionId:void 0,retryable:!!m?.retryable,reconciliationRequired:m?.reconciliation_required!==!1}):new Error(m?.error||`Request failed (${d.status}). Try again.`)}return{data:m,voucherReceiptHeader: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 Zt(`${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 Zt(`${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={};ms(g,{BRAND:()=>Tf,DIRTY:()=>tn,EMPTY_PATH:()=>rf,INVALID:()=>R,NEVER:()=>ug,OK:()=>pe,ParseStatus:()=>le,Schema:()=>N,ZodAny:()=>Ot,ZodArray:()=>pt,ZodBigInt:()=>rn,ZodBoolean:()=>on,ZodBranded:()=>wr,ZodCatch:()=>hn,ZodDate:()=>sn,ZodDefault:()=>gn,ZodDiscriminatedUnion:()=>To,ZodEffects:()=>$e,ZodEnum:()=>pn,ZodError:()=>ve,ZodFirstPartyTypeKind:()=>I,ZodFunction:()=>Ao,ZodIntersection:()=>un,ZodIssueCode:()=>h,ZodLazy:()=>dn,ZodLiteral:()=>mn,ZodMap:()=>Fn,ZodNaN:()=>Hn,ZodNativeEnum:()=>fn,ZodNever:()=>Ne,ZodNull:()=>cn,ZodNullable:()=>We,ZodNumber:()=>nn,ZodObject:()=>Se,ZodOptional:()=>Re,ZodParsedType:()=>v,ZodPipeline:()=>xr,ZodPromise:()=>Mt,ZodReadonly:()=>yn,ZodRecord:()=>Eo,ZodSchema:()=>N,ZodSet:()=>Vn,ZodString:()=>Pt,ZodSymbol:()=>Un,ZodTransformer:()=>$e,ZodTuple:()=>Ge,ZodType:()=>N,ZodUndefined:()=>an,ZodUnion:()=>ln,ZodUnknown:()=>mt,ZodVoid:()=>jn,addIssueToContext:()=>b,any:()=>Nf,array:()=>jf,bigint:()=>If,boolean:()=>pl,coerce:()=>lg,custom:()=>ul,date:()=>$f,datetimeRegex:()=>cl,defaultErrorMap:()=>ut,discriminatedUnion:()=>qf,effect:()=>tg,enum:()=>Xf,function:()=>Jf,getErrorMap:()=>Nn,getParsedType:()=>Ke,instanceof:()=>Af,intersection:()=>Bf,isAborted:()=>ko,isAsync:()=>Ln,isDirty:()=>Co,isValid:()=>$t,late:()=>Ef,lazy:()=>Yf,literal:()=>Zf,makeIssue:()=>Sr,map:()=>Wf,nan:()=>Rf,nativeEnum:()=>Qf,never:()=>Df,null:()=>Mf,nullable:()=>rg,number:()=>ml,object:()=>Ff,objectUtil:()=>ti,oboolean:()=>cg,onumber:()=>ag,optional:()=>ng,ostring:()=>ig,pipeline:()=>sg,preprocess:()=>og,promise:()=>eg,quotelessJson:()=>ef,record:()=>Gf,set:()=>zf,setErrorMap:()=>nf,strictObject:()=>Vf,string:()=>dl,symbol:()=>Pf,transformer:()=>tg,tuple:()=>Kf,undefined:()=>Of,union:()=>Hf,unknown:()=>Lf,util:()=>D,void:()=>Uf});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 ti;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(ti||(ti={}));var v=D.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ke=e=>{switch(typeof e){case"undefined":return v.undefined;case"string":return v.string;case"number":return Number.isNaN(e)?v.nan:v.number;case"boolean":return v.boolean;case"function":return v.function;case"bigint":return v.bigint;case"symbol":return v.symbol;case"object":return Array.isArray(e)?v.array:e===null?v.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?v.promise:typeof Map<"u"&&e instanceof Map?v.map:typeof Set<"u"&&e instanceof Set?v.set:typeof Date<"u"&&e instanceof Date?v.date:v.object;default:return v.unknown}};var h=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"]),ef=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ve=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(n(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,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()}};ve.create=e=>new ve(e);var tf=(e,t)=>{let n;switch(e.code){case h.invalid_type:e.received===v.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case h.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,D.jsonStringifyReplacer)}`;break;case h.unrecognized_keys:n=`Unrecognized key(s) in object: ${D.joinValues(e.keys,", ")}`;break;case h.invalid_union:n="Invalid input";break;case h.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${D.joinValues(e.options)}`;break;case h.invalid_enum_value:n=`Invalid enum value. Expected ${D.joinValues(e.options)}, received '${e.received}'`;break;case h.invalid_arguments:n="Invalid function arguments";break;case h.invalid_return_type:n="Invalid function return type";break;case h.invalid_date:n="Invalid date";break;case h.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 h.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 h.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 h.custom:n="Invalid input";break;case h.invalid_intersection_types:n="Intersection results could not be merged";break;case h.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case h.not_finite:n="Number must be finite";break;default:n=t.defaultError,D.assertNever(e)}return{message:n}},ut=tf;var rl=ut;function nf(e){rl=e}function Nn(){return rl}var Sr=e=>{let{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=r.filter(l=>!!l).slice().reverse();for(let l of c)a=l(i,{data:t,defaultError:a}).message;return{...o,path:s,message:a}},rf=[];function b(e,t){let n=Nn(),r=Sr({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===ut?void 0:ut].filter(o=>!!o)});e.common.issues.push(r)}var le=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 R;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 R;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}}},R=Object.freeze({status:"aborted"}),tn=e=>({status:"dirty",value:e}),pe=e=>({status:"valid",value:e}),ko=e=>e.status==="aborted",Co=e=>e.status==="dirty",$t=e=>e.status==="valid",Ln=e=>typeof Promise<"u"&&e instanceof Promise;var C;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(C||(C={}));var Ie=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}},ol=(e,t)=>{if($t(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 ve(e.common.issues);return this._error=n,this._error}}};function O(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(i,a)=>{let{message:c}=e;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??n??a.defaultError}},description:o}}var N=class{get description(){return this._def.description}_getType(t){return Ke(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Ke(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new le,ctx:{common:t.parent.common,data:t.data,parsedType:Ke(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Ln(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:Ke(t)},o=this._parseSync({data:t,path:r.path,parent:r});return ol(r,o)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Ke(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return $t(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=>$t(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:Ke(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(Ln(o)?o:Promise.resolve(o));return ol(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:h.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new $e({schema:this,typeName:I.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 Re.create(this,this._def)}nullable(){return We.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return pt.create(this)}promise(){return Mt.create(this,this._def)}or(t){return ln.create([this,t],this._def)}and(t){return un.create(this,t,this._def)}transform(t){return new $e({...O(this._def),schema:this,typeName:I.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new gn({...O(this._def),innerType:this,defaultValue:n,typeName:I.ZodDefault})}brand(){return new wr({typeName:I.ZodBranded,type:this,...O(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new hn({...O(this._def),innerType:this,catchValue:n,typeName:I.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return xr.create(this,t)}readonly(){return yn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},of=/^c[^\s-]{8,}$/i,sf=/^[0-9a-z]+$/,af=/^[0-9A-HJKMNP-TV-Z]{26}$/i,cf=/^[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,lf=/^[a-z0-9_-]{21}$/i,uf=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,df=/^[-+]?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)?)??$/,mf=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,pf="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ni,ff=/^(?:(?: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])$/,gf=/^(?:(?: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])$/,hf=/^(([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]))$/,yf=/^(([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])$/,_f=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,bf=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,il="((\\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])))",vf=new RegExp(`^${il}$`);function al(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 Sf(e){return new RegExp(`^${al(e)}$`)}function cl(e){let t=`${il}T${al(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 wf(e,t){return!!((t==="v4"||!t)&&ff.test(e)||(t==="v6"||!t)&&hf.test(e))}function xf(e,t){if(!uf.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 kf(e,t){return!!((t==="v4"||!t)&&gf.test(e)||(t==="v6"||!t)&&yf.test(e))}var Pt=class e extends N{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==v.string){let s=this._getOrReturnCtx(t);return b(s,{code:h.invalid_type,expected:v.string,received:s.parsedType}),R}let r=new le,o;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),b(o,{code:h.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),b(o,{code:h.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?b(o,{code:h.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&b(o,{code:h.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")mf.test(t.data)||(o=this._getOrReturnCtx(t,o),b(o,{validation:"email",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")ni||(ni=new RegExp(pf,"u")),ni.test(t.data)||(o=this._getOrReturnCtx(t,o),b(o,{validation:"emoji",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")cf.test(t.data)||(o=this._getOrReturnCtx(t,o),b(o,{validation:"uuid",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")lf.test(t.data)||(o=this._getOrReturnCtx(t,o),b(o,{validation:"nanoid",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")of.test(t.data)||(o=this._getOrReturnCtx(t,o),b(o,{validation:"cuid",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")sf.test(t.data)||(o=this._getOrReturnCtx(t,o),b(o,{validation:"cuid2",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")af.test(t.data)||(o=this._getOrReturnCtx(t,o),b(o,{validation:"ulid",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),b(o,{validation:"url",code:h.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),b(o,{validation:"regex",code:h.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),b(o,{code:h.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),b(o,{code:h.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),b(o,{code:h.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?cl(s).test(t.data)||(o=this._getOrReturnCtx(t,o),b(o,{code:h.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?vf.test(t.data)||(o=this._getOrReturnCtx(t,o),b(o,{code:h.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?Sf(s).test(t.data)||(o=this._getOrReturnCtx(t,o),b(o,{code:h.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?df.test(t.data)||(o=this._getOrReturnCtx(t,o),b(o,{validation:"duration",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?wf(t.data,s.version)||(o=this._getOrReturnCtx(t,o),b(o,{validation:"ip",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?xf(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),b(o,{validation:"jwt",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?kf(t.data,s.version)||(o=this._getOrReturnCtx(t,o),b(o,{validation:"cidr",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?_f.test(t.data)||(o=this._getOrReturnCtx(t,o),b(o,{validation:"base64",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?bf.test(t.data)||(o=this._getOrReturnCtx(t,o),b(o,{validation:"base64url",code:h.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:h.invalid_string,...C.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...C.errToObj(t)})}url(t){return this._addCheck({kind:"url",...C.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...C.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...C.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...C.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...C.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...C.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...C.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...C.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...C.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...C.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...C.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...C.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,...C.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,...C.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...C.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...C.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...C.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...C.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...C.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...C.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...C.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...C.errToObj(n)})}nonempty(t){return this.min(1,C.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}};Pt.create=e=>new Pt({checks:[],typeName:I.ZodString,coerce:e?.coerce??!1,...O(e)});function Cf(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 nn=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)!==v.number){let s=this._getOrReturnCtx(t);return b(s,{code:h.invalid_type,expected:v.number,received:s.parsedType}),R}let r,o=new le;for(let s of this._def.checks)s.kind==="int"?D.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),b(r,{code:h.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),b(r,{code:h.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),b(r,{code:h.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Cf(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),b(r,{code:h.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),b(r,{code:h.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,C.toString(n))}gt(t,n){return this.setLimit("min",t,!1,C.toString(n))}lte(t,n){return this.setLimit("max",t,!0,C.toString(n))}lt(t,n){return this.setLimit("max",t,!1,C.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:C.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:C.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:C.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:C.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:C.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:C.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:C.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:C.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:C.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:C.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)}};nn.create=e=>new nn({checks:[],typeName:I.ZodNumber,coerce:e?.coerce||!1,...O(e)});var rn=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)!==v.bigint)return this._getInvalidInput(t);let r,o=new le;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),b(r,{code:h.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),b(r,{code:h.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),b(r,{code:h.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 b(n,{code:h.invalid_type,expected:v.bigint,received:n.parsedType}),R}gte(t,n){return this.setLimit("min",t,!0,C.toString(n))}gt(t,n){return this.setLimit("min",t,!1,C.toString(n))}lte(t,n){return this.setLimit("max",t,!0,C.toString(n))}lt(t,n){return this.setLimit("max",t,!1,C.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:C.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:C.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:C.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:C.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:C.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:C.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}};rn.create=e=>new rn({checks:[],typeName:I.ZodBigInt,coerce:e?.coerce??!1,...O(e)});var on=class extends N{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==v.boolean){let r=this._getOrReturnCtx(t);return b(r,{code:h.invalid_type,expected:v.boolean,received:r.parsedType}),R}return pe(t.data)}};on.create=e=>new on({typeName:I.ZodBoolean,coerce:e?.coerce||!1,...O(e)});var sn=class e extends N{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==v.date){let s=this._getOrReturnCtx(t);return b(s,{code:h.invalid_type,expected:v.date,received:s.parsedType}),R}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return b(s,{code:h.invalid_date}),R}let r=new le,o;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),b(o,{code:h.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),b(o,{code:h.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:C.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:C.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};sn.create=e=>new sn({checks:[],coerce:e?.coerce||!1,typeName:I.ZodDate,...O(e)});var Un=class extends N{_parse(t){if(this._getType(t)!==v.symbol){let r=this._getOrReturnCtx(t);return b(r,{code:h.invalid_type,expected:v.symbol,received:r.parsedType}),R}return pe(t.data)}};Un.create=e=>new Un({typeName:I.ZodSymbol,...O(e)});var an=class extends N{_parse(t){if(this._getType(t)!==v.undefined){let r=this._getOrReturnCtx(t);return b(r,{code:h.invalid_type,expected:v.undefined,received:r.parsedType}),R}return pe(t.data)}};an.create=e=>new an({typeName:I.ZodUndefined,...O(e)});var cn=class extends N{_parse(t){if(this._getType(t)!==v.null){let r=this._getOrReturnCtx(t);return b(r,{code:h.invalid_type,expected:v.null,received:r.parsedType}),R}return pe(t.data)}};cn.create=e=>new cn({typeName:I.ZodNull,...O(e)});var Ot=class extends N{constructor(){super(...arguments),this._any=!0}_parse(t){return pe(t.data)}};Ot.create=e=>new Ot({typeName:I.ZodAny,...O(e)});var mt=class extends N{constructor(){super(...arguments),this._unknown=!0}_parse(t){return pe(t.data)}};mt.create=e=>new mt({typeName:I.ZodUnknown,...O(e)});var Ne=class extends N{_parse(t){let n=this._getOrReturnCtx(t);return b(n,{code:h.invalid_type,expected:v.never,received:n.parsedType}),R}};Ne.create=e=>new Ne({typeName:I.ZodNever,...O(e)});var jn=class extends N{_parse(t){if(this._getType(t)!==v.undefined){let r=this._getOrReturnCtx(t);return b(r,{code:h.invalid_type,expected:v.void,received:r.parsedType}),R}return pe(t.data)}};jn.create=e=>new jn({typeName:I.ZodVoid,...O(e)});var pt=class e extends N{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==v.array)return b(n,{code:h.invalid_type,expected:v.array,received:n.parsedType}),R;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(b(n,{code:i?h.too_big:h.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&&(b(n,{code:h.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&&(b(n,{code:h.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 Ie(n,i,n.path,a)))).then(i=>le.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new Ie(n,i,n.path,a)));return le.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:C.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:C.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:C.toString(n)}})}nonempty(t){return this.min(1,t)}};pt.create=(e,t)=>new pt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:I.ZodArray,...O(t)});function Dn(e){if(e instanceof Se){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Re.create(Dn(r))}return new Se({...e._def,shape:()=>t})}else return e instanceof pt?new pt({...e._def,type:Dn(e.element)}):e instanceof Re?Re.create(Dn(e.unwrap())):e instanceof We?We.create(Dn(e.unwrap())):e instanceof Ge?Ge.create(e.items.map(t=>Dn(t))):e}var Se=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)!==v.object){let l=this._getOrReturnCtx(t);return b(l,{code:h.invalid_type,expected:v.object,received:l.parsedType}),R}let{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ne&&this._def.unknownKeys==="strip"))for(let l in o.data)i.includes(l)||a.push(l);let c=[];for(let l of i){let u=s[l],d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Ie(o,d,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Ne){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(l==="strict")a.length>0&&(b(o,{code:h.unrecognized_keys,keys:a}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Ie(o,d,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,f=await u.value;l.push({key:d,value:f,alwaysSet:u.alwaysSet})}return l}).then(l=>le.mergeObjectSync(r,l)):le.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(t){return C.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:C.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:I.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 Dn(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 Re;)s=s._def.innerType;n[r]=s}return new e({...this._def,shape:()=>n})}keyof(){return ll(D.objectKeys(this.shape))}};Se.create=(e,t)=>new Se({shape:()=>e,unknownKeys:"strip",catchall:Ne.create(),typeName:I.ZodObject,...O(t)});Se.strictCreate=(e,t)=>new Se({shape:()=>e,unknownKeys:"strict",catchall:Ne.create(),typeName:I.ZodObject,...O(t)});Se.lazycreate=(e,t)=>new Se({shape:e,unknownKeys:"strip",catchall:Ne.create(),typeName:I.ZodObject,...O(t)});var ln=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 ve(a.ctx.common.issues));return b(n,{code:h.invalid_union,unionErrors:i}),R}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of r){let l={...n,common:{...n.common,issues:[]},parent:null},u=c._parseSync({data:n.data,path:n.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new ve(c));return b(n,{code:h.invalid_union,unionErrors:a}),R}}get options(){return this._def.options}};ln.create=(e,t)=>new ln({options:e,typeName:I.ZodUnion,...O(t)});var dt=e=>e instanceof dn?dt(e.schema):e instanceof $e?dt(e.innerType()):e instanceof mn?[e.value]:e instanceof pn?e.options:e instanceof fn?D.objectValues(e.enum):e instanceof gn?dt(e._def.innerType):e instanceof an?[void 0]:e instanceof cn?[null]:e instanceof Re?[void 0,...dt(e.unwrap())]:e instanceof We?[null,...dt(e.unwrap())]:e instanceof wr||e instanceof yn?dt(e.unwrap()):e instanceof hn?dt(e._def.innerType):[],To=class e extends N{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==v.object)return b(n,{code:h.invalid_type,expected:v.object,received:n.parsedType}),R;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}):(b(n,{code:h.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),R)}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=dt(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:I.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...O(r)})}};function ri(e,t){let n=Ke(e),r=Ke(t);if(e===t)return{valid:!0,data:e};if(n===v.object&&r===v.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 c=ri(e[a],t[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===v.array&&r===v.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let s=0;s<e.length;s++){let i=e[s],a=t[s],c=ri(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return n===v.date&&r===v.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var un=class extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=(s,i)=>{if(ko(s)||ko(i))return R;let a=ri(s.value,i.value);return a.valid?((Co(s)||Co(i))&&n.dirty(),{status:n.value,value:a.data}):(b(r,{code:h.invalid_intersection_types}),R)};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}))}};un.create=(e,t,n)=>new un({left:e,right:t,typeName:I.ZodIntersection,...O(n)});var Ge=class e extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==v.array)return b(r,{code:h.invalid_type,expected:v.array,received:r.parsedType}),R;if(r.data.length<this._def.items.length)return b(r,{code:h.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),R;!this._def.rest&&r.data.length>this._def.items.length&&(b(r,{code:h.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Ie(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>le.mergeArray(n,i)):le.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ge.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ge({items:e,typeName:I.ZodTuple,rest:null,...O(t)})};var Eo=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!==v.object)return b(r,{code:h.invalid_type,expected:v.object,received:r.parsedType}),R;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new Ie(r,a,r.path,a)),value:i._parse(new Ie(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?le.mergeObjectAsync(n,o):le.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:I.ZodRecord,...O(r)}):new e({keyType:Pt.create(),valueType:t,typeName:I.ZodRecord,...O(n)})}},Fn=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!==v.map)return b(r,{code:h.invalid_type,expected:v.map,received:r.parsedType}),R;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,c],l)=>({key:o._parse(new Ie(r,a,r.path,[l,"key"])),value:s._parse(new Ie(r,c,r.path,[l,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return R;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let c of i){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return R;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}}}};Fn.create=(e,t,n)=>new Fn({valueType:t,keyType:e,typeName:I.ZodMap,...O(n)});var Vn=class e extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==v.set)return b(r,{code:h.invalid_type,expected:v.set,received:r.parsedType}),R;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(b(r,{code:h.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&&(b(r,{code:h.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return R;u.status==="dirty"&&n.dirty(),l.add(u.value)}return{status:n.value,value:l}}let a=[...r.data.values()].map((c,l)=>s._parse(new Ie(r,c,r.path,l)));return r.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(t,n){return new e({...this._def,minSize:{value:t,message:C.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:C.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};Vn.create=(e,t)=>new Vn({valueType:e,minSize:null,maxSize:null,typeName:I.ZodSet,...O(t)});var Ao=class e extends N{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==v.function)return b(n,{code:h.invalid_type,expected:v.function,received:n.parsedType}),R;function r(a,c){return Sr({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Nn(),ut].filter(l=>!!l),issueData:{code:h.invalid_arguments,argumentsError:c}})}function o(a,c){return Sr({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Nn(),ut].filter(l=>!!l),issueData:{code:h.invalid_return_type,returnTypeError:c}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof Mt){let a=this;return pe(async function(...c){let l=new ve([]),u=await a._def.args.parseAsync(c,s).catch(m=>{throw l.addIssue(r(c,m)),l}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,s).catch(m=>{throw l.addIssue(o(d,m)),l})})}else{let a=this;return pe(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new ve([r(c,l.error)]);let u=Reflect.apply(i,this,l.data),d=a._def.returns.safeParse(u,s);if(!d.success)throw new ve([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:Ge.create(t).rest(mt.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||Ge.create([]).rest(mt.create()),returns:n||mt.create(),typeName:I.ZodFunction,...O(r)})}},dn=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})}};dn.create=(e,t)=>new dn({getter:e,typeName:I.ZodLazy,...O(t)});var mn=class extends N{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return b(n,{received:n.data,code:h.invalid_literal,expected:this._def.value}),R}return{status:"valid",value:t.data}}get value(){return this._def.value}};mn.create=(e,t)=>new mn({value:e,typeName:I.ZodLiteral,...O(t)});function ll(e,t){return new pn({values:e,typeName:I.ZodEnum,...O(t)})}var pn=class e extends N{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return b(n,{expected:D.joinValues(r),received:n.parsedType,code:h.invalid_type}),R}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 b(n,{received:n.data,code:h.invalid_enum_value,options:r}),R}return pe(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})}};pn.create=ll;var fn=class extends N{_parse(t){let n=D.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==v.string&&r.parsedType!==v.number){let o=D.objectValues(n);return b(r,{expected:D.joinValues(o),received:r.parsedType,code:h.invalid_type}),R}if(this._cache||(this._cache=new Set(D.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let o=D.objectValues(n);return b(r,{received:r.data,code:h.invalid_enum_value,options:o}),R}return pe(t.data)}get enum(){return this._def.values}};fn.create=(e,t)=>new fn({values:e,typeName:I.ZodNativeEnum,...O(t)});var Mt=class extends N{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==v.promise&&n.common.async===!1)return b(n,{code:h.invalid_type,expected:v.promise,received:n.parsedType}),R;let r=n.parsedType===v.promise?n.data:Promise.resolve(n.data);return pe(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Mt.create=(e,t)=>new Mt({type:e,typeName:I.ZodPromise,...O(t)});var $e=class extends N{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===I.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=>{b(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 R;let c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?R:c.status==="dirty"?tn(c.value):n.value==="dirty"?tn(c.value):c});{if(n.value==="aborted")return R;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?R:a.status==="dirty"?tn(a.value):n.value==="dirty"?tn(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?R:(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"?R:(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(!$t(i))return R;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=>$t(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):R);D.assertNever(o)}};$e.create=(e,t,n)=>new $e({schema:e,typeName:I.ZodEffects,effect:t,...O(n)});$e.createWithPreprocess=(e,t,n)=>new $e({schema:t,effect:{type:"preprocess",transform:e},typeName:I.ZodEffects,...O(n)});var Re=class extends N{_parse(t){return this._getType(t)===v.undefined?pe(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Re.create=(e,t)=>new Re({innerType:e,typeName:I.ZodOptional,...O(t)});var We=class extends N{_parse(t){return this._getType(t)===v.null?pe(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};We.create=(e,t)=>new We({innerType:e,typeName:I.ZodNullable,...O(t)});var gn=class extends N{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===v.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};gn.create=(e,t)=>new gn({innerType:e,typeName:I.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...O(t)});var hn=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 Ln(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ve(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ve(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};hn.create=(e,t)=>new hn({innerType:e,typeName:I.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...O(t)});var Hn=class extends N{_parse(t){if(this._getType(t)!==v.nan){let r=this._getOrReturnCtx(t);return b(r,{code:h.invalid_type,expected:v.nan,received:r.parsedType}),R}return{status:"valid",value:t.data}}};Hn.create=e=>new Hn({typeName:I.ZodNaN,...O(e)});var Tf=Symbol("zod_brand"),wr=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}},xr=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"?R:s.status==="dirty"?(n.dirty(),tn(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"?R: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:I.ZodPipeline})}},yn=class extends N{_parse(t){let n=this._def.innerType._parse(t),r=o=>($t(o)&&(o.value=Object.freeze(o.value)),o);return Ln(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};yn.create=(e,t)=>new yn({innerType:e,typeName:I.ZodReadonly,...O(t)});function sl(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function ul(e,t={},n){return e?Ot.create().superRefine((r,o)=>{let s=e(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=sl(t,r),c=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=sl(t,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Ot.create()}var Ef={object:Se.lazycreate},I;(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"})(I||(I={}));var Af=(e,t={message:`Input not instance of ${e.name}`})=>ul(n=>n instanceof e,t),dl=Pt.create,ml=nn.create,Rf=Hn.create,If=rn.create,pl=on.create,$f=sn.create,Pf=Un.create,Of=an.create,Mf=cn.create,Nf=Ot.create,Lf=mt.create,Df=Ne.create,Uf=jn.create,jf=pt.create,Ff=Se.create,Vf=Se.strictCreate,Hf=ln.create,qf=To.create,Bf=un.create,Kf=Ge.create,Gf=Eo.create,Wf=Fn.create,zf=Vn.create,Jf=Ao.create,Yf=dn.create,Zf=mn.create,Xf=pn.create,Qf=fn.create,eg=Mt.create,tg=$e.create,ng=Re.create,rg=We.create,og=$e.createWithPreprocess,sg=xr.create,ig=()=>dl().optional(),ag=()=>ml().optional(),cg=()=>pl().optional(),lg={string:(e=>Pt.create({...e,coerce:!0})),number:(e=>nn.create({...e,coerce:!0})),boolean:(e=>on.create({...e,coerce:!0})),bigint:(e=>rn.create({...e,coerce:!0})),date:(e=>sn.create({...e,coerce:!0}))};var ug=R;var dg=/^[A-Za-z0-9._-]+$/,mg=/^[A-Za-z0-9._-]+(\|[A-Za-z0-9._-]+)*$/,fl=new Set([".",".."]),ye=class extends Error{pattern;constructor(t,n){super(`Invalid freeReadPathPattern ${JSON.stringify(n)}: ${t}`),this.pattern=n,this.name="FreePathPatternError"}};function pg(e,t){if(e==="*")return{raw:e,kind:"single"};if(e==="**")return{raw:e,kind:"multi"};if(e.startsWith("(")){let n=e.endsWith(")?"),r=e.endsWith(")");if(!n&&!r)throw new ye(`malformed alternation segment ${JSON.stringify(e)}`,t);let o=n?e.slice(1,-2):e.slice(1,-1);if(!mg.test(o))throw new ye(`malformed alternation segment ${JSON.stringify(e)}`,t);let s=o.split("|");if(s.some(i=>fl.has(i)))throw new ye(`alternation segment ${JSON.stringify(e)} may not contain '.' or '..'`,t);return{raw:e,kind:n?"alt-optional":"alt",alternatives:s}}if(dg.test(e)){if(fl.has(e))throw new ye(`literal segment ${JSON.stringify(e)} is not permitted`,t);return{raw:e,kind:"literal"}}throw new ye(`segment ${JSON.stringify(e)} must be '*', '**', a [A-Za-z0-9._-]+ literal, or (a|b) alternation`,t)}function fg(e){if(typeof e!="string"||e.length===0)throw new ye("must be a non-empty string",String(e));if(!e.startsWith("/"))throw new ye("must start with '/'",e);if(e.slice(1).includes("//"))throw new ye("empty segments ('//') are not permitted",e);if(e.length>1&&e.endsWith("/"))throw new ye("must not end with '/'",e);let n=e.slice(1).split("/").map(s=>pg(s,e));if(n.filter(s=>s.kind==="multi").length>1)throw new ye("at most one '**' is permitted per pattern",e);if(n[0]?.kind==="multi")throw new ye("'**' may not be the first segment (a literal prefix anchor is required)",e);let o=n.findIndex(s=>s.kind==="alt-optional");if(o!==-1&&o!==n.length-1)throw new ye("optional alternation '(...)?' is only allowed as the final segment",e);return n}function oi(e){fg(e)}var gl=["tempo","mpp_self","merchant_self"],hl=["catalog_static","fal_direct","fal_queue","openrouter_chat","openrouter_image","platform_proxy","tempo_gateway","x402_gateway"],yl=["image","audio","queued_audio","video","queued_video","model_3d","llm","transcription","utility"],_l=["images[0].url","image.url","audio.url","audio_file.url","audio_url","video.url","model_mesh.url","text","choices[0].message.content","choices[0].message.images[0].image_url.url","request_id"];var ii=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()}),gg=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:ii.optional()}).passthrough(),ai=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")})]),ci=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()}),bl=g.object({attestation:g.boolean().optional(),rateLimitMs:g.number().positive().optional()}),vl=g.object({displayName:g.string().optional(),feedbackEligible:g.boolean().optional(),suggestionEligible:g.boolean().optional(),batchable:g.boolean().optional()}),Sl=g.object({enabled:g.boolean().optional(),gatewayPath:g.string().min(1).startsWith("/").optional(),method:g.enum(["GET","POST","PUT","PATCH","DELETE"]).optional(),timeoutMs:g.number().int().positive().max(12e4).optional()}).strict(),hg=g.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),yg=120,_g=120,bg=1200,vg=/^[^\u0000-\u001F\u007F]+$/;function si(e,t){return g.string().min(1).max(e).regex(vg,`${t} must not contain control characters`)}var li={id:g.string().min(1),name:si(yg,"name"),description:si(bg,"description"),provider:g.string().min(1),model:g.string().min(1),category:hg,priceCents:g.number().nonnegative(),inputSchema:g.record(g.unknown()),gatewayUrl:g.string().min(1),merchantName:si(_g,"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:ii.optional(),priceDisplay:g.string().optional(),pricingModel:g.enum(["per-call","per-token","band"]).optional(),pricingInfo:gg.optional(),status:g.enum(["available","unavailable"]).optional(),handler:ai.optional(),pricing:ci.optional(),security:bl.optional(),engagement:vl.optional(),gatewayConfig:Sl.optional(),freeReadPathPattern:g.string().optional().superRefine((e,t)=>{if(e!==void 0)try{oi(e)}catch(n){t.addIssue({code:g.ZodIssueCode.custom,message:n instanceof Error?n.message:String(n)})}}),enabled:g.boolean().optional(),beta:g.boolean().optional(),deprecated:g.boolean().optional(),internal:g.boolean().optional(),replacementTool:g.string().optional(),minCliVersion:g.string().optional(),sunsetAt:g.string().optional(),rail:g.enum(gl).optional(),executionKind:g.enum(hl).optional(),resultKind:g.enum(yl).optional(),extractionMode:g.enum(_l).optional(),pricingStrategy:g.enum(["flat","token","band"]).optional()},wl=g.object({...li,dispatch:g.literal("routed"),routedPath:g.string().min(1).startsWith("/")}).strict(),xl=g.object({...li,dispatch:g.literal("enveloped")}).strict(),kl=g.object({...li,handler:ai,pricing:ci}).strict(),Cl=g.union([g.discriminatedUnion("dispatch",[wl,xl]),kl]);var ui=/^[a-z0-9][a-z0-9_-]*$/;var xg="https://fal.run",Rl="https://openrouter.mpp.tempo.xyz",mi=1024,Io=8192,kg=4096,Cg=10;function Tg(e){return e>=Cg?kg:Io}function Il(e,t){let n=typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):mi;return Math.min(n,t)}function Eg(e){let{attestation:t,tool_id:n,...r}=e;return r}var Tl={"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 Ro(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"&&Tl[r]&&(i.image_size=Tl[r]),i)}function Ag(e){let{attestation:t,tool_id:n,...r}=e;return r}function El(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 Rg(e,t,n,r,o,s,i,a,c){return{id:e,name:t,description:n,provider:r,model:o.replace(/^\//,""),category:s,gatewayUrl:`https://${r}${o}`,merchantName:t,inputSchema:a,handler:{type:"custom",merchantSlug:r,subPath:o},pricing:{amount:i,currency:"USD",display:`$${(i/100).toFixed(2)}`},priceCents:i,tags:[],...c}}function Ig(e,t,n,r,o,s,i,a){return Rg(e,t,n,"suno-ai",r,o,s,i,{merchantName:"Suno AI",...a})}function ne(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:`${xg}/${r}`,merchantName:"fal.ai",buildBody:Eg,tags:[],...a}}function $l(e,t=Io){return n=>{let{attestation:r,tool_id:o,model:s,prompt:i,system_prompt:a,max_tokens:c,max_completion_tokens:l,messages:u,temperature:d,...f}=n;return typeof s=="string"&&s.length>0&&s!==e&&console.warn("[catalog] openrouterBuildBody: caller model override ignored",{catalogModel:e,callerModel:s}),{messages:Array.isArray(u)?u:[...a?[{role:"system",content:a}]:[],{role:"user",content:i}],temperature:d??.7,...f,model:e,max_tokens:Il(c??l,t)}}}function Pl(e,t=Io){return n=>{let{attestation:r,tool_id:o,prompt:s,image_url:i,aspect_ratio:a,max_tokens:c,max_completion_tokens:l,model:u,messages:d,image_config:f,temperature:m,..._}=n,S=[{type:"text",text:s}];return typeof i=="string"&&i.length>0&&S.push({type:"image_url",image_url:{url:i}}),{messages:Array.isArray(d)?d:[{role:"user",content:S}],temperature:m??.7,..._,model:e,...typeof a=="string"&&a.length>0?{image_config:{aspect_ratio:a}}:{},max_tokens:Il(c??l,t)}}}function X(e,t,n,r,o,s,i){let a=i?.maxOutputTokens??Tg(s),c=i?.perRequestFeeCents??0,l=500/1e6*o*100,u=500/1e6*s*100,d=Math.max(1,Math.ceil(l+u+c)),{perRequestFeeCents:f,maxOutputTokens:m,..._}=i??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"llm",priceCents:d,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The prompt or question to send to the model"},system_prompt:{type:"string",description:"Optional system prompt to set model behavior"},max_tokens:{type:"integer",description:`Maximum tokens in response (default: ${mi}); values above ${a} are clamped to ${a}`,minimum:1,maximum:a},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${Rl}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:$l(r,a),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:o,outputPerMillion:s,...c>0?{perRequestFeeCents:c}:{}},..._}}function di(e,t,n,r,o,s){let i=s?.maxOutputTokens??Io,{maxOutputTokens:a,...c}=s??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"image",pricingStrategy:"band",priceCents:o,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate or edit"},image_url:{type:"string",description:"Optional source image URL for edits"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"1:1"},max_tokens:{type:"integer",description:`Maximum text tokens in response metadata (default: ${mi}); values above ${i} are clamped to ${i}`,minimum:1,maximum:i},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${Rl}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:Pl(r,i),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...c}}var pi=[ne("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"]}),ne("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:Ro}),ne("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:Ro}),ne("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:Ro}),ne("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"]}),di("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),di("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}}),di("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}}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),Ig("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}}}),ne("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"]}),ne("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"]}),ne("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"]}),ne("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"]}),X("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"]}),X("or-gpt-55","GPT-5.5","OpenAI frontier model for complex professional reasoning, coding, and long-context analysis.","openai/gpt-5.5",5,30,{tags:["llm","gpt","openai","frontier","reasoning","coding","long-context"]}),X("or-gpt-55-pro","GPT-5.5 Pro","OpenAI high-capability frontier model optimized for deep reasoning and high-stakes workloads.","openai/gpt-5.5-pro",30,180,{tags:["llm","gpt","openai","frontier","pro","deep-reasoning","coding","long-context"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("or-gemini-35-flash","Gemini 3.5 Flash","Google frontier Flash model for multimodal reasoning, coding, and parallel agentic workflows.","google/gemini-3.5-flash",1.5,9,{tags:["llm","gemini","google","frontier","multimodal","reasoning","coding","fast"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("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"]}),X("or-perplexity-sonar","Perplexity Sonar","Search-augmented LLM. Answers with real-time web sources and citations.","perplexity/sonar",1,1,{perRequestFeeCents:.5,tags:["llm","perplexity","search","web","citations","real-time"]}),{dispatch:"enveloped",id:"query_onchain_prices",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly and daily granularity.",provider:"allium",model:"allium-prices",category:"onchain",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly) or '1d' (daily). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",internal:!0,executionKind:"x402_gateway",resultKind:"utility",gatewayConfig:{enabled:!1,gatewayPath:"/gateway",method:"POST",timeoutMs:3e4},buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:El,tags:["onchain","prices","allium","crypto"]},{dispatch:"enveloped",id:"parallel-search-tempo",name:"Parallel Search (Tempo)",description:"Internal Tempo gateway route for Parallel's paid search endpoint.",provider:"parallel",model:"search",category:"utility",priceCents:1,inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query. Mapped by Parallel to objective when provided."},objective:{type:"string",description:"Search objective. Use with search_queries for advanced requests."},search_queries:{type:"array",items:{type:"string"},description:"Optional explicit search query list."},mode:{type:"string",enum:["one-shot","fast"],description:"Parallel search mode.",default:"one-shot"}},anyOf:[{required:["query"]},{required:["objective"]}]},gatewayUrl:"https://parallelmpp.dev/api/search",merchantName:"Parallel",internal:!0,rail:"tempo",executionKind:"tempo_gateway",resultKind:"utility",gatewayConfig:{enabled:!1,gatewayPath:"/gateway",method:"POST",timeoutMs:3e4},buildBody:Ag,tags:["search","parallel","tempo","internal"]},{dispatch:"enveloped",id:"generate_image_card",name:"Generate Image (Ultra)",description:"Generate a high-quality AI image (FLUX Pro Ultra, 2K, ~$0.06).",provider:"fal",model:"fal-ai/flux-pro/v1.1-ultra",category:"image",priceCents:6,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1-ultra",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro-ultra",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),t},tags:["image","flux","ultra","legacy"]},{dispatch:"enveloped",id:"generate_image_fast_card",name:"Generate Image (Fast)",description:"Generate an AI image (FLUX Pro v1.1, 1K, ~$0.04).",provider:"fal",model:"fal-ai/flux-pro/v1.1",category:"image",priceCents:4,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro",buildBody:e=>Ro({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"]},ne("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"}),ne("edit_image_seed_card","Edit Image (SeedEdit)","Inpaint/edit an image with a prompt using SeedEdit.","fal-ai/bytedance/seededit","image",5,{type:"object",properties:{image_url:{type:"string"},prompt:{type:"string"},seed:{type:"number"}},required:["image_url","prompt"]},{buildBody:e=>{let t={image_url:e.image_url,prompt:e.prompt};return e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","edit","inpaint","seededit"],deprecated:!0,replacementTool:"or-gemini-nano-banana"}),{dispatch:"enveloped",id:"generate_video_tempo_card",name:"Generate Video (Grok)",description:"Generate a video from a text prompt using Grok Imagine Video.",provider:"fal",model:"xai/grok-imagine-video/text-to-video",category:"video",priceCents:30,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/xai/grok-imagine-video/text-to-video",merchantName:"Grok Video via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),t},tags:["video","grok","legacy"]},{dispatch:"enveloped",id:"generate_video_kling_card",name:"Generate Video (Kling)",description:"Generate a video using Kling v1.6 (async, ~$0.40).",provider:"fal",model:"fal-ai/kling-video/v1.6/standard/text-to-video",category:"video",priceCents:40,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/kling-video/v1.6/standard/text-to-video",merchantName:"Kling via fal.ai",deprecated:!0,replacementTool:"fal-kling-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","kling","legacy"]},{dispatch:"enveloped",id:"generate_video_wan_card",name:"Generate Video (Wan)",description:"Generate a video using Wan T2V (async, ~$0.25).",provider:"fal",model:"fal-ai/wan/t2v-1.3b",category:"video",priceCents:25,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/wan/t2v-1.3b",merchantName:"Wan T2V via fal.ai",deprecated:!0,replacementTool:"fal-wan-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","wan","legacy"]},{dispatch:"enveloped",id:"generate_video_minimax_card",name:"Generate Video (MiniMax)",description:"Generate a video using MiniMax (async, ~$0.35).",provider:"fal",model:"fal-ai/minimax/video-01",category:"video",priceCents:35,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/minimax/video-01",merchantName:"MiniMax via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","minimax","legacy"]},{id:"check_fal_status",name:"Check fal Async Job Status",description:"Poll an async fal.ai queue job for completion. Free.",provider:"fal",model:"queue-status",category:"image",priceCents:0,inputSchema:{type:"object",properties:{model_path:{type:"string",description:"Model path (e.g. fal-ai/kling-video/v1.6/standard/text-to-video)"},request_id:{type:"string"}},required:["model_path","request_id"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue",merchantName:"fal.ai",handler:{type:"local",fn:"check_fal_status"},pricing:{amount:0,currency:"USD",display:"$0.00",free:!0},freeReadPathPattern:"/api/v1/fal/**/requests/*/(status)?",tags:["status","fal","async"]},{dispatch:"enveloped",id:"generate_3d_card",name:"Generate 3D Model",description:"Generate a 3D mesh from a text prompt using Meshy (async, ~$0.50).",provider:"fal",model:"fal-ai/meshy-ai/text-to-3d",category:"3d",priceCents:50,inputSchema:{type:"object",properties:{object_prompt:{type:"string"},style_prompt:{type:"string"},negative_prompt:{type:"string"},art_style:{type:"string"},seed:{type:"number"}},required:["object_prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/meshy-ai/text-to-3d",merchantName:"Meshy via fal.ai",deprecated:!0,replacementTool:"fal-trellis-3d",buildBody:e=>{let t={object_prompt:e.object_prompt};return e.style_prompt&&(t.style_prompt=e.style_prompt),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.art_style&&(t.art_style=e.art_style),e.seed!==void 0&&(t.seed=e.seed),t},tags:["3d","mesh","meshy","legacy"]},{dispatch:"enveloped",id:"generate_speech_card",name:"Generate Speech",description:"Text-to-speech using F5-TTS with optional voice cloning.",provider:"fal",model:"fal-ai/f5-tts",category:"tts",priceCents:3,inputSchema:{type:"object",properties:{gen_text:{type:"string",description:"Text to synthesize"},ref_audio_url:{type:"string",description:"Reference audio URL (for voice cloning)"},ref_text:{type:"string",description:"Transcription of ref audio"},remove_silence:{type:"boolean"}},required:["gen_text"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/f5-tts",merchantName:"fal.ai",buildBody:e=>{let t={gen_text:e.gen_text};return e.ref_audio_url&&(t.ref_audio_url=e.ref_audio_url),e.ref_text&&(t.ref_text=e.ref_text),e.remove_silence!==void 0&&(t.remove_silence=e.remove_silence),t},deprecated:!0,replacementTool:"fal-metavoice",tags:["tts","speech","f5-tts","legacy"]},{dispatch:"enveloped",id:"generate_music_tempo_card",name:"Generate Music (Suno) \u2014 retired",description:"[Retired] Suno music generation. Use `generate_music` (ACE-Step) instead.",enabled:!1,sunsetAt:"2026-06-25",provider:"suno",model:"suno-v4",category:"audio",priceCents:50,inputSchema:{type:"object",properties:{prompt:{type:"string"},instrumental:{type:"boolean"},model:{type:"string",default:"V4"}},required:["prompt"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/generate-music",merchantName:"Suno via Tempo",buildBody:e=>({prompt:e.prompt,customMode:!1,instrumental:e.instrumental??!1,model:e.model||"V4"}),isAsync:!0,pollUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",pollInterval:15e3,pollTimeout:3e5,deprecated:!0,replacementTool:"fal-ace-step-music",tags:["music","audio","suno","async","legacy"]},{dispatch:"enveloped",id:"check_music_status_tempo_card",name:"Check Music Status (Suno) \u2014 retired",description:"[Retired] Suno status poll. No replacement; ACE-Step jobs poll via `check_fal_status`.",enabled:!1,sunsetAt:"2026-06-25",provider:"suno",model:"suno-status",category:"audio",priceCents:0,inputSchema:{type:"object",properties:{taskId:{type:"string"}},required:["taskId"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",merchantName:"Suno Status",buildBody:e=>({taskId:e.taskId}),deprecated:!0,tags:["music","status","suno","legacy"]},{dispatch:"enveloped",id:"query_onchain_prices_card",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly, daily, and weekly granularity.",provider:"allium",model:"allium-prices",category:"llm",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly), '1d' (daily), or '1w' (weekly). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",deprecated:!0,replacementTool:"query_onchain_prices",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:El,tags:["onchain","prices","allium","crypto","legacy"]}];function kr(e){return pi.find(t=>t.id===e)}var Ol=1,Ml=["pick_one","fan_out"],Nl=["concat","dedupe_by_url","top_k_by_score"],Og=8,Mg=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()}),Ng=g.object({toolId:g.string().min(1),notes:g.string().min(1)}),Lg=g.string().regex(/^[a-z0-9_-]{1,32}$/,"tier key must be 1-32 chars [a-z0-9_-]"),Dg=g.object({providers:g.array(g.string().min(1)).min(1).max(Og),merge:g.enum(Nl),maxResults:g.number().int().positive().optional()}),Ll=g.object({mode:g.enum(Ml).default("pick_one"),intro:g.string().min(1),defaultTier:g.string().min(1),tiers:g.record(Lg,Ng).refine(e=>Object.keys(e).length>0,{message:"must have at least one tier"}),fanOut:Dg.optional(),guidance:g.string().min(1),inputProperties:g.record(g.string(),Mg),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"]}),Ug=g.object({version:g.literal(Ol),generatedAt:g.string().datetime(),tools:g.record(g.string().regex(ui,"tool name must match MCP naming rules"),Ll).refine(e=>Object.keys(e).length>0,{message:"manifest must have at least one tool"})});var Mo=require("child_process"),Bl=require("util"),Kl=E(require("crypto")),W=E(require("fs")),Gl=E(require("os")),fe=E(require("path"));var Le=(0,Bl.promisify)(Mo.execFile),Vg=()=>process.platform==="darwin",Nt=()=>process.platform==="win32",Lt=fe.join(Gl.homedir(),".visa-mcp","bin"),_n=fe.join(Lt,"Visa CLI"),ft=fe.join(Lt,"visa-keychain-win.exe"),Wl=fe.join(__dirname,"..","native"),Dl="6",Ul=fe.join(Lt,"visa-keychain.version"),jl=fe.join(Lt,"visa-keychain.sha256"),Fl="1",Vl=fe.join(Lt,"visa-keychain-win.version"),Hl=fe.join(Lt,"visa-keychain-win.sha256"),zl=[fe.join(Wl,"bin","win32-x64","visa-keychain-win.exe"),fe.resolve(__dirname,"..","..","native","bin","win32-x64","visa-keychain-win.exe"),fe.resolve(__dirname,"..","native","bin","win32-x64","visa-keychain-win.exe")];function $o(e){let t=W.readFileSync(e);return Kl.createHash("sha256").update(t).digest("hex")}function Hg(e){let t=e.trim();if(t.startsWith("OK:"))return t.slice(3);if(t==="OK")return;let n=t.startsWith("ERROR:")?t.slice(6):"Unknown error";throw new Error(n)}async function fi(){try{if(W.readFileSync(Ul,"utf-8").trim()===Dl&&W.existsSync(_n)){let r=W.readFileSync(jl,"utf-8").trim();if($o(_n)!==r)p.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),W.unlinkSync(_n);else return _n}}catch{}let e=fe.join(Wl,"visa-keychain.m");if(W.existsSync(e)||(e=fe.resolve(__dirname,"..","..","native","visa-keychain.m")),W.existsSync(e)||(e=fe.resolve(__dirname,"..","native","visa-keychain.m")),!W.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");W.mkdirSync(Lt,{recursive:!0,mode:448});try{await Le("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",_n,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=$o(_n);return W.writeFileSync(jl,t,{mode:384}),W.writeFileSync(Ul,Dl,{mode:384}),_n}function Jl(){for(let e of zl)if(W.existsSync(e))return e;return null}async function qn(){try{if(W.readFileSync(Vl,"utf-8").trim()===Fl&&W.existsSync(ft)){let r=W.readFileSync(Hl,"utf-8").trim();if($o(ft)!==r)p.warn("binary:hash-mismatch:win32",{message:"Windows binary hash mismatch. Redeploying."}),W.unlinkSync(ft);else return ft}}catch{}let e=Jl();if(!e)throw new Error(`visa-keychain-win.exe not found in package. Reinstall @visa/cli.
124
+ If building from source, run native/build-win.bat first.`);W.mkdirSync(Lt,{recursive:!0}),W.copyFileSync(e,ft);let t=$o(ft);return W.writeFileSync(Hl,t,{mode:384}),W.writeFileSync(Vl,Fl,{mode:384}),ft}async function qg(){return Nt()?qn():fi()}var Po="visa-cli",Oo="attestation-key";async function Bg(e){try{await Le("security",["delete-generic-password","-s",Po,"-a",Oo],{timeout:5e3})}catch{}await Le("security",["add-generic-password","-s",Po,"-a",Oo,"-w",e],{timeout:5e3})}function Kg(e){let t=typeof e?.code=="number"?e.code:void 0,n=typeof e?.stderr=="string"?e.stderr:"",r=typeof e?.stdout=="string"?e.stdout:"",o=[n,r,e?.message].filter(Boolean).join(" ").trim();return t===44||/could not be found|item(?: was)? not found|no such keychain item|not found/i.test(o)?{state:"absent",usable:!1,message:"No local attestation key was found."}:/user interaction is not allowed|user canceled|user cancelled|authorization failed|interaction not allowed|keychain.*locked|denied|not authorized/i.test(o)?{state:"denied",usable:!1,message:"The local attestation key exists but Keychain access was denied or unavailable."}:{state:"error",usable:!1,message:o||"Could not read the local attestation key from Keychain."}}async function Gg(){try{let{stdout:e}=await Le("security",["find-generic-password","-s",Po,"-a",Oo,"-w"],{timeout:5e3}),t=e.trim();return t?{key:t,status:{state:"present",usable:!0}}:{key:null,status:{state:"absent",usable:!1,message:"No local attestation key was found."}}}catch(e){return{key:null,status:Kg(e)}}}async function gi(){let e=await Gg();if(e.key)return e.key;if(e.status.state==="absent")return null;throw new Error(e.status.message||"Could not read the local attestation key from Keychain.")}async function Yl(e){let t=await qg(),n;try{n=(await Le(t,e,{timeout:6e4})).stdout}catch(r){n=r.stdout||"";let o=n.trim();throw o.startsWith("ERROR:")?new Error(o.slice(6)):new Error(r.stderr?.trim()||r.message||"Unknown error")}return Hg(n)}var ql=!1;function Wg(){if(!Nt())return!1;try{return W.existsSync(ft)||Jl()!==null?!0:(ql||(ql=!0,p.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:ft,searchedPrebuiltPaths:zl})),!1)}catch{return!1}}function re(){return Tn()||Vg()?!0:Nt()?Wg():!1}async function No(){if(Nt()){let o=await qn(),{stdout:s}=await Le(o,["generate-key"],{timeout:3e4}),i=s.trim();if(i.startsWith("OK:"))return i.slice(3);throw new Error(i.startsWith("ERROR:")?i.slice(6):"Key generation failed")}let e=await Yl(["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 Bg(n),r}async function Lo(){if(Nt())try{let e=await qn(),{stdout:t}=await Le(e,["public-key"],{timeout:1e4});return t.trim().startsWith("OK:")}catch{return!1}return await gi()!==null}async function Zl(){if(Tn())return"mock-public-key-spki";if(Nt()){let n=await qn(),{stdout:r}=await Le(n,["public-key"],{timeout:6e4}),o=r.trim();if(o.startsWith("OK:"))return o.slice(3);throw new Error(o.startsWith("ERROR:")?o.slice(6):"Attestation key not found. Run setup to generate a new key.")}let e=await gi();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await fi();return new Promise((n,r)=>{let o=(0,Mo.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 bn(e,t){if(Tn())return Promise.resolve(Ta());if(Nt()){let s=await qn(),i=["sign",e];t&&i.push(t);let{stdout:a}=await Le(s,i,{timeout:6e4}),c=a.trim();if(c.startsWith("OK:"))return c.slice(3);throw new Error(c.startsWith("ERROR:")?c.slice(6):"Unknown error")}let n=await gi();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await fi(),o=["sign",e];return t&&o.push(t),new Promise((s,i)=>{let a=(0,Mo.execFile)(r,o,{timeout:6e4},(c,l)=>{let u=(l||"").trim();if(c){u.startsWith("ERROR:")?i(new Error(u.slice(6))):i(new Error(c.stderr?.trim()||c.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 Do(){if(Nt()){try{let e=await qn();await Le(e,["delete-key"],{timeout:1e4})}catch{}return}try{await Le("security",["delete-generic-password","-s",Po,"-a",Oo],{timeout:5e3})}catch{}try{await Yl(["delete-key"])}catch{}}var zg=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],Jg=[...zg.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 yi(e,t=Jg){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=hi(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(hi(r.match.provider)))&&r.match.keywords.every(o=>n.includes(hi(o))))return r.targetToolId;return null}function hi(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}var Tr={generate_image:{intro:'Generate an AI image from a text prompt \u2014 useful for hero shots, marketing assets, social posts, blog covers, app mockups, or any time the user asks for art, a logo, an icon, a thumbnail, or "a picture of \u2026". From $0.01 (fast) to $0.06 (pro), returns a hosted PNG/JPG URL. Default tier: balanced ($0.04, 1K, ~10s).',tiers:{balanced:{toolId:"fal-flux-pro",notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",notes:"Recraft V3 \u2014 vector/flat/illustration styles"}},guidance:"If the user didn't specify a tier, pick 'balanced' unless the prompt clearly signals otherwise (text \u2192 text_heavy, logo/icon \u2192 vector, quick test \u2192 fast, hero/print \u2192 pro).",inputProperties:{prompt:{type:"string",description:"Text description of the image to generate."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9", "1:1", "9:16".',default:"16:9"}},required:["prompt"]},generate_video:{intro:'Generate a short AI video from a text prompt \u2014 useful for product demos, social clips, mood reels, ad concepts, or any "make me a video of \u2026" request. $0.10\u2013$0.40 per ~6s clip depending on tier. Async: returns a request_id; use execute_tool with tool_id "check_fal_status" to resolve it (60\u2013180s).',tiers:{balanced:{toolId:"fal-minimax-video",notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",notes:"Kling \u2014 highest quality, cinematic"}},guidance:'Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate and are processed asynchronously. The response includes a request_id and model_path. Poll with execute_tool using tool_id "check_fal_status" and the exact request_id/model_path returned by the async response. Do not substitute the catalog model path manually. Do not poll more than once per 30 seconds.',inputProperties:{prompt:{type:"string",description:"Text description of the video scene."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9" or "9:16".',default:"16:9"}},required:["prompt"]},generate_music:{intro:'Generate an original music track from a prompt via ACE-Step. ~$0.02 for the default 60s track. Use for songs, backing tracks, jingles, vocal music, instrumental music, or any "make a song/music/track" request. Takes ~60-90s and may return a request_id to poll with check_fal_status. For SFX, chimes, ambient beds, or TTS, use generate_audio instead.',tiers:{ace_step:{toolId:"fal-ace-step-music",notes:"ACE-Step \u2014 prompt-to-music with vocals or instrumentals"}},guidance:"Use for songs and music tracks. Takes ~60-90s and may return a request_id to poll with check_fal_status. For sound effects, chimes, ambient beds, or TTS, use generate_audio instead.",inputProperties:{prompt:{type:"string",description:"Musical style, mood, instruments, subject, and lyrics direction."},instrumental:{type:"boolean",description:"True for instrumental music with no vocals; false for vocal tracks.",default:!1},duration:{type:"number",description:"Duration in seconds.",default:60}},required:["prompt"]},generate_audio:{intro:'Generate sound effects from a text prompt (sfx tier \u2014 default), or voice-cloned speech from text + a reference audio URL (tts tier). $0.03\u2013$0.04. Use for SFX, chimes, UI sounds, ambient audio (default sfx), or voice cloning when a reference audio URL is available (pass tier:"tts"). Default tier is sfx; pass tier:"tts" for voice cloning.',tiers:{sfx:{toolId:"fal-stable-audio",notes:"Stable Audio \u2014 sound effects and ambient from a prompt"},tts:{toolId:"fal-metavoice",notes:"MetaVoice \u2014 voice cloning TTS (requires a voice sample URL)"}},guidance:'Default tier is sfx: pass prompt describing the sound. For tts (voice cloning): pass tier:"tts" + text + audio_url.',inputProperties:{prompt:{type:"string",description:"Description of sound to generate (sfx tier, default)."},text:{type:"string",description:"Text to speak aloud (tts tier)."},audio_url:{type:"string",description:"URL of a voice sample to clone (tts tier, required for voice cloning)."}},required:[]},generate_3d:{intro:"Generate a 3D mesh (GLB) from an image URL via Trellis. ~$0.08, ~30\u201360s. Use when the user shares an image and asks for a 3D model, asset, AR-ready mesh, or game-ready GLB.",tiers:{trellis:{toolId:"fal-trellis-3d",notes:"Trellis \u2014 image-to-3D, returns a GLB mesh URL"}},guidance:"Pass an image URL. Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{image_url:{type:"string",description:"URL of the image to convert to a 3D model."}},required:["image_url"]},upscale_image:{intro:'Upscale an image to 4\xD7 resolution via Aura SR (preserves detail without hallucination). ~$0.03. Use whenever the user shares a low-res image and asks to "upscale", "make this higher resolution", "4x this", "enhance", or to print/export at larger size.',tiers:{aura:{toolId:"fal-aura-sr",notes:"Aura SR \u2014 default; preserves detail without hallucination"}},guidance:"Pass the existing image URL. Returns an upscaled version.",inputProperties:{image_url:{type:"string",description:"URL of the image to upscale."}},required:["image_url"]},transcribe_audio:{intro:'Transcribe speech in an audio or video file (URL) to text via OpenAI Whisper. ~$0.02 per file, multilingual, handles long files. Use whenever the user asks to "transcribe this", "what does this audio say", "make subtitles", "convert this to text", or shares an audio/video URL with no other clear intent.',tiers:{whisper:{toolId:"fal-whisper",notes:"OpenAI Whisper \u2014 fast, multilingual"}},guidance:"Pass the URL. Returns the transcript text.",inputProperties:{audio_url:{type:"string",description:"URL of the audio or video file to transcribe."}},required:["audio_url"]},run_llm:{intro:"Run a text prompt through a different LLM (GPT-4o-mini, Claude Sonnet, DeepSeek R1/V3, Perplexity Sonar with web search, or Llama 70B). Token-metered, typically ~$0.01\u2013$0.10 per call. Use for: web-grounded answers (search tier), second-opinion reasoning (reasoning tier), code generation in a different family (coding tier), deep math/logic (deep_reasoning tier), or fast cheap text cleanup (fast tier). Pair with batch for multi-model councils.",tiers:{fast:{toolId:"or-gpt-4o-mini",notes:"GPT-4o Mini. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",notes:"Claude Sonnet. Strong reasoning, long-context. Warn user it is materially pricier than `fast`."},frontier_openai:{toolId:"or-gpt-55",notes:"GPT-5.5. OpenAI frontier model for complex professional reasoning."},frontier_openai_pro:{toolId:"or-gpt-55-pro",notes:"GPT-5.5 Pro. Highest-capability OpenAI frontier tier; materially more expensive."},frontier_anthropic:{toolId:"or-claude-opus",notes:"Claude Opus 4.7. Anthropic frontier model for complex tasks."},frontier_google:{toolId:"or-gemini-35-flash",notes:"Gemini 3.5 Flash. Google frontier Flash model for multimodal reasoning and coding."},deep_reasoning:{toolId:"or-deepseek-r1",notes:"DeepSeek R1. Deep chain-of-thought reasoning, mid-range pricing."},search:{toolId:"or-perplexity-sonar",notes:"Perplexity Sonar. Search-augmented, web-grounded with citations."},open_source:{toolId:"or-llama-70b",notes:"Llama 3.3 70B. Open-source large model."},coding:{toolId:"or-deepseek-chat",notes:"DeepSeek Chat V3. Strong at code generation."}},guidance:"Pick based on the user's need: fast (most questions, cheapest), reasoning (complex analysis; warn user it is materially pricier than fast), frontier_* (top-model council / highest quality; warn user these are materially pricier), search (questions about current events), coding (code generation), deep_reasoning (hard math/logic problems).",inputProperties:{prompt:{type:"string",description:"The user query."},system_prompt:{type:"string",description:"Optional system prompt to set model behavior."},max_tokens:{type:"number",description:"Maximum output tokens.",default:1024,minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature \u2014 0 is deterministic, higher is more creative.",default:.7,minimum:0,maximum:2}},required:["prompt"]}};function Dt(e,t,n){if(!Ql(e))return Qg(e,n);let r=Xl[e];if(!r)return e;let o=Object.keys(r.tiers),s=t||o[0],i=eh(e,s,n);return i||th(e,r,s,o)}function Qg(e,t){return yi({requestedTool:e,intentText:t})??e}function eh(e,t,n){return yi({requestedTool:e,metaTool:e,tier:t,intentText:n})}function th(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 Xl=Tr;function Ql(e){return e in Xl}var Er=Object.keys(Tr);function _i(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function eu(e=process.env){return _i(e)!==null}var Du=require("child_process"),ge=E(require("crypto")),je=E(require("fs")),$r=E(require("os")),Qo=E(require("path"));function vn(e,t={}){if(!e||typeof e!="object")return e;let n=e,r=t.tag??(typeof n.merchantName=="string"?n.merchantName:"media"),o=n.content?.[0]?.text,s=typeof o=="string"?En(o):null,i=Array.isArray(n.urls)?n.urls[0]:void 0,c=typeof i=="string"&&i.startsWith("data:")?En(i):null;if(!s&&!c)return e;let l=s??c,u=s?"content":"urls",d;try{d=rr(l,{tag:nh(r,n)})}catch(m){return{...n,_inline_media_warning:`Failed to persist inline media to disk: ${m instanceof Error?m.message:String(m)}`}}let f={...n,filePath:d.filePath,mime:d.mime,bytes:d.bytes};return u==="urls"?f.urls=void 0:(f.content=Array.isArray(n.content)?[...n.content]:[{}],f.content[0]={...f.content[0]??{},text:`[inline media saved to ${d.filePath}]`}),f}function nh(e,t){let n=typeof t.transactionId=="string"?t.transactionId:typeof t.transaction_id=="string"?t.transaction_id:null;return n?`${e}-${n}`:e}var tu=!1;async function Bn(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(p.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(tu)throw p.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;tu=!0,p.info("attestation:starting-browser-recovery");try{let s=await n();if(!s.success)throw p.error("attestation:browser-recovery-failed",{message:s.message}),r;let i=await No();return await e.registerAttestationKey(i),await e.setBiometricPreference({required:!0}),p.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),p.info("attestation:key-reregistered-after-recovery"),await t()}catch(s){throw p.error("attestation:recovery-failure",{error:s.message}),r}}throw r}}function ze(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}async function Uo(e,t){if(!re())return{ok:!1,code:"TOUCH_ID_UNAVAILABLE",message:"Touch ID is not available in this process. Run `visa-cli setup` from an interactive macOS terminal before enabling Touch ID."};if(!await Lo())return{ok:!1,code:"LOCAL_ATTESTATION_KEY_MISSING",message:"No local attestation key found on this device. Run `visa-cli setup` before enabling Touch ID; otherwise payments and biometric off can require a key this device cannot produce."};let n=await e.getStatus(t);return ze(n)?{ok:!0,status:n}:{ok:!1,code:"SERVER_ATTESTATION_KEY_MISSING",message:"No server attestation key is registered for this account. Run `visa-cli setup` before enabling Touch ID."}}var nu="2.7.1-rc.6";function bi(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function jo(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=So(t);return o!==void 0?{value:o,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function Te(e){return e==null?"\u2014":e?"yes":"no"}function Fo(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function rh(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function oh(){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=ei("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:Xs,source:{kind:"default"}}}async function Ar(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(L){n=L?.message||"unknown error"}let r=[],o=process.env.VISA_AUTH_URL,s=Qs("auth.serverUrl"),i=ke(),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:Te(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),t?.githubUser&&r.push({key:"account.githubUser",value:t.githubUser,formatted:t.githubUser,source:{kind:"server"}}),t?.userId&&r.push({key:"account.userId",value:t.userId,formatted:t.userId,source:{kind:"server"},hint:"Opaque stable account id used for account-scoped local credentials."});let c=t?t.attestationRequired!==!1:void 0;r.push({key:"biometric.required",value:c,formatted:Te(c),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"},hint:c===!1?"Touch ID prompts are suppressed. Re-enable with `visa-cli config biometric on`.":void 0}),r.push({key:"biometric.keyRegistered",value:t?.hasAttestationKey??null,formatted:Te(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:re(),formatted:Te(re()),source:{kind:"device"}});let l=t?.spendingControls,u=l?l.max_transaction_amount??l.maxTransactionAmount??null:null,d=l?l.daily_limit??l.dailyLimit??null:null;r.push({key:"spending.maxPerTxn",value:u,formatted:Fo(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:Fo(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:Fo(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:Fo(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(L=>L.isDefault)??t?.cards?.[0];f&&r.push({key:"cards.default",value:{brand:f.brand??null,last4:f.last4},formatted:`${f.brand||"card"} \u2022\u2022\u2022\u2022 ${f.last4}`,source:{kind:"server"}});let m=oh();r.push({key:"credit.sessionCapCents",value:m.value,formatted:rh(m.value),source:m.source});let _=Yc();_.length>0&&r.push({key:"settings.retired",value:_.map(L=>L.key),formatted:_.map(L=>L.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${_.map(L=>`visa-cli config unset ${L.key}`).join(" && ")}`});let S=jo("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:S.value,formatted:Te(S.value),source:S.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let $=jo("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:$.value,formatted:Te($.value),source:$.source});let H=Be(),U;process.env.VISA_CLI_NO_UPDATE_CHECK?U={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?U={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?U={kind:"env",var:"NODE_ENV"}:U={kind:"default"},r.push({key:"ui.updateCheck",value:!H,formatted:Te(!H),source:U});let w=jo("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:w.value,formatted:Te(w.value),source:w.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let x=jo("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:x.value,formatted:Te(x.value),source:x.source});let y=process.env.VISA_DRY_RUN,k=eu();if(r.push({key:"tools.dryRun",value:k,formatted:Te(k),source:y===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:nu,formatted:nu,source:{kind:"default"}}),e.includeDev){let L=process.env.VISA_MOCK_KEYCHAIN,Oe=bt();r.push({key:"dev.mockKeychain",value:Oe,formatted:Te(Oe),source:bi("VISA_MOCK_KEYCHAIN",!!L),hint:fs()});let Bt=process.env.VISA_MOCK_TOUCHID,xe=Tn();r.push({key:"dev.mockTouchid",value:xe,formatted:Te(xe),source:bi("VISA_MOCK_TOUCHID",!!Bt),hint:fs()});let K=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!K,formatted:Te(!!K),source:bi("VISA_CLI_DEBUG",!!K)})}return{entries:r,statusError:n}}function sh(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 ru(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}(${sh(s.source)})`),t.verbose&&s.hint&&o.push(` ${"\u21B3".padStart(n)} ${s.hint}`)}return o.join(`
125
+ `)}function ou(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 su(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 Ut=require("fs"),au=require("os"),vi=require("path"),ih=(0,vi.join)((0,au.homedir)(),".visa-mcp"),iu=(0,vi.join)(ih,"mcp-session-budget.json");function Vo(){try{(0,Ut.existsSync)(iu)&&(0,Ut.unlinkSync)(iu)}catch{}}var wi=require("crypto"),Ue=E(Rr()),Sn=null,Ee=0,Kn=0,we=0,jt=null,xi=null,ki=null,qo=Promise.resolve();function kh(e){return Number((0,Ue.fromCents)(e))}function uu(e){return(0,Ue.toCents)((0,Ue.micros)(BigInt(e)))}function lu(e){return(0,Ue.toWire)((0,Ue.fromCents)(e))}function Si(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Ho(e){return typeof e=="string"&&/^\d+$/.test(e)}var Ch=43,Th=new RegExp(`^[A-Za-z0-9_-]{${Ch}}$`);function Eh(e){return typeof e=="string"&&Th.test(e)}function Ah(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||Sn&&e.session_id!==Sn||typeof e.nonce!="string"||e.nonce.length===0||!Eh(e.server_signature)||!Si(e.cumulative)||!Si(e.remaining)||!Si(e.delta)||e.cumulative<Ee||we>0&&e.cumulative>we||we>0&&e.remaining>we||e.cumulative_micros!==void 0&&!Ho(e.cumulative_micros)||e.remaining_micros!==void 0&&!Ho(e.remaining_micros)||e.delta_micros!==void 0&&!Ho(e.delta_micros)||e.reserved_micros!==void 0&&!Ho(e.reserved_micros))}function ht(e){Sn=e,Ee=0,Kn=0,we=0,jt=null,xi=null,ki=null,qo=Promise.resolve()}function Ir(e){we=Math.max(0,Math.floor(e))}function Ci(){return Sn}function Ti(e){if(!Sn)return null;let t=Ee+Kn;return we>0&&t>we&&(t=we),{session_budget_id:Sn,cumulative_micros:kh(t),nonce:(0,wi.randomUUID)(),idempotency_key:e||(0,wi.randomUUID)()}}function Ei(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 Ah(r)?(Ee=Math.max(Ee,r.cumulative),Kn=0,jt=r,r):null}function du(){return jt}function Ai(e){let t=uu(e.cumulative_micros);Ee=Math.max(Ee,t),Kn=0;let n={status:"accepted",session_id:e.session_budget_id,cumulative:Ee,remaining:Math.max(0,we-Ee),delta:0,cumulative_micros:lu(Ee),remaining_micros:lu(Math.max(0,we-Ee)),delta_micros:"0",nonce:e.nonce};return jt=n,n}function Ri(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,Ue.toCents)((0,Ue.micros)(n));if(!Number.isFinite(r)||r<0)return;xi=t;let o=e,s=typeof o.session_id=="string"?o.session_id:Sn??"";jt?(typeof o.remaining_micros=="string"&&/^\d+$/.test(o.remaining_micros)&&(jt.remaining_micros=o.remaining_micros),typeof o.charged_micros=="string"&&/^\d+$/.test(o.charged_micros)&&(jt.delta_micros=o.charged_micros)):jt={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 mu(e){let t=e.receipt??null;ki={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:uu(e.voucher.cumulative_micros),estimatedCumulativeCents:Bo(),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 pu(){return ki}function fu(){return Ee}function gu(){return xi}function Bo(){let e=Ee+Kn;return we>0&&e>we&&(e=we),e}function hu(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return qo=qo.then(()=>{Kn+=t}),qo}var Rh=10,Ih=1,Q=null,yu=Promise.resolve();function Ii(e){let t=yu.catch(()=>{}).then(e);return yu=t.then(()=>{},()=>{}),t}var _e=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 $i(e,t,n){return Ii(()=>_u(e,t,n))}async function _u(e,t,n){if(Vo(),Q&&new Date(Q.expiresAt).getTime()>Date.now())return Ci()!==Q.budgetId&&(ht(Q.budgetId),Ir(Q.totalCents)),p.info("mcp-session:active-hit",{budgetId:Q.budgetId,tool:n.toolName,remainingEstimatedCents:Q.totalCents-Bo()}),{budgetId:Q.budgetId,isFresh:!1,totalCents:Q.totalCents,requestedCapCents:Q.totalCents,appliedCapCents:Q.totalCents,clampedReason:null};Q&&(Q=null,ht(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"?Ih:Rh,i=Math.max(s,Math.ceil(n.minRequiredCents??s));if(r.balanceCents<i)throw new _e(r.balanceCents,i);let a=n.capCentsOverride??Qc(),c=Math.min(a,r.balanceCents),l=c<a?"balance":null,u=await t("session_create",c,"Visa CLI Session",`open credit-model session with $${(c/100).toFixed(2)} cap`,n.userContext),d=await e.createSessionBudget({total_cents:c,session_kind:o,...u?{attestation:u}:{}});if(!d.success||!d.budget){let m=d.error||"unknown error";throw new Error(`Failed to open credit session: ${m}`)}let f={budgetId:d.budget.id,expiresAt:d.budget.expiresAt,totalCents:d.budget.totalCents,createdAt:d.budget.createdAt};return Q=f,ht(f.budgetId),Ir(f.totalCents),p.info("mcp-session:opened",{budgetId:f.budgetId,capCents:f.totalCents,requestedCapCents:a,clampedReason:l,sessionKind:o,expiresAt:f.expiresAt,tool:n.toolName}),{budgetId:f.budgetId,isFresh:!0,totalCents:f.totalCents,requestedCapCents:a,appliedCapCents:f.totalCents,clampedReason:l}}async function bu(e,t,n){return Ii(async()=>{let o=Ft()?await vu(e):null,s=await _u(e,t,n);return{budgetId:s.budgetId,totalCents:s.totalCents,closedPrevious:o,requestedCapCents:s.requestedCapCents,appliedCapCents:s.appliedCapCents,clampedReason:s.clampedReason}})}async function vu(e){let n=Ft()?.budgetId??Ci(),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){p.warn("mcp-session:close-server-failed",{budgetId:n,error:i?.message||String(i)})}return Vo(),Q=null,ht(null),{closedServerSide:r,budgetId:n,finalCumulativeCents:o,finalCumulativeMicros:s}}async function Ko(e){return Ii(()=>vu(e))}function Ft(){return Vo(),Q?new Date(Q.expiresAt).getTime()<=Date.now()?(Q=null,ht(null),null):{budgetId:Q.budgetId,totalCents:Q.totalCents,lastReceiptCumulative:fu(),lastReceiptCumulativeMicros:du()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:gu(),estimatedCumulative:Bo(),lastToolSpend:pu(),expiresAt:Q.expiresAt}:null}var wu=E(Rr()),Su=10000n;function $h(e){return e<=0n?0:Number((e+Su-1n)/Su)}function xu(e){return $h((0,wu.fromUsd)(e))}var Go=E(Rr()),Ph=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;function Wo(e){if(typeof e!="string"||!Ph.test(e))return{ok:!1,error:"amount must be a USD amount with at most two decimal places"};let[t,n=""]=e.split("."),r=BigInt(t)*100n+BigInt(n.padEnd(2,"0"));if(r>BigInt(Number.MAX_SAFE_INTEGER))return{ok:!1,error:"amount is too large"};let o=Number(r);return o<=0?{ok:!1,error:"amount must be greater than $0.00"}:{ok:!0,cents:o,displayUsd:(0,Go.toDisplay)((0,Go.fromCents)(o),{symbol:""})}}var zo="Buying credits requires local biometric attestation from a Touch ID-capable Mac or a Windows Hello-capable PC running the Visa CLI. This device cannot create the required attestation, so no card charge was attempted. Credits are account-level, so you can top up this account from any interactive biometric-capable CLI, then use the balance from this remote server.",ku="Tell the user that buying credits requires a local CLI/MCP process with Touch ID (Mac) or Windows Hello (PC) today. Credits are account-level: suggest topping up the same account from any interactive biometric-capable CLI, then continuing on this remote server. Do not retry buy_credits from this process; it cannot produce the required card-charge attestation.";var Cu=Promise.resolve(),Tu=!1;function es(e){let t=Cu.catch(()=>{}).then(e);return Cu=t.then(()=>{},()=>{}),t}async function Uu(e){let t=await ue(()=>$i(P,Qe,{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 Fh(),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;p.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 On){if(p.warn("mcp-session:server-invalidated-budget",{code:u.code,budgetId:u.budgetId??t.budgetId,tool:e.toolId}),await Ko(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 Tu||(Tu=!0,console.error(`[visa-cli] Your session was closed by another process; reopened automatically as pay-as-you-go.
126
+ To require an explicit session approval instead, set VISA_REQUIRE_EXPLICIT_SESSION=true.`)),p.info("mcp-session:falling-back-to-payg",{code:u.code,tool:e.toolId}),ju(e)}throw u instanceof Qt?(p.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=Ei(s)??(n?Ai(n):null);if(Ri(o?.receipt_v2),await hu(e.estimatedAmountCents),mu({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),Vu(o))return vn(o);let c=await Fu();if(e.idempotencyKey&&Hu(o,c,e.idempotencyKey))return vn(o);let l=c?Zo(c):null;return vn(qu(o,r,l))}function Ye(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function Mi(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(Mi).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${Mi(r)}`).join(",")}}`}function Oh(e,t,n,r){let o=ge.createHash("sha256").update(`${n}:${Mi(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${o}`}function Mh(e,t){return`${e}:${t}`}function Nh(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 Eu(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,o=Je(r),s=o!==null?o.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=Nh(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),c=i!=null?String(i):a;return{batch_id:e,item_id:Mh(e,t),index:t,...c!==void 0?{transaction_id:c}:{},...a!==void 0?{ledger_id:a}:{},...s?{amountMicros:s,amount_micros:s,cost_micros:s}:{}}}async function ju(e){return ue(()=>Lh(e))}async function Lh(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 _e(n.balanceCents,t);let r=t,o=Zo(n),s=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(r/100).toFixed(2)})`,i=await Qe("session_create",r,"Visa CLI Session",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 c=a.budget.id;ht(c),Ir(a.budget.totalCents),p.info("on-demand-session:opened",{budgetId:c,capCents:a.budget.totalCents,tool:e.toolId});try{let l=Ti(e.idempotencyKey);if(!l)throw new Error(`Internal: mintVoucher returned null after on-demand session-open ${c}`);let{data:u,voucherReceiptHeader:d}=await P.shortcutWithSession(e.toolId,l,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(Ei(d)||Ai(l),Ri(u?.receipt_v2),Vu(u))return vn(u);let f=await Fu();if(e.idempotencyKey&&Hu(u,f,e.idempotencyKey))return vn(u);let m=f?Zo(f):null;return vn(qu(u,o,m))}finally{try{await P.closeSession(c)}catch(l){p.warn("on-demand-session:close-failed",{budgetId:c,error:l?.message||String(l)})}ht(null),p.info("on-demand-session:closed",{budgetId:c,tool:e.toolId})}}async function Ht(e){return es(async()=>Ft()?Uu(e):ju(e))}function ts(){return ke()}var P=new Ce(()=>F.getSessionToken());function Je(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function Zo(e){return Je(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function Dh(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 Uh(e){let t=Je(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=Je(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=Je(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function Jo(e,t="INVALID_TOOL_PARAMS"){return{success:!1,error_code:t,code:t,error:e,message:e}}function jh(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 Fh(){try{let e=await P.getBalance();return e.success?Zo(e):null}catch{return null}}async function Fu(){try{let e=await P.getBalance();return e.success?e:null}catch{return null}}function Vu(e){if(!e||e.success===!1)return!1;let t=Je(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=Je(e.amountMicros??e.amount_micros??e.charged_micros),r=t??n;if(r===null||r<=0n)return!1;let o=r.toString();return e.amountMicros??=o,e.amount_micros??=o,e.charged_micros??=o,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),!0}function Hu(e,t,n){if(!e||e.success===!1||!t||!Array.isArray(t.ledger))return!1;let r=t.ledger.find(a=>a.idempotencyKey===n);if(!r)return!1;let o=Je(r.deltaMicros)??BigInt(r.deltaCents)*10000n,s=o<0n?-o:o;if(s<=0n)return!1;let i=s.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(s)/1e6),!0}function qu(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 Vh="2.7.1-rc.6",Xw=["","","You're ready to go! Try:","","Core:",'\u2022 "Show my account status" \u2192 get_status','\u2022 "List my enrolled cards" \u2192 get_cards','\u2022 "Show my paid tool use history" \u2192 transaction_history','\u2022 "Set my daily top-up limit to $50" \u2192 update_spending_controls','\u2022 "Generate 3 variations in parallel" \u2192 batch',"","Category tools:",'\u2022 "Generate an image of a sunset over Tokyo" \u2192 generate_image','\u2022 "Make a 4-second video of a penguin juggling" \u2192 generate_video','\u2022 "Make a song about coding late at night" \u2192 generate_music','\u2022 "Create a sound effect for a checkout chime" \u2192 generate_audio','\u2022 "Create a 3D asset from this product sketch" \u2192 generate_3d','\u2022 "Upscale this product image" \u2192 upscale_image','\u2022 "Transcribe this meeting recording" \u2192 transcribe_audio','\u2022 "Run a reasoning model on this prompt" \u2192 run_llm',"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
127
+ `);function Ze(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=ar(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(Zc())return{opened:!1,url:t,blockedReason:"suppressed"};let n=Es();if(n.headless)return p.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let r=Va(t,ts());if(!r)return p.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let o=qa(r);return o?((0,Du.execFile)(o.cmd,o.args,s=>{s&&p.warn(`Browser open failed: ${s.message}. URL: ${r}`)}),{opened:!0,url:r}):(p.info(`No browser command for platform "${$r.platform()}". URL: ${r}`),{opened:!1,url:r,blockedReason:"unsupported_platform"})}async function ue(e){return Bn(P,e,Zu)}var Bu="get_cards",Ku="set_default_card";function Hh(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 '${Bu}' to see enrolled cards and '${Ku}' to switch, then retry the original request.`}function qh(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 '${Bu}' to see enrolled cards and '${Ku}' to switch. Do not retry automatically.`}function Xe(e,t){let n=e.retryable?Hh(e.code,e.retryAfter):qh(e.code,t.merchantName);return{success:!1,declined:!0,retryable:e.retryable,code:e.code,reason:e.reason,payment_error_class:e.paymentErrorClass,correlation_id:e.correlationId,transactionId:e.transactionId,retryAfter:e.retryAfter,merchantName:t.merchantName,amount:t.amount,message:e.message,agent_guidance:n}}function Bh(e){return{success:!1,error:e.message,error_code:e.code,transactionId:e.transactionId,reconciliation_required:e.reconciliationRequired,retryable:e.retryable,agent_guidance:"The top-up charge outcome is ambiguous. Tell the user not to retry with a new idempotency key or start another top-up. They should check transaction_history in a few minutes or contact support with the transactionId."}}var Gn=null,Kh=3e4;function Gu(){Gn=null}var Vt=class extends Error{constructor(n){super(`${Xo()} attestation is required for this action, but it is not available in this MCP process. `+Ni());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function ns(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. `+Ni()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function Gh(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:zo,agent_guidance:ku}}function Xo(){return process.platform==="darwin"?"Touch ID":"local biometric"}function Ni(){return process.platform==="darwin"?"Run the action from an interactive terminal with Touch ID access, or use reset with confirm:true to clear stale server biometric state through GitHub re-authentication.":"This platform cannot create Visa CLI Touch ID attestations. Use reset with confirm:true to clear stale server biometric state through GitHub re-authentication."}async function Wh(e){let t=Date.now();if(Gn&&Gn.expiresAt>t)return{required:Gn.required,hasRegisteredKey:Gn.hasRegisteredKey};try{let n=await P.getStatus(e),r=n.attestationRequired!==!1,o=ze(n);return Gn={required:r,hasRegisteredKey:o,expiresAt:t+Kh},{required:r,hasRegisteredKey:o}}catch{return{required:!0,hasRegisteredKey:!0}}}async function Qe(e,t,n,r,o,s){if(!s?.forceRequired){let i=await Wh(o);if(!i.required){p.info("attestation:skipped-by-server-policy",{context:e});return}if(!i.hasRegisteredKey){p.info("attestation:skipped-no-registered-key",{context:e});return}}if(!re())throw p.warn("attestation:unavailable",{context:e}),new Vt(e);p.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");p.info("touchid:prompt",{context:e,amount:t,merchant:n});let c=await bn(a,r);return p.info("attestation:success",{context:e,amount:t,merchant:n}),{signature:c,nonce:i,amount:t,merchant:n}}catch(i){throw p.error("attestation:failure",{context:e,amount:t,merchant:n,error:i.message}),i}}var Au="[dry-run] https://placeholder.visa-cli.dev/image.png",zh=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"]),Jh=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 Yh(e,t){return t==="run_llm"||e.startsWith("or-")?"llm":t==="generate_image"||zh.has(e)?"image":t==="generate_video"||Jh.has(e)?"video":null}function Zh(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function Xh(e){return e==="llm"?"OpenRouter":"fal.ai"}function Wn(e,t,n,r){let o={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:Xh(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${Zh(n)}`;return{...o,content:i,data:{content:i,model:t,dry_run:!0}}}return{...o,urls:[Au],data:{[e==="video"?"videoUrl":"imageUrl"]:Au,metadata:{dry_run:!0}}}}async function Pi(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:ge.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){p.warn("dry_run:telemetry_failed",{tool:e.toolName,error:o?.message||String(o),mode:t})}}var Qh="https://openrouter.ai/api/v1/chat/completions",ey="openrouter/free",ty=50,ny=15e3;function ry(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 oy(e,t,n){let r=process.env.OPENROUTER_API_KEY;if(!r)return p.warn("preflight:no_openrouter_key_falling_back_to_mock",{tool:e}),{result:Wn("llm",e,t,n),degraded:!0,resolvedModel:null};let o=ry(t),s;try{s=await Zt(Qh,{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:ey,messages:[{role:"user",content:o}],max_tokens:ty}),timeoutMs:ny})}catch(u){return p.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:Wn("llm",e,t,n),degraded:!0,resolvedModel:null}}if(!s.ok){let u=await s.text().catch(()=>"");return p.warn("preflight:openrouter_http_error_falling_back_to_mock",{tool:e,status:s.status,bodyExcerpt:u.slice(0,200)}),{result:Wn("llm",e,t,n),degraded:!0,resolvedModel:null}}let i;try{i=await s.json()}catch(u){return p.warn("preflight:openrouter_invalid_json_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:Wn("llm",e,t,n),degraded:!0,resolvedModel:null}}let a=typeof i?.choices?.[0]?.message?.content=="string"?i.choices[0].message.content:"",c=typeof i?.model=="string"?i.model:null;return{result:{success:!0,transactionId:`preflight:${n??e}`,amount:0,rail:"preflight",merchantName:"OpenRouter",dry_run:!0,preflight:!0,metadata:{dry_run:!0,preflight:!0,model_used:c},content:a,data:{content:a,model:c??e,dry_run:!0,preflight:!0}},degraded:!1,resolvedModel:c}}async function rs(e,t,n,r){let o=_i();if(!o)return null;let s=Yh(e,r);if(!s)return null;let i=Date.now();if(o==="mock"){let l=Wn(s,e,t,r);return await Pi({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:l,userContext:n,startedAt:i,mode:"mock"}),p.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:s,mode:o}),l}if(s!=="llm"){p.warn("preflight:not_supported_for_kind_falling_back_to_mock",{tool:e,kind:s});let l=Wn(s,e,t,r);return await Pi({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:l,userContext:n,startedAt:i,mode:"preflight"}),l}let{result:a,resolvedModel:c}=await oy(e,t,r);return await Pi({toolName:r??e,resolvedModel:c??(r&&r!==e?e:null),toolParams:t,result:a,userContext:n,startedAt:i,mode:"preflight"}),p.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:s,mode:o}),a}async function yt(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 _t(e){return xu(e.amount)}function sy(){return Qo.join($r.homedir(),".visa-mcp","allium-results")}var Qw=16*1024,e0=50*1024*1024;function iy(){let e=sy();try{if(!je.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=je.readdirSync(e),n=0,r=0;for(let o of t)try{let s=je.statSync(Qo.join(e,o));s.isFile()&&(n+=s.size,r++)}catch{}return{file_count:r,size_bytes:n,path:e}}catch(t){return p.warn("allium:disk_usage_error",{error:t.message}),{file_count:0,size_bytes:0,path:e}}}var Ru=3600*1e3,Oi=0;function ay(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function Pr(e){if(!Xc()&&!(Date.now()<Oi))try{if(!await F.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}}),p.info("feed:submitted",{tool:e.tool,mediaType:e.mediaType,transactionId:e.transactionId})}catch(t){if(ay(t)){let n=Oi===0;Oi=Date.now()+Ru,n&&p.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:Ru});return}p.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function cy(e,t){let n=(e.state||"").trim().toUpperCase(),r=(e.county||"").trim(),o=(e.start_date||"").trim(),s=(e.end_date||o).trim();if(!/^[A-Z]{2}$/.test(n))throw new Error('state must be a 2-letter US state code (e.g. "VA").');if(!r)throw new Error("county is required.");if(!/^\d{4}-\d{2}$/.test(o))throw new Error('start_date must be YYYY-MM (e.g. "2025-08").');if(s&&!/^\d{4}-\d{2}$/.test(s))throw new Error("end_date must be YYYY-MM.");let i="Visa SMI",a=.1,c=`Pay $0.10 to ${i} for SMI data (${n} / ${r})`;p.info("payment:attempt",{tool:"get_visa_smi",amount:a,merchant:i});try{return await ue(async()=>{let l=await Qe("get_visa_smi",a,i,c),u=await P.getVisaSmi({state:n,county:r,start_date:o,end_date:s,attestation:l,idempotencyKey:ge.randomUUID()},t);return u.success?p.info("payment:success",{tool:"get_visa_smi",merchant:i,charged_cents:u.charged_cents}):p.warn("payment:declined",{tool:"get_visa_smi",merchant:i,message:u.error}),u})}catch(l){if(l instanceof me)return p.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:l.code,retryable:l.retryable}),Xe(l,{amount:a,merchantName:i,description:"Visa SMI data"});throw p.error("payment:failure",{tool:"get_visa_smi",merchant:i,error:l.message}),l}}async function ly(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 rs("generate_image_card",e,t);if(n)return n;let r=await yt("generate_image_card",void 0,t),o=ge.randomUUID();p.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await ue(async()=>{let s;try{s=await Ht({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:_t(r),userContext:t,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof _e)return Ye(i);throw i}return p.info("payment:success",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Ze(i)),Pr({prompt:e.prompt,tool:"generate_image_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):p.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof me)return p.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Xe(s,r);throw p.error("payment:failure",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function uy(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 rs("generate_image_fast_card",e,t);if(n)return n;let r=await yt("generate_image_fast_card",void 0,t),o=ge.randomUUID();p.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await ue(async()=>{let s;try{s=await Ht({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:_t(r),userContext:t,timeoutMs:6e4,idempotencyKey:o})}catch(i){if(i instanceof _e)return Ye(i);throw i}return p.info("payment:success",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Ze(i)),Pr({prompt:e.prompt,tool:"generate_image_fast_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):p.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof me)return p.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Xe(s,r);throw p.error("payment:failure",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function dy(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 rs("generate_video_tempo_card",e,t);if(n)return n;let r=await yt("generate_video_tempo_card",void 0,t),o=ge.randomUUID();p.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await ue(async()=>{let s;try{s=await Ht({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:_t(r),userContext:t,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof _e)return Ye(i);throw i}return p.info("payment:success",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Ze(i)),Pr({prompt:e.prompt,tool:"generate_video_tempo_card",mediaUrl:s.urls[0],mediaType:"video",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):p.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof me)return p.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Xe(s,r);throw p.error("payment:failure",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function my(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 yt("generate_music_tempo_card",void 0,t),r=ge.randomUUID();p.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await ue(async()=>{let o;try{o=await Ht({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:_t(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(s){if(s instanceof _e)return Ye(s);throw s}return p.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=>Ze(s)),Pr({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,p.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):p.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof me)return p.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Xe(o,n);throw p.error("payment:failure",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}async function py(e,t){let n=await yt("check_music_status_tempo_card",void 0,t),r=ge.randomUUID();p.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await ue(async()=>{let o;try{o=await Ht({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:_t(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof _e)return Ye(s);throw s}return p.info("payment:success",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),o.urls?.length&&o.urls.forEach(s=>Ze(s)),o})}catch(o){if(o instanceof me)return p.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Xe(o,n);throw p.error("payment:failure",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}async function fy(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 yt("query_onchain_prices",void 0,t),r=ge.randomUUID();p.info("payment:attempt",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName});try{return await ue(async()=>{let o;try{o=await Ht({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:_t(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof _e)return Ye(s);throw s}if(p.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 me)return p.warn("payment:declined",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Xe(o,n);throw p.error("payment:failure",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}var gy=["generate_music_tempo_card"],Iu=10,$u=5,Pu=new Map;function Ou(e){let t=Pu.get(e);if(t!==void 0)return t;let r=kr(e)?.isAsync===!0||gy.includes(e);return Pu.set(e,r),r}var hy=36e4,yy=18e4,_y=15e3,by=12e4,vy=2e3;function Mu(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}async function Sy(e,t){let n;if(e.requests?.some(y=>y.tool||y.tool_id)&&e.requests)n=e.requests.map(y=>{let k=y.tool||y.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 L=Dt(k,y.tier||e.tier,y.prompt??t),{tool:Oe,tool_id:Bt,tier:xe,params:K,...se}=y,Vr=K&&typeof K=="object"?{...K,...se}:se;return{resolvedTool:L,params:Vr}});else if(e.tool){let y=Dt(e.tool,e.tier,e.params?.prompt??t);n=(e.requests||(e.count&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(L=>({resolvedTool:y,params:L}))}else return Mu("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return Mu("BATCH_EMPTY","Batch requires at least one item.");if(n.length>Iu)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${Iu} items. Please split into smaller batches.`};if([...new Set(n.map(y=>y.resolvedTool))].some(Ou)&&n.length>$u)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${$u} items. Please use multiple batches for more.`};let i=[...new Set(n.map(y=>y.resolvedTool))],a=i.length===1,c={};for(let y of i)c[y]=await Xu(y);let l=new Set(i.filter(y=>c[y]&&Qu(c[y]))),u={};for(let y of i)l.has(y)||(u[y]=await yt(y,void 0,t));let d=0;for(let y of n)d+=u[y.resolvedTool]?.amount??0;let f=[...new Set([...Object.values(u).map(y=>y.merchantName),...i.filter(y=>l.has(y)).map(y=>c[y]?.name??y)])].join(", "),m=a?i[0]:"mixed";p.info("payment:attempt",{tool:"batch",batchTool:m,count:n.length,totalAmount:d,merchant:f,heterogeneous:!a});let _=n.some(y=>Ou(y.resolvedTool)),S=n.some(y=>y.resolvedTool.startsWith("or-")||y.resolvedTool==="run_llm"||y.resolvedTool==="execute_tool"),$=_?hy:S?yy+n.length*_y:by+n.length*vy,H=ge.randomUUID(),U=[],w=0,x=0n;return es(async()=>{let y=!Ft();if(y&&d>0)try{let k=Math.max(1,Math.ceil(d*100));await ue(()=>$i(P,Qe,{toolName:"batch",userContext:t,sessionKind:"one_shot",minRequiredCents:k,capCentsOverride:k}))}catch(k){return k instanceof _e?Ye(k):(p.warn("payment:batch-prewarm-failed",{batchTool:m,count:n.length,error:k?.message||String(k)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:k?.message||"Failed to authenticate batch session",tool:m,count:n.length,failedCount:n.length,results:[]})}try{for(let K=0;K<n.length;K+=1){let se=n[K],Vr=u[se.resolvedTool];try{let Z=l.has(se.resolvedTool)?await P.shortcut(se.resolvedTool,se.params,$,t,"batch"):await Uu({toolId:se.resolvedTool,toolParams:se.params,estimatedAmountCents:_t(Vr),userContext:t,metaTool:"batch",timeoutMs:$,idempotencyKey:Oh(H,K,se.resolvedTool,se.params)});if(l.has(se.resolvedTool)&&Z&&typeof Z=="object"&&!Array.isArray(Z)&&Z.merchantName==null&&(Z.merchantName=c[se.resolvedTool]?.name??se.resolvedTool),U.push({success:Z?.success!==!1,tool:se.resolvedTool,...Z,...Eu(H,K,Z)}),Z?.success!==!1){let er=Je(Z?.amountMicros??Z?.amount_micros),ga=typeof Z?.amount=="number"?Z.amount:Vr?.amount??0;er!==null&&er>0n?x+=er:x+=BigInt(Math.round(ga*1e6)),w+=ga}Z?.urls&&Z.urls.forEach(er=>Ze(er))}catch(Z){if(Z instanceof _e&&U.length===0)return Ye(Z);p.warn("payment:batch-item-failed",{tool:se.resolvedTool,index:K,error:Z?.message||String(Z)}),U.push({success:!1,tool:se.resolvedTool,...Eu(H,K),error:Z?.message||String(Z)})}}let k=U.filter(K=>K?.success===!1).length,L=U.length-k,Oe=U.flatMap(K=>Array.isArray(K?.urls)?K.urls:[]),Bt=x>0n?Number(x)/1e6:Math.round((w+Number.EPSILON)*100)/100,xe=L===0?"failure":k===0?"success":"partial";return p.info("payment:success",{tool:"batch",batchTool:m,count:n.length,totalAmount:d,totalCharged:Bt,merchant:f,successCount:L,failedCount:k,outcome:xe,mode:"session",batchId:H}),{success:L>0,outcome:xe,batch_id:H,tool:a?i[0]:m,count:n.length,successCount:L,failedCount:k,totalCharged:Bt,...x>0n?{totalChargedMicros:x.toString(),amountMicros:x.toString(),amount_micros:x.toString()}:{},merchantName:f,results:U,...Oe.length?{urls:Oe}:{}}}catch(k){if(k instanceof me)return p.warn("payment:declined",{tool:"batch",batchTool:m,count:n.length,totalAmount:d,merchant:f,code:k.code,retryable:k.retryable}),Xe(k,{amount:d,merchantName:f});throw p.error("payment:failure",{tool:"batch",batchTool:m,count:n.length,totalAmount:d,merchant:f,error:k.message}),k}finally{if(y){let k=await Ko(P);p.info("batch-session:closed",{budgetId:k.budgetId,closedServerSide:k.closedServerSide})}}})}function wy(){let e=!1,t;try{let r=Qo.join($r.homedir(),".claude","settings.json");if(je.existsSync(r)){let o=JSON.parse(je.readFileSync(r,"utf-8")),s=typeof o.statusLine=="object"?o.statusLine.command:"";e=Et(s)}}catch{}let n=so();return n||(t="visa-cli config hud enable"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function xy(e){let[t,n]=await Promise.all([P.getStatus(e),P.getBalance().catch(s=>(p.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=iy();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=wy(),!t.hud.statusLine&&!t.hud.shellHud&&(t._hud_nudge="The user has no HUD surfaces enabled. Mention once, naturally, that they can enable a live spend dashboard with `visa-cli config hud enable` \u2014 it shows balance, active tools, and spend on every prompt."),t.version=Vh,Array.isArray(t.cards)&&(t.cards=t.cards.map(s=>({...s,displayName:Li(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=Ft();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 Li(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 Wu(e,t){try{let r=((await P.getStatus(t)).cards||[]).find(o=>o?.id===e);if(r)return Li(r)}catch(n){p.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function ky(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:Li(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 Cy(e,t){return await P.getTransactions({limit:e.limit,offset:e.offset},t)}async function Ty(e,t){return await P.feedback(e.message,e.transaction_id,t)}async function Ey(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return wn("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=Wo(String(e.amount));if(n.ok===!1)return{success:!1,error:n.error};let r=n.cents,o=r/100,s=ge.randomUUID();p.info("buy_credits:attempt",{amountCents:r});try{return await ue(async()=>{let i=await Qe("balance-topup",o,"Visa CLI Balance",`top up balance with $${n.displayUsd}`,t,{forceRequired:!0}),a=await P.topupBalance({amount_cents:r,idempotency_key:s,attestation:i});if(a.success){p.info("buy_credits:success",{amountCents:r,balanceCents:a.balanceCents});let c=((a.balanceCents??0)/100).toFixed(2),l=(r/100).toFixed(2);return{...a,amount:r/100,amountMicros:String(r*1e4),merchantName:"Visa CLI Balance",message:`Added $${l} \u2014 balance is now $${c}`}}return p.warn("buy_credits:failed",{amountCents:r,error:a.error}),a})}catch(i){if(i instanceof Vt)return Gh();if(i instanceof at)return p.warn("buy_credits:ambiguous",{amountCents:r,code:i.code,transactionId:i.transactionId}),Bh(i);throw p.error("buy_credits:failure",{amountCents:r,error:i.message}),i}}function wn(e,t){return{success:!1,error:t,code:e,message:t}}async function Ay(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return wn("MISSING_CONFIRMATION","Please confirm by setting confirm: true to update spending controls.");if(e.maxTransactionAmount!==void 0&&(typeof e.maxTransactionAmount!="number"||!Number.isFinite(e.maxTransactionAmount)||e.maxTransactionAmount<.01))return wn("INVALID_VALUE","maxTransactionAmount must be at least $0.01");if(e.dailyLimit!==void 0&&(typeof e.dailyLimit!="number"||!Number.isFinite(e.dailyLimit)||e.dailyLimit<1))return wn("INVALID_VALUE","dailyLimit must be at least $1");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return wn("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");p.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await ue(async()=>{let n=await Qe("spending-controls",0,"","update spending controls"),r=await P.updateSpendingControls({maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit,confirm:!0,attestation:n},t);return p.info("spending_controls:success",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit}),r})}catch(n){if(p.error("spending_controls:failure",{error:n.message}),n instanceof Vt)return ns(n,"update_spending_controls");if(String(n?.message||n).includes("Attestation required"))return wn("ATTESTATION_REQUIRED","Changing spending controls requires local attestation, even when payment biometric prompts are disabled.");throw n}}async function Ry(e){let t=await Ar({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 Iy(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."};p.info("config:set",{key:e.key});try{let t=wo(e.key,e.value);return p.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 ct?"UNKNOWN_KEY":t instanceof lt?"SERVER_CONTROLLED":t instanceof At?"RETIRED_KEY":"INVALID_VALUE";return p.warn("config:set:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(It).sort()}}}async function $y(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."};p.info("config:unset",{key:e.key});try{let t=xo(e.key);return p.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 ct?"UNKNOWN_KEY":t instanceof lt?"SERVER_CONTROLLED":t instanceof At?"RETIRED_KEY":"INVALID_VALUE";return p.warn("config:unset:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(It).sort()}}}async function Py(e){let t=await P.getStatus(e),n=t.attestationRequired!==!1,r=ze(t),o=re(),s=n?r?o?`${Xo()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${Xo()} is not available in this process. ${Ni()}`:"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 Oy(e){p.info("biometric:on");let t=await Uo(P,e);if(t.ok===!1)return{success:!1,error:t.code,error_code:t.code,message:t.message,agent_guidance:`${t.message} Do not call biometric_on again until the user has completed setup in an interactive terminal.`};let n=await P.setBiometricPreference({required:!0},e);return n.success?(Gu(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:n.error||"unknown error"}}async function My(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return wn("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.");p.info("biometric:off");try{return await ue(async()=>{let n=await P.getStatus(t),r;if(ze(n)&&(r=await Qe("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${Xo()} 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 Gu(),{success:!0,required:!1,message:"Touch ID is no longer required for payments."}})}catch(n){if(p.error("biometric:off:failure",{error:n.message}),n instanceof Vt)return ns(n,"biometric_off");throw n}}var Nu=3e4,Ny=3e5;async function zu(e,t,n="login"){let r=ge.randomUUID(),o=`${e}${e.includes("?")?"&":"?"}state=${r}`,s=Ze(o);return!s.opened&&s.blockedReason!=="non_internal_host"&&s.blockedReason!=="invalid_url"?Ju(o,s,n):s.opened?{...await Yu(r,t,n),browserUrl:o}:{success:!1,browserUrl:o,message:`Could not open the browser URL safely. Please check the configured auth server and try again. URL: ${o}`}}function Ju(e,t,n){let r=n==="enrollment"?"card enrollment":n==="attestation-recovery"?"biometric reset":"login",o=t.blockedReason==="suppressed"?"browser auto-open is suppressed":t.blockedReason==="headless"?"this process appears to be headless":t.blockedReason==="unsupported_platform"?"this platform has no configured browser opener":"browser auto-open is unavailable";return{success:!1,requiresBrowser:!0,browserUrl:e,message:`Browser auto-open was skipped because ${o}. Open this URL to continue ${r}: ${e}`}}async function Yu(e,t,n="login"){let r=Date.now()+Ny;for(;Date.now()<r;)try{let s=await fetch(`${ts()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:Nu,...t&&{user_context:t}}),signal:AbortSignal.timeout(Nu+5e3)});if(!s.ok){await kt(s,a=>{p.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 p.info("auth:attestation_recovery_complete",{user:i.user||""}),{success:!0,message:"Server-side biometric state cleared. Run visa-cli setup to register a fresh key before reenabling Touch ID."};let a=i.welcomeBonusCents??0,c=su(a);if(n!=="enrollment"&&i.sessionToken){await F.saveSessionToken(i.sessionToken);let u=i.user||"",d=i.last4||"****";return p.info("auth:login_complete",{user:u,last4:d,bonusCents:a}),{success:!0,message:`Signed in as ${u}. Card ending in ${d} enrolled and ready for payments.`,...c||{}}}let l=i.last4||"****";return p.info("auth:card_added",{last4:l,bonusCents:a}),{success:!0,message:`Card ending in ${l} enrolled and ready for payments.`,...c||{}}}}catch{await kt(void 0,s=>{p.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 Zu(e){let t=ge.randomUUID(),n;try{n=await P.startAttestationRecovery(t,e)}catch(s){return{success:!1,message:`Could not start biometric reset: ${s?.message||"unknown error"}`}}if(!n.success||!n.recoveryUrl)return{success:!1,message:n.error||"Could not start biometric reset. Please try again."};let r=Ze(n.recoveryUrl);return!r.opened&&r.blockedReason!=="non_internal_host"&&r.blockedReason!=="invalid_url"?Ju(n.recoveryUrl,r,"attestation-recovery"):r.opened?{...await Yu(t,e,"attestation-recovery"),browserUrl:n.recoveryUrl}:{success:!1,browserUrl:n.recoveryUrl,message:`Could not open the browser URL safely. Please check the configured auth server and try again. URL: ${n.recoveryUrl}`}}async function Ly(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."};p.info("cards:remove_attempt",{cardId:n});let r=`remove-card:${n}`,o=`remove ${await Wu(n,t)}`;try{return await ue(async()=>{let s=await Qe(r,0,"",o,t,{forceRequired:!0}),i=await P.removeCard(n,{attestation:s},t);return p.info("cards:remove_success",{cardId:n,promotedId:i?.promotedId??null}),i})}catch(s){if(p.error("cards:remove_failure",{cardId:n,error:s.message}),s instanceof Vt)return ns(s,"remove_card");throw s}}async function Dy(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."};p.info("cards:set_default_attempt",{cardId:n});let r=`set-default-card:${n}`,o=`set ${await Wu(n,t)} as default`;try{return await ue(async()=>{let s=await Qe(r,0,"",o,t,{forceRequired:!0}),i=await P.setDefaultCard(n,{attestation:s},t);return p.info("cards:set_default_success",{cardId:n}),i})}catch(s){if(p.error("cards:set_default_failure",{cardId:n,error:s.message}),s instanceof Vt)return ns(s,"set_default_card");throw s}}async function Uy(e){return p.info("auth:login_attempt"),zu(`${ts()}/login`,e)}function jy(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 Fy(e={},t){let n;try{n=jy(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return es(async()=>{let r=await ue(()=>bu(P,Qe,{toolName:"start_session",userContext:t,capCentsOverride:n}));p.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 Vy(){let e=Ft();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 Hy(){return es(async()=>{let e=Ft();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 Ko(P);p.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=Uh(e),r=Je(t.finalCumulativeMicros),o=r??(typeof t.finalCumulativeCents=="number"?BigInt(Math.max(0,t.finalCumulativeCents))*10000n:n.micros),s=Number(o/10000n);return p.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 ${Dh(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 qy(e){if(p.info("auth:add_card_attempt"),!await F.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 zu(`${ts()}/enroll-card?code=${encodeURIComponent(n)}`,e,"enrollment")}async function By(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};p.info("reset:attempt");let n=!1;try{let r=await P.getStatus(t);if(r&&ze(r)){let o=await Zu(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}`};p.warn("reset:server_attestation_status_unavailable",{error:o})}try{await P.logout(void 0,t)}catch{}if(await F.clearAll(),re())try{await Do()}catch{}return p.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 Ky(e){let t=e.query?.trim()||void 0,n=e.category?.trim()||void 0,r=!t&&!n;p.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 l of s){let u=l.category||"other";(a[u]??=[]).push(l)}let c=Object.keys(a).sort().map(l=>{let u=a[l].map((f,m)=>`${m+1}. **${f.name}** (${f.id})
128
128
  ${f.description}
129
- Provider: ${f.provider} | Price: ${Mu(f)}
129
+ Provider: ${f.provider} | Price: ${Lu(f)}
130
130
  Params: ${Object.keys(f.inputSchema?.properties||f.inputSchema||{}).join(", ")||"none"}`).join(`
131
131
 
132
132
  `);return`## ${l.length<=3?l.toUpperCase():l.charAt(0).toUpperCase()+l.slice(1)}
@@ -139,22 +139,22 @@ ${c}
139
139
 
140
140
  Use execute_tool with the tool id and required params to run any of these.`}],_tools:s}}let i=s.map((a,c)=>`${c+1}. **${a.name}** (${a.id})
141
141
  ${a.description}
142
- Provider: ${a.provider} | Category: ${a.category} | Price: ${Mu(a)}
142
+ Provider: ${a.provider} | Category: ${a.category} | Price: ${Lu(a)}
143
143
  Params: ${Object.keys(a.inputSchema?.properties||a.inputSchema||{}).join(", ")||"none"}`).join(`
144
144
 
145
145
  `);return p.info("catalog:discovered",{count:s.length}),{content:[{type:"text",text:`Found ${s.length} tool(s):
146
146
 
147
147
  ${i}
148
148
 
149
- Use execute_tool with the tool id and required params to run any of these.`}],_tools:s}}catch(o){throw p.error("catalog:discover:error",{error:o.message}),new Error(`Failed to search tool catalog: ${o.message}`)}}function Mu(e){return e.priceDisplay??`$${(e.priceCents/100).toFixed(2)}`}function Hy(e,t){return t==="image"||t==="video"||t==="audio"?t:e?.match(/\.(mp4|webm|mov)/)?"video":"image"}function Yo(e,t){return Array.isArray(e.type)?e.type.includes(t):e.type===t}function qy(e,t,n){let r=e.inputSchema;if(!r||r.type!=="object")return null;let o=r.properties??{},s=n??e.id;for(let a of Object.keys(t))if(!Object.prototype.hasOwnProperty.call(o,a)){let c=Object.keys(o),l=c.length>0?` Expected: ${c.join(", ")}.`:"";return`Unknown parameter "${a}" for ${s}.${l}`}let i=(r.required??[]).filter(a=>!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0);if(i.length>1)return`${i.join(", ")} are required for ${s}.`;for(let a of r.required??[]){if(!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0)return`${a} is required for ${s}.`;if(t[a]===null)return`${a} cannot be null.`;if(typeof t[a]=="string"&&t[a].trim()==="")return`${a} cannot be empty.`}for(let[a,c]of Object.entries(t)){let l=o[a];if(!(!l||c===void 0||c===null)){if(l.enum&&!l.enum.includes(c))return`${a} must be one of: ${l.enum.map(String).join(", ")}.`;if(Yo(l,"integer")){if(typeof c!="number"||!Number.isInteger(c))return`${a} must be an integer.`}else if(Yo(l,"number")){if(typeof c!="number"||!Number.isFinite(c))return`${a} must be a number.`}else if(Yo(l,"string")){if(typeof c!="string")return`${a} must be a string.`;if(c.trim()==="")return`${a} cannot be empty.`;if(l.minLength!==void 0&&c.length<l.minLength)return`${a} is too short.`;if(l.maxLength!==void 0&&c.length>l.maxLength)return`${a} is too long.`}else if(Yo(l,"boolean")&&typeof c!="boolean")return`${a} must be a boolean.`;if(typeof c=="number"){if(l.minimum!==void 0&&c<l.minimum)return`${a} must be at least ${l.minimum}.`;if(l.maximum!==void 0&&c>l.maximum)return`${a} must be at most ${l.maximum}.`}}}return null}async function Yu(e){let t=kr(e);if(t)return t;try{return await P.catalogTool(e)}catch(n){return p.warn("catalog:resolve:error",{tool:e,error:n?.message||String(n)}),null}}function Zu(e){let t=e.priceCents,n=e.pricing;return e.executionMode==="free_authenticated"||e.accessMode==="free"||n?.free===!0||t===0||n?.amount===0}async function By(e,t,n="execute_tool"){let{tool_id:r,params:o,...s}=e,i=o||s;if(!r)return Jo("tool_id is required. Use discover_tools first to find available tools.","MISSING_TOOL_ID");p.info("catalog:execute",{tool:r,metaTool:n});let a=await Yu(r);if(!a)return Jo(`Unknown tool: '${r}'. Use discover_tools first to find available tools.`,"UNKNOWN_TOOL");if(a.deprecated){let m=a.replacementTool?` Use '${a.replacementTool}' instead.`:"";return Jo(`Tool '${r}' is deprecated and is no longer available for new paid calls.${m}`,"DEPRECATED_TOOL")}let l=qy(a,i,n&&n!=="execute_tool"?n:void 0);if(l)return p.info("catalog:execute:validation_failed",{tool:r,metaTool:n,error:l}),Jo(l);let u=await rs(r,i,t,n);if(u)return u;if(Zu(a)){p.info("catalog:execute:free",{tool:r,metaTool:n});let m=await P.shortcut(r,i,6e4,t,n);return m&&typeof m=="object"&&!Array.isArray(m)&&m.merchantName==null&&(m.merchantName=a.name??r),m}let d=await ht(r,void 0,t),f=ge.randomUUID();p.info("payment:attempt",{tool:r,amount:d.amount,merchant:d.merchantName});try{return await ue(async()=>{let m;try{m=await Ht({toolId:r,toolParams:i,estimatedAmountCents:yt(d),userContext:t,metaTool:n,timeoutMs:12e4,idempotencyKey:f})}catch(y){if(y instanceof _e)return Ye(y);throw y}if(p.info("payment:success",{tool:r,amount:d.amount,merchant:d.merchantName,mode:"session"}),m&&typeof m=="object"&&!Array.isArray(m)&&m.merchantName==null&&(m.merchantName=a?.name??r),m.urls?.length){m.urls.forEach(S=>Ze(S));let y=Hy(m.urls[0],m.mediaType);Pr({prompt:i.prompt||`${r} execution`,tool:r,mediaUrl:m.urls[0],mediaType:y,cost:m.amount??d.amount,transactionId:m.transactionId,userContext:t})}return m})}catch(m){return m instanceof me?(p.warn("payment:declined",{tool:r,amount:d.amount,merchant:d.merchantName,code:m.code,retryable:m.retryable}),Xe(m,d)):(Ky(m?.message)?p.warn("payment:ambiguous",{tool:r,amount:d.amount,merchant:d.merchantName,error:m.message,note:"Polling/timeout error on async tool \u2014 call may have succeeded. Verify via `visa-cli transactions list`."}):p.error("payment:failure",{tool:r,amount:d.amount,merchant:d.merchantName,error:m.message}),Nh({toolId:r,surface:n,merchantName:d.merchantName,amount:d.amount,message:m?.message||"Tool execution failed."}))}}function Ky(e){return e?/\b(task_id|polling?|timeout|timed out|queue|IN_QUEUE|aborted)\b/i.test(e):!1}var De=class{static async getStatus(t){return vy(t)}static async getVisaSmi(t,n){return oy(t,n)}static async getCards(t){return by(t)}static async transactionHistory(t,n){return Sy(t||{},n)}static async feedback(t,n){return wy(t,n)}static async updateSpendingControls(t,n){return ky(t,n)}static async configList(t){return Cy(t||{})}static async configSet(t){return Ty(t||{})}static async configUnset(t){return Ey(t||{})}static async biometricStatus(t){return Ay(t)}static async biometricOn(t){return Ry(t)}static async biometricOff(t,n){return Iy(t,n)}static async reset(t,n){return Fy(t,n)}static async login(t){return My(t)}static async closeSession(t){return Uy()}static async startSession(t,n){return Ly(t||{},n)}static async getSessionStatus(t){return Dy()}static async addCard(t){return jy(t)}static async removeCard(t,n){return Py(t,n)}static async setDefaultCard(t,n){return Oy(t,n)}static async buyCredits(t,n){return xy(t,n)}static async batch(t,n){return yy(t,n)}static async discoverTools(t){return Vy(t)}static async executeTool(t,n,r="execute_tool"){return By(t,n,r)}static async shortcut(t,n,r){switch(t){case"generate_image_card":return sy(n,r);case"generate_image_fast_card":return iy(n,r);case"generate_video_tempo_card":return ay(n,r);case"generate_music_tempo_card":return cy(n,r);case"check_music_status_tempo_card":return ly(n,r);case"query_onchain_prices_card":return uy(n,r);default:{let o=await ht(t,void 0,r);p.info("payment:attempt",{tool:t});try{let s=await Ht({toolId:t,toolParams:n,estimatedAmountCents:yt(o),userContext:r,timeoutMs:6e4});return p.info("payment:success",{tool:t,mode:"session"}),s.urls?.length&&s.urls.forEach(i=>Ze(i)),s}catch(s){if(s instanceof _e)return Ye(s);if(s instanceof me)return p.warn("payment:declined",{tool:t,code:s.code,retryable:s.retryable}),Xe(s,o);throw p.error("payment:failure",{tool:t,error:s.message}),s}}}}static async submitFeedback(t,n,r){p.info("feedback:submit",{length:t.length,transactionId:n,hasContext:!!r});try{let o=await P.submitFeedback(t,n,r);return p.info("feedback:submitted",{transactionId:n}),o}catch(o){let s=o instanceof Error?o.message:"Unknown error";throw p.error("feedback:error",{error:s,transactionId:n}),o}}static async getFeedback(t,n){p.info("feedback:list",{limit:t||20});try{let r=await P.getFeedback(t,n);return p.info("feedback:listed",{count:r?.feedback?.length||0}),r}catch(r){let o=r instanceof Error?r.message:"Unknown error";throw p.error("feedback:error",{error:o}),r}}};function Xu(e,t=process.stderr){if(Be()||!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(`
149
+ Use execute_tool with the tool id and required params to run any of these.`}],_tools:s}}catch(o){throw p.error("catalog:discover:error",{error:o.message}),new Error(`Failed to search tool catalog: ${o.message}`)}}function Lu(e){return e.priceDisplay??`$${(e.priceCents/100).toFixed(2)}`}function Gy(e,t){return t==="image"||t==="video"||t==="audio"?t:e?.match(/\.(mp4|webm|mov)/)?"video":"image"}function Yo(e,t){return Array.isArray(e.type)?e.type.includes(t):e.type===t}function Wy(e,t,n){let r=e.inputSchema;if(!r||r.type!=="object")return null;let o=r.properties??{},s=n??e.id;for(let a of Object.keys(t))if(!Object.prototype.hasOwnProperty.call(o,a)){let c=Object.keys(o),l=c.length>0?` Expected: ${c.join(", ")}.`:"";return`Unknown parameter "${a}" for ${s}.${l}`}let i=(r.required??[]).filter(a=>!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0);if(i.length>1)return`${i.join(", ")} are required for ${s}.`;for(let a of r.required??[]){if(!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0)return`${a} is required for ${s}.`;if(t[a]===null)return`${a} cannot be null.`;if(typeof t[a]=="string"&&t[a].trim()==="")return`${a} cannot be empty.`}for(let[a,c]of Object.entries(t)){let l=o[a];if(!(!l||c===void 0||c===null)){if(l.enum&&!l.enum.includes(c))return`${a} must be one of: ${l.enum.map(String).join(", ")}.`;if(Yo(l,"integer")){if(typeof c!="number"||!Number.isInteger(c))return`${a} must be an integer.`}else if(Yo(l,"number")){if(typeof c!="number"||!Number.isFinite(c))return`${a} must be a number.`}else if(Yo(l,"string")){if(typeof c!="string")return`${a} must be a string.`;if(c.trim()==="")return`${a} cannot be empty.`;if(l.minLength!==void 0&&c.length<l.minLength)return`${a} is too short.`;if(l.maxLength!==void 0&&c.length>l.maxLength)return`${a} is too long.`}else if(Yo(l,"boolean")&&typeof c!="boolean")return`${a} must be a boolean.`;if(typeof c=="number"){if(l.minimum!==void 0&&c<l.minimum)return`${a} must be at least ${l.minimum}.`;if(l.maximum!==void 0&&c>l.maximum)return`${a} must be at most ${l.maximum}.`}}}return null}async function Xu(e){let t=kr(e);if(t)return t;try{return await P.catalogTool(e)}catch(n){return p.warn("catalog:resolve:error",{tool:e,error:n?.message||String(n)}),null}}function Qu(e){let t=e.priceCents,n=e.pricing;return e.executionMode==="free_authenticated"||e.accessMode==="free"||n?.free===!0||t===0||n?.amount===0}async function zy(e,t,n="execute_tool"){let{tool_id:r,params:o,...s}=e,i=o||s;if(!r)return Jo("tool_id is required. Use discover_tools first to find available tools.","MISSING_TOOL_ID");p.info("catalog:execute",{tool:r,metaTool:n});let a=await Xu(r);if(!a)return Jo(`Unknown tool: '${r}'. Use discover_tools first to find available tools.`,"UNKNOWN_TOOL");if(a.deprecated){let m=a.replacementTool?` Use '${a.replacementTool}' instead.`:"";return Jo(`Tool '${r}' is deprecated and is no longer available for new paid calls.${m}`,"DEPRECATED_TOOL")}let l=Wy(a,i,n&&n!=="execute_tool"?n:void 0);if(l)return p.info("catalog:execute:validation_failed",{tool:r,metaTool:n,error:l}),Jo(l);let u=await rs(r,i,t,n);if(u)return u;if(Qu(a)){p.info("catalog:execute:free",{tool:r,metaTool:n});let m=await P.shortcut(r,i,6e4,t,n);return m&&typeof m=="object"&&!Array.isArray(m)&&m.merchantName==null&&(m.merchantName=a.name??r),m}let d=await yt(r,void 0,t),f=ge.randomUUID();p.info("payment:attempt",{tool:r,amount:d.amount,merchant:d.merchantName});try{return await ue(async()=>{let m;try{m=await Ht({toolId:r,toolParams:i,estimatedAmountCents:_t(d),userContext:t,metaTool:n,timeoutMs:12e4,idempotencyKey:f})}catch(_){if(_ instanceof _e)return Ye(_);throw _}if(p.info("payment:success",{tool:r,amount:d.amount,merchant:d.merchantName,mode:"session"}),m&&typeof m=="object"&&!Array.isArray(m)&&m.merchantName==null&&(m.merchantName=a?.name??r),m.urls?.length){m.urls.forEach(S=>Ze(S));let _=Gy(m.urls[0],m.mediaType);Pr({prompt:i.prompt||`${r} execution`,tool:r,mediaUrl:m.urls[0],mediaType:_,cost:m.amount??d.amount,transactionId:m.transactionId,userContext:t})}return m})}catch(m){return m instanceof me?(p.warn("payment:declined",{tool:r,amount:d.amount,merchant:d.merchantName,code:m.code,retryable:m.retryable}),Xe(m,d)):(Jy(m?.message)?p.warn("payment:ambiguous",{tool:r,amount:d.amount,merchant:d.merchantName,error:m.message,note:"Polling/timeout error on async tool \u2014 call may have succeeded. Verify via `visa-cli transactions list`."}):p.error("payment:failure",{tool:r,amount:d.amount,merchant:d.merchantName,error:m.message}),jh({toolId:r,surface:n,merchantName:d.merchantName,amount:d.amount,message:m?.message||"Tool execution failed."}))}}function Jy(e){return e?/\b(task_id|polling?|timeout|timed out|queue|IN_QUEUE|aborted)\b/i.test(e):!1}var De=class{static async getStatus(t){return xy(t)}static async getVisaSmi(t,n){return cy(t,n)}static async getCards(t){return ky(t)}static async transactionHistory(t,n){return Cy(t||{},n)}static async feedback(t,n){return Ty(t,n)}static async updateSpendingControls(t,n){return Ay(t,n)}static async configList(t){return Ry(t||{})}static async configSet(t){return Iy(t||{})}static async configUnset(t){return $y(t||{})}static async biometricStatus(t){return Py(t)}static async biometricOn(t){return Oy(t)}static async biometricOff(t,n){return My(t,n)}static async reset(t,n){return By(t,n)}static async login(t){return Uy(t)}static async closeSession(t){return Hy()}static async startSession(t,n){return Fy(t||{},n)}static async getSessionStatus(t){return Vy()}static async addCard(t){return qy(t)}static async removeCard(t,n){return Ly(t,n)}static async setDefaultCard(t,n){return Dy(t,n)}static async buyCredits(t,n){return Ey(t,n)}static async batch(t,n){return Sy(t,n)}static async discoverTools(t){return Ky(t)}static async executeTool(t,n,r="execute_tool"){return zy(t,n,r)}static async shortcut(t,n,r){switch(t){case"generate_image_card":return ly(n,r);case"generate_image_fast_card":return uy(n,r);case"generate_video_tempo_card":return dy(n,r);case"generate_music_tempo_card":return my(n,r);case"check_music_status_tempo_card":return py(n,r);case"query_onchain_prices_card":return fy(n,r);default:{let o=await yt(t,void 0,r);p.info("payment:attempt",{tool:t});try{let s=await Ht({toolId:t,toolParams:n,estimatedAmountCents:_t(o),userContext:r,timeoutMs:6e4});return p.info("payment:success",{tool:t,mode:"session"}),s.urls?.length&&s.urls.forEach(i=>Ze(i)),s}catch(s){if(s instanceof _e)return Ye(s);if(s instanceof me)return p.warn("payment:declined",{tool:t,code:s.code,retryable:s.retryable}),Xe(s,o);throw p.error("payment:failure",{tool:t,error:s.message}),s}}}}static async submitFeedback(t,n,r){p.info("feedback:submit",{length:t.length,transactionId:n,hasContext:!!r});try{let o=await P.submitFeedback(t,n,r);return p.info("feedback:submitted",{transactionId:n}),o}catch(o){let s=o instanceof Error?o.message:"Unknown error";throw p.error("feedback:error",{error:s,transactionId:n}),o}}static async getFeedback(t,n){p.info("feedback:list",{limit:t||20});try{let r=await P.getFeedback(t,n);return p.info("feedback:listed",{count:r?.feedback?.length||0}),r}catch(r){let o=r instanceof Error?r.message:"Unknown error";throw p.error("feedback:error",{error:o}),r}}};function ed(e,t=process.stderr){if(Be()||!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(`
150
150
  \x1B[33m\u2191 ${r}\x1B[0m
151
- `),!0}function Qu(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]=Gy(o,n[o]?.description);return r}function Gy(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 Wy(e){let t=et(e.referralCode,"");if(!t)return[];let n=["Referrals",` Your code ${t}`],r=et(e.referralLink,"");if(r&&n.push(` Your link ${r}`),typeof e.referralCount=="number"&&Number.isFinite(e.referralCount)){let o=Math.max(0,Math.trunc(e.referralCount));n.push(` Joined ${o} ${o===1?"person":"people"} via your link`)}return n}var zy=20;function td(e,t,n,r){let o=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=t_(e.spendingControls).dailyLimit,a=Math.max(0,Or(e.dailyCardFundedTopupSpent??e.dailySpent)),c=i>0?Math.min(i,Math.max(0,Or(e.dailyCardFundedTopupRemaining??e.dailyRemaining??i-a))):0,l=i>0?Math.min(1,a/i):0,d=(Array.isArray(t)?t:[]).filter(Zy),f=d.slice(0,3),m=Xy(d,3),y=(e.cards??[]).slice(0,3),S=r.latestVersion?xn(r.latestVersion):"",$=r.updateCheckDisabled?"update checks disabled":S?`update ready: v${S}`:"up to date",H=Math.round(l*100),U=et(e.status,e.enrolled?"approved":"not enrolled"),x=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${U} | touch id: ${n?"ready":"unavailable"}`,`Version: v${o} | ${$}`,`Top-up meter: ${ed(l)} ${String(H).padStart(3," ")}% | remaining ${zn(c)}/day | daily top-up cap ${zn(i)}`,"","Card top-ups",` Remaining ${zn(c)} / ${zn(i)}`,` Usage ${ed(l)} ${H}%`,` Top-ups today ${zn(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...y.length>0?y.map(C=>` ${e_(C)}`):[" No cards enrolled"],"","Last 3 services",...m.length>0?m.map((C,L)=>` ${L+1}. ${C}`):[" No paid services yet"],"","Recent receipts",...f.length>0?f.map(C=>` ${Qy(C)}`):[" No receipts yet"]],_=Wy(e);return _.length>0&&x.push("",..._),S&&!r.updateCheckDisabled?(x.push("",`Update: v${S} ready \u2014 run \`visa-cli update\``),r.updateMessage&&x.push(` ${xn(r.updateMessage)}`)):r.updateMessage&&x.push("",`Update: ${xn(r.updateMessage)}`),`${x.join(`
151
+ `),!0}function td(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]=Yy(o,n[o]?.description);return r}function Yy(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 Zy(e){let t=et(e.referralCode,"");if(!t)return[];let n=["Referrals",` Your code ${t}`],r=et(e.referralLink,"");if(r&&n.push(` Your link ${r}`),typeof e.referralCount=="number"&&Number.isFinite(e.referralCount)){let o=Math.max(0,Math.trunc(e.referralCount));n.push(` Joined ${o} ${o===1?"person":"people"} via your link`)}return n}var Xy=20;function rd(e,t,n,r){let o=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=s_(e.spendingControls).dailyLimit,a=Math.max(0,Or(e.dailyCardFundedTopupSpent??e.dailySpent)),c=i>0?Math.min(i,Math.max(0,Or(e.dailyCardFundedTopupRemaining??e.dailyRemaining??i-a))):0,l=i>0?Math.min(1,a/i):0,d=(Array.isArray(t)?t:[]).filter(t_),f=d.slice(0,3),m=n_(d,3),_=(e.cards??[]).slice(0,3),S=r.latestVersion?xn(r.latestVersion):"",$=r.updateCheckDisabled?"update checks disabled":S?`update ready: v${S}`:"up to date",H=Math.round(l*100),U=et(e.status,e.enrolled?"approved":"not enrolled"),x=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${U} | touch id: ${n?"ready":"unavailable"}`,`Version: v${o} | ${$}`,`Top-up meter: ${nd(l)} ${String(H).padStart(3," ")}% | remaining ${zn(c)}/day | daily top-up cap ${zn(i)}`,"","Card top-ups",` Remaining ${zn(c)} / ${zn(i)}`,` Usage ${nd(l)} ${H}%`,` Top-ups today ${zn(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",..._.length>0?_.map(k=>` ${o_(k)}`):[" No cards enrolled"],"","Last 3 services",...m.length>0?m.map((k,L)=>` ${L+1}. ${k}`):[" No paid services yet"],"","Recent receipts",...f.length>0?f.map(k=>` ${r_(k)}`):[" No receipts yet"]],y=Zy(e);return y.length>0&&x.push("",...y),S&&!r.updateCheckDisabled?(x.push("",`Update: v${S} ready \u2014 run \`visa-cli update\``),r.updateMessage&&x.push(` ${xn(r.updateMessage)}`)):r.updateMessage&&x.push("",`Update: ${xn(r.updateMessage)}`),`${x.join(`
152
152
  `)}
153
- `}function Jy(e){return e.tool_name!=null}function Yy(e){return Or(e.amount)===0&&e.status==="failed"}function Zy(e){return Jy(e)&&!Yy(e)}function Xy(e,t=1/0){let n=new Set,r=[];for(let o of e){if(r.length>=t)break;let s=et(o.merchant_name,"Unknown merchant"),i=et(o.tool_name,"unknown_tool"),a=`${s} :: ${i}`;n.has(a)||(n.add(a),r.push(`${s} [${i}]`))}return r}function Qy(e){let t=et(e.merchant_name,"Unknown merchant"),n=et(e.tool_name,"unknown_tool"),r=zn(Or(e.amount)),o=et(e.status,"unknown"),s=n_(e.created_at);return`${r} ${o.padEnd(9)} ${t} [${n}] ${s}`}function e_(e){let t=et(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function t_(e){return{dailyLimit:Or(e?.daily_limit??e?.dailyLimit??0)}}function Or(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function zn(e){return`$${e.toFixed(2)}`}function ed(e,t=zy){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function et(e,t){let n=xn(e??"").trim();return n.length>0?n:t}function n_(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?et(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function xn(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 r_=/^[1-9]\d{0,9}$/;function Di(e){if(!r_.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 nd(e){let t=xn(e.brand||"Visa"),n=xn(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 tt=E(require("fs")),oe=E(require("path")),o_=["npm","pnpm","yarn","bun"],s_=/\s+/,i_=process.platform==="win32"?"visa-cli.cmd":"visa-cli",Ui=["node_modules","@visa","cli"];function a_(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(s_)[0]??"",r=n.indexOf("/"),o=r===-1?n:n.slice(0,r);return o_.includes(o)?o:void 0}function ji(e){if(!e)return;let t=e;try{t=tt.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 c_(e=process.argv[1]){return a_()??ji(process.env.npm_execpath)??ji(process.env.npm_node_execpath)??ji(e)}function l_(e=process.env.PATH??""){let t=[];for(let n of e.split(oe.delimiter))n&&t.push(n);return t}function u_(e=process.env.PATH??""){let t=new Set,n=[];for(let r of l_(e))try{let o=oe.join(r,i_);tt.accessSync(o,tt.constants.X_OK);let s=oe.resolve(o);t.has(s)||(t.add(s),n.push(o))}catch{}return n}function rd(e){try{let t=tt.readFileSync(oe.join(e,"package.json"),"utf-8"),n=JSON.parse(t);if(n.name==="@visa/cli"&&typeof n.version=="string")return n.version}catch{}}function d_(e){let t=oe.resolve(e).split(oe.sep);for(let n=t.length-Ui.length;n>=0;n--)if(Ui.every((r,o)=>t[n+o]===r)){let r=t.slice(0,n+Ui.length).join(oe.sep)||oe.sep;if(rd(r))return r}}function m_(e){if(!e)return;let t=oe.normalize(e),n=t.split(oe.sep),r=s=>s.every((a,c)=>n[n.length-s.length+c]===a)?n.slice(0,-s.length).join(oe.sep)||oe.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 p_(e,t){let n=oe.resolve(e);try{n=tt.realpathSync(e)}catch{}let r=d_(n);return{binPath:e,realPath:n,packageRoot:r,version:r?rd(r):void 0,prefix:m_(r),isActive:n===t}}function f_(e,t=process.env.PATH??""){let n=e??process.argv[1],r=n?oe.resolve(n):"";try{n&&(r=tt.realpathSync(n))}catch{}let o=e?[e]:[n,...u_(t)].filter(Boolean),s=new Map;for(let d of o){let f=p_(d,r),m=s.get(f.realPath);s.set(f.realPath,m?{...f,binPath:m.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 c=new Set(i.map(d=>d.packageRoot).filter(Boolean)),l=!!a?.packageRoot&&c.size>1,u=a?.prefix;return{active:a,installs:i,hasConflictingInstalls:l,recommendedPrefix:u}}function g_(e,t=process.platform){return/^[A-Za-z0-9_./:@+-]+$/.test(e)?e:t==="win32"?`"${e.replace(/"/g,'""')}"`:`'${e.replace(/'/g,"'\\''")}'`}function Fi(e,t,n,r={}){let o=t??c_(n)??"npm",s=r.withDiagnostics?f_(n):void 0,a=`@visa/cli@${e??"latest"}`;switch(o){case"npm":if(s?.hasConflictingInstalls&&s.recommendedPrefix){let c=s.recommendedPrefix;return{packageManager:o,command:"npm",args:["install","-g","--prefix",c,a],display:`npm install -g --prefix ${g_(c)} ${a}`,diagnostics:s}}return{packageManager:o,command:"npm",args:["install","-g",a],display:`npm install -g ${a}`,diagnostics:s};case"pnpm":return{packageManager:o,command:"pnpm",args:["add","-g",a],display:`pnpm add -g ${a}`,diagnostics:s};case"yarn":return{packageManager:o,command:"yarn",args:["global","add",a],display:`yarn global add ${a}`,diagnostics:s};case"bun":return{packageManager:o,command:"bun",args:["add","-g",a],display:`bun add -g ${a}`,diagnostics:s}}}function h_(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 Vi(e,t){if(!e.hasConflictingInstalls)return null;let n=["Multiple Visa CLI installs detected.",...e.installs.map(h_)];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(`
154
- `)}var ls=E(Rr());var y_=["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 __(){let e=new Set;for(let t of y_)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of Er)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var p0=__();var Hi=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 _0=new Set(Er),v0=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...Hi,...Er]);var j=E(require("fs")),M=E(require("path")),od=E(require("os")),ee=od.homedir(),v_=["Claude_","Anthropic.ClaudeDesktop_"],Jn=class extends Error{constructor(n,r,o){super(S_(n,r,o));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function sd(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
155
- `)}function b_(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=sd(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function S_(e,t,n){let r=t.replace(ee,"~"),o=sd(n).split(`
156
- `).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 Mr(){return process.env.APPDATA||M.join(ee,"AppData","Roaming")}function w_(){return process.env.LOCALAPPDATA||M.join(ee,"AppData","Local")}function qi(e){return process.platform==="win32"?e.win32:e.posix}function id(){if(process.platform!=="win32")return;let e=M.join(w_(),"Packages");if(j.existsSync(e))try{let t=j.readdirSync(e,"utf-8");for(let n of v_){let r=t.filter(o=>o.startsWith(n)).sort()[0];if(r)return M.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function ad(){if(process.platform==="win32"){let e=id();return e?M.join(e,"claude_desktop_config.json"):M.join(Mr(),"Claude","claude_desktop_config.json")}return M.join(ee,"Library","Application Support","Claude","claude_desktop_config.json")}function cd(){if(process.platform!=="win32")return[M.join(ee,"Library","Application Support","Claude")];let e=[M.join(Mr(),"Claude")],t=id();return t&&e.push(t),e}function os(e){return e.id==="claude-desktop"?ad():e.globalConfigPath}function x_(e){return e.id==="claude-desktop"?cd():e.detectPaths}var Fe=[{id:"claude",displayName:"Claude Code",globalConfigPath:M.join(ee,".claude.json"),configKey:"mcpServers",detectPaths:[M.join(ee,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:ad(),configKey:"mcpServers",detectPaths:cd(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:M.join(ee,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[M.join(ee,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:M.join(ee,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[M.join(ee,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:M.join(ee,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[M.join(ee,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:qi({win32:M.join(Mr(),"Roo","mcp_settings.json"),posix:M.join(ee,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[M.join(ee,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:M.join(ee,".vscode","mcp.json"),configKey:"servers",detectPaths:[M.join(ee,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:qi({win32:M.join(Mr(),"Zed","settings.json"),posix:M.join(ee,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:qi({win32:[M.join(Mr(),"Zed")],posix:[M.join(ee,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:M.join(ee,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[M.join(ee,".codex")],postInstallHint:"Restart Codex to connect."}];function Bi(e){return Fe.find(t=>t.id===e)}function Nr(e){return x_(e).some(t=>{if(t.includes("*")){let n=M.dirname(t),r=M.basename(t).replaceAll("*","");if(!j.existsSync(n))return!1;try{return j.readdirSync(n).some(o=>o.startsWith(r))}catch{return!1}}return j.existsSync(t)})}function ld(){return{command:"node",args:[M.resolve(__dirname,"mcp-server/index.js")]}}function Ki(e,t){return t==="project"?"json":e.configFormat??"json"}function k_(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 Gi(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(`
157
- `),r=Gi(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]]=k_(i[2]))}return Object.keys(o).length>0?o:void 0}function C_(e,t,n){let r=`[${n.args.map(c=>`"${c}"`).join(", ")}]`,o=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],s=e.split(`
153
+ `}function Qy(e){return e.tool_name!=null}function e_(e){return Or(e.amount)===0&&e.status==="failed"}function t_(e){return Qy(e)&&!e_(e)}function n_(e,t=1/0){let n=new Set,r=[];for(let o of e){if(r.length>=t)break;let s=et(o.merchant_name,"Unknown merchant"),i=et(o.tool_name,"unknown_tool"),a=`${s} :: ${i}`;n.has(a)||(n.add(a),r.push(`${s} [${i}]`))}return r}function r_(e){let t=et(e.merchant_name,"Unknown merchant"),n=et(e.tool_name,"unknown_tool"),r=zn(Or(e.amount)),o=et(e.status,"unknown"),s=i_(e.created_at);return`${r} ${o.padEnd(9)} ${t} [${n}] ${s}`}function o_(e){let t=et(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function s_(e){return{dailyLimit:Or(e?.daily_limit??e?.dailyLimit??0)}}function Or(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function zn(e){return`$${e.toFixed(2)}`}function nd(e,t=Xy){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function et(e,t){let n=xn(e??"").trim();return n.length>0?n:t}function i_(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?et(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function xn(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 a_=/^[1-9]\d{0,9}$/;function Di(e){if(!a_.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 od(e){let t=xn(e.brand||"Visa"),n=xn(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 tt=E(require("fs")),oe=E(require("path")),c_=["npm","pnpm","yarn","bun"],l_=/\s+/,u_=process.platform==="win32"?"visa-cli.cmd":"visa-cli",Ui=["node_modules","@visa","cli"];function d_(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(l_)[0]??"",r=n.indexOf("/"),o=r===-1?n:n.slice(0,r);return c_.includes(o)?o:void 0}function ji(e){if(!e)return;let t=e;try{t=tt.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 m_(e=process.argv[1]){return d_()??ji(process.env.npm_execpath)??ji(process.env.npm_node_execpath)??ji(e)}function p_(e=process.env.PATH??""){let t=[];for(let n of e.split(oe.delimiter))n&&t.push(n);return t}function f_(e=process.env.PATH??""){let t=new Set,n=[];for(let r of p_(e))try{let o=oe.join(r,u_);tt.accessSync(o,tt.constants.X_OK);let s=oe.resolve(o);t.has(s)||(t.add(s),n.push(o))}catch{}return n}function sd(e){try{let t=tt.readFileSync(oe.join(e,"package.json"),"utf-8"),n=JSON.parse(t);if(n.name==="@visa/cli"&&typeof n.version=="string")return n.version}catch{}}function g_(e){let t=oe.resolve(e).split(oe.sep);for(let n=t.length-Ui.length;n>=0;n--)if(Ui.every((r,o)=>t[n+o]===r)){let r=t.slice(0,n+Ui.length).join(oe.sep)||oe.sep;if(sd(r))return r}}function h_(e){if(!e)return;let t=oe.normalize(e),n=t.split(oe.sep),r=s=>s.every((a,c)=>n[n.length-s.length+c]===a)?n.slice(0,-s.length).join(oe.sep)||oe.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 y_(e,t){let n=oe.resolve(e);try{n=tt.realpathSync(e)}catch{}let r=g_(n);return{binPath:e,realPath:n,packageRoot:r,version:r?sd(r):void 0,prefix:h_(r),isActive:n===t}}function __(e,t=process.env.PATH??""){let n=e??process.argv[1],r=n?oe.resolve(n):"";try{n&&(r=tt.realpathSync(n))}catch{}let o=e?[e]:[n,...f_(t)].filter(Boolean),s=new Map;for(let d of o){let f=y_(d,r),m=s.get(f.realPath);s.set(f.realPath,m?{...f,binPath:m.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 c=new Set(i.map(d=>d.packageRoot).filter(Boolean)),l=!!a?.packageRoot&&c.size>1,u=a?.prefix;return{active:a,installs:i,hasConflictingInstalls:l,recommendedPrefix:u}}function b_(e,t=process.platform){return/^[A-Za-z0-9_./:@+-]+$/.test(e)?e:t==="win32"?`"${e.replace(/"/g,'""')}"`:`'${e.replace(/'/g,"'\\''")}'`}function Fi(e,t,n,r={}){let o=t??m_(n)??"npm",s=r.withDiagnostics?__(n):void 0,a=`@visa/cli@${e??"latest"}`;switch(o){case"npm":if(s?.hasConflictingInstalls&&s.recommendedPrefix){let c=s.recommendedPrefix;return{packageManager:o,command:"npm",args:["install","-g","--prefix",c,a],display:`npm install -g --prefix ${b_(c)} ${a}`,diagnostics:s}}return{packageManager:o,command:"npm",args:["install","-g",a],display:`npm install -g ${a}`,diagnostics:s};case"pnpm":return{packageManager:o,command:"pnpm",args:["add","-g",a],display:`pnpm add -g ${a}`,diagnostics:s};case"yarn":return{packageManager:o,command:"yarn",args:["global","add",a],display:`yarn global add ${a}`,diagnostics:s};case"bun":return{packageManager:o,command:"bun",args:["add","-g",a],display:`bun add -g ${a}`,diagnostics:s}}}function v_(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 Vi(e,t){if(!e.hasConflictingInstalls)return null;let n=["Multiple Visa CLI installs detected.",...e.installs.map(v_)];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(`
154
+ `)}var ls=E(Rr());function S_(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function id(e){if(!e)return{canContinue:!1,message:"Biometric attestation is unavailable and Visa CLI could not verify server attestation policy.",hint:"Re-run setup from an interactive device with Touch ID (Mac) or Windows Hello (PC) before using payment commands."};let t=S_(e);return e.attestationRequired!==!1||t?{canContinue:!1,message:"Biometric attestation is unavailable, but this account requires a registered local attestation key.",hint:"Re-run setup from an interactive device with Touch ID (Mac) or Windows Hello (PC), or use an already-registered device to recover or change biometric policy."}:{canContinue:!0,message:"Biometric attestation is unavailable; continuing only because server biometric policy is disabled and no attestation key is registered."}}var w_=["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 x_(){let e=new Set;for(let t of w_)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of Er)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var b0=x_();var Hi=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 k0=new Set(Er),C0=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...Hi,...Er]);var j=E(require("fs")),M=E(require("path")),ad=E(require("os")),ee=ad.homedir(),k_=["Claude_","Anthropic.ClaudeDesktop_"],Jn=class extends Error{constructor(n,r,o){super(T_(n,r,o));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function cd(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
155
+ `)}function C_(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=cd(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function T_(e,t,n){let r=t.replace(ee,"~"),o=cd(n).split(`
156
+ `).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 Mr(){return process.env.APPDATA||M.join(ee,"AppData","Roaming")}function E_(){return process.env.LOCALAPPDATA||M.join(ee,"AppData","Local")}function qi(e){return process.platform==="win32"?e.win32:e.posix}function ld(){if(process.platform!=="win32")return;let e=M.join(E_(),"Packages");if(j.existsSync(e))try{let t=j.readdirSync(e,"utf-8");for(let n of k_){let r=t.filter(o=>o.startsWith(n)).sort()[0];if(r)return M.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function ud(){if(process.platform==="win32"){let e=ld();return e?M.join(e,"claude_desktop_config.json"):M.join(Mr(),"Claude","claude_desktop_config.json")}return M.join(ee,"Library","Application Support","Claude","claude_desktop_config.json")}function dd(){if(process.platform!=="win32")return[M.join(ee,"Library","Application Support","Claude")];let e=[M.join(Mr(),"Claude")],t=ld();return t&&e.push(t),e}function os(e){return e.id==="claude-desktop"?ud():e.globalConfigPath}function A_(e){return e.id==="claude-desktop"?dd():e.detectPaths}var Fe=[{id:"claude",displayName:"Claude Code",globalConfigPath:M.join(ee,".claude.json"),configKey:"mcpServers",detectPaths:[M.join(ee,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:ud(),configKey:"mcpServers",detectPaths:dd(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:M.join(ee,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[M.join(ee,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:M.join(ee,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[M.join(ee,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:M.join(ee,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[M.join(ee,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:qi({win32:M.join(Mr(),"Roo","mcp_settings.json"),posix:M.join(ee,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[M.join(ee,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:M.join(ee,".vscode","mcp.json"),configKey:"servers",detectPaths:[M.join(ee,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:qi({win32:M.join(Mr(),"Zed","settings.json"),posix:M.join(ee,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:qi({win32:[M.join(Mr(),"Zed")],posix:[M.join(ee,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:M.join(ee,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[M.join(ee,".codex")],postInstallHint:"Restart Codex to connect."}];function Bi(e){return Fe.find(t=>t.id===e)}function Nr(e){return A_(e).some(t=>{if(t.includes("*")){let n=M.dirname(t),r=M.basename(t).replaceAll("*","");if(!j.existsSync(n))return!1;try{return j.readdirSync(n).some(o=>o.startsWith(r))}catch{return!1}}return j.existsSync(t)})}function md(){return{command:"node",args:[M.resolve(__dirname,"mcp-server/index.js")]}}function Ki(e,t){return t==="project"?"json":e.configFormat??"json"}function R_(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 Gi(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(`
157
+ `),r=Gi(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]]=R_(i[2]))}return Object.keys(o).length>0?o:void 0}function I_(e,t,n){let r=`[${n.args.map(c=>`"${c}"`).join(", ")}]`,o=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],s=e.split(`
158
158
  `),i=Gi(s,t);if(i){s.splice(i.start,i.end-i.start,...o);let c=s.join(`
159
159
  `);return c.endsWith(`
160
160
  `)?c:c+`
@@ -162,25 +162,25 @@ Use execute_tool with the tool id and required params to run any of these.`}],_t
162
162
 
163
163
  `:"")+o.join(`
164
164
  `)+`
165
- `}function T_(e,t){let n=e.split(`
165
+ `}function $_(e,t){let n=e.split(`
166
166
  `),r=Gi(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
167
167
  `).replace(/\n{3,}/g,`
168
168
 
169
- `)):e}function Lr(e,t="global"){let n=t==="project"?M.join(process.cwd(),".mcp.json"):os(e);try{let r=M.dirname(n);j.existsSync(r)||j.mkdirSync(r,{recursive:!0});let o=Ki(e,t),s=ld();if(o==="toml"){let i=j.existsSync(n)?j.readFileSync(n,"utf-8"):"",a=C_(i,"visa-cli",s);j.writeFileSync(n,a)}else{let i={};if(j.existsSync(n))try{i=JSON.parse(j.readFileSync(n,"utf-8"))}catch{i={}}i[e.configKey]=i[e.configKey]||{},i[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(s):s,j.writeFileSync(n,JSON.stringify(i,null,2)+`
170
- `)}}catch(r){throw b_(r)?new Jn(e,n,r):r}return{installed:!0,configPath:n,message:e.postInstallHint}}function zi(e,t="global"){let n=t==="project"?M.join(process.cwd(),".mcp.json"):os(e);if(!j.existsSync(n))return{removed:!1,configPath:n};if(Ki(e,t)==="toml"){let i=j.readFileSync(n,"utf-8");return Wi(i,"visa-cli")?(j.writeFileSync(n,T_(i,"visa-cli")),{removed:!0,configPath:n}):{removed:!1,configPath:n}}let o;try{o=JSON.parse(j.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"],j.writeFileSync(n,JSON.stringify(o,null,2)+`
171
- `),{removed:!0,configPath:n})}function ud(e,t="global"){let n=t==="project"?M.join(process.cwd(),".mcp.json"):os(e);if(!j.existsSync(n))return!1;if(Ki(e,t)==="toml")try{let o=j.readFileSync(n,"utf-8");return!!Wi(o,"visa-cli")}catch{return!1}try{return!!JSON.parse(j.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function E_(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 A_(e,t){if(e===t)return!0;let n=M.resolve(e),r=M.resolve(t);if(n===r)return!0;try{let o=j.realpathSync(n),s=j.realpathSync(r);return o===s}catch{return!1}}function Dr(){let e=ld(),t=e.args[e.args.length-1],n=[];for(let r of Fe){let o=os(r);if(!j.existsSync(o))continue;let s=r.configFormat??"json",i;if(s==="toml")try{let l=j.readFileSync(o,"utf-8");i=Wi(l,"visa-cli")}catch{continue}else{let l;try{l=JSON.parse(j.readFileSync(o,"utf-8"))}catch{continue}i=l?.[r.configKey]?.["visa-cli"]}if(!i)continue;let a=E_(i);if(!a||A_(a,t))continue;let c=j.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:o,currentPath:a,expectedPath:t,staleReason:c})}return n}function Ji(e){return{configPath:Lr(e.client,"global").configPath}}var ea=(0,xd.promisify)(wd.execFile);function Yi(){let e=st();setImmediate(()=>{Us(e,{getCommand:()=>mo(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 P_(e){let t=z.homedir(),n=o=>o.replace(t,"~"),r=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
172
- ${r}: ${n(e.currentPath)}`}function kd(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(P_(n))}function dd(e){console.log(` ! ${e.client.displayName} skipped: ${e.message}`)}function Ve(){this.help({error:!1})}var J=new Sd.Command,O_=new Set(["pay",...Hi]),as=null,Ur=!1;function ce(){return as=new Ce(()=>F.getSessionToken()),as}function md(e){if(e instanceof Xt)return!0;let t=e instanceof Error?e.message:"";return/attestation required|invalid signature|rotate biometric key|biometric key/i.test(t)}var pd=0,fd="",M_="attestation-key-rotation",N_="api-keys-create",gd=0,hd="";async function L_(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:pd,merchant:fd,context:M_})).toString("base64");return{signature:await vn(n,"verify Visa CLI Touch ID setup"),nonce:t,amount:pd,merchant:fd}}async function D_(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:gd,merchant:hd,context:N_})).toString("base64");return{signature:await vn(n,"create a Visa API token"),nonce:t,amount:gd,merchant:hd}}async function U_(e){let t=await e.getStatus();return t.attestationRequired!==!1||ze(t)}async function j_(e){let t=await Jl(),n=await L_(e);await e.registerAttestationKey(t,n)}async function Cd(e,t,n=!1){let r=await No();console.log(" Attestation key generated."),await e.registerAttestationKey(r),console.log(" Attestation key registered with server."),t&&(await e.setBiometricPreference({required:!0}),n&&p.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 Zi(e){if(!await sa(e))throw new Error("Could not clear stale server biometric state. Run `visa-cli config reset`, then `visa-cli setup`.");await Cd(e,!0,!0)}function oa(e){return async()=>{let t=await sa(e);return{success:t,...t?{}:{message:"Biometric recovery was not completed."}}}}async function F_(e){let r=Date.now()+3e5;for(;Date.now()<r;)try{let o=await globalThis.fetch(`${ke()}/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 xt(o,i=>{p.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 xt(void 0,s=>{p.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 sa(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(!ze(t))return!1;let n=cs.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 As(r.recoveryUrl),await F_(n),console.log(" Server biometric state cleared."),!0}function Yn(e){return`$${(e/100).toFixed(2)}`}function Td(e){return typeof e=="number"?Yn(e):"no cap"}function ta(e,t,n=!1){if(!e){let i=Yn(t);return n&&t>=0?`+${i}`:i}let r=(0,ls.fromWire)(e),o=r%10000n===0n?2:6,s=(0,ls.toDisplay)(r,{decimals:o});return n&&r>=0n?`+${s}`:s}function V_(e){return ta(e,0)}function H_(e){let t=`visa-cli-${z.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 q_(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=>O_.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 yd(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 _d(e){if(e===!1)return null;if(!e)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error("--total-cap must be a positive USD amount.");let n=Math.round(t*100);if(n<100||n>1e6)throw new Error("--total-cap must be between 1 and 10000 USD.");return n}var na=!1;async function Ed(e){let t=(0,ra.createInterface)({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function B_(e,t=!1){let n=yd(e);if(n!==void 0||t||!process.stdin.isTTY)return n;if(await qs("Use recommended API key caps ($5/day and $25 total)? Without caps, leaked keys can spend from prepaid balance until revoked.",!0))return na=!0,500;let o=await Ed("Daily cap USD (1-100): ");if(!o)throw new Error("--daily-cap is required when declining the recommended daily cap.");return yd(o)}async function K_(e,t=!1){let n=_d(e);if(n!==void 0||t||!process.stdin.isTTY)return n;if(na)return na=!1,2500;let r=await Ed("Cumulative cap USD (1-10000, default 25): ");return _d(r||"25")}function Ad(e){return e&&e.length>0?e.join(", "):"all tools"}function ia(e,t){return t||(typeof e!="number"||!Number.isFinite(e)?"price unknown":`$${(e/100).toFixed(2)}`)}function G_(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 Rd(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 Xi(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function W_(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 z_(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(`
169
+ `)):e}function Lr(e,t="global"){let n=t==="project"?M.join(process.cwd(),".mcp.json"):os(e);try{let r=M.dirname(n);j.existsSync(r)||j.mkdirSync(r,{recursive:!0});let o=Ki(e,t),s=md();if(o==="toml"){let i=j.existsSync(n)?j.readFileSync(n,"utf-8"):"",a=I_(i,"visa-cli",s);j.writeFileSync(n,a)}else{let i={};if(j.existsSync(n))try{i=JSON.parse(j.readFileSync(n,"utf-8"))}catch{i={}}i[e.configKey]=i[e.configKey]||{},i[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(s):s,j.writeFileSync(n,JSON.stringify(i,null,2)+`
170
+ `)}}catch(r){throw C_(r)?new Jn(e,n,r):r}return{installed:!0,configPath:n,message:e.postInstallHint}}function zi(e,t="global"){let n=t==="project"?M.join(process.cwd(),".mcp.json"):os(e);if(!j.existsSync(n))return{removed:!1,configPath:n};if(Ki(e,t)==="toml"){let i=j.readFileSync(n,"utf-8");return Wi(i,"visa-cli")?(j.writeFileSync(n,$_(i,"visa-cli")),{removed:!0,configPath:n}):{removed:!1,configPath:n}}let o;try{o=JSON.parse(j.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"],j.writeFileSync(n,JSON.stringify(o,null,2)+`
171
+ `),{removed:!0,configPath:n})}function pd(e,t="global"){let n=t==="project"?M.join(process.cwd(),".mcp.json"):os(e);if(!j.existsSync(n))return!1;if(Ki(e,t)==="toml")try{let o=j.readFileSync(n,"utf-8");return!!Wi(o,"visa-cli")}catch{return!1}try{return!!JSON.parse(j.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function P_(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 O_(e,t){if(e===t)return!0;let n=M.resolve(e),r=M.resolve(t);if(n===r)return!0;try{let o=j.realpathSync(n),s=j.realpathSync(r);return o===s}catch{return!1}}function Dr(){let e=md(),t=e.args[e.args.length-1],n=[];for(let r of Fe){let o=os(r);if(!j.existsSync(o))continue;let s=r.configFormat??"json",i;if(s==="toml")try{let l=j.readFileSync(o,"utf-8");i=Wi(l,"visa-cli")}catch{continue}else{let l;try{l=JSON.parse(j.readFileSync(o,"utf-8"))}catch{continue}i=l?.[r.configKey]?.["visa-cli"]}if(!i)continue;let a=P_(i);if(!a||O_(a,t))continue;let c=j.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:o,currentPath:a,expectedPath:t,staleReason:c})}return n}function Ji(e){return{configPath:Lr(e.client,"global").configPath}}var ea=(0,Td.promisify)(Cd.execFile);function Yi(){let e=st();setImmediate(()=>{Us(e,{getCommand:()=>mo(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 D_(e){let t=z.homedir(),n=o=>o.replace(t,"~"),r=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
172
+ ${r}: ${n(e.currentPath)}`}function Ed(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(D_(n))}function fd(e){console.log(` ! ${e.client.displayName} skipped: ${e.message}`)}function Ve(){this.help({error:!1})}var J=new kd.Command,U_=new Set(["pay",...Hi]),as=null,Ur=!1;function ae(){return as=new Ce(()=>F.getSessionToken()),as}function gd(e){if(e instanceof Xt)return!0;let t=e instanceof Error?e.message:"";return/attestation required|invalid signature|rotate biometric key|biometric key/i.test(t)}var hd=0,yd="",j_="attestation-key-rotation",F_="api-keys-create",_d=0,bd="";async function V_(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:hd,merchant:yd,context:j_})).toString("base64");return{signature:await bn(n,"verify Visa CLI Touch ID setup"),nonce:t,amount:hd,merchant:yd}}async function H_(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:_d,merchant:bd,context:F_})).toString("base64");return{signature:await bn(n,"create a Visa API token"),nonce:t,amount:_d,merchant:bd}}async function q_(e){let t=await e.getStatus();return t.attestationRequired!==!1||ze(t)}async function B_(e){let t=await Zl(),n=await V_(e);await e.registerAttestationKey(t,n)}async function Ad(e,t,n=!1){let r=await No();console.log(" Attestation key generated."),await e.registerAttestationKey(r),console.log(" Attestation key registered with server."),t&&(await e.setBiometricPreference({required:!0}),n&&p.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 Zi(e){if(!await sa(e))throw new Error("Could not clear stale server biometric state. Run `visa-cli config reset`, then `visa-cli setup`.");await Ad(e,!0,!0)}function oa(e){return async()=>{let t=await sa(e);return{success:t,...t?{}:{message:"Biometric recovery was not completed."}}}}async function K_(e){let r=Date.now()+3e5;for(;Date.now()<r;)try{let o=await globalThis.fetch(`${ke()}/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 kt(o,i=>{p.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 kt(void 0,s=>{p.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 sa(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(!ze(t))return!1;let n=cs.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 As(r.recoveryUrl),await K_(n),console.log(" Server biometric state cleared."),!0}function Yn(e){return`$${(e/100).toFixed(2)}`}function Rd(e){return typeof e=="number"?Yn(e):"no cap"}function ta(e,t,n=!1){if(!e){let i=Yn(t);return n&&t>=0?`+${i}`:i}let r=(0,ls.fromWire)(e),o=r%10000n===0n?2:6,s=(0,ls.toDisplay)(r,{decimals:o});return n&&r>=0n?`+${s}`:s}function G_(e){return ta(e,0)}function W_(e){let t=`visa-cli-${z.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 z_(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=>U_.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 vd(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 Sd(e){if(e===!1)return null;if(!e)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error("--total-cap must be a positive USD amount.");let n=Math.round(t*100);if(n<100||n>1e6)throw new Error("--total-cap must be between 1 and 10000 USD.");return n}var na=!1;async function Id(e){let t=(0,ra.createInterface)({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function J_(e,t=!1){let n=vd(e);if(n!==void 0||t||!process.stdin.isTTY)return n;if(await qs("Use recommended API key caps ($5/day and $25 total)? Without caps, leaked keys can spend from prepaid balance until revoked.",!0))return na=!0,500;let o=await Id("Daily cap USD (1-100): ");if(!o)throw new Error("--daily-cap is required when declining the recommended daily cap.");return vd(o)}async function Y_(e,t=!1){let n=Sd(e);if(n!==void 0||t||!process.stdin.isTTY)return n;if(na)return na=!1,2500;let r=await Id("Cumulative cap USD (1-10000, default 25): ");return Sd(r||"25")}function $d(e){return e&&e.length>0?e.join(", "):"all tools"}function ia(e,t){return t||(typeof e!="number"||!Number.isFinite(e)?"price unknown":`$${(e/100).toFixed(2)}`)}function Z_(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 Pd(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 Xi(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function X_(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 Q_(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(`
173
173
  Merchant tools
174
- `),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(` ${Xi(i.id,t).padEnd(t)} ${ia(i.priceCents,i.priceDisplay).padEnd(n)} ${Xi(i.category||"other",r).padEnd(r)} ${Xi(Rd(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 J_(e){console.log(`
174
+ `),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(` ${Xi(i.id,t).padEnd(t)} ${ia(i.priceCents,i.priceDisplay).padEnd(n)} ${Xi(i.category||"other",r).padEnd(r)} ${Xi(Pd(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 eb(e){console.log(`
175
175
  Merchant tools
176
- `);for(let[t,n]of W_(e)){console.log(t[0]?.toUpperCase()+t.slice(1));for(let r of n)console.log(` ${r.id.padEnd(28)} ${ia(r.priceCents,r.priceDisplay).padEnd(8)} ${r.description}`),console.log(` Params: ${Rd(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"
177
- `)}function aa(e,t={}){let n=t.format&&Qr(t.format)?t.format:void 0;if(t.json||n!==void 0){let i=t.command??"tool.run",a=n??"json",c,l=e?.content?.[0]?.text;typeof l=="string"&&(c=l);let u=Array.isArray(e?.urls)&&typeof e.urls[0]=="string"?e.urls[0]:void 0;if(!c&&u&&u.startsWith("data:")&&(c=u),c)try{let d=En(c);if(d){let f=typeof e?.merchantName=="string"?e.merchantName:"media",m=typeof e?.transactionId=="string"?`${f}-${e.transactionId}`:f,y=rr(d,{tag:m}),S=xs(i,e);S.success&&(S.filePath=y.filePath,S.mime=y.mime,S.bytes=y.bytes,u&&u.startsWith("data:")&&(S.urls=void 0)),ir(S,a);return}}catch(d){ir(or(i,`Failed to save inline media: ${d instanceof Error?d.message:String(d)}`),a),process.exitCode=$d;return}ir(xs(i,e),a);return}if(e?.content?.[0]?.text&&typeof e.content[0].text=="string"){try{let i=En(e.content[0].text);if(i){let a=typeof e?.merchantName=="string"?e.merchantName:"media",c=typeof e?.transactionId=="string"?`${a}-${e.transactionId}`:a,l=rr(i,{tag:c});console.log("Saved inline image to file:"),console.log(` ${l.filePath}`),console.log(` (${l.mime}, ${(l.bytes/1024).toFixed(1)} KB)`),console.log(` Open with: open "${l.filePath}"`);return}}catch(i){console.error(`(warning: could not save inline image to disk: ${i instanceof Error?i.message:String(i)})`)}console.log(e.content[0].text);return}let o=Array.isArray(e?.urls)?e.urls:Array.isArray(e?.receipt?.urls)?e.receipt.urls:[];if(e?.success===!1){let i=JSON.stringify(e,null,2);console.log("Result:"),console.log(i);return}if(console.log("Done"),typeof e?.merchantName=="string"&&console.log(`Merchant: ${e.merchantName}`),typeof e?.amount=="number"&&console.log(`Cost: $${e.amount.toFixed(2)}`),typeof e?.transactionId=="string"&&console.log(`Transaction: ${e.transactionId}`),o.length>0){console.log(`
176
+ `);for(let[t,n]of X_(e)){console.log(t[0]?.toUpperCase()+t.slice(1));for(let r of n)console.log(` ${r.id.padEnd(28)} ${ia(r.priceCents,r.priceDisplay).padEnd(8)} ${r.description}`),console.log(` Params: ${Pd(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"
177
+ `)}function aa(e,t={}){let n=t.format&&Qr(t.format)?t.format:void 0;if(t.json||n!==void 0){let i=t.command??"tool.run",a=n??"json",c,l=e?.content?.[0]?.text;typeof l=="string"&&(c=l);let u=Array.isArray(e?.urls)&&typeof e.urls[0]=="string"?e.urls[0]:void 0;if(!c&&u&&u.startsWith("data:")&&(c=u),c)try{let d=En(c);if(d){let f=typeof e?.merchantName=="string"?e.merchantName:"media",m=typeof e?.transactionId=="string"?`${f}-${e.transactionId}`:f,_=rr(d,{tag:m}),S=xs(i,e);S.success&&(S.filePath=_.filePath,S.mime=_.mime,S.bytes=_.bytes,u&&u.startsWith("data:")&&(S.urls=void 0)),ir(S,a);return}}catch(d){ir(or(i,`Failed to save inline media: ${d instanceof Error?d.message:String(d)}`),a),process.exitCode=Md;return}ir(xs(i,e),a);return}if(e?.content?.[0]?.text&&typeof e.content[0].text=="string"){try{let i=En(e.content[0].text);if(i){let a=typeof e?.merchantName=="string"?e.merchantName:"media",c=typeof e?.transactionId=="string"?`${a}-${e.transactionId}`:a,l=rr(i,{tag:c});console.log("Saved inline image to file:"),console.log(` ${l.filePath}`),console.log(` (${l.mime}, ${(l.bytes/1024).toFixed(1)} KB)`),console.log(` Open with: open "${l.filePath}"`);return}}catch(i){console.error(`(warning: could not save inline image to disk: ${i instanceof Error?i.message:String(i)})`)}console.log(e.content[0].text);return}let o=Array.isArray(e?.urls)?e.urls:Array.isArray(e?.receipt?.urls)?e.receipt.urls:[];if(e?.success===!1){let i=JSON.stringify(e,null,2);console.log("Result:"),console.log(i);return}if(console.log("Done"),typeof e?.merchantName=="string"&&console.log(`Merchant: ${e.merchantName}`),typeof e?.amount=="number"&&console.log(`Cost: $${e.amount.toFixed(2)}`),typeof e?.transactionId=="string"&&console.log(`Transaction: ${e.transactionId}`),o.length>0){console.log(`
178
178
  Result URLs:`);for(let i of o)console.log(` ${i}`);return}let s=JSON.stringify(e,null,2);s&&s!=="{}"&&(console.log(`
179
- Result:`),console.log(s))}var Y_=new Set(["INVALID_TOOL_PARAMS","MISSING_TOOL_ID","UNKNOWN_TOOL"]),Id=0,$d=1,Z_=2;function X_(e){if(e?.success!==!1)return Id;let n=(typeof e?.error_code=="string"?e.error_code:typeof e?.code=="string"?e.code:"").toUpperCase();return Y_.has(n)?Z_:$d}function ca(e){let t=X_(e);t!==Id&&(process.exitCode=t)}function Zn(e,t,n={}){let r=typeof n=="boolean"?{json:n}:n,o=t instanceof Error?t.message:String(t),s=r.format&&Qr(r.format)?r.format:void 0;if(r.json||s!==void 0){let i=s??"json";ir(or(e,o),i)}else console.error("Error:",o);process.exit(1)}async function Q_(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 Pd=100,Od=200;function vd(e){let t=Number.parseInt(e,10);return Number.isNaN(t)?Number.NaN:t}function ev(e){let t=typeof e.limit=="number"&&Number.isInteger(e.limit)?Math.max(1,Math.min(e.limit,Od)):Pd,n=typeof e.offset=="number"&&Number.isInteger(e.offset)?Math.max(0,e.offset):0;return{limit:t,offset:n}}function tv(e){let t=`
179
+ Result:`),console.log(s))}var tb=new Set(["INVALID_TOOL_PARAMS","MISSING_TOOL_ID","UNKNOWN_TOOL"]),Od=0,Md=1,nb=2;function rb(e){if(e?.success!==!1)return Od;let n=(typeof e?.error_code=="string"?e.error_code:typeof e?.code=="string"?e.code:"").toUpperCase();return tb.has(n)?nb:Md}function ca(e){let t=rb(e);t!==Od&&(process.exitCode=t)}function Zn(e,t,n={}){let r=typeof n=="boolean"?{json:n}:n,o=t instanceof Error?t.message:String(t),s=r.format&&Qr(r.format)?r.format:void 0;if(r.json||s!==void 0){let i=s??"json";ir(or(e,o),i)}else console.error("Error:",o);process.exit(1)}async function ob(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 Nd=100,Ld=200;function wd(e){let t=Number.parseInt(e,10);return Number.isNaN(t)?Number.NaN:t}function sb(e){let t=typeof e.limit=="number"&&Number.isInteger(e.limit)?Math.max(1,Math.min(e.limit,Ld)):Nd,n=typeof e.offset=="number"&&Number.isInteger(e.offset)?Math.max(0,e.offset):0;return{limit:t,offset:n}}function ib(e){let t=`
180
180
  Options:
181
181
  `,n=`
182
182
  Commands:
183
- `,r=e.indexOf(t),o=e.indexOf(n);if(r===-1||o===-1||r>o)return e;let s=f=>{let y=e.slice(f+1).search(/\n[A-Z][A-Za-z ]+:\n/);return y===-1?e.length:f+1+y},i=s(r),a=s(o),c=e.slice(0,r),l=e.slice(r,i),u=e.slice(o,a),d=e.slice(a);return`${c}${u}${l}${d}`}function nv(e){if(!e.startsWith("Usage: "))return e;let t=e.indexOf(`
183
+ `,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),c=e.slice(0,r),l=e.slice(r,i),u=e.slice(o,a),d=e.slice(a);return`${c}${u}${l}${d}`}function ab(e){if(!e.startsWith("Usage: "))return e;let t=e.indexOf(`
184
184
 
185
185
  `);if(t===-1)return e;let n=e.slice(0,t),r=e.slice(t+2),o=r.indexOf(`
186
186
 
@@ -188,16 +188,16 @@ Commands:
188
188
 
189
189
  ${n}
190
190
 
191
- ${i}`:e}function rv(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(`
192
- `).map(ov).join(`
193
- `);return`${n}${r}${s}`})}function ov(e){if(!e.startsWith(" "))return e;let n=2,r=n;for(;r<e.length&&e[r]!==" "&&e[r]!==" ";)r+=1;if(r===n)return e;let o=-1;for(let c=r;c<e.length-1;c+=1){if(e[c]!==" "||e[c+1]!==" ")continue;let l=c+2;for(;l<e.length&&e[l]===" ";)l+=1;if(l<e.length){o=l;break}}if(o===-1)return e;let s=e.slice(n,r),i=e.slice(o),a=Math.max(2,o-2-s.length);return` ${s}${" ".repeat(a)}${i}`}function sv(e){return e.replace(/^(Usage: .+?) \[options\](?= |$)/gm,"$1")}function iv(e){return e.replace(/^Options:$/gm,"Flags:")}function Md(e){let t=e.helpInformation.bind(e);e.helpInformation=()=>iv(sv(rv(tv(nv(t())))));for(let n of e.commands)Md(n)}function av(e){let t=new Map(e.map((r,o)=>[r,o]));J.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})}J.name("visa-cli").description("Visa CLI - set up MCP payments, manage credentials, and monitor AI spend").version(nr().version).addHelpCommand(!1).action(Ve);J.hook("preAction",async()=>{await $a()});J.command("setup").description("Register MCP server, authenticate, and generate attestation key").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--yes","Accept setup prompts without asking for unattended setup").option("--hud","Install the Visa HUD during setup without prompting").option("--no-hud","Skip installing the Visa HUD during setup").action(async e=>{let t=!1,n=()=>{t||(t=!0,console.log(`
191
+ ${i}`:e}function cb(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(`
192
+ `).map(lb).join(`
193
+ `);return`${n}${r}${s}`})}function lb(e){if(!e.startsWith(" "))return e;let n=2,r=n;for(;r<e.length&&e[r]!==" "&&e[r]!==" ";)r+=1;if(r===n)return e;let o=-1;for(let c=r;c<e.length-1;c+=1){if(e[c]!==" "||e[c+1]!==" ")continue;let l=c+2;for(;l<e.length&&e[l]===" ";)l+=1;if(l<e.length){o=l;break}}if(o===-1)return e;let s=e.slice(n,r),i=e.slice(o),a=Math.max(2,o-2-s.length);return` ${s}${" ".repeat(a)}${i}`}function ub(e){return e.replace(/^(Usage: .+?) \[options\](?= |$)/gm,"$1")}function db(e){return e.replace(/^Options:$/gm,"Flags:")}function Dd(e){let t=e.helpInformation.bind(e);e.helpInformation=()=>db(ub(cb(ib(ab(t())))));for(let n of e.commands)Dd(n)}function mb(e){let t=new Map(e.map((r,o)=>[r,o]));J.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})}J.name("visa-cli").description("Visa CLI - set up MCP payments, manage credentials, and monitor AI spend").version(nr().version).addHelpCommand(!1).action(Ve);J.hook("preAction",async()=>{await $a()});J.command("setup").description("Register MCP server, authenticate, and generate attestation key").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--yes","Accept setup prompts without asking for unattended setup").option("--hud","Install the Visa HUD during setup without prompting").option("--no-hud","Skip installing the Visa HUD during setup").action(async e=>{let t=!1,n=()=>{t||(t=!0,console.log(`
194
194
 
195
- Setup interrupted.`),console.log(" If you signed in via the browser but did not finish card enrollment, the"),console.log(" server-side enrollment may have expired. Re-run `visa-cli setup` \u2014 it will"),console.log(" resume from your current state or restart cleanly."),console.log(""),process.exit(130))};process.on("SIGINT",n);let r=()=>{process.removeListener("SIGINT",n)};try{if(e.check){let w=Dr();kd(w,"MCP config check:"),w.length>0&&(console.log("\nRun `visa-cli setup` (or `visa-cli install --repair`) to rewrite these entries."),r(),process.exit(1)),r();return}console.log("Step 1: Registering MCP server...");let o=Dr(),s=new Map(o.map(w=>[w.client.id,w])),i=new Set,a=new Set,c=new Set;for(let w of Fe)if(Nr(w)){let x;try{x=Lr(w)}catch(L){if(L instanceof Jn){dd(L),a.add(w.displayName),c.add(w.id);continue}throw L}let _=s.get(w.id),C=_?` \u2014 repaired stale ${_.staleReason} entry`:"";console.log(` \u2713 ${w.displayName} (${x.configPath.replace(z.homedir(),"~")})${C}`),_&&i.add(w.id)}let l=o.filter(w=>!i.has(w.client.id)&&!c.has(w.client.id)),u=0;for(let w of l){try{Ji(w)}catch(x){if(x instanceof Jn){dd(x),a.add(w.client.displayName),c.add(w.client.id);continue}throw x}console.log(` \u2713 ${w.client.displayName} (${w.configPath.replace(z.homedir(),"~")}) \u2014 repaired stale ${w.staleReason} entry`),u++}let d=i.size+u;d===0&&a.size===0?console.log(" \u2713 MCP config verified \u2014 nothing to repair."):d>0&&console.log(` \u2713 Repaired ${d} stale MCP config ${d===1?"entry":"entries"}.`),a.size>0&&console.log(` ! Skipped MCP registration for: ${Array.from(a).join(", ")}. Rerun with access to those config files to complete registration.`),console.log(`
196
- Step 2: Checking authentication...`);let f=await F.getSessionToken();if(f)try{await new Ce(()=>Promise.resolve(f)).getStatus(),console.log(" Already authenticated.")}catch(w){let x=w instanceof Error?w.message:"";x.includes("session has expired")||x.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await F.clearAll(),f=null):console.log(` Couldn't verify session (${x||"unknown error"}) \u2014 continuing with existing token.`)}if(!f){let w=null;try{let{stdout:x}=await ea("gh",["auth","token"],{timeout:5e3});w=x.trim()}catch{}if(w||(w=process.env.GITHUB_TOKEN||null),w)try{console.log(" Found GitHub token \u2014 attempting headless login...");let x=await globalThis.fetch(`${ke()}/v1/auth/token-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({github_token:w}),signal:AbortSignal.timeout(1e4)});if(x.ok){let _=await x.json();if(_.success&&_.sessionToken){let C=_.sessionToken;f=C,await F.saveSessionToken(C),console.log(` Signed in as ${_.user} (headless).`)}}else(await x.json().catch(()=>({}))).hint==="card_required"&&console.log(" GitHub token valid but no card on file \u2014 opening browser to finish onboarding...")}catch{}}if(f||(console.log(" No session found. Opening browser for GitHub login..."),f=await new Promise(async(w,x)=>{let _=cs.randomUUID(),C=`${ke()}/login?state=${_}`;await As(C);let L=3e4,Oe=300*1e3,Bt=Date.now()+Oe;for(;Date.now()<Bt;)try{let xe=await globalThis.fetch(`${ke()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:_,timeout:L}),signal:AbortSignal.timeout(L+5e3)});if(!xe.ok){await xt(xe,se=>{p.warn("auth_status:retry_after_http_error",{status:xe.status,delayMs:se})});continue}let K=await xe.json();if(K.status==="pending")continue;if(K.status==="expired"){x(new Error("Session expired. Please run setup again."));return}if(K.status==="complete"&&K.sessionToken){console.log(` Signed in as ${K.user}.`),w(K.sessionToken);return}}catch{await xt(void 0,xe=>{p.warn("auth_status:retry_after_network_error",{delayMs:xe})})}x(new Error("Login timed out after 5 minutes. Please run setup again."))}),await F.saveSessionToken(f),console.log(" Session token saved.")),console.log(`
197
- Step 3: Setting up authentication...`),!re())console.log(" Not macOS \u2014 skipping biometric setup.");else{try{await ea("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 w=ce();try{let x=await w.getStatus(),_=!0;if(ze(x))if(await Lo())try{await j_(w),console.log(" Attestation key already registered with server."),console.log(" Existing local Touch ID key verified and preserved."),_=!1}catch(C){if(!md(C))throw C;console.log(" Existing local Touch ID key does not match server biometric state."),await Zi(w),_=!1}else console.log(" Server already has a biometric key, but this device has no local key."),await Zi(w),_=!1;_&&await Cd(w,x.attestationRequired===!1)}catch(x){let _=x?.message||"unknown error";if(md(x)){console.log(" Server already has a biometric key for this account, but this device cannot prove access to it.");let C=!1;try{await Zi(w),C=!0}catch(L){console.error(` Biometric recovery failed: ${L?.message||"unknown error"}`)}if(!C){let L=x instanceof Xt&&x.hint?x.hint:"Run `visa-cli config reset` to clear server-side biometric state through GitHub, then run `visa-cli setup` again.";console.error(` ${L}`),process.exit(1)}}else console.error(` Biometric setup failed: ${_}`),process.exit(1)}}let m=st(),y=Y.existsSync(Pe.join(z.homedir(),".claude.json")),S=e.hud===!0;if(e.hud===void 0&&y&&!e.yes&&process.stdin.isTTY&&(console.log(`
198
- Step 4: Visa HUD`),console.log(" Pin balance, card, spend, model, and session activity below the Claude Code input."),console.log(Dc()),S=await qs(" Install the Visa HUD now?",!1)),S)if(!y)console.log(`
195
+ Setup interrupted.`),console.log(" If you signed in via the browser but did not finish card enrollment, the"),console.log(" server-side enrollment may have expired. Re-run `visa-cli setup` \u2014 it will"),console.log(" resume from your current state or restart cleanly."),console.log(""),process.exit(130))};process.on("SIGINT",n);let r=()=>{process.removeListener("SIGINT",n)};try{if(e.check){let w=Dr();Ed(w,"MCP config check:"),w.length>0&&(console.log("\nRun `visa-cli setup` (or `visa-cli install --repair`) to rewrite these entries."),r(),process.exit(1)),r();return}console.log("Step 1: Registering MCP server...");let o=Dr(),s=new Map(o.map(w=>[w.client.id,w])),i=new Set,a=new Set,c=new Set;for(let w of Fe)if(Nr(w)){let x;try{x=Lr(w)}catch(L){if(L instanceof Jn){fd(L),a.add(w.displayName),c.add(w.id);continue}throw L}let y=s.get(w.id),k=y?` \u2014 repaired stale ${y.staleReason} entry`:"";console.log(` \u2713 ${w.displayName} (${x.configPath.replace(z.homedir(),"~")})${k}`),y&&i.add(w.id)}let l=o.filter(w=>!i.has(w.client.id)&&!c.has(w.client.id)),u=0;for(let w of l){try{Ji(w)}catch(x){if(x instanceof Jn){fd(x),a.add(w.client.displayName),c.add(w.client.id);continue}throw x}console.log(` \u2713 ${w.client.displayName} (${w.configPath.replace(z.homedir(),"~")}) \u2014 repaired stale ${w.staleReason} entry`),u++}let d=i.size+u;d===0&&a.size===0?console.log(" \u2713 MCP config verified \u2014 nothing to repair."):d>0&&console.log(` \u2713 Repaired ${d} stale MCP config ${d===1?"entry":"entries"}.`),a.size>0&&console.log(` ! Skipped MCP registration for: ${Array.from(a).join(", ")}. Rerun with access to those config files to complete registration.`),console.log(`
196
+ Step 2: Checking authentication...`);let f=await F.getSessionToken();if(f)try{await new Ce(()=>Promise.resolve(f)).getStatus(),console.log(" Already authenticated.")}catch(w){let x=w instanceof Error?w.message:"";x.includes("session has expired")||x.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await F.clearAll(),f=null):console.log(` Couldn't verify session (${x||"unknown error"}) \u2014 continuing with existing token.`)}if(!f){let w=null;try{let{stdout:x}=await ea("gh",["auth","token"],{timeout:5e3});w=x.trim()}catch{}if(w||(w=process.env.GITHUB_TOKEN||null),w)try{console.log(" Found GitHub token \u2014 attempting headless login...");let x=await globalThis.fetch(`${ke()}/v1/auth/token-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({github_token:w}),signal:AbortSignal.timeout(1e4)});if(x.ok){let y=await x.json();if(y.success&&y.sessionToken){let k=y.sessionToken;f=k,await F.saveSessionToken(k),console.log(` Signed in as ${y.user} (headless).`)}}else(await x.json().catch(()=>({}))).hint==="card_required"&&console.log(" GitHub token valid but no card on file \u2014 opening browser to finish onboarding...")}catch{}}if(f||(console.log(" No session found. Opening browser for GitHub login..."),f=await new Promise(async(w,x)=>{let y=cs.randomUUID(),k=`${ke()}/login?state=${y}`;await As(k);let L=3e4,Oe=300*1e3,Bt=Date.now()+Oe;for(;Date.now()<Bt;)try{let xe=await globalThis.fetch(`${ke()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:y,timeout:L}),signal:AbortSignal.timeout(L+5e3)});if(!xe.ok){await kt(xe,se=>{p.warn("auth_status:retry_after_http_error",{status:xe.status,delayMs:se})});continue}let K=await xe.json();if(K.status==="pending")continue;if(K.status==="expired"){x(new Error("Session expired. Please run setup again."));return}if(K.status==="complete"&&K.sessionToken){console.log(` Signed in as ${K.user}.`),w(K.sessionToken);return}}catch{await kt(void 0,xe=>{p.warn("auth_status:retry_after_network_error",{delayMs:xe})})}x(new Error("Login timed out after 5 minutes. Please run setup again."))}),await F.saveSessionToken(f),console.log(" Session token saved.")),console.log(`
197
+ Step 3: Setting up authentication...`),re()){try{await ea("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 w=ae();try{let x=await w.getStatus(),y=!0;if(ze(x))if(await Lo())try{await B_(w),console.log(" Attestation key already registered with server."),console.log(" Existing local Touch ID key verified and preserved."),y=!1}catch(k){if(!gd(k))throw k;console.log(" Existing local Touch ID key does not match server biometric state."),await Zi(w),y=!1}else console.log(" Server already has a biometric key, but this device has no local key."),await Zi(w),y=!1;y&&await Ad(w,x.attestationRequired===!1)}catch(x){let y=x?.message||"unknown error";if(gd(x)){console.log(" Server already has a biometric key for this account, but this device cannot prove access to it.");let k=!1;try{await Zi(w),k=!0}catch(L){console.error(` Biometric recovery failed: ${L?.message||"unknown error"}`)}if(!k){let L=x instanceof Xt&&x.hint?x.hint:"Run `visa-cli config reset` to clear server-side biometric state through GitHub, then run `visa-cli setup` again.";console.error(` ${L}`),process.exit(1)}}else console.error(` Biometric setup failed: ${y}`),process.exit(1)}}else{let w=ae(),x;try{x=await w.getStatus()}catch(k){console.error(" Biometric attestation (Touch ID or Windows Hello) is unavailable in this process."),console.error(` Could not verify server biometric policy: ${k?.message||"unknown error"}`),console.error(" Re-run setup from an interactive device with Touch ID (Mac) or Windows Hello (PC) before using payment commands."),process.exit(1)}let y=id(x);y.canContinue||(console.error(` ${y.message}`),y.hint&&console.error(` ${y.hint}`),process.exit(1)),console.log(` ${y.message}`)}let m=st(),_=Y.existsSync(Pe.join(z.homedir(),".claude.json")),S=e.hud===!0;if(e.hud===void 0&&_&&!e.yes&&process.stdin.isTTY&&(console.log(`
198
+ Step 4: Visa HUD`),console.log(" Pin balance, card, spend, model, and session activity below the Claude Code input."),console.log(Dc()),S=await qs(" Install the Visa HUD now?",!1)),S)if(!_)console.log(`
199
199
  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(`
200
- Step 4: Enabling the Visa spend HUD...`);let w=pr(m),x=w.installed==="new"||w.installed==="already-visa"||w.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${x}${w.message}`);try{let _=ce(),C=await _.getStatus(),L={currentVersion:_.getClientVersion(),latestVersion:_.lastSignals?.updateAvailable?.latestVersion,updateCheckDisabled:Be()},Oe=Os(C,L);Ms(Oe,C),console.log(` Preview: ${Oe.split(`
200
+ Step 4: Enabling the Visa spend HUD...`);let w=pr(m),x=w.installed==="new"||w.installed==="already-visa"||w.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${x}${w.message}`);try{let y=ae(),k=await y.getStatus(),L={currentVersion:y.getClientVersion(),latestVersion:y.lastSignals?.updateAvailable?.latestVersion,updateCheckDisabled:Be()},Oe=Os(k,L);Ms(Oe,k),console.log(` Preview: ${Oe.split(`
201
201
  `)[0]}`)}catch{}}else e.hud!==!1&&(console.log(`
202
202
  Step 4: Visa HUD not installed.`),console.log(" Enable later with: visa-cli config hud enable"));let $="\x1B[1m",H="\x1B[2m",U="\x1B[0m";console.log(`
203
203
  \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
@@ -227,61 +227,61 @@ Step 4: Visa HUD not installed.`),console.log(" Enable later with: visa-cli co
227
227
 
228
228
  ${$}Verify:${U} visa-cli status
229
229
  ${$}Docs:${U} https://visacli.sh
230
- `),r()}catch(o){console.error("Error:",o.message),r(),process.exit(1)}});J.command("install [client]",{hidden:!0}).description("Register MCP server with an AI client (claude, cursor, windsurf, cline, zed, ...)").option("--all","Install for all detected clients").option("--list","Show supported clients and install status").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--repair","Repair stale MCP client configs without re-running the full setup flow").option("--scope <scope>","Install scope: global or project","global").action(async(e,t)=>{try{if(t.check){let s=Dr();kd(s,"MCP config check:"),s.length>0&&process.exit(1);return}if(t.repair){let s=Dr();if(s.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of s)Ji(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(z.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
230
+ `),r()}catch(o){console.error("Error:",o.message),r(),process.exit(1)}});J.command("install [client]",{hidden:!0}).description("Register MCP server with an AI client (claude, cursor, windsurf, cline, zed, ...)").option("--all","Install for all detected clients").option("--list","Show supported clients and install status").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--repair","Repair stale MCP client configs without re-running the full setup flow").option("--scope <scope>","Install scope: global or project","global").action(async(e,t)=>{try{if(t.check){let s=Dr();Ed(s,"MCP config check:"),s.length>0&&process.exit(1);return}if(t.repair){let s=Dr();if(s.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of s)Ji(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(z.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
231
231
  Repaired ${s.length} stale MCP config ${s.length===1?"entry":"entries"}.`);return}if(t.list){console.log(`
232
232
  \x1B[1mSupported MCP Clients\x1B[0m
233
- `),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 Fe){let c=Nr(a),l=ud(a),u=c?"Yes":"No",d=l?"Yes":"No",f=a.globalConfigPath.replace(z.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 Fe){if(!Nr(a)){i.push(a.displayName);continue}Lr(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(`
234
- Supported clients: ${Fe.map(s=>s.id).join(", ")}`),process.exit(1));let r=Bi(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${Fe.map(s=>s.id).join(", ")}`),process.exit(1)),n==="global"&&!Nr(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let o=Lr(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)}});J.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{Ur=!1;try{let e=ce(),[t,n]=await Promise.all([e.getStatus(),e.getTransactions().catch(o=>{if(process.env.VISA_CLI_DEBUG){let s=o instanceof Error?o.message:String(o);process.stderr.write(`[visa-cli] getTransactions failed (HUD will omit): ${s}
235
- `)}return{transactions:[]}})]),r={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:Be()};process.stdout.write(td(t,Array.isArray(n?.transactions)?n.transactions:[],re(),r)),Ur=!0}catch(e){Ur=!1,console.error("Error:",e.message),process.exit(1)}});function cv(e){let t=e.map(nd),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(`
233
+ `),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 Fe){let c=Nr(a),l=pd(a),u=c?"Yes":"No",d=l?"Yes":"No",f=a.globalConfigPath.replace(z.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 Fe){if(!Nr(a)){i.push(a.displayName);continue}Lr(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(`
234
+ Supported clients: ${Fe.map(s=>s.id).join(", ")}`),process.exit(1));let r=Bi(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${Fe.map(s=>s.id).join(", ")}`),process.exit(1)),n==="global"&&!Nr(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let o=Lr(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)}});J.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{Ur=!1;try{let e=ae(),[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}
235
+ `)}return{transactions:[]}})]),r={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:Be()};process.stdout.write(rd(t,Array.isArray(n?.transactions)?n.transactions:[],re(),r)),Ur=!0}catch(e){Ur=!1,console.error("Error:",e.message),process.exit(1)}});function pb(e){let t=e.map(od),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(`
236
236
  Cards
237
237
  `),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(`
238
238
  Use:`),console.log(" visa-cli cards default <id>"),console.log(` visa-cli cards remove <id>
239
- `)}async function Nd(e,t){if(t.yes)return"confirmed";if(!process.stdin.isTTY)return"refused-non-tty";let n=(0,ra.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 us=J.command("cards").description("Manage enrolled payment cards").addHelpCommand(!1).action(Ve);us.command("list").alias("ls").description("List enrolled payment cards").action(async()=>{try{let e=await De.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}cv(t)}catch(e){console.error("Error:",e.message),process.exit(1)}});us.command("add").description("Add a new Visa card").action(async()=>{try{let e=await De.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)}});us.command("remove <card-id>").alias("rm").description("Remove an enrolled card").option("-y, --yes","Skip the interactive confirmation prompt").action(async(e,t)=>{try{let n=Di(e),r=await Nd(`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 De.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)}});us.command("default <card-id>").alias("set-default").description("Set the default payment card").action(async e=>{try{let t=Di(e),n=await De.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 la=J.command("tokens",{hidden:!0}).description("Create and manage API tokens for apps and agents").addHelpCommand(!1).action(Ve);function ua(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)}function lv(e){let t=e instanceof Error?e.message:String(e);return t.includes("EMPLOYEE_ONLY_FEATURE")||t.includes("Visa Key management is limited to approved rollout users")||t.includes("Token management is restricted to Visa employees")}async function da(e){let t=Object.prototype.hasOwnProperty.call(process.env,"VISA_CLI_API_KEY"),n=process.env.VISA_CLI_API_KEY;delete process.env.VISA_CLI_API_KEY;try{return await e()}finally{t&&(process.env.VISA_CLI_API_KEY=n)}}la.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").option("--total-cap <usd>","Cumulative cap in USD, between 1 and 10000").option("--no-total-cap","Create without a cumulative cap (higher risk; daily cap still applies)").option("--json","Output raw JSON").action(async(e,t)=>{try{let n=await B_(t.dailyCap,t.json),r=await K_(t.totalCap,t.json),o=await da(async()=>{let s=ce(),i={label:H_(e),allowed_tools:q_(t.tools),daily_cap_cents:n,total_cap_cents:r};return await U_(s)?await Bn(s,async()=>{let a=await D_(s);return s.createAppApiKey({...i,attestation:a})},oa(s)):await s.createAppApiKey(i)});if(t.json){console.log(JSON.stringify(o,null,2));return}console.log("API token created."),console.log(""),console.log(`Key: ${o.key}`),console.log(`Label: ${o.label}`),console.log(`Owner: ${o.owner}`),console.log(`Allowed tools: ${Ad(o.allowed_tools)}`),console.log(`Daily cap: ${Yn(o.daily_cap_cents)}/day`),console.log(`Total cap: ${Td(o.total_cap_cents)}`),console.log(""),console.log("Store this key now. It will not be shown again."),console.log(""),o.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("")):o.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("Direct execution flow:"),console.log(` curl -X POST ${ke()}/v1/api/tools/or-gpt-4o-mini/execute \\`),console.log(` -H "X-Api-Key: ${o.key}" \\`),console.log(' -H "Idempotency-Key: idem-at-least-16" \\'),console.log(' -H "Content-Type: application/json" \\'),console.log(` -d '{"input":{"messages":[{"role":"user","content":"Say hello in one sentence."}]}}'`),console.log(""),console.log("This key spends from your prepaid balance directly. Account/key caps"),console.log("enforce limits; there is no public session to open, track, or close.")}catch(n){ua(n)}});la.command("list").description("List API tokens for the authenticated user").option("--json","Output raw JSON").action(async e=>{try{let t=await da(async()=>await ce().listAppApiKeys());if(e.json){console.log(JSON.stringify(t,null,2));return}let n=t.keys||[];if(n.length===0){console.log("No API tokens found. Create one with: visa-cli tokens create");return}console.log("API tokens"),console.log("");for(let r of n)console.log(`${r.id}. ${r.label} (${r.key_prefix})`),console.log(` Status: ${r.status}`),console.log(` Owner: ${r.owner}`),console.log(` Allowed tools: ${Ad(r.allowed_tools)}`),console.log(` Daily cap: ${Yn(r.daily_cap_cents)}/day`),console.log(` Total cap: ${Td(r.total_cap_cents)}`),console.log(` Last used: ${r.last_used_at||"never"}`)}catch(t){ua(t)}});la.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 n=await da(async()=>await ce().revokeAppApiKey(t));console.log(`Revoked API token ${n.revoked}.`)}catch(t){ua(t)}});async function Ld(){try{console.log(`Resetting Visa CLI...
240
- `);let e=ce();await sa(e);try{await e.logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}if(await F.clearAll(),console.log(" Keychain credentials cleared."),re())try{await Do(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}console.log(`
241
- Reset complete.`)}catch(e){console.error("Error:",e.message),process.exit(1)}}J.command("reset",{hidden:!0}).description("Deprecated alias for `config reset`").action(Ld);var ma=J.command("balance").description("Manage prepaid balance").addHelpCommand(!1).action(Ve);ma.command("show").description("Show prepaid balance + recent ledger entries").action(async()=>{try{let t=await new Ce(()=>F.getSessionToken()).getBalance();if(console.log(`
239
+ `)}async function Ud(e,t){if(t.yes)return"confirmed";if(!process.stdin.isTTY)return"refused-non-tty";let n=(0,ra.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 us=J.command("cards").description("Manage enrolled payment cards").addHelpCommand(!1).action(Ve);us.command("list").alias("ls").description("List enrolled payment cards").action(async()=>{try{let e=await De.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}pb(t)}catch(e){console.error("Error:",e.message),process.exit(1)}});us.command("add").description("Add a new Visa card").action(async()=>{try{let e=await De.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)}});us.command("remove <card-id>").alias("rm").description("Remove an enrolled card").option("-y, --yes","Skip the interactive confirmation prompt").action(async(e,t)=>{try{let n=Di(e),r=await Ud(`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 De.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)}});us.command("default <card-id>").alias("set-default").description("Set the default payment card").action(async e=>{try{let t=Di(e),n=await De.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 la=J.command("tokens",{hidden:!0}).description("Create and manage API tokens for apps and agents").addHelpCommand(!1).action(Ve);function ua(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)}function fb(e){let t=e instanceof Error?e.message:String(e);return t.includes("EMPLOYEE_ONLY_FEATURE")||t.includes("Visa Key management is limited to approved rollout users")||t.includes("Token management is restricted to Visa employees")}async function da(e){let t=Object.prototype.hasOwnProperty.call(process.env,"VISA_CLI_API_KEY"),n=process.env.VISA_CLI_API_KEY;delete process.env.VISA_CLI_API_KEY;try{return await e()}finally{t&&(process.env.VISA_CLI_API_KEY=n)}}la.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").option("--total-cap <usd>","Cumulative cap in USD, between 1 and 10000").option("--no-total-cap","Create without a cumulative cap (higher risk; daily cap still applies)").option("--json","Output raw JSON").action(async(e,t)=>{try{let n=await J_(t.dailyCap,t.json),r=await Y_(t.totalCap,t.json),o=await da(async()=>{let s=ae(),i={label:W_(e),allowed_tools:z_(t.tools),daily_cap_cents:n,total_cap_cents:r};return await q_(s)?await Bn(s,async()=>{let a=await H_(s);return s.createAppApiKey({...i,attestation:a})},oa(s)):await s.createAppApiKey(i)});if(t.json){console.log(JSON.stringify(o,null,2));return}console.log("API token created."),console.log(""),console.log(`Key: ${o.key}`),console.log(`Label: ${o.label}`),console.log(`Owner: ${o.owner}`),console.log(`Allowed tools: ${$d(o.allowed_tools)}`),console.log(`Daily cap: ${Yn(o.daily_cap_cents)}/day`),console.log(`Total cap: ${Rd(o.total_cap_cents)}`),console.log(""),console.log("Store this key now. It will not be shown again."),console.log(""),o.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("")):o.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("Direct execution flow:"),console.log(` curl -X POST ${ke()}/v1/api/tools/or-gpt-4o-mini/execute \\`),console.log(` -H "X-Api-Key: ${o.key}" \\`),console.log(' -H "Idempotency-Key: idem-at-least-16" \\'),console.log(' -H "Content-Type: application/json" \\'),console.log(` -d '{"input":{"messages":[{"role":"user","content":"Say hello in one sentence."}]}}'`),console.log(""),console.log("This key spends from your prepaid balance directly. Account/key caps"),console.log("enforce limits; there is no public session to open, track, or close.")}catch(n){ua(n)}});la.command("list").description("List API tokens for the authenticated user").option("--json","Output raw JSON").action(async e=>{try{let t=await da(async()=>await ae().listAppApiKeys());if(e.json){console.log(JSON.stringify(t,null,2));return}let n=t.keys||[];if(n.length===0){console.log("No API tokens found. Create one with: visa-cli tokens create");return}console.log("API tokens"),console.log("");for(let r of n)console.log(`${r.id}. ${r.label} (${r.key_prefix})`),console.log(` Status: ${r.status}`),console.log(` Owner: ${r.owner}`),console.log(` Allowed tools: ${$d(r.allowed_tools)}`),console.log(` Daily cap: ${Yn(r.daily_cap_cents)}/day`),console.log(` Total cap: ${Rd(r.total_cap_cents)}`),console.log(` Last used: ${r.last_used_at||"never"}`)}catch(t){ua(t)}});la.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 n=await da(async()=>await ae().revokeAppApiKey(t));console.log(`Revoked API token ${n.revoked}.`)}catch(t){ua(t)}});async function jd(){try{console.log(`Resetting Visa CLI...
240
+ `);let e=ae();await sa(e);try{await e.logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}if(await F.clearAll(),console.log(" Keychain credentials cleared."),re())try{await Do(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}console.log(`
241
+ Reset complete.`)}catch(e){console.error("Error:",e.message),process.exit(1)}}J.command("reset",{hidden:!0}).description("Deprecated alias for `config reset`").action(jd);var ma=J.command("balance").description("Manage prepaid balance").addHelpCommand(!1).action(Ve);ma.command("show").description("Show prepaid balance + recent ledger entries").action(async()=>{try{let t=await new Ce(()=>F.getSessionToken()).getBalance();if(console.log(`
242
242
  Balance: ${ta(t.balanceMicros,t.balanceCents)}
243
243
  `),t.ledger.length===0){console.log(` (no ledger entries \u2014 top up to begin: visa-cli balance topup --amount 5)
244
- `);return}let n=t.ledger.slice(0,20),r=[],o=t.balanceCents,s=t.balanceMicros?BigInt(t.balanceMicros):null;for(let u of n)r.push(s!=null?s.toString():String(o*1e4)),s!=null&&u.deltaMicros?s-=BigInt(u.deltaMicros):(s=null,o-=u.deltaCents);let i=19,a=11,c=13,l=18;console.log(` ${"TIMESTAMP".padEnd(i)} ${"DELTA".padStart(a)} ${"BALANCE".padStart(c)} ${"REASON".padEnd(l)} TOOL`),console.log(` ${"\u2500".repeat(i)} ${"\u2500".repeat(a)} ${"\u2500".repeat(c)} ${"\u2500".repeat(l)} ${"\u2500".repeat(20)}`),n.forEach((u,d)=>{let f=(u.createdAt||"").slice(0,19),m=ta(u.deltaMicros,u.deltaCents,!0),y=V_(r[d]),S=(u.reason??"").slice(0,l),$=u.toolName??"";console.log(` ${f.padEnd(i)} ${m.padStart(a)} ${y.padStart(c)} ${S.padEnd(l)} ${$}`)}),console.log()}catch(e){e instanceof at&&(console.error(`Top-up pending reconciliation [${e.code}]: ${e.message}`),e.transactionId&&console.error(`Transaction: ${e.transactionId}`),process.exit(1)),console.error("Error:",e.message),process.exit(1)}});ma.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=Wo(e.amount);if(!t.ok)throw new Error(t.error);let n=t.cents,r=n/100,o=new Ce(()=>F.getSessionToken());if(!re())throw new Error(zo);let s=cs.randomUUID(),i=await Bn(o,async()=>{let a;if(re()){let{nonce:c}=await o.getAttestationChallenge(),l=Buffer.from(JSON.stringify({nonce:c,amount:r,merchant:"Visa CLI Balance",context:"balance-topup"})).toString("base64");a={signature:await vn(l,`top up balance with $${t.displayUsd}`),nonce:c,amount:r,merchant:"Visa CLI Balance"}}return o.topupBalance({amount_cents:n,idempotency_key:s,attestation:a})},oa(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}`),ic();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 Dd=ma.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(Ve);Dd.command("show").description("Show current auto-topup configuration").action(async()=>{try{let t=await new Ce(()=>F.getSessionToken()).getAutoTopup();if(t.targetCents==null||t.targetCents===0){console.log(`
244
+ `);return}let n=t.ledger.slice(0,20),r=[],o=t.balanceCents,s=t.balanceMicros?BigInt(t.balanceMicros):null;for(let u of n)r.push(s!=null?s.toString():String(o*1e4)),s!=null&&u.deltaMicros?s-=BigInt(u.deltaMicros):(s=null,o-=u.deltaCents);let i=19,a=11,c=13,l=18;console.log(` ${"TIMESTAMP".padEnd(i)} ${"DELTA".padStart(a)} ${"BALANCE".padStart(c)} ${"REASON".padEnd(l)} TOOL`),console.log(` ${"\u2500".repeat(i)} ${"\u2500".repeat(a)} ${"\u2500".repeat(c)} ${"\u2500".repeat(l)} ${"\u2500".repeat(20)}`),n.forEach((u,d)=>{let f=(u.createdAt||"").slice(0,19),m=ta(u.deltaMicros,u.deltaCents,!0),_=G_(r[d]),S=(u.reason??"").slice(0,l),$=u.toolName??"";console.log(` ${f.padEnd(i)} ${m.padStart(a)} ${_.padStart(c)} ${S.padEnd(l)} ${$}`)}),console.log()}catch(e){e instanceof at&&(console.error(`Top-up pending reconciliation [${e.code}]: ${e.message}`),e.transactionId&&console.error(`Transaction: ${e.transactionId}`),process.exit(1)),console.error("Error:",e.message),process.exit(1)}});ma.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=Wo(e.amount);if(!t.ok)throw new Error(t.error);let n=t.cents,r=n/100,o=new Ce(()=>F.getSessionToken());if(!re())throw new Error(zo);let s=cs.randomUUID(),i=await Bn(o,async()=>{let a;if(re()){let{nonce:c}=await o.getAttestationChallenge(),l=Buffer.from(JSON.stringify({nonce:c,amount:r,merchant:"Visa CLI Balance",context:"balance-topup"})).toString("base64");a={signature:await bn(l,`top up balance with $${t.displayUsd}`),nonce:c,amount:r,merchant:"Visa CLI Balance"}}return o.topupBalance({amount_cents:n,idempotency_key:s,attestation:a})},oa(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}`),ic();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 Fd=ma.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(Ve);Fd.command("show").description("Show current auto-topup configuration").action(async()=>{try{let t=await new Ce(()=>F.getSessionToken()).getAutoTopup();if(t.targetCents==null||t.targetCents===0){console.log(`
245
245
  Auto-topup: disabled
246
- `);return}let n=Yn(t.targetCents),r=Yn(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)}});Dd.command("disable").description("Disable auto-topup").action(async()=>{try{let t=await new Ce(()=>F.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 uv=J.command("session",{hidden:!0}).description("Inspect session budgets");uv.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 Ce(()=>F.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(`
246
+ `);return}let n=Yn(t.targetCents),r=Yn(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)}});Fd.command("disable").description("Disable auto-topup").action(async()=>{try{let t=await new Ce(()=>F.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 gb=J.command("session",{hidden:!0}).description("Inspect session budgets");gb.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 Ce(()=>F.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(`
247
247
  Session: ${e}`),o){let i=(o.totalCents/100).toFixed(2),a=(o.cumulativeCents/100).toFixed(2),c=(o.remainingCents/100).toFixed(2);console.log(` Status: ${o.status}${o.expired?" (expired)":""}`),console.log(` Budget: $${i} \xB7 spent $${a} \xB7 remaining $${c}`),console.log(` Created: ${o.createdAt}`),console.log(` Expires: ${o.expiresAt}`)}if(s?.ledger?.length){console.log(`
248
248
  PSP References (CyberSource activity):`);let i=8,a=9,c=36;console.log(` ${"TYPE".padEnd(i)} ${"AMOUNT".padStart(a)} ${"CYBERSOURCE TX ID".padEnd(c)} CREATED`),console.log(` ${"\u2500".repeat(i)} ${"\u2500".repeat(a)} ${"\u2500".repeat(c)} ${"\u2500".repeat(19)}`);for(let l of s.ledger){let u=`$${(l.amountCents/100).toFixed(2)}`;console.log(` ${l.type.padEnd(i)} ${u.padStart(a)} ${(l.transactionId||"").padEnd(c)} ${(l.createdAt||"").slice(0,19)}`)}}else o&&console.log(`
249
- (no PSP references yet \u2014 no holds placed)`);console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});async function Ud(e){(!e||e.trim().length===0)&&(console.log('Usage: visa-cli feedback "your message"'),process.exit(1));try{await F.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await ce().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}}J.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action(Ud);J.command("update").description("Update Visa CLI to the latest stable version").action(async()=>{let e=Fi(void 0,void 0,void 0,{withDiagnostics:!0}),t=e.diagnostics?Vi(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 ea(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=Us(st(),{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 nt=J.command("config").description("Manage CLI configuration and local integrations").addHelpCommand(!1).action(Ve);function jd(e){return[Pe.join(e,".zshrc"),Pe.join(e,".bashrc"),Pe.join(e,".bash_profile"),Pe.join(e,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),Pe.join(e,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),Pe.join(e,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),Pe.join(e,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),Pe.join(e,".config","powershell","Microsoft.PowerShell_profile.ps1")]}function dv(e){let t=new Map;for(let n of jd(e))try{Y.existsSync(n)&&t.set(n,Y.readFileSync(n,"utf-8"))}catch{}return t}function mv(e){let t=[];for(let[n,r]of e)try{(Y.existsSync(n)?Y.readFileSync(n,"utf-8"):"")!==r&&t.push(n)}catch{}return t}function pv(e){let t=[];for(let n of jd(e))try{if(!Y.existsSync(n))continue;let r=Y.readFileSync(n,"utf-8");dr(r)!==r.trimEnd()&&t.push(n)}catch{}return t}nt.command("feedback",{hidden:!0}).description("Deprecated alias for `feedback`").argument("[message]","Your feedback message").action(Ud);nt.command("list").description("Show resolved config values (env vars, server state, defaults) with their source").option("--json","Output as JSON for scripting / agent consumption").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").option("--verbose","Show one-line hints beneath entries that have them").action(async e=>{try{let t=ce(),n=await Ar({api:t,includeDev:!!e.dev});if(e.json){console.log(nu(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(tu(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});nt.command("get <key>").description("Print the resolved value of a single config key (pipe-friendly)").option("--raw","Print the underlying value as JSON instead of the formatted display string").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").action(async(e,t)=>{try{let n=ce(),o=(await Ar({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 fv(){return Object.entries(Rt).map(([e,t])=>` ${e.padEnd(22)} (${t.type}) ${t.description}`).join(`
249
+ (no PSP references yet \u2014 no holds placed)`);console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});async function Vd(e){(!e||e.trim().length===0)&&(console.log('Usage: visa-cli feedback "your message"'),process.exit(1));try{await F.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await ae().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}}J.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action(Vd);J.command("update").description("Update Visa CLI to the latest stable version").action(async()=>{let e=Fi(void 0,void 0,void 0,{withDiagnostics:!0}),t=e.diagnostics?Vi(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 ea(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=Us(st(),{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 nt=J.command("config").description("Manage CLI configuration and local integrations").addHelpCommand(!1).action(Ve);function Hd(e){return[Pe.join(e,".zshrc"),Pe.join(e,".bashrc"),Pe.join(e,".bash_profile"),Pe.join(e,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),Pe.join(e,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),Pe.join(e,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),Pe.join(e,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),Pe.join(e,".config","powershell","Microsoft.PowerShell_profile.ps1")]}function hb(e){let t=new Map;for(let n of Hd(e))try{Y.existsSync(n)&&t.set(n,Y.readFileSync(n,"utf-8"))}catch{}return t}function yb(e){let t=[];for(let[n,r]of e)try{(Y.existsSync(n)?Y.readFileSync(n,"utf-8"):"")!==r&&t.push(n)}catch{}return t}function _b(e){let t=[];for(let n of Hd(e))try{if(!Y.existsSync(n))continue;let r=Y.readFileSync(n,"utf-8");dr(r)!==r.trimEnd()&&t.push(n)}catch{}return t}nt.command("feedback",{hidden:!0}).description("Deprecated alias for `feedback`").argument("[message]","Your feedback message").action(Vd);nt.command("list").description("Show resolved config values (env vars, server state, defaults) with their source").option("--json","Output as JSON for scripting / agent consumption").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").option("--verbose","Show one-line hints beneath entries that have them").action(async e=>{try{let t=ae(),n=await Ar({api:t,includeDev:!!e.dev});if(e.json){console.log(ou(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(ru(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});nt.command("get <key>").description("Print the resolved value of a single config key (pipe-friendly)").option("--raw","Print the underlying value as JSON instead of the formatted display string").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").action(async(e,t)=>{try{let n=ae(),o=(await Ar({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 bb(){return Object.entries(It).map(([e,t])=>` ${e.padEnd(22)} (${t.type}) ${t.description}`).join(`
250
250
  `)}nt.command("set <key> <value>").description("Persist a CLI setting to ~/.visa-mcp/settings.json").addHelpText("after",`
251
251
  Settable keys:
252
- ${fv()}`).action((e,t)=>{try{let n=wo(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 ct||n instanceof lt||n instanceof Et?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});nt.command("unset <key>").description("Remove a CLI setting from ~/.visa-mcp/settings.json (falls back to env var or default)").action(e=>{try{let t=xo(e);t.removed?(console.log(`Removed ${t.key} from ${t.path}`),t.requiresRestart&&console.log("Restart Claude Code (or your MCP-enabled client) for the change to take effect.")):console.log(`No-op: ${t.key} was not set in ${t.path}.`)}catch(t){console.error(`Error: ${t.message}`),process.exit(1)}});nt.command("reset").description("Log out and clear all credentials").action(Ld);var pa=nt.command("biometric").description("Manage Touch ID / biometric attestation enforcement").addHelpCommand(!1).action(Ve);pa.command("status").description("Show current biometric enforcement state").action(async()=>{try{await F.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let n=await ce().getStatus(),r=n.attestationRequired!==!1,o=!!n.hasAttestationKey,s=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)}});pa.command("on").description("Require Touch ID for payments (security upgrade \u2014 no Touch ID needed)").action(async()=>{try{await F.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=ce(),n=await Uo(t);n.ok||(console.error(`Error: ${n.message}`),process.exit(1));let r=await t.setBiometricPreference({required:!0});r.success||(console.error(`Failed: ${r.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is now REQUIRED for payments.")}catch(e){console.error("Error:",e.message),process.exit(1)}});pa.command("off").description("Disable Touch ID requirement (security downgrade \u2014 one Touch ID confirmation required)").action(async()=>{try{await F.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=ce(),n=await t.getStatus();if(n.attestationRequired===!1){console.log("Touch ID is already disabled.");return}n.hasAttestationKey&&!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 Bn(t,async()=>{let o;if(n.hasAttestationKey&&re())try{let{nonce:s}=await t.getAttestationChallenge(),i=0,a="",c=Buffer.from(JSON.stringify({nonce:s,amount:i,merchant:a,context:"biometric-preference"})).toString("base64");o={signature:await vn(c,"disable Touch ID requirement"),nonce:s,amount:i,merchant:a}}catch(s){throw new Error(`Touch ID confirmation failed: ${s?.message||"cancelled"}`)}return t.setBiometricPreference({required:!1,attestation:o})},oa(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 kn=nt.command("shell-hud").description("Manage the shell prompt HUD (opt-in \u2014 prefer: visa-cli config hud enable)").addHelpCommand(!1).action(Ve);function Fd(){let e=io();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function Vd(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 gv(){Vd(Hs(void 0,{homeDir:z.homedir(),installVisaStatusLine:pr,installShellHud:io}))}function Hd(){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"),gv()}function ds(){let e=ot();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}kn.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Fd);kn.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(Hd);kn.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(ds);kn.command("disable").description("Disable the persistent shell HUD").action(ds);kn.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${ao()}
252
+ ${bb()}`).action((e,t)=>{try{let n=wo(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 ct||n instanceof lt||n instanceof At?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});nt.command("unset <key>").description("Remove a CLI setting from ~/.visa-mcp/settings.json (falls back to env var or default)").action(e=>{try{let t=xo(e);t.removed?(console.log(`Removed ${t.key} from ${t.path}`),t.requiresRestart&&console.log("Restart Claude Code (or your MCP-enabled client) for the change to take effect.")):console.log(`No-op: ${t.key} was not set in ${t.path}.`)}catch(t){console.error(`Error: ${t.message}`),process.exit(1)}});nt.command("reset").description("Log out and clear all credentials").action(jd);var pa=nt.command("biometric").description("Manage Touch ID / biometric attestation enforcement").addHelpCommand(!1).action(Ve);pa.command("status").description("Show current biometric enforcement state").action(async()=>{try{await F.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let n=await ae().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)}});pa.command("on").description("Require Touch ID for payments (security upgrade \u2014 no Touch ID needed)").action(async()=>{try{await F.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=ae(),n=await Uo(t);n.ok||(console.error(`Error: ${n.message}`),process.exit(1));let r=await t.setBiometricPreference({required:!0});r.success||(console.error(`Failed: ${r.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is now REQUIRED for payments.")}catch(e){console.error("Error:",e.message),process.exit(1)}});pa.command("off").description("Disable Touch ID requirement (security downgrade \u2014 one Touch ID confirmation required)").action(async()=>{try{await F.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=ae(),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 Bn(t,async()=>{let o;if(n.hasAttestationKey&&re())try{let{nonce:s}=await t.getAttestationChallenge(),i=0,a="",c=Buffer.from(JSON.stringify({nonce:s,amount:i,merchant:a,context:"biometric-preference"})).toString("base64");o={signature:await bn(c,"disable Touch ID requirement"),nonce:s,amount:i,merchant:a}}catch(s){throw new Error(`Touch ID confirmation failed: ${s?.message||"cancelled"}`)}return t.setBiometricPreference({required:!1,attestation:o})},oa(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 kn=nt.command("shell-hud").description("Manage the shell prompt HUD (opt-in \u2014 prefer: visa-cli config hud enable)").addHelpCommand(!1).action(Ve);function qd(){let e=io();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function Bd(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 vb(){Bd(Hs(void 0,{homeDir:z.homedir(),installVisaStatusLine:pr,installShellHud:io}))}function Kd(){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"),vb()}function ds(){let e=ot();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}kn.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(qd);kn.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(Kd);kn.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(ds);kn.command("disable").description("Disable the persistent shell HUD").action(ds);kn.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${ao()}
253
253
  `)});kn.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,r=(d,f,m)=>{console.log(` ${f?"\u2713":"\u2717"} ${d}: ${m}`),f||(n=!1)};console.log(`Shell HUD Doctor
254
- `);let o=Pn();if(r("Shell detected",!!o,o??"none (zsh, bash, or PowerShell required)"),o){let d=ur(o),f=e(d);if(r("RC file exists",f,d.replace(z.homedir(),"~")),f){let y=t(d,"utf-8").includes("visa-cli shell hud v2");r("HUD block installed",!!y,y?"found in rc file":"missing \u2014 run: visa-cli config hud enable shell")}}let s=kt(),i=e(s);if(r("Cache file",i,i?s.replace(z.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let d=JSON.parse(t(s,"utf-8")),f=Date.now()-(d.renderedAt??0),m=Math.round(f/1e3),y=m<=30;console.log(` ${y?"\u2713":"\u26A0"} Cache freshness: ${m}s old${y?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{r("Cache readable",!1,"corrupt JSON")}let a=lr(),c=e(a),l="missing";if(c)try{l=t(a,"utf-8").trim().slice(0,80)}catch{l="unreadable"}r("Line file",c,l);let u=!1;try{u=!!await F.getSessionToken()}catch{}if(r("Auth token",u,u?"found in keychain":"missing \u2014 run: visa-cli setup"),u)try{await ce().getStatus(),r("API connectivity",!0,"GET /v1/status OK")}catch(d){let f=d instanceof Error?d.message:"unknown error";r("API connectivity",!1,f)}console.log(n?`
254
+ `);let o=Pn();if(r("Shell detected",!!o,o??"none (zsh, bash, or PowerShell required)"),o){let d=ur(o),f=e(d);if(r("RC file exists",f,d.replace(z.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=Ct(),i=e(s);if(r("Cache file",i,i?s.replace(z.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let d=JSON.parse(t(s,"utf-8")),f=Date.now()-(d.renderedAt??0),m=Math.round(f/1e3),_=m<=30;console.log(` ${_?"\u2713":"\u26A0"} Cache freshness: ${m}s old${_?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{r("Cache readable",!1,"corrupt JSON")}let a=lr(),c=e(a),l="missing";if(c)try{l=t(a,"utf-8").trim().slice(0,80)}catch{l="unreadable"}r("Line file",c,l);let u=!1;try{u=!!await F.getSessionToken()}catch{}if(r("Auth token",u,u?"found in keychain":"missing \u2014 run: visa-cli setup"),u)try{await ae().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?`
255
255
  All checks passed.`:`
256
- Some checks failed \u2014 see above.`),n||process.exit(1)});async function qd(e){if(!(!e.force&&oc()))try{await Rs();let t=ce(),[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:o.status==="rejected"&&lv(o.reason)&&(i.apiKeyStatus="rollout_locked"),s.status==="fulfilled"){let u=s.value,f=(Array.isArray(u)?u:Array.isArray(u.transactions)?u.transactions:[]).find(m=>m&&typeof m.tool_name=="string"&&m.tool_name.length>0);f&&f.created_at&&(i.lastService={toolName:f.tool_name,createdAt:f.created_at})}let c={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:Be()},l=Os(i,c);Ms(l,i)}catch(t){let n=t instanceof Error?t.message:"unknown refresh failure";sc(n)}finally{Wt()}}kn.command("refresh").description("Refresh the shell HUD cache (no-op if cache is fresh unless --force)").option("--force","Bypass the cache freshness gate and always refresh").action(qd);var Cn=J.command("shell-hud",{hidden:!0}).description("Deprecated alias for `config shell-hud`");Cn.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Fd);Cn.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(Hd);Cn.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(ds);Cn.command("disable").description("Disable the persistent shell HUD").action(ds);Cn.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${ao()}
257
- `)});Cn.command("doctor").description("Show the new shell HUD doctor command").action(()=>{console.log("Run: visa-cli config shell-hud doctor")});Cn.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(qd);async function Bd(e){try{await Rs();let t=await bc(),n=ao(),r=n,o=n.split(`
256
+ Some checks failed \u2014 see above.`),n||process.exit(1)});async function Gd(e){if(!(!e.force&&oc()))try{await Rs();let t=ae(),[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:o.status==="rejected"&&fb(o.reason)&&(i.apiKeyStatus="rollout_locked"),s.status==="fulfilled"){let u=s.value,f=(Array.isArray(u)?u:Array.isArray(u.transactions)?u.transactions:[]).find(m=>m&&typeof m.tool_name=="string"&&m.tool_name.length>0);f&&f.created_at&&(i.lastService={toolName:f.tool_name,createdAt:f.created_at})}let c={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:Be()},l=Os(i,c);Ms(l,i)}catch(t){let n=t instanceof Error?t.message:"unknown refresh failure";sc(n)}finally{Wt()}}kn.command("refresh").description("Refresh the shell HUD cache (no-op if cache is fresh unless --force)").option("--force","Bypass the cache freshness gate and always refresh").action(Gd);var Cn=J.command("shell-hud",{hidden:!0}).description("Deprecated alias for `config shell-hud`");Cn.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(qd);Cn.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(Kd);Cn.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(ds);Cn.command("disable").description("Disable the persistent shell HUD").action(ds);Cn.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${ao()}
257
+ `)});Cn.command("doctor").description("Show the new shell HUD doctor command").action(()=>{console.log("Run: visa-cli config shell-hud doctor")});Cn.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(Gd);async function Wd(e){try{await Rs();let t=await vc(),n=ao(),r=n,o=n.split(`
258
258
  `)[0],s=ac();if(!t&&o.includes("loading")){process.stdout.write(`VISA | HUD not initialized \u2014 run: visa-cli config hud enable
259
259
  `),Yi();return}if(e.json){let a=await Tc(r,t,s);process.stdout.write(`${JSON.stringify(a,null,2)}
260
260
  `),Yi();return}let i=await xc(r,t,s);process.stdout.write(`${i}
261
- `),Yi()}catch(t){let n=t instanceof Error?t.message:"unknown error";console.error(`Failed to render Visa HUD: ${n}`),process.exit(1)}}nt.command("statusline").description("Output the Visa HUD for agent statusline integrations").option("--json","Output structured JSON for clients that render their own HUD").action(Bd);J.command("statusline",{hidden:!0}).description("Deprecated alias for `config statusline`").option("--json","Output structured JSON for clients that render their own HUD").action(Bd);var Xn=nt.command("hud").description("Manage the Visa spend HUD \u2014 one command for all surfaces").addHelpCommand(!1);Xn.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(`
261
+ `),Yi()}catch(t){let n=t instanceof Error?t.message:"unknown error";console.error(`Failed to render Visa HUD: ${n}`),process.exit(1)}}nt.command("statusline").description("Output the Visa HUD for agent statusline integrations").option("--json","Output structured JSON for clients that render their own HUD").action(Wd);J.command("statusline",{hidden:!0}).description("Deprecated alias for `config statusline`").option("--json","Output structured JSON for clients that render their own HUD").action(Wd);var Xn=nt.command("hud").description("Manage the Visa spend HUD \u2014 one command for all surfaces").addHelpCommand(!1);Xn.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(`
262
262
  ${e}Visa HUD Status${o}
263
- `);let s=st(),i=!1,a=!1;try{if(Y.existsSync(s)){let y=JSON.parse(Y.readFileSync(s,"utf-8")),S=typeof y.statusLine=="object"?y.statusLine.command:"";i=Tt(S),a=!!y.statusLine&&!i}}catch{}let c=i?`${n}\u2713${o}`:`${t}\u2717${o}`,l=i?"registered in ~/.claude/settings.json":a?`${r}another HUD is configured${o} \u2014 edit settings.json to switch`:"not enabled";console.log(` ${c} ${e}Claude Code${o} (statusLine) ${l}`);let u=Jt(z.homedir()),d=u.length>0||so(),f=d?`${n}\u2713${o}`:`${t}\u2717${o}`,m=d?`installed in shell rc file${u.length>0?` (${u.map(y=>y.replace(z.homedir(),"~")).join(", ")})`:""}`:"not installed (opt-in)";console.log(` ${f} ${e}Shell prompt${o} ${m}`),i&&d&&console.log(` ${r}!${o} ${e}Overlap${o} Claude statusLine and shell prompt HUD are both installed. Remove shell prompt output with: visa-cli config hud disable shell`),console.log(`
264
- ${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()});Xn.command("enable").description("Enable the Visa HUD \u2014 claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{Vd(Hs(e,{homeDir:z.homedir(),installVisaStatusLine:pr,installShellHud:io}))});Xn.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=ot();s.removed||(console.error(s.message),process.exit(1)),console.log(s.message);return}let n=ho(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=st(),i=js(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&&!fo()&&Jt(z.homedir()).length>0){let l=ot();l.removed&&l.rcPaths&&l.rcPaths.length>0&&(console.log(`Also cleaned legacy shell-prompt HUD block from ${l.rcPaths.map(u=>u.replace(z.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=ot();console.log(s.message),s.removed&&(o=!0),!s.removed&&n!=="all"&&(r=!0)}n==="all"&&!o&&(r=!0),r&&process.exit(1)});Xn.command("doctor").description("Diagnose HUD installation and connectivity across all surfaces").option("--fix","Self-heal locally fixable issues (stale cache, legacy placeholder, orphan precmd block)").option("-y, --yes","Allow --fix to remove overlapping shell HUD blocks without an interactive prompt").action(async e=>{let t=!0,n=(m,y,S)=>{console.log(` ${y?"\u2713":"\u2717"} ${m}: ${S}`),y||(t=!1)};console.log(`Visa HUD Doctor
265
- `);let r=[],o=Fi(void 0,void 0,void 0,{withDiagnostics:!0}),s=o.diagnostics?Vi(o.diagnostics,o.display):null;s&&(console.log(`\u26A0 ${s}`),console.log(""));let i=st(),a=!1;try{if(Y.existsSync(i)){let m=JSON.parse(Y.readFileSync(i,"utf-8")),y=typeof m.statusLine=="object"?m.statusLine.command:"";a=Tt(y)}}catch{}n("Claude Code statusLine",a,a?"registered":"not registered \u2014 run: visa-cli config hud enable");let c=pv(z.homedir()),l=Pn();if(n("Shell detected",!!l,l??"none (zsh, bash, or PowerShell required)"),l){let m=ur(l),y=Y.existsSync(m);if(n("RC file exists",y,m.replace(z.homedir(),"~")),y){let $=Y.readFileSync(m,"utf-8").includes("visa-cli shell hud v2");console.log(` ${$?"\u2713":"\u2013"} Shell HUD block: ${$?"installed":"not installed (opt-in \u2014 run: visa-cli config hud enable shell)"}`)}}if(c.length>0&&console.log(` \u2713 Shell HUD rc scan: installed in ${c.map(m=>m.replace(z.homedir(),"~")).join(", ")}`),a&&c.length>0&&e.fix){let m=c.map(S=>S.replace(z.homedir(),"~")).join(", "),y=e.yes===!0;if(!y&&process.stdin.isTTY&&(y=await Nd(`Remove shell prompt HUD block from ${m}?`,{})==="confirmed"),y){let S=dv(z.homedir());ot();let $=mv(S);if($.length>0){let H=$.map(U=>U.replace(z.homedir(),"~")).join(", ");console.log(` \u2713 --fix: cleaned legacy shell-prompt HUD block from ${H}`),r.push(`removed shell precmd block from ${H}`)}}else console.log(` ! --fix: preserving shell prompt HUD block in ${m}; rerun with --yes or remove it explicitly with: visa-cli config hud disable shell`)}else a&&c.length>0&&console.log(" ! Overlap notice: Claude Code statusLine and shell prompt HUD are both installed. If the prompt output is unintended, run: visa-cli config hud disable shell \u2014 or rerun with: visa-cli config hud doctor --fix --yes");let u=kt(),d=Y.existsSync(u);if(n("HUD cache file",d,d?u.replace(z.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),d)try{let m=JSON.parse(Y.readFileSync(u,"utf-8")),y=Date.now()-(m.renderedAt??0),S=Math.round(y/1e3),$=S<=30,H=typeof m.line=="string"?m.line:"",U=H.length>0&&co(H);if(console.log(` ${$?"\u2713":"\u26A0"} Cache freshness: ${S}s old${$?"":" (stale \u2014 will refresh on next prompt)"}`),U&&console.log(' \u26A0 Cache content: legacy placeholder (HUD will display "VISA | HUD not ready" until next successful refresh)'),e.fix&&(!$||U)){let w=!1;try{Y.rmSync(u,{force:!0}),w=!0}catch{}try{let x=lr();Y.existsSync(x)&&(Y.rmSync(x,{force:!0}),w=!0)}catch{}if(w){let x=U?"cache held legacy placeholder":`cache was ${S}s stale`;console.log(` \u2713 --fix: cleared HUD cache (${x}); next prompt will trigger a fresh refresh`),r.push("cleared HUD cache");let _=Pe.join(z.homedir(),".visa-cli","shell-hud.lock");Y.existsSync(_)&&(Wt(),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{Y.rmSync(u,{force:!0}),console.log(" \u2713 --fix: removed corrupt cache file; next prompt will trigger a fresh refresh"),r.push("removed corrupt cache");let m=Pe.join(z.homedir(),".visa-cli","shell-hud.lock");Y.existsSync(m)&&(Wt(),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 F.getSessionToken()}catch{}if(n("Auth token",f,f?"found in keychain":"missing \u2014 run: visa-cli setup"),f)try{await ce().getStatus(),n("API connectivity",!0,"GET /v1/status OK")}catch(m){let y=m instanceof Error?m.message:"unknown error";n("API connectivity",!1,y)}e.fix&&(r.length===0?console.log(`
263
+ `);let s=st(),i=!1,a=!1;try{if(Y.existsSync(s)){let _=JSON.parse(Y.readFileSync(s,"utf-8")),S=typeof _.statusLine=="object"?_.statusLine.command:"";i=Et(S),a=!!_.statusLine&&!i}}catch{}let c=i?`${n}\u2713${o}`:`${t}\u2717${o}`,l=i?"registered in ~/.claude/settings.json":a?`${r}another HUD is configured${o} \u2014 edit settings.json to switch`:"not enabled";console.log(` ${c} ${e}Claude Code${o} (statusLine) ${l}`);let u=Jt(z.homedir()),d=u.length>0||so(),f=d?`${n}\u2713${o}`:`${t}\u2717${o}`,m=d?`installed in shell rc file${u.length>0?` (${u.map(_=>_.replace(z.homedir(),"~")).join(", ")})`:""}`:"not installed (opt-in)";console.log(` ${f} ${e}Shell prompt${o} ${m}`),i&&d&&console.log(` ${r}!${o} ${e}Overlap${o} Claude statusLine and shell prompt HUD are both installed. Remove shell prompt output with: visa-cli config hud disable shell`),console.log(`
264
+ ${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()});Xn.command("enable").description("Enable the Visa HUD \u2014 claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{Bd(Hs(e,{homeDir:z.homedir(),installVisaStatusLine:pr,installShellHud:io}))});Xn.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=ot();s.removed||(console.error(s.message),process.exit(1)),console.log(s.message);return}let n=ho(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=st(),i=js(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&&!fo()&&Jt(z.homedir()).length>0){let l=ot();l.removed&&l.rcPaths&&l.rcPaths.length>0&&(console.log(`Also cleaned legacy shell-prompt HUD block from ${l.rcPaths.map(u=>u.replace(z.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=ot();console.log(s.message),s.removed&&(o=!0),!s.removed&&n!=="all"&&(r=!0)}n==="all"&&!o&&(r=!0),r&&process.exit(1)});Xn.command("doctor").description("Diagnose HUD installation and connectivity across all surfaces").option("--fix","Self-heal locally fixable issues (stale cache, legacy placeholder, orphan precmd block)").option("-y, --yes","Allow --fix to remove overlapping shell HUD blocks without an interactive prompt").action(async e=>{let t=!0,n=(m,_,S)=>{console.log(` ${_?"\u2713":"\u2717"} ${m}: ${S}`),_||(t=!1)};console.log(`Visa HUD Doctor
265
+ `);let r=[],o=Fi(void 0,void 0,void 0,{withDiagnostics:!0}),s=o.diagnostics?Vi(o.diagnostics,o.display):null;s&&(console.log(`\u26A0 ${s}`),console.log(""));let i=st(),a=!1;try{if(Y.existsSync(i)){let m=JSON.parse(Y.readFileSync(i,"utf-8")),_=typeof m.statusLine=="object"?m.statusLine.command:"";a=Et(_)}}catch{}n("Claude Code statusLine",a,a?"registered":"not registered \u2014 run: visa-cli config hud enable");let c=_b(z.homedir()),l=Pn();if(n("Shell detected",!!l,l??"none (zsh, bash, or PowerShell required)"),l){let m=ur(l),_=Y.existsSync(m);if(n("RC file exists",_,m.replace(z.homedir(),"~")),_){let $=Y.readFileSync(m,"utf-8").includes("visa-cli shell hud v2");console.log(` ${$?"\u2713":"\u2013"} Shell HUD block: ${$?"installed":"not installed (opt-in \u2014 run: visa-cli config hud enable shell)"}`)}}if(c.length>0&&console.log(` \u2713 Shell HUD rc scan: installed in ${c.map(m=>m.replace(z.homedir(),"~")).join(", ")}`),a&&c.length>0&&e.fix){let m=c.map(S=>S.replace(z.homedir(),"~")).join(", "),_=e.yes===!0;if(!_&&process.stdin.isTTY&&(_=await Ud(`Remove shell prompt HUD block from ${m}?`,{})==="confirmed"),_){let S=hb(z.homedir());ot();let $=yb(S);if($.length>0){let H=$.map(U=>U.replace(z.homedir(),"~")).join(", ");console.log(` \u2713 --fix: cleaned legacy shell-prompt HUD block from ${H}`),r.push(`removed shell precmd block from ${H}`)}}else console.log(` ! --fix: preserving shell prompt HUD block in ${m}; rerun with --yes or remove it explicitly with: visa-cli config hud disable shell`)}else a&&c.length>0&&console.log(" ! Overlap notice: Claude Code statusLine and shell prompt HUD are both installed. If the prompt output is unintended, run: visa-cli config hud disable shell \u2014 or rerun with: visa-cli config hud doctor --fix --yes");let u=Ct(),d=Y.existsSync(u);if(n("HUD cache file",d,d?u.replace(z.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),d)try{let m=JSON.parse(Y.readFileSync(u,"utf-8")),_=Date.now()-(m.renderedAt??0),S=Math.round(_/1e3),$=S<=30,H=typeof m.line=="string"?m.line:"",U=H.length>0&&co(H);if(console.log(` ${$?"\u2713":"\u26A0"} Cache freshness: ${S}s old${$?"":" (stale \u2014 will refresh on next prompt)"}`),U&&console.log(' \u26A0 Cache content: legacy placeholder (HUD will display "VISA | HUD not ready" until next successful refresh)'),e.fix&&(!$||U)){let w=!1;try{Y.rmSync(u,{force:!0}),w=!0}catch{}try{let x=lr();Y.existsSync(x)&&(Y.rmSync(x,{force:!0}),w=!0)}catch{}if(w){let x=U?"cache held legacy placeholder":`cache was ${S}s stale`;console.log(` \u2713 --fix: cleared HUD cache (${x}); next prompt will trigger a fresh refresh`),r.push("cleared HUD cache");let y=Pe.join(z.homedir(),".visa-cli","shell-hud.lock");Y.existsSync(y)&&(Wt(),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{Y.rmSync(u,{force:!0}),console.log(" \u2713 --fix: removed corrupt cache file; next prompt will trigger a fresh refresh"),r.push("removed corrupt cache");let m=Pe.join(z.homedir(),".visa-cli","shell-hud.lock");Y.existsSync(m)&&(Wt(),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 F.getSessionToken()}catch{}if(n("Auth token",f,f?"found in keychain":"missing \u2014 run: visa-cli setup"),f)try{await ae().getStatus(),n("API connectivity",!0,"GET /v1/status OK")}catch(m){let _=m instanceof Error?m.message:"unknown error";n("API connectivity",!1,_)}e.fix&&(r.length===0?console.log(`
266
266
  --fix: no locally fixable issues found.`):console.log(`
267
267
  --fix: applied ${r.length} change${r.length===1?"":"s"} \u2014 ${r.join("; ")}.`)),console.log(t?`
268
268
  All checks passed.`:`
269
269
  Some checks failed \u2014 see above.`),t||process.exit(1)});Xn.command("enable-claude").description("Alias for: hud enable claude").action(()=>{let e=st(),t=pr(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});Xn.command("disable-claude").description("Alias for: hud disable claude").action(()=>{let e=st(),t=js(e);console.log(t.message),t.removed||process.exit(1)});var Qn=J.command("merchants").description("List discoverable platform merchants and refresh JIT tools").addHelpCommand(!1).action(Ve);Qn.description("Discover and run paid merchant tools");Qn.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 Ce(()=>F.getSessionToken()),n=await t.listPublicMerchants();if(n.length===0){e.json?console.log(JSON.stringify({merchants:[]},null,2)):console.log(`
270
270
  No live platform merchants on this auth server.
271
271
  `);return}let r=await Promise.all(n.map(async a=>{let c=await t.getPublicMerchantDiscover(a.slug);return{slug:a.slug,display_name:a.display_name,provider:c?.title??a.display_name,merchant_of_record:c?.merchant_of_record??a.display_name,upstream:c?.upstream,tools:(c?.routes??[]).filter(l=>l.tool_id).map(l=>({tool_id:l.tool_id,mcp_name:l.tool_id.replace(/-/g,"_"),method:l.method,path:l.path,price_cents:l.price_cents,category:l.category??null,description:l.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 c=a.merchant_of_record!==a.provider?` ${s}(MoR: ${a.merchant_of_record})${i}`:"";if(console.log(` ${o}${a.provider}${i}${c} ${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 l of a.tools){let u=l.category?` ${s}[${l.category}]${i}`:"",d=`$${(l.price_cents/100).toFixed(2)}`;console.log(` ${l.tool_id}${u} ${s}\u2192 Claude: ${l.mcp_name}${i} ${d} ${s}${l.method} ${l.path}${i}`),l.description&&console.log(` ${s}${l.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}
272
- `)}catch(t){console.error("Error:",t.message),process.exit(1)}});Qn.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 ${Pd}, max ${Od})`,vd).option("--offset <n>","Pagination offset (default 0)",vd).action(async e=>{try{let t=ce(),{limit:n,offset:r}=ev(e),o=await Q_(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?J_(o):z_(o)}catch(t){console.error("Error:",t.message),process.exit(1)}});Qn.command("describe <tool>").description("Show tool schema, price, and examples").action(async e=>{try{let n=await ce().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(`
272
+ `)}catch(t){console.error("Error:",t.message),process.exit(1)}});Qn.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 ${Nd}, max ${Ld})`,wd).option("--offset <n>","Pagination offset (default 0)",wd).action(async e=>{try{let t=ae(),{limit:n,offset:r}=sb(e),o=await ob(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?eb(o):Q_(o)}catch(t){console.error("Error:",t.message),process.exit(1)}});Qn.command("describe <tool>").description("Show tool schema, price, and examples").action(async e=>{try{let n=await ae().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(`
273
273
  ${n.id}
274
274
  `),console.log(n.description),console.log(`
275
275
  Price`),console.log(` ${ia(n.priceCents,n.priceDisplay)}`),console.log(`
276
276
  Provider`),console.log(` ${n.provider} \xB7 ${n.category}`),console.log(`
277
277
  Inputs`);let r=n.inputSchema?.properties;if(r&&typeof r=="object"&&!Array.isArray(r)){let s=Array.isArray(n.inputSchema.required)?new Set(n.inputSchema.required):new Set,i=Object.entries(r),a=Math.max(12,...i.map(([c])=>c.length));for(let[c,l]of i){let u=s.has(c)?"required":"optional",d=Mc(l),f=d?` ${d.padEnd(8)}`:" ",m=l?.description?` - ${l.description}`:"";console.log(` ${c.padEnd(a)} ${u}${f}${m}`)}}else console.log(" No published schema. Use --json with the request body.");console.log(`
278
- Examples`);let o=Qu(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 hv(e){return["fal-flux-pro-ultra","fal-flux-pro","fal-flux-schnell","fal-recraft-v3","fal-ideogram-v2","fal-minimax-video","fal-wan-video","fal-kling-video","fal-ace-step-music","query_onchain_prices"].includes(e)}async function fa(e,t,n){return hv(e)?De.shortcut(e,t,n):De.executeTool({tool_id:e,params:t},n,"execute_tool")}Qn.command("run <tool>").description("Run any merchant tool by id").option("--json <json>","Tool parameters as a JSON object").option("--prompt <prompt>","Prompt parameter for prompt-shaped tools").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=G_(t.json,"--json");t.prompt&&(n.prompt=t.prompt),Zr({yes:t.yes}),console.log(`Running ${e}`);let r=await fa(e,n,`visa-cli merchants run ${e}`);aa(r),ca(r)}catch(n){console.error("Error:",n.message),process.exit(1)}});Qn.command("refresh").description("Hint: restart the MCP server (Claude/Cursor) to refresh discovered tools \u2014 discovery is in-process").action(()=>{console.log(`
278
+ Examples`);let o=td(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 Sb(e){return["fal-flux-pro-ultra","fal-flux-pro","fal-flux-schnell","fal-recraft-v3","fal-ideogram-v2","fal-minimax-video","fal-wan-video","fal-kling-video","fal-ace-step-music","query_onchain_prices"].includes(e)}async function fa(e,t,n){return Sb(e)?De.shortcut(e,t,n):De.executeTool({tool_id:e,params:t},n,"execute_tool")}Qn.command("run <tool>").description("Run any merchant tool by id").option("--json <json>","Tool parameters as a JSON object").option("--prompt <prompt>","Prompt parameter for prompt-shaped tools").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=Z_(t.json,"--json");t.prompt&&(n.prompt=t.prompt),Zr({yes:t.yes}),console.log(`Running ${e}`);let r=await fa(e,n,`visa-cli merchants run ${e}`);aa(r),ca(r)}catch(n){console.error("Error:",n.message),process.exit(1)}});Qn.command("refresh").description("Hint: restart the MCP server (Claude/Cursor) to refresh discovered tools \u2014 discovery is in-process").action(()=>{console.log(`
279
279
  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.
280
280
  `)});var jr=J.command("generate").description("Generate media with merchant tools").addHelpCommand(!1).action(Ve);async function Fr(e){Zr({yes:e.yes}),e.json||e.format&&Qr(e.format)||(console.log(`
281
281
  ${e.kind}
282
282
  `),console.log(`Using: ${e.toolId}`),console.log(`Prompt: ${e.prompt}
283
- `));let n=await fa(e.toolId,e.params,`visa-cli generate ${e.kind.toLowerCase()}: ${e.prompt}`);aa(n,{json:e.json,format:e.format,command:e.command??`generate.${e.kind.toLowerCase().replace(/\s+/g,"_")}`}),ca(n)}var qt=(e,t)=>n=>(t.includes(n)||J.error(`error: option '${e}' accepts ${t.map(r=>`'${r}'`).join(", ")} (got '${n}')`,{exitCode:2}),n);jr.command("image [prompt]").description("Generate an image from a prompt (accepts stdin via `-` or --stdin)").option("--quality <quality>","Image quality: standard or high",qt("--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)",qt("--format",wt)).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 Kt(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 Fr({kind:"Image generation",toolId:r,params:o,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.image"})}catch(n){Zn("generate.image",n,{json:t.json,format:t.format})}});jr.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)",qt("--format",wt)).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 Kt(e,t),r={prompt:n};t.aspectRatio&&(r.aspect_ratio=t.aspectRatio),t.duration&&(r.duration=Number(t.duration)),await Fr({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){Zn("generate.video",n,{json:t.json,format:t.format})}});jr.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)",qt("--format",wt)).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 Kt(e,t),r={prompt:n};t.instrumental&&(r.instrumental=!0),t.duration&&(r.duration=Number(t.duration)),await Fr({kind:"Music generation",toolId:t.tool??Dt("generate_music"),params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.music"})}catch(n){Zn("generate.music",n,{json:t.json,format:t.format})}});jr.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)",qt("--format",wt)).option("--stdin","Read text from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=t.audioUrl??t.refAudioUrl;n||J.error("error: option '--audio-url <url>' is required for visa-cli generate speech",{exitCode:2});let r=await Kt(e,t),o={text:r,audio_url:n};await Fr({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){Zn("generate.speech",n,{json:t.json,format:t.format})}});jr.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)",qt("--format",wt)).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 Kt(e,t),r={image_url:n};await Fr({kind:"3D generation",toolId:t.tool??Dt("generate_3d"),params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.3d"})}catch(n){Zn("generate.3d",n,{json:t.json,format:t.format})}});var Qi="reasoning",bd=Object.keys(Tr.run_llm.tiers);J.command("run-llm [prompt]").description(`Run a chat-completion against an OpenRouter-backed LLM (default tier: ${Qi})`).option("--tier <tier>",`LLM tier: ${bd.join(" | ")} (resolves to a catalog tool id via the run_llm meta-tool)`,qt("--tier",bd),Qi).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)",qt("--format",wt)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=t.imageUrl;if(t.fromStdin){let l=await Cs(),u=JSON.parse(l),d=Na(u,t.fromStdin);n=n??d}let r=await Kt(e,{stdin:t.stdin&&!t.fromStdin});Zr({yes:t.yes});let o={prompt:r},s=await Da(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??Qi,a=t.model??Dt("run_llm",i);if(!t.json){console.log(`
283
+ `));let n=await fa(e.toolId,e.params,`visa-cli generate ${e.kind.toLowerCase()}: ${e.prompt}`);aa(n,{json:e.json,format:e.format,command:e.command??`generate.${e.kind.toLowerCase().replace(/\s+/g,"_")}`}),ca(n)}var qt=(e,t)=>n=>(t.includes(n)||J.error(`error: option '${e}' accepts ${t.map(r=>`'${r}'`).join(", ")} (got '${n}')`,{exitCode:2}),n);jr.command("image [prompt]").description("Generate an image from a prompt (accepts stdin via `-` or --stdin)").option("--quality <quality>","Image quality: standard or high",qt("--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)",qt("--format",xt)).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 Kt(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 Fr({kind:"Image generation",toolId:r,params:o,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.image"})}catch(n){Zn("generate.image",n,{json:t.json,format:t.format})}});jr.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)",qt("--format",xt)).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 Kt(e,t),r={prompt:n};t.aspectRatio&&(r.aspect_ratio=t.aspectRatio),t.duration&&(r.duration=Number(t.duration)),await Fr({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){Zn("generate.video",n,{json:t.json,format:t.format})}});jr.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)",qt("--format",xt)).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 Kt(e,t),r={prompt:n};t.instrumental&&(r.instrumental=!0),t.duration&&(r.duration=Number(t.duration)),await Fr({kind:"Music generation",toolId:t.tool??Dt("generate_music"),params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.music"})}catch(n){Zn("generate.music",n,{json:t.json,format:t.format})}});jr.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)",qt("--format",xt)).option("--stdin","Read text from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=t.audioUrl??t.refAudioUrl;n||J.error("error: option '--audio-url <url>' is required for visa-cli generate speech",{exitCode:2});let r=await Kt(e,t),o={text:r,audio_url:n};await Fr({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){Zn("generate.speech",n,{json:t.json,format:t.format})}});jr.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)",qt("--format",xt)).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 Kt(e,t),r={image_url:n};await Fr({kind:"3D generation",toolId:t.tool??Dt("generate_3d"),params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.3d"})}catch(n){Zn("generate.3d",n,{json:t.json,format:t.format})}});var Qi="reasoning",xd=Object.keys(Tr.run_llm.tiers);J.command("run-llm [prompt]").description(`Run a chat-completion against an OpenRouter-backed LLM (default tier: ${Qi})`).option("--tier <tier>",`LLM tier: ${xd.join(" | ")} (resolves to a catalog tool id via the run_llm meta-tool)`,qt("--tier",xd),Qi).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)",qt("--format",xt)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=t.imageUrl;if(t.fromStdin){let l=await Cs(),u=JSON.parse(l),d=Na(u,t.fromStdin);n=n??d}let r=await Kt(e,{stdin:t.stdin&&!t.fromStdin});Zr({yes:t.yes});let o={prompt:r},s=await Da(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??Qi,a=t.model??Dt("run_llm",i);if(!t.json){console.log(`
284
284
  LLM completion
285
285
  `),console.log(`Using: ${a}`);let l=r.length>200?`${r.slice(0,200)}\u2026`:r;console.log(`Prompt: ${l}
286
286
  `)}let c=await fa(a,o,"visa-cli run-llm");aa(c,{json:t.json,format:t.format,command:"run-llm"}),ca(c)}catch(n){Zn("run-llm",n,{json:t.json,format:t.format})}});J.command("uninstall [client]").description("Remove MCP server from an AI client").option("--all","Remove from all clients").option("--scope <scope>","Uninstall scope: global or project","global").action(async(e,t)=>{try{let n=t.scope==="project"?"project":"global";if(t.all){let s=[];for(let i of Fe)zi(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(`
287
- Supported clients: ${Fe.map(s=>s.id).join(", ")}`),process.exit(1));let r=Bi(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${Fe.map(s=>s.id).join(", ")}`),process.exit(1));let o=zi(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)}});J.hook("postAction",()=>{if(Ur){Ur=!1;return}as&&Xu(as.lastSignals)});av(["setup","install","status","cards","tokens","balance","merchants","generate","run-llm","config","feedback","update","uninstall"]);Md(J);J.parseAsync().catch(async e=>{console.error("Error:",e instanceof Error?e.message:String(e));let{reportFatal:t}=await Promise.resolve().then(()=>(is(),ss));await t(e)});process.on("uncaughtException",async e=>{console.error("Uncaught exception:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(is(),ss));await t(e)});process.on("unhandledRejection",async e=>{console.error("Unhandled rejection:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(is(),ss));await t(e)});0&&(module.exports={printGroupHelpAndExit});
287
+ Supported clients: ${Fe.map(s=>s.id).join(", ")}`),process.exit(1));let r=Bi(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${Fe.map(s=>s.id).join(", ")}`),process.exit(1));let o=zi(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)}});J.hook("postAction",()=>{if(Ur){Ur=!1;return}as&&ed(as.lastSignals)});mb(["setup","install","status","cards","tokens","balance","merchants","generate","run-llm","config","feedback","update","uninstall"]);Dd(J);J.parseAsync().catch(async e=>{console.error("Error:",e instanceof Error?e.message:String(e));let{reportFatal:t}=await Promise.resolve().then(()=>(is(),ss));await t(e)});process.on("uncaughtException",async e=>{console.error("Uncaught exception:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(is(),ss));await t(e)});process.on("unhandledRejection",async e=>{console.error("Unhandled rejection:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(is(),ss));await t(e)});0&&(module.exports={printGroupHelpAndExit});