@visa/cli 2.1.1 → 2.1.2

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 eu=Object.create;var hs=Object.defineProperty;var tu=Object.getOwnPropertyDescriptor;var nu=Object.getOwnPropertyNames;var ru=Object.getPrototypeOf,su=Object.prototype.hasOwnProperty;var ou=(e,t)=>()=>(e&&(t=e(e=0)),t);var si=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),oi=(e,t)=>{for(var n in t)hs(e,n,{get:t[n],enumerable:!0})},iu=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of nu(t))!su.call(e,s)&&s!==n&&hs(e,s,{get:()=>t[s],enumerable:!(r=tu(t,s))||r.enumerable});return e};var R=(e,t,n)=>(n=e!=null?eu(ru(e)):{},iu(t||!e||!e.__esModule?hs(n,"default",{value:e,enumerable:!0}):n,e));var dr=si((Lh,vu)=>{vu.exports={name:"@visa/cli",version:"2.1.1",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{"sync:server-json":"node scripts/sync-server-json.mjs","check:server-json":"node scripts/sync-server-json.mjs --check",prebuild:"node scripts/sync-server-json.mjs && pnpm --filter @visa/money build && pnpm --filter @visa-cli/tools build",build:"tsc --noEmit && node esbuild.config.js",prepack:"node scripts/sync-server-json.mjs --check",dev:"tsc --watch",pretest:"pnpm build",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0",commander:"^12.1.0",zod:"^3.23.0"},devDependencies:{"@visa/money":"workspace:*","@visa/observability":"workspace:*","@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.31.0","@types/jest":"^30.0.0","@types/node":"^25.9.0","@typescript-eslint/eslint-plugin":"^8.59.4","@typescript-eslint/parser":"^8.59.4","@types/express":"^5.0.0",esbuild:"^0.27.4",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.3","ts-jest":"^29.4.10",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","server.json","README.md","LICENSE"]}});var Wn=si(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.micros=Mp;Q.fromCents=Op;Q.fromUsdc=Np;Q.fromUsd=Lp;Q.toCents=Dp;Q.toCentsForAcquirer=Up;Q.toUsdc=jp;Q.toWire=qp;Q.fromWire=Vp;Q.toDisplay=Fp;Q.toUsdRounded2dp=Bp;Q.add=Hp;Q.sub=Kp;Q.clampNonNegative=Gp;Q.isNonNegative=zp;Q.max=Wp;Q.min=Jp;var et=10000n,wc=1000000n;function Mp(e){return e}function Op(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*et}function Np(e){return e}function Lp(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function Dp(e){if(e>=0n)return Number(e/et);let t=e/et,n=e%et;return Number(n===0n?t:t-1n)}function Up(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/et)}function jp(e){return e}function qp(e){return e.toString()}function Vp(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 Fp(e,t={}){let n=t.decimals??2,r=t.symbol??"$",s=e<0n,o=s?-e:e,i=o/wc,a=o%wc,l=s?"-":"";if(n===0)return`${l}${r}${i.toString()}`;let c=a.toString().padStart(6,"0").slice(0,n);return`${l}${r}${i.toString()}.${c}`}function Bp(e){let t=e<0n,n=t?-e:e,r=n/et,o=n%et*2n,i;o<et?i=r:o>et?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function Hp(e,t){return e+t}function Kp(e,t){return e-t}function Gp(e){return e<0n?0n:e}function zp(e){return e>=0n}function Wp(e,t){return e>t?e:t}function Jp(e,t){return e<t?e:t}});var ls={};oi(ls,{initSentry:()=>Gg,isSentryConfigured:()=>Kg,reportFatal:()=>zg});function Kg(){return!1}async function Gg(){return null}async function zg(e,t){process.exit(t?.exitCode??1)}var us=ou(()=>{});var Rl=require("commander"),ms=R(require("crypto")),$e=R(require("fs")),K=R(require("os")),Et=R(require("path")),Il=require("child_process"),$l=R(require("node:readline/promises")),Pl=require("util");var lr=require("child_process"),gi=require("util"),lt=R(require("fs")),ur=R(require("os")),ws=R(require("path"));var li=R(require("crypto"));var Ke="e9501a252b778bce5a3d77710667afdd9198a750d1d989d95fb32d80e485bf15";var ui="VISA_ALLOW_INSECURE_MOCKS",ii,ai,ci;function ys(e){return`${e}-${li.randomBytes(24).toString("base64url")}`}function di(e=process.env){return e.NODE_ENV==="test"||e[ui]==="true"}function at(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&di(e)}function nn(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&di(e)}function _s(){return`Set ${ui}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function mi(){return ii??=ys("mock-session"),ii}function pi(e=process.env){return e.NODE_ENV==="test"?Ke:(ai??=ys("mock-rc"),ai)}function fi(){return ci??=ys("mock-signature"),ci}var Pe=(0,gi.promisify)(lr.execFile),xs=ws.join(ur.homedir(),".visa-mcp"),Rn=ws.join(xs,"session-token"),Se="visa-cli",ct="session-token",ar="rc-access",au=5e3,cr=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function cu(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
2
- `)}function hi(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=cu(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function lu(){try{let{stdout:e}=await Pe("security",["find-generic-password","-s",Se,"-a",ct,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(hi(e))throw new cr("Unable to read Visa CLI credentials from macOS Keychain. In sandboxed agents such as Codex, rerun with keychain access or run this command outside the sandbox.");return null}}async function uu(e){try{try{await Pe("security",["delete-generic-password","-s",Se,"-a",ct],{timeout:5e3})}catch{}return await Pe("security",["add-generic-password","-s",Se,"-a",ct,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function du(){try{await Pe("security",["delete-generic-password","-s",Se,"-a",ct],{timeout:5e3})}catch{}}async function mu(){if(!Cs())return null;try{let{stdout:e}=await Pe("secret-tool",["lookup","service",Se,"account",ct],{timeout:5e3});return e.trim()||null}catch{return null}}async function pu(e){if(!Cs())return!1;try{let t=(0,lr.execFile)("secret-tool",["store","--label",`${Se} ${ct}`,"service",Se,"account",ct]);return t.stdin?(t.stdin.write(e),t.stdin.end(),await Promise.race([new Promise((n,r)=>{t.on("exit",s=>s===0?n():r(new Error(`secret-tool exited ${s}`))),t.on("error",r)}),new Promise((n,r)=>setTimeout(()=>{t.kill(),r(new Error("secret-tool timed out"))},au))]),!0):!1}catch{return!1}}async function fu(){if(Cs())try{await Pe("secret-tool",["clear","service",Se,"account",ct],{timeout:5e3})}catch{}}function Cs(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function gu(){try{let{stdout:e}=await Pe("security",["find-generic-password","-s",Se,"-a",ar,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function hu(e){try{try{await Pe("security",["delete-generic-password","-s",Se,"-a",ar],{timeout:5e3})}catch{}await Pe("security",["add-generic-password","-s",Se,"-a",ar,"-w",e],{timeout:5e3})}catch{}}async function yu(){try{await Pe("security",["delete-generic-password","-s",Se,"-a",ar],{timeout:5e3})}catch{}}function bs(){try{return lt.readFileSync(Rn,"utf-8").trim()||null}catch(e){if(hi(e))throw new cr(`Unable to read Visa CLI credentials from ${Rn}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function yi(e){lt.mkdirSync(xs,{recursive:!0,mode:448}),lt.writeFileSync(Rn,e,{mode:384}),process.platform==="win32"&&_u(Rn)}function Ss(){try{lt.unlinkSync(Rn)}catch{}}function _u(e){try{let t=ur.userInfo().username;(0,lr.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 vs(){switch(process.platform){case"darwin":return{get:lu,store:uu,delete:du};case"linux":return{get:mu,store:pu,delete:fu};default:return{get:async()=>bs(),store:async e=>{try{return yi(e),!0}catch{return!1}},delete:async()=>Ss(),storesInSessionFile:!0}}}var U=class{static async getSessionToken(){if(at())return Promise.resolve(mi());let t=vs(),n=await t.get();if(n)return n;let r=bs();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(at())return;let n=vs();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||Ss();return}await n.delete()}if(yi(t),bs()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${xs} is writable.`))}static async getRcAccessToken(){return at()?pi():gu()}static async saveRcAccessToken(t){at()||await hu(t)}static async deleteSessionToken(){if(at())return;await vs().delete(),Ss()}static async clearAll(){await this.deleteSessionToken(),await yu()}};var mr=R(require("crypto")),pr=R(require("tty")),fr=R(require("fs"));function bu(e){return/-rc\.|-beta\./.test(e)}function ks(e){return mr.createHash("sha256").update(e.trim()).digest("hex")}function _i(e){return Ke==="SKIP"?!0:mr.timingSafeEqual(Buffer.from(ks(e)),Buffer.from(Ke))}function Su(){try{let e=fr.openSync("/dev/tty","r+"),t=new pr.ReadStream(e),n=new pr.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{fr.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 wu(e){return new Promise((t,n)=>{let r;try{r=Su()}catch(u){n(u);return}let{input:s,output:o,cleanupStreams:i}=r,a=()=>{s.off("data",c);try{s.setRawMode?.(!1)}catch{}i()};o.write(e),s.setRawMode?.(!0),s.resume(),s.setEncoding("utf8");let l="",c=u=>{u==="\r"||u===`
1
+ "use strict";var ru=Object.create;var lr=Object.defineProperty;var su=Object.getOwnPropertyDescriptor;var ou=Object.getOwnPropertyNames;var iu=Object.getPrototypeOf,au=Object.prototype.hasOwnProperty;var cu=(e,t)=>()=>(e&&(t=e(e=0)),t);var ii=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),_s=(e,t)=>{for(var n in t)lr(e,n,{get:t[n],enumerable:!0})},ai=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ou(t))!au.call(e,s)&&s!==n&&lr(e,s,{get:()=>t[s],enumerable:!(r=su(t,s))||r.enumerable});return e};var R=(e,t,n)=>(n=e!=null?ru(iu(e)):{},ai(t||!e||!e.__esModule?lr(n,"default",{value:e,enumerable:!0}):n,e)),lu=e=>ai(lr({},"__esModule",{value:!0}),e);var fr=ii((Vh,wu)=>{wu.exports={name:"@visa/cli",version:"2.1.2",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{"sync:server-json":"node scripts/sync-server-json.mjs","check:server-json":"node scripts/sync-server-json.mjs --check",prebuild:"node scripts/sync-server-json.mjs && pnpm --filter @visa/money build && pnpm --filter @visa-cli/tools build",build:"tsc --noEmit && node esbuild.config.js",prepack:"node scripts/sync-server-json.mjs --check",dev:"tsc --watch",pretest:"pnpm build",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0",commander:"^12.1.0",zod:"^3.23.0"},devDependencies:{"@visa/money":"workspace:*","@visa/observability":"workspace:*","@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.31.0","@types/jest":"^30.0.0","@types/node":"^25.9.0","@typescript-eslint/eslint-plugin":"^8.59.4","@typescript-eslint/parser":"^8.59.4","@types/express":"^5.0.0",esbuild:"^0.27.4",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.3","ts-jest":"^29.4.10",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","server.json","README.md","LICENSE"]}});var Yn=ii(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.micros=Lp;Q.fromCents=Dp;Q.fromUsdc=Up;Q.fromUsd=jp;Q.toCents=Vp;Q.toCentsForAcquirer=qp;Q.toUsdc=Fp;Q.toWire=Bp;Q.fromWire=Hp;Q.toDisplay=Kp;Q.toUsdRounded2dp=Gp;Q.add=zp;Q.sub=Wp;Q.clampNonNegative=Jp;Q.isNonNegative=Yp;Q.max=Zp;Q.min=Xp;var nt=10000n,kc=1000000n;function Lp(e){return e}function Dp(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*nt}function Up(e){return e}function jp(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function Vp(e){if(e>=0n)return Number(e/nt);let t=e/nt,n=e%nt;return Number(n===0n?t:t-1n)}function qp(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/nt)}function Fp(e){return e}function Bp(e){return e.toString()}function Hp(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 Kp(e,t={}){let n=t.decimals??2,r=t.symbol??"$",s=e<0n,o=s?-e:e,i=o/kc,a=o%kc,l=s?"-":"";if(n===0)return`${l}${r}${i.toString()}`;let c=a.toString().padStart(6,"0").slice(0,n);return`${l}${r}${i.toString()}.${c}`}function Gp(e){let t=e<0n,n=t?-e:e,r=n/nt,o=n%nt*2n,i;o<nt?i=r:o>nt?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function zp(e,t){return e+t}function Wp(e,t){return e-t}function Jp(e){return e<0n?0n:e}function Yp(e){return e>=0n}function Zp(e,t){return e>t?e:t}function Xp(e,t){return e<t?e:t}});var ds={};_s(ds,{initSentry:()=>Jg,isSentryConfigured:()=>Wg,reportFatal:()=>Yg});function Wg(){return!1}async function Jg(){return null}async function Yg(e,t){process.exit(t?.exitCode??1)}var ms=cu(()=>{});var Mh={};_s(Mh,{printGroupHelpAndExit:()=>Pe});module.exports=lu(Mh);var Pl=require("commander"),fs=R(require("crypto")),$e=R(require("fs")),K=R(require("os")),At=R(require("path")),Ml=require("child_process"),Ol=R(require("node:readline/promises")),Nl=require("util");var mr=require("child_process"),yi=require("util"),ut=R(require("fs")),pr=R(require("os")),Cs=R(require("path"));var di=R(require("crypto"));var ze="e9501a252b778bce5a3d77710667afdd9198a750d1d989d95fb32d80e485bf15";var mi="VISA_ALLOW_INSECURE_MOCKS",ci,li,ui;function vs(e){return`${e}-${di.randomBytes(24).toString("base64url")}`}function pi(e=process.env){return e.NODE_ENV==="test"||e[mi]==="true"}function ct(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&pi(e)}function rn(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&pi(e)}function bs(){return`Set ${mi}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function fi(){return ci??=vs("mock-session"),ci}function gi(e=process.env){return e.NODE_ENV==="test"?ze:(li??=vs("mock-rc"),li)}function hi(){return ui??=vs("mock-signature"),ui}var Me=(0,yi.promisify)(mr.execFile),ks=Cs.join(pr.homedir(),".visa-mcp"),In=Cs.join(ks,"session-token"),Se="visa-cli",lt="session-token",ur="rc-access",uu=5e3,dr=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function du(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
2
+ `)}function _i(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=du(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function mu(){try{let{stdout:e}=await Me("security",["find-generic-password","-s",Se,"-a",lt,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(_i(e))throw new dr("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 pu(e){try{try{await Me("security",["delete-generic-password","-s",Se,"-a",lt],{timeout:5e3})}catch{}return await Me("security",["add-generic-password","-s",Se,"-a",lt,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function fu(){try{await Me("security",["delete-generic-password","-s",Se,"-a",lt],{timeout:5e3})}catch{}}async function gu(){if(!Ts())return null;try{let{stdout:e}=await Me("secret-tool",["lookup","service",Se,"account",lt],{timeout:5e3});return e.trim()||null}catch{return null}}async function hu(e){if(!Ts())return!1;try{let t=(0,mr.execFile)("secret-tool",["store","--label",`${Se} ${lt}`,"service",Se,"account",lt]);return t.stdin?(t.stdin.write(e),t.stdin.end(),await Promise.race([new Promise((n,r)=>{t.on("exit",s=>s===0?n():r(new Error(`secret-tool exited ${s}`))),t.on("error",r)}),new Promise((n,r)=>setTimeout(()=>{t.kill(),r(new Error("secret-tool timed out"))},uu))]),!0):!1}catch{return!1}}async function yu(){if(Ts())try{await Me("secret-tool",["clear","service",Se,"account",lt],{timeout:5e3})}catch{}}function Ts(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function _u(){try{let{stdout:e}=await Me("security",["find-generic-password","-s",Se,"-a",ur,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function vu(e){try{try{await Me("security",["delete-generic-password","-s",Se,"-a",ur],{timeout:5e3})}catch{}await Me("security",["add-generic-password","-s",Se,"-a",ur,"-w",e],{timeout:5e3})}catch{}}async function bu(){try{await Me("security",["delete-generic-password","-s",Se,"-a",ur],{timeout:5e3})}catch{}}function ws(){try{return ut.readFileSync(In,"utf-8").trim()||null}catch(e){if(_i(e))throw new dr(`Unable to read Visa CLI credentials from ${In}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function vi(e){ut.mkdirSync(ks,{recursive:!0,mode:448}),ut.writeFileSync(In,e,{mode:384}),process.platform==="win32"&&Su(In)}function xs(){try{ut.unlinkSync(In)}catch{}}function Su(e){try{let t=pr.userInfo().username;(0,mr.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 Ss(){switch(process.platform){case"darwin":return{get:mu,store:pu,delete:fu};case"linux":return{get:gu,store:hu,delete:yu};default:return{get:async()=>ws(),store:async e=>{try{return vi(e),!0}catch{return!1}},delete:async()=>xs(),storesInSessionFile:!0}}}var U=class{static async getSessionToken(){if(ct())return Promise.resolve(fi());let t=Ss(),n=await t.get();if(n)return n;let r=ws();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(ct())return;let n=Ss();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||xs();return}await n.delete()}if(vi(t),ws()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${ks} is writable.`))}static async getRcAccessToken(){return ct()?gi():_u()}static async saveRcAccessToken(t){ct()||await vu(t)}static async deleteSessionToken(){if(ct())return;await Ss().delete(),xs()}static async clearAll(){await this.deleteSessionToken(),await bu()}};var gr=R(require("crypto")),hr=R(require("tty")),yr=R(require("fs"));function xu(e){return/-rc\.|-beta\./.test(e)}function Es(e){return gr.createHash("sha256").update(e.trim()).digest("hex")}function bi(e){return ze==="SKIP"?!0:gr.timingSafeEqual(Buffer.from(Es(e)),Buffer.from(ze))}function Cu(){try{let e=yr.openSync("/dev/tty","r+"),t=new hr.ReadStream(e),n=new hr.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{yr.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 ku(e){return new Promise((t,n)=>{let r;try{r=Cu()}catch(u){n(u);return}let{input:s,output:o,cleanupStreams:i}=r,a=()=>{s.off("data",c);try{s.setRawMode?.(!1)}catch{}i()};o.write(e),s.setRawMode?.(!0),s.resume(),s.setEncoding("utf8");let l="",c=u=>{u==="\r"||u===`
3
3
  `?(o.write(`
4
4
  `),a(),t(l)):u===""?(o.write(`
5
- `),a(),n(new Error("Cancelled"))):u==="\x7F"||u==="\b"?l.length>0&&(l=l.slice(0,-1),o.write("\b \b")):(l+=u,o.write("\u2022"))};s.on("data",c)})}var xu=`
5
+ `),a(),n(new Error("Cancelled"))):u==="\x7F"||u==="\b"?l.length>0&&(l=l.slice(0,-1),o.write("\b \b")):(l+=u,o.write("\u2022"))};s.on("data",c)})}var Tu=`
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,16 +11,16 @@
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 vi(e={}){let t=e.version??dr().version;if(!bu(t))return;let n=process.env.VISA_RC_CODE;if(n&&_i(n)){await U.saveRcAccessToken(ks(n));return}if(e.isMcp??!1){let i=await U.getRcAccessToken();if(i&&(Ke==="SKIP"||i===Ke))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
15
- `),process.exit(1)}let s=await U.getRcAccessToken();if(s&&(Ke==="SKIP"||s===Ke))return;console.log(xu);let o=3;for(let i=1;i<=o;i++){let a;try{a=await wu(" Enter RC access code: ")}catch{process.exit(1)}if(_i(a)){await U.saveRcAccessToken(ks(a)),console.log(`
14
+ `;async function Si(e={}){let t=e.version??fr().version;if(!xu(t))return;let n=process.env.VISA_RC_CODE;if(n&&bi(n)){await U.saveRcAccessToken(Es(n));return}if(e.isMcp??!1){let i=await U.getRcAccessToken();if(i&&(ze==="SKIP"||i===ze))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
15
+ `),process.exit(1)}let s=await U.getRcAccessToken();if(s&&(ze==="SKIP"||s===ze))return;console.log(Tu);let o=3;for(let i=1;i<=o;i++){let a;try{a=await ku(" Enter RC access code: ")}catch{process.exit(1)}if(bi(a)){await U.saveRcAccessToken(Es(a)),console.log(`
16
16
  Access granted. Welcome.
17
17
  `);return}i<o&&console.log(`
18
18
  Invalid code. ${o-i} attempt(s) remaining.
19
19
  `)}console.log(`
20
20
  Invalid code. Contact your team lead.
21
- `),process.exit(1)}var Si=require("child_process");function Ts(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 Cu(e){let n=e.length+4;return[`\u250C${"\u2500".repeat(n)}\u2510`,`\u2502${" ".repeat(2)}${e}${" ".repeat(2)}\u2502`,`\u2514${"\u2500".repeat(n)}\u2518`].join(`
22
- `)}function In(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 wi(e,t){let n=In(e);if(!n)return null;let r,s;try{r=new URL(n),s=new URL(t)}catch{return null}return r.origin===s.origin?n:null}function xi(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 Ci(e,t=process.platform){let n=In(e);return n?xi(n,t):null}function bi(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function Es(e,t={}){let n=t.log??(c=>console.log(c)),r=t.env??process.env,s=t.platform??process.platform,o=In(e),i=t.spawn??((c,u,d)=>{(0,Si.execFile)(c,u,f=>d(f))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let c of Cu(o??e).split(`
23
- `))n(` ${c}`);if(n(""),!o){n(" (Auth URL is not a valid absolute http(s) URL \u2014 skipping browser auto-open.)"),n(" Open the URL above manually to continue."),n("");return}let a=Ts(r,s);if(a.headless){n(` (${a.reason} \u2014 skipping browser auto-open.)`),n(" Open the URL above on any device with a browser. The CLI will"),n(" continue waiting for you to complete sign-in."),n("");return}let l=xi(o,s);if(!l){n(` No known browser-open command for platform "${s}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(c=>{let u=d=>{d?bi(n,d):(n(" Opened browser. Waiting for you to sign in..."),n("")),c()};try{i(l.cmd,l.args,u)}catch(d){bi(n,d instanceof Error?d:new Error(String(d))),c()}})}function ku(e){return new Promise(t=>setTimeout(t,e))}function ki(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 Ti(e){return!Number.isFinite(e)||e===null||e<=0?1e3:Math.min(Math.max(Math.ceil(e),1e3),3e4)}async function Tu(e,t=Math.random()*250){let n=s=>Math.min(s+Math.max(0,Math.ceil(t)),3e4);if(!e||e.status!==429)return n(1e3);let r=ki(e.headers?.get("Retry-After"));if(r!==null)return n(Ti(r));if(typeof e.json=="function")try{let s=await e.json();return n(Ti(ki(s?.retryAfter)))}catch{return n(1e3)}return n(1e3)}async function ut(e,t){let n=await Tu(e);return t?.(n),await ku(n),n}var Vi=R(require("crypto")),Fi=require("child_process"),de=R(require("fs")),Bi=R(require("os")),he=R(require("path"));var j=R(require("fs")),At=R(require("os")),H=R(require("path")),Ii=require("child_process");var Ei=R(require("fs")),Eu=["npm","pnpm","yarn","bun"],Au=/\s+/;function Ru(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(Au)[0]??"",r=n.indexOf("/"),s=r===-1?n:n.slice(0,r);return Eu.includes(s)?s:void 0}function As(e){if(!e)return;let t=e;try{t=Ei.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 Iu(e=process.argv[1]){return Ru()??As(process.env.npm_execpath)??As(process.env.npm_node_execpath)??As(e)}function Rs(e,t,n){let r=t??Iu(n)??"npm",o=`@visa/cli@${e??"latest"}`;switch(r){case"npm":return{packageManager:r,command:"npm",args:["install","-g",o],display:`npm install -g ${o}`};case"pnpm":return{packageManager:r,command:"pnpm",args:["add","-g",o],display:`pnpm add -g ${o}`};case"yarn":return{packageManager:r,command:"yarn",args:["global","add",o],display:`yarn global add ${o}`};case"bun":return{packageManager:r,command:"bun",args:["add","-g",o],display:`bun add -g ${o}`}}}function rn(e,t,n){return Rs(e,t,n).display}var $u=2,on="# >>> visa-cli shell hud v2 >>>",gr="# <<< visa-cli shell hud v2 <<<",Ps="# >>> visa-cli shell hud >>>",Pu="# <<< visa-cli shell hud <<<",$i=3e4,Mu=6e4,Ou="VISA | HUD not ready \u2014 run: visa-cli config hud doctor",Nu={currentVersion:"0.0.0"},Lu=3e4;function Ms(){try{return H.join(Ls(),".visa-cli")}catch{return H.join(At.tmpdir(),".visa-cli")}}function dt(){return H.join(Ms(),"shell-hud.json")}function hr(){return H.join(Ms(),"shell-hud.line")}function Pi(){return H.join(Ms(),"shell-hud.lock")}function cn(e){let t=e??process.env.SHELL;if(!t)return null;let n=H.basename(t.replace(/\\/g,"/")).toLowerCase();return n==="zsh"?"zsh":n==="bash"?"bash":n==="pwsh"||n==="pwsh.exe"||n==="powershell"||n==="powershell.exe"?"powershell":null}function Pn(e){let t=Ls();if(e==="zsh")return H.join(t,".zshrc");if(e==="bash")return H.join(t,".bashrc");let n=(process.platform==="win32","PowerShell");return H.join(t,"Documents",n,"Microsoft.PowerShell_profile.ps1")}function Du(e){let t=Ls(),n=[{shell:"zsh",rcPath:H.join(t,".zshrc")},{shell:"bash",rcPath:H.join(t,".bashrc")},{shell:"bash",rcPath:H.join(t,".bash_profile")},{shell:"powershell",rcPath:H.join(t,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1")}];if(!e)return n;let r=n.filter(o=>o.shell===e),s=n.filter(o=>o.shell!==e);return[...r,...s]}function Uu(e){let t="$HOME/.visa-cli/shell-hud.line",n=Zu(e),r=Xu(e);if(e==="zsh")return`${on}
21
+ `),process.exit(1)}var xi=require("child_process");function As(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 Eu(e){let n=e.length+4;return[`\u250C${"\u2500".repeat(n)}\u2510`,`\u2502${" ".repeat(2)}${e}${" ".repeat(2)}\u2502`,`\u2514${"\u2500".repeat(n)}\u2518`].join(`
22
+ `)}function $n(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 Ci(e,t){let n=$n(e);if(!n)return null;let r,s;try{r=new URL(n),s=new URL(t)}catch{return null}return r.origin===s.origin?n:null}function ki(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 Ti(e,t=process.platform){let n=$n(e);return n?ki(n,t):null}function wi(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function Rs(e,t={}){let n=t.log??(c=>console.log(c)),r=t.env??process.env,s=t.platform??process.platform,o=$n(e),i=t.spawn??((c,u,d)=>{(0,xi.execFile)(c,u,f=>d(f))});n(""),n(" Sign in to Visa CLI by opening this URL in your browser:"),n("");for(let c of Eu(o??e).split(`
23
+ `))n(` ${c}`);if(n(""),!o){n(" (Auth URL is not a valid absolute http(s) URL \u2014 skipping browser auto-open.)"),n(" Open the URL above manually to continue."),n("");return}let a=As(r,s);if(a.headless){n(` (${a.reason} \u2014 skipping browser auto-open.)`),n(" Open the URL above on any device with a browser. The CLI will"),n(" continue waiting for you to complete sign-in."),n("");return}let l=ki(o,s);if(!l){n(` No known browser-open command for platform "${s}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(c=>{let u=d=>{d?wi(n,d):(n(" Opened browser. Waiting for you to sign in..."),n("")),c()};try{i(l.cmd,l.args,u)}catch(d){wi(n,d instanceof Error?d:new Error(String(d))),c()}})}function Au(e){return new Promise(t=>setTimeout(t,e))}function Ei(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 Ai(e){return!Number.isFinite(e)||e===null||e<=0?1e3:Math.min(Math.max(Math.ceil(e),1e3),3e4)}async function Ru(e,t=Math.random()*250){let n=s=>Math.min(s+Math.max(0,Math.ceil(t)),3e4);if(!e||e.status!==429)return n(1e3);let r=Ei(e.headers?.get("Retry-After"));if(r!==null)return n(Ai(r));if(typeof e.json=="function")try{let s=await e.json();return n(Ai(Ei(s?.retryAfter)))}catch{return n(1e3)}return n(1e3)}async function dt(e,t){let n=await Ru(e);return t?.(n),await Au(n),n}var Bi=R(require("crypto")),Hi=require("child_process"),de=R(require("fs")),Ki=R(require("os")),he=R(require("path"));var j=R(require("fs")),Rt=R(require("os")),H=R(require("path")),Pi=require("child_process");var Ri=R(require("fs")),Iu=["npm","pnpm","yarn","bun"],$u=/\s+/;function Pu(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split($u)[0]??"",r=n.indexOf("/"),s=r===-1?n:n.slice(0,r);return Iu.includes(s)?s:void 0}function Is(e){if(!e)return;let t=e;try{t=Ri.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 Mu(e=process.argv[1]){return Pu()??Is(process.env.npm_execpath)??Is(process.env.npm_node_execpath)??Is(e)}function $s(e,t,n){let r=t??Mu(n)??"npm",o=`@visa/cli@${e??"latest"}`;switch(r){case"npm":return{packageManager:r,command:"npm",args:["install","-g",o],display:`npm install -g ${o}`};case"pnpm":return{packageManager:r,command:"pnpm",args:["add","-g",o],display:`pnpm add -g ${o}`};case"yarn":return{packageManager:r,command:"yarn",args:["global","add",o],display:`yarn global add ${o}`};case"bun":return{packageManager:r,command:"bun",args:["add","-g",o],display:`bun add -g ${o}`}}}function sn(e,t,n){return $s(e,t,n).display}var Ou=2,an="# >>> visa-cli shell hud v2 >>>",_r="# <<< visa-cli shell hud v2 <<<",Os="# >>> visa-cli shell hud >>>",Nu="# <<< visa-cli shell hud <<<",Mi=3e4,Lu=6e4,Du="VISA | HUD not ready \u2014 run: visa-cli config hud doctor",Uu={currentVersion:"0.0.0"},ju=3e4;function Ns(){try{return H.join(Us(),".visa-cli")}catch{return H.join(Rt.tmpdir(),".visa-cli")}}function mt(){return H.join(Ns(),"shell-hud.json")}function vr(){return H.join(Ns(),"shell-hud.line")}function Oi(){return H.join(Ns(),"shell-hud.lock")}function ln(e){let t=e??process.env.SHELL;if(!t)return null;let n=H.basename(t.replace(/\\/g,"/")).toLowerCase();return n==="zsh"?"zsh":n==="bash"?"bash":n==="pwsh"||n==="pwsh.exe"||n==="powershell"||n==="powershell.exe"?"powershell":null}function Mn(e){let t=Us();if(e==="zsh")return H.join(t,".zshrc");if(e==="bash")return H.join(t,".bashrc");let n=(process.platform==="win32","PowerShell");return H.join(t,"Documents",n,"Microsoft.PowerShell_profile.ps1")}function Vu(e){let t=Us(),n=[{shell:"zsh",rcPath:H.join(t,".zshrc")},{shell:"bash",rcPath:H.join(t,".bashrc")},{shell:"bash",rcPath:H.join(t,".bash_profile")},{shell:"powershell",rcPath:H.join(t,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1")}];if(!e)return n;let r=n.filter(o=>o.shell===e),s=n.filter(o=>o.shell!==e);return[...r,...s]}function qu(e){let t="$HOME/.visa-cli/shell-hud.line",n=ed(e),r=td(e);if(e==="zsh")return`${an}
24
24
  _visa_cli_shell_hud_precmd() {
25
25
  setopt localoptions no_bg_nice
26
26
  if [[ -f "${t}" ]]; then
@@ -37,7 +37,7 @@ autoload -Uz add-zsh-hook
37
37
  if [[ -z "\${precmd_functions[(r)_visa_cli_shell_hud_precmd]}" ]]; then
38
38
  add-zsh-hook precmd _visa_cli_shell_hud_precmd
39
39
  fi
40
- ${gr}`;if(e==="powershell"){let s="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${on}
40
+ ${_r}`;if(e==="powershell"){let s="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${an}
41
41
  if (-not (Test-Path Function:\\global:__visa_cli_original_prompt)) {
42
42
  $function:global:__visa_cli_original_prompt = if (Test-Path Function:\\prompt) { $function:prompt } else { { '' } }
43
43
  }
@@ -56,7 +56,7 @@ function global:prompt {
56
56
  }
57
57
  & $function:global:__visa_cli_original_prompt
58
58
  }
59
- ${gr}`}return`${on}
59
+ ${_r}`}return`${an}
60
60
  __visa_cli_shell_hud_precmd() {
61
61
  if [ -f "${t}" ]; then
62
62
  cat "${t}"
@@ -73,42 +73,42 @@ case ";$PROMPT_COMMAND;" in
73
73
  *";__visa_cli_shell_hud_precmd;"*) ;;
74
74
  *) PROMPT_COMMAND="__visa_cli_shell_hud_precmd\${PROMPT_COMMAND:+;$PROMPT_COMMAND}" ;;
75
75
  esac
76
- ${gr}`}function Mi(e){let t=e;for(let[n,r]of[[on,gr],[Ps,Pu]])t=t.replace(new RegExp(`\\n?${Ri(n)}[\\s\\S]*?${Ri(r)}\\n?`,"g"),"");return t.trimEnd()}function ju(e,t){let n=Mi(e).trimEnd(),r=Uu(t);return n.length>0?`${n}
76
+ ${_r}`}function Ni(e){let t=e;for(let[n,r]of[[an,_r],[Os,Nu]])t=t.replace(new RegExp(`\\n?${$i(n)}[\\s\\S]*?${$i(r)}\\n?`,"g"),"");return t.trimEnd()}function Fu(e,t){let n=Ni(e).trimEnd(),r=qu(t);return n.length>0?`${n}
77
77
 
78
78
  ${r}
79
79
  `:`${r}
80
- `}function yr(e=cn()){if(!e)return!1;try{let t=Pn(e),n=j.readFileSync(t,"utf-8");return n.includes(on)||n.includes(Ps)}catch{return!1}}function Mn(e=At.homedir()){let t=[H.join(e,".zshrc"),H.join(e,".bashrc")],n=[];for(let r of t)try{if(!j.existsSync(r))continue;let s=j.readFileSync(r,"utf-8");(s.includes(on)||s.includes(Ps))&&n.push(r)}catch{}return n}function _r(e=cn()){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=Pn(e);let n=j.existsSync(t)?j.readFileSync(t,"utf-8"):"",r=ju(n,e),s=r!==n;return s&&an(t,r),{installed:!0,changed:s,shell:e,rcPath:t,message:s?`Persistent shell HUD installed in ${t}. Open a new terminal to start seeing it. Disable it any time with: visa-cli config shell-hud disable`:`Persistent shell HUD already installed in ${t}. Disable it any time with: visa-cli config shell-hud disable`}}catch(n){return{installed:!1,changed:!1,shell:e,rcPath:t,message:`Failed to install persistent shell HUD in ${t}: ${$s(n)}`}}}function vr(e=cn()){let t=[],n=[],r=[];try{for(let s of Du(e))if(n.push(s.rcPath),!!j.existsSync(s.rcPath))try{let o=j.readFileSync(s.rcPath,"utf-8"),i=Mi(o);if(i===o.trimEnd())continue;an(s.rcPath,i.length>0?`${i}
81
- `:""),t.push(s.rcPath)}catch(o){r.push(`${s.rcPath}: ${$s(o)}`)}return t.length>0?{removed:!0,shell:e,rcPath:t[0],rcPaths:t,message:r.length>0?`Removed persistent shell HUD from ${t.join(", ")}. Some rc files could not be updated: ${r.join("; ")}.`:`Removed persistent shell HUD from ${t.join(", ")}.`}:r.length>0?{removed:!1,shell:e,rcPath:n[0],rcPaths:n,message:`Failed to remove persistent shell HUD: ${r.join("; ")}`}:{removed:!0,shell:e,rcPath:n[0],rcPaths:n,message:"Persistent shell HUD was not installed in any supported shell rc file."}}catch(s){return{removed:!1,shell:e,message:`Failed to remove persistent shell HUD: ${$s(s)}`}}}function Os(e,t){let n=t??Nu,r=n.currentVersion==="0.0.0"&&e.version?e.version:n.currentVersion,s=Ge(r),o=` ${B("\u2502",q.dim)} `,i=Oi(n),a=Hu(n,i),l=a||n.updateCheckDisabled?"":i,c=Bu(s,l);if(!e.enrolled)return[c,B("setup needed",q.visaGold),a].filter(Boolean).join(o);let u=Ju(e),d=Fu(e),f=Ge(At.hostname().split(".")[0]),g=[c,f?B(f,q.dim):"",B(u,q.visaGold),a].filter(Boolean).join(o),w=[d,qu(e)].filter(Boolean),y=w.length>0?w.join(o):"";return y?`${g}
82
- ${y}`:g}function qu(e){let t=` ${B("\u2502",q.dim)} `,n=[];if(typeof e.dailySpent=="number"&&Number.isFinite(e.dailySpent)){let r=Math.max(0,e.dailySpent);n.push(B(`spent today ${sn(r)}`,q.dim))}if(typeof e.apiKeyCount=="number"&&Number.isFinite(e.apiKeyCount)){let r=Math.max(0,Math.floor(e.apiKeyCount)),s=r===1?"api key":"api keys";n.push(B(`${r} ${s}`,q.dim))}if(e.lastService&&typeof e.lastService.toolName=="string"&&e.lastService.toolName.length>0){let r=Ge(e.lastService.toolName),s=Vu(e.lastService.createdAt),o=B(s?`last ${r} ${s}`:`last ${r}`,q.dim);n.push(o)}return n.join(t)}function Vu(e){if(!e)return"";let t=Date.parse(e);if(!Number.isFinite(t))return"";let n=Date.now()-t;if(n<0)return"";let r=Math.floor(n/1e3);if(r<60)return`${r}s`;let s=Math.floor(r/60);if(s<60)return`${s}m`;let o=Math.floor(s/60);return o<24?`${o}h`:`${Math.floor(o/24)}d`}function Fu(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 B("balance unknown",q.dim);let r=t/100;if(n){let i=Math.max(0,n.capCents),a=Math.max(0,n.estimatedRemainingCents),l=Math.max(0,i-a),c=i>0?Math.max(0,Math.min(1,l/i)):0;return`${Wu(c)} ${B(`${sn(a/100)} in session`,q.green)} ${B(`(${sn(l/100)}/${sn(i/100)} cap)`,q.dim)} ${B("\xB7",q.dim)} ${B(`${sn(r)} balance`,q.dim)}`}let s=10,o=`balance ${sn(r)}`;return t>=s?B(o,q.green):B(`${o} \u2014 top up via buy_credits`,q.visaGold)}function Bu(e,t){let n=e,r=`${B("VISA CLI",q.visaBlue)} ${B(`v${n}`,q.visaBlueSoft)}`;if(!t)return r;let s=t;return`${r} ${B("\u2B06 update",q.visaGold)} ${B(`v${s}`,q.visaGold)}`}function Hu(e,t){if(t&&!e.updateCheckDisabled){let n=Ge(rn(t));return B(`run: ${n}`,q.visaGold)}return t?null:Ku(e)}function Oi(e){return e.latestVersion?Ge(e.latestVersion):""}function Ku(e){let t=Oi(e);return t?B(`update ready v${t}`,q.visaGold):null}function Ni(){let e=On();return!(!e||Date.now()-e.renderedAt>$i||e.cwd&&e.cwd!==process.cwd())}function br(){let e=On(),t=Date.now();if(e&&t-e.renderedAt<=$i||(zu(),e?.line))return Ai(e.line,e,t);try{let n=hr();if(j.existsSync(n)){let r=j.readFileSync(n,"utf-8").trimEnd();if(r&&!Ui(r))return r}}catch{}return Ou}function Ai(e,t,n){let r=n-t.renderedAt,s=typeof t.refreshFailedAt=="number"&&t.refreshFailedAt>t.renderedAt,o=[];if(r>=Mu&&o.push(`stale ${Gu(r)}`),s&&o.push("\u26A0 refresh failed"),o.length===0)return e;let i=` ${B("\xB7",q.dim)} ${B(o.join(" \xB7 "),q.visaGold)}`,a=e.split(`
80
+ `}function br(e=ln()){if(!e)return!1;try{let t=Mn(e),n=j.readFileSync(t,"utf-8");return n.includes(an)||n.includes(Os)}catch{return!1}}function On(e=Rt.homedir()){let t=[H.join(e,".zshrc"),H.join(e,".bashrc")],n=[];for(let r of t)try{if(!j.existsSync(r))continue;let s=j.readFileSync(r,"utf-8");(s.includes(an)||s.includes(Os))&&n.push(r)}catch{}return n}function Sr(e=ln()){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=Mn(e);let n=j.existsSync(t)?j.readFileSync(t,"utf-8"):"",r=Fu(n,e),s=r!==n;return s&&cn(t,r),{installed:!0,changed:s,shell:e,rcPath:t,message:s?`Persistent shell HUD installed in ${t}. Open a new terminal to start seeing it. Disable it any time with: visa-cli config shell-hud disable`:`Persistent shell HUD already installed in ${t}. Disable it any time with: visa-cli config shell-hud disable`}}catch(n){return{installed:!1,changed:!1,shell:e,rcPath:t,message:`Failed to install persistent shell HUD in ${t}: ${Ms(n)}`}}}function wr(e=ln()){let t=[],n=[],r=[];try{for(let s of Vu(e))if(n.push(s.rcPath),!!j.existsSync(s.rcPath))try{let o=j.readFileSync(s.rcPath,"utf-8"),i=Ni(o);if(i===o.trimEnd())continue;cn(s.rcPath,i.length>0?`${i}
81
+ `:""),t.push(s.rcPath)}catch(o){r.push(`${s.rcPath}: ${Ms(o)}`)}return t.length>0?{removed:!0,shell:e,rcPath:t[0],rcPaths:t,message:r.length>0?`Removed persistent shell HUD from ${t.join(", ")}. Some rc files could not be updated: ${r.join("; ")}.`:`Removed persistent shell HUD from ${t.join(", ")}.`}:r.length>0?{removed:!1,shell:e,rcPath:n[0],rcPaths:n,message:`Failed to remove persistent shell HUD: ${r.join("; ")}`}:{removed:!0,shell:e,rcPath:n[0],rcPaths:n,message:"Persistent shell HUD was not installed in any supported shell rc file."}}catch(s){return{removed:!1,shell:e,message:`Failed to remove persistent shell HUD: ${Ms(s)}`}}}function Ls(e,t){let n=t??Uu,r=n.currentVersion==="0.0.0"&&e.version?e.version:n.currentVersion,s=We(r),o=` ${B("\u2502",V.dim)} `,i=Li(n),a=zu(n,i),l=a||n.updateCheckDisabled?"":i,c=Gu(s,l);if(!e.enrolled)return[c,B("setup needed",V.visaGold),a].filter(Boolean).join(o);let u=Xu(e),d=Ku(e),f=We(Rt.hostname().split(".")[0]),g=[c,f?B(f,V.dim):"",B(u,V.visaGold),a].filter(Boolean).join(o),w=[d,Bu(e)].filter(Boolean),y=w.length>0?w.join(o):"";return y?`${g}
82
+ ${y}`:g}function Bu(e){let t=` ${B("\u2502",V.dim)} `,n=[];if(typeof e.dailySpent=="number"&&Number.isFinite(e.dailySpent)){let r=Math.max(0,e.dailySpent);n.push(B(`spent today ${on(r)}`,V.dim))}if(typeof e.apiKeyCount=="number"&&Number.isFinite(e.apiKeyCount)){let r=Math.max(0,Math.floor(e.apiKeyCount)),s=r===1?"api key":"api keys";n.push(B(`${r} ${s}`,V.dim))}if(e.lastService&&typeof e.lastService.toolName=="string"&&e.lastService.toolName.length>0){let r=We(e.lastService.toolName),s=Hu(e.lastService.createdAt),o=B(s?`last ${r} ${s}`:`last ${r}`,V.dim);n.push(o)}return n.join(t)}function Hu(e){if(!e)return"";let t=Date.parse(e);if(!Number.isFinite(t))return"";let n=Date.now()-t;if(n<0)return"";let r=Math.floor(n/1e3);if(r<60)return`${r}s`;let s=Math.floor(r/60);if(s<60)return`${s}m`;let o=Math.floor(s/60);return o<24?`${o}h`:`${Math.floor(o/24)}d`}function Ku(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 B("balance unknown",V.dim);let r=t/100;if(n){let i=Math.max(0,n.capCents),a=Math.max(0,n.estimatedRemainingCents),l=Math.max(0,i-a),c=i>0?Math.max(0,Math.min(1,l/i)):0;return`${Zu(c)} ${B(`${on(a/100)} in session`,V.green)} ${B(`(${on(l/100)}/${on(i/100)} cap)`,V.dim)} ${B("\xB7",V.dim)} ${B(`${on(r)} balance`,V.dim)}`}let s=10,o=`balance ${on(r)}`;return t>=s?B(o,V.green):B(`${o} \u2014 top up via buy_credits`,V.visaGold)}function Gu(e,t){let n=e,r=`${B("VISA CLI",V.visaBlue)} ${B(`v${n}`,V.visaBlueSoft)}`;if(!t)return r;let s=t;return`${r} ${B("\u2B06 update",V.visaGold)} ${B(`v${s}`,V.visaGold)}`}function zu(e,t){if(t&&!e.updateCheckDisabled){let n=We(sn(t));return B(`run: ${n}`,V.visaGold)}return t?null:Wu(e)}function Li(e){return e.latestVersion?We(e.latestVersion):""}function Wu(e){let t=Li(e);return t?B(`update ready v${t}`,V.visaGold):null}function Di(){let e=Nn();return!(!e||Date.now()-e.renderedAt>Mi||e.cwd&&e.cwd!==process.cwd())}function xr(){let e=Nn(),t=Date.now();if(e&&t-e.renderedAt<=Mi||(Yu(),e?.line))return Ii(e.line,e,t);try{let n=vr();if(j.existsSync(n)){let r=j.readFileSync(n,"utf-8").trimEnd();if(r&&!Vi(r))return r}}catch{}return Du}function Ii(e,t,n){let r=n-t.renderedAt,s=typeof t.refreshFailedAt=="number"&&t.refreshFailedAt>t.renderedAt,o=[];if(r>=Lu&&o.push(`stale ${Ju(r)}`),s&&o.push("\u26A0 refresh failed"),o.length===0)return e;let i=` ${B("\xB7",V.dim)} ${B(o.join(" \xB7 "),V.visaGold)}`,a=e.split(`
83
83
  `);for(let l=a.length-1;l>=0;l--)if(a[l].length>0)return a[l]=`${a[l]}${i}`,a.join(`
84
- `);return`${e}${i}`}function Gu(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 Ns(e,t){try{let n=H.dirname(dt());j.mkdirSync(n,{recursive:!0});let r=e.split(`
85
- `).map(o=>Ge(o)).filter(o=>o.length>0).join(`
86
- `),s={hudVersion:$u,renderedAt:Date.now(),line:r,cwd:process.cwd(),status:t};an(dt(),JSON.stringify(s)+`
87
- `),an(hr(),r+`
88
- `)}catch{}}function Li(e){try{let t=On();if(!t)return;let n=Math.max(Date.now(),t.renderedAt+1),r={...t,refreshFailedAt:n,refreshErrorReason:Ge(e).slice(0,200)};an(dt(),JSON.stringify(r)+`
89
- `)}catch{}}function Di(){try{let e=On();if(!e)return;let t={...e,renderedAt:0};an(dt(),JSON.stringify(t)+`
90
- `)}catch{}}function $n(){try{j.unlinkSync(Pi())}catch{}}function On(){let e=dt();if(!j.existsSync(e))return null;try{let t=JSON.parse(j.readFileSync(e,"utf-8"));return typeof t?.line=="string"&&Ui(t.line)?null:t}catch{return null}}function Ui(e){let t=(e.split(`
91
- `)[0]??"").trim();if(t.length===0)return!1;let n=t.replace(/\[[0-?]*[ -/]*[@-~]/g,"").trim();return!!(/^VISA\s*\|\s*loading\b/i.test(n)||/^VISA\s*\|\s*HUD\s+not\s+(ready|initialized)\b/i.test(n))}function ji(){return On()?.status??null}function zu(){if(process.env.JEST_WORKER_ID)return;let e=Pi();try{if(j.mkdirSync(H.dirname(e),{recursive:!0}),!Qu(e))return;let t=process.argv[1]?H.resolve(process.argv[1]):"";if(!t){$n();return}let n=(0,Ii.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});n.once("error",$n),n.unref()}catch{$n()}}function Ge(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim()}function Wu(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${B(r||"",q.green)}${B(s||"",q.dim)}`}function sn(e){return`$${e.toFixed(2)}`}function Ju(e){let t=e.cards?.find(a=>a.isDefault)??e.cards?.[0];if(!t)return"card none";let n=typeof t.brand=="string"?t.brand:"card",r=typeof t.last4=="string"?t.last4:"????",s=Ge(n.toUpperCase()),o=Ge(r);return`${t.isDefault?"default":"active"} ${s} ****${o}`}function Yu(){let e=(process.env.COLORTERM??"").toLowerCase();if(e==="truecolor"||e==="24bit")return!0;let t=(process.env.TERM??"").toLowerCase();return t.includes("truecolor")||t.includes("24bit")}var Is=Yu(),q={reset:"\x1B[0m",visaBlue:Is?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:Is?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:Is?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function B(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${q.reset}`}function Ri(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ls(){let e=At.homedir();if(!e||!H.isAbsolute(e))throw new Error("unable to determine a valid home directory");return H.resolve(e)}function Zu(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function Xu(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function Qu(e){for(let t=0;t<2;t+=1){let n;try{return n=j.openSync(e,"wx"),j.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=j.statSync(e);if(Date.now()-s.mtimeMs<=Lu)return!1;j.unlinkSync(e)}catch{}}finally{n!==void 0&&j.closeSync(n)}}return!1}function $s(e){return e instanceof Error?e.message:"unknown file system error"}function an(e,t){j.mkdirSync(H.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;j.writeFileSync(n,t),j.renameSync(n,e)}function Hi(e,t){de.mkdirSync(he.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Vi.randomBytes(8).toString("hex")}.tmp`;try{de.writeFileSync(n,JSON.stringify(t,null,2)+`
92
- `),de.renameSync(n,e)}catch(r){try{de.unlinkSync(n)}catch{}throw r}}function qi(e){return`'${e.replace(/'/g,"'\\''")}'`}var Us="# visa-cli-hud-v1";function ed(e,t){if(!e&&!t&&td())return`visa-cli config statusline ${Us}`;let n=e??process.execPath,r=t??process.argv[1]??"",s=r?he.resolve(r):"";return`${s?`${qi(n)} ${qi(s)} config statusline`:"visa-cli config statusline"} ${Us}`}function td(){try{return(0,Fi.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function Rt(e){return typeof e!="string"?!1:e.includes(Us)?!0:e.includes("visa-cli")&&e.includes("statusline")}function nd(e){let t=he.dirname(he.resolve(e));return he.basename(t)===".claude"?he.dirname(t):Bi.homedir()}function rd(e,t){let n=he.relative(t,e);return!n.startsWith("..")&&!he.isAbsolute(n)?`~/${n}`:e}function Ds(e,t){let n=nd(t),r=Mn(n);if(r.length===0)return e;let s=r.map(o=>rd(o,n)).join(", ");return`${e}
93
- Note: a legacy shell-prompt HUD block was detected in ${s}. Remove it with: visa-cli config hud disable shell`}function Nn(e,t=ed){let n={},r=!1;if(de.existsSync(e)){r=!0;try{n=JSON.parse(de.readFileSync(e,"utf-8"))}catch(s){return{installed:"malformed-json",message:`~/.claude/settings.json is not valid JSON (${s.message}). Fix the file manually, then run: visa-cli config hud enable claude`}}}if(n.statusLine){let s=typeof n.statusLine=="object"?n.statusLine.command:"";return Rt(s)?{installed:"already-visa",message:Ds("Visa HUD already registered in ~/.claude/settings.json.",e)}:{installed:"other-hud-present",message:Ds("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()},Hi(e,n),{installed:"new",message:Ds(`Visa HUD registered in ~/.claude/settings.json${r?"":" (new file)"}. Restart Claude Code to see it pinned below the input.`,e)}}catch(s){return{installed:"error",message:`Failed to write settings: ${s.message}. Enable manually later with: visa-cli config hud enable claude`}}}function js(e){if(!de.existsSync(e))return{removed:!1,message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(de.readFileSync(e,"utf-8"))}catch(r){return{removed:!1,message:`~/.claude/settings.json is not valid JSON: ${r.message}`}}if(!t.statusLine)return{removed:!1,message:"No statusLine configured."};let n=typeof t.statusLine=="object"?t.statusLine.command:"";return Rt(n)?(delete t.statusLine,Hi(e,t),{removed:!0,message:"Visa HUD removed from ~/.claude/settings.json. Restart Claude Code to take effect."}):{removed:!1,message:"statusLine is owned by another tool \u2014 leaving it alone."}}var ze=R(require("fs")),Me=R(require("path")),sd=1,It={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},od=["terminal","claude","claude-code","all"];function wr(e){let t=e.toLowerCase();return od.includes(t)?t:null}var id=50,ad=64*1024,Ki=10,qs=80;function cd(){let e=(process.env.COLORTERM??"").toLowerCase();if(e==="truecolor"||e==="24bit")return!0;let t=(process.env.TERM??"").toLowerCase();return t.includes("truecolor")||t.includes("24bit")}var Vs=cd(),S={reset:"\x1B[0m",visaBlue:Vs?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:Vs?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:Vs?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function x(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${S.reset}`}function Gi(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function Yi(e=process.stdin){return e.isTTY?null:new Promise(t=>{let n=[],r=!1,s=()=>{e.removeListener("data",i),e.removeListener("end",a),e.removeListener("error",l),clearTimeout(c)},o=u=>{r||(r=!0,s(),t(u))},i=u=>{n.push(typeof u=="string"?Buffer.from(u):u)},a=()=>{let u=Buffer.concat(n).toString("utf-8").trim();if(!u)return o(null);try{let d=JSON.parse(u);o(d&&typeof d=="object"?d:null)}catch{o(null)}},l=()=>o(null),c=setTimeout(()=>{n.length>0?a():o(null)},id);e.on("data",i),e.on("end",a),e.on("error",l)})}function Ln(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${x(r||"",S.visaBlueSoft)}${x(s||"",S.dim)}`}function Dn(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 ld(e){if(ia(e))return dd(e);let t=` ${x("\u2502",S.dim)} `,n=Sr(e)||"claude",r=e.cwd?Y(Me.basename(e.cwd)):"",s=xr(e.workspace),o=r||s,i=s&&s!==o?` ${x(`@${s}`,S.visaBlueSoft)}`:"",a=[x(`[${n}]`,S.visaBlueSoft)];o&&a.push(`${x(o,S.visaGold)}${i}`);let l=Y(e.git_branch??e.branch??"");l&&a.push(`${x("git:(",S.dim)}${x(l,S.visaBlueSoft)}${x(")",S.dim)}`);let c=a.join(t),u=Number(e.context_window?.context_window_size??0),d=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,f=e.context_window?.current_usage,g=[f?.input_tokens,f?.output_tokens,f?.cache_creation_input_tokens,f?.cache_read_input_tokens].filter(z=>typeof z=="number"&&Number.isFinite(z)),w=g.length>0?g.reduce((z,F)=>z+F,0):null,y=Number(e.context_window?.total_input_tokens??w??f?.input_tokens??0),k=d!==null?Math.max(0,Math.min(1,d/100)):u>0?Math.max(0,Math.min(1,y/u)):0,O=d!==null&&u>0?Math.round(k*u):y,N;if(u>0||d!==null){let z=`${String(Math.round(k*100)).padStart(2," ")}%`,F=u>0?` ${x(`(${Dn(O)}/${Dn(u)})`,S.dim)}`:"";N=`${x("Context",S.dim)} ${Ln(k)} ${x(z,S.green)}${F}`}else N=`${x("Context",S.dim)} ${x("-",S.dim)}`;let C=Zi(e.rate_limits),T=[N];C&&T.push(C);let V=T.join(t);return`${c}
94
- ${V}`}function ud(e){if(ia(e))return null;let t=` ${x("\u2502",S.dim)} `,n=Sr(e)||"claude",r=e.cwd?Y(Me.basename(e.cwd)):"",s=xr(e.workspace),o=r||s,i=s&&s!==o?` ${x(`@${s}`,S.visaBlueSoft)}`:"",a=[x(`[${n}]`,S.visaBlueSoft)];o&&a.push(`${x(o,S.visaGold)}${i}`);let l=Y(e.git_branch??e.branch??"");l&&a.push(`${x("git:(",S.dim)}${x(l,S.visaBlueSoft)}${x(")",S.dim)}`);let c=Number(e.context_window?.context_window_size??0),u=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,d=e.context_window?.current_usage,f=[d?.input_tokens,d?.output_tokens,d?.cache_creation_input_tokens,d?.cache_read_input_tokens].filter(T=>typeof T=="number"&&Number.isFinite(T)),g=f.length>0?f.reduce((T,V)=>T+V,0):null,w=Number(e.context_window?.total_input_tokens??g??d?.input_tokens??0),y=u!==null?Math.max(0,Math.min(1,u/100)):c>0?Math.max(0,Math.min(1,w/c)):0,k=u!==null&&c>0?Math.round(y*c):w,O;if(c>0||u!==null){let T=`${String(Math.round(y*100)).padStart(2," ")}%`,V=c>0?` ${x(`(${Dn(k)}/${Dn(c)})`,S.dim)}`:"";O=`${x("Context",S.dim)} ${Ln(y)} ${x(T,S.green)}${V}`}else O=`${x("Context",S.dim)} ${x("-",S.dim)}`;let N=Zi(e.rate_limits),C=[O];return N&&C.push(N),{identity:a.join(t),metrics:C.join(t)}}function dd(e){let t=` ${x("\u2502",S.dim)} `,n=aa(e),r=n.model||"codex",s=[x(`[${r}]`,S.visaBlueSoft)];n.project&&s.push(x(n.project,S.visaGold)),n.gitBranch&&s.push(`${x("git",S.dim)} ${x(n.gitBranch,S.visaGold)}`);let o=s.join(t),i=[];if(typeof n.contextUsedPercent=="number"){let l=Math.max(0,Math.min(1,n.contextUsedPercent/100));i.push(`${x("Context",S.dim)} ${Ln(l)} ${x(`${Math.round(n.contextUsedPercent)}%`,S.green)}`)}else if(typeof n.contextRemainingPercent=="number"){let l=100-n.contextRemainingPercent,c=Math.max(0,Math.min(1,l/100));i.push(`${x("Context",S.dim)} ${Ln(c)} ${x(`${Math.round(l)}%`,S.green)}`)}typeof n.usedTokens=="number"&&i.push(`${x("Tokens",S.dim)} ${Dn(n.usedTokens)}`),n.status&&i.push(`${x("Status",S.dim)} ${x(n.status,S.visaBlueSoft)}`),n.threadTitle&&i.push(`${x("Thread",S.dim)} ${x(n.threadTitle,S.visaBlueSoft)}`);let a=i.length>0?i.join(t):`${x("Context",S.dim)} ${x("-",S.dim)}`;return`${o}
95
- ${a}`}function md(e){if(typeof e!="number"||e<=0)return"";let n=(e>1e12?e:e*1e3)-Date.now();if(n<=0||n>=10080*60*1e3)return"";let r=Math.floor(n/6e4),s=Math.floor(r/60),o=r%60;return s>0?`${s}h ${o}m`:`${o}m`}function zi(e,t){if(!e||typeof e.used_percentage!="number")return null;let n=Math.max(0,Math.min(100,e.used_percentage)),r=n/100,s=Ln(r),o=n>=90?"\x1B[38;5;196m":n>=70?S.visaGold:S.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=md(e.resets_at),l=a?` ${x(`(${a} / ${t})`,S.dim)}`:` ${x(`(${t})`,S.dim)}`;return`${s} ${x(i,o)}${l}`}function Zi(e){if(!e)return null;let t=zi(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?zi(e.seven_day,"7d"):null;if(!t&&!r)return null;let s=` ${x("\u2502",S.dim)} `,o=[t,r].filter(Boolean);return`${x("Usage",S.dim)} ${o.join(s)}`}function Xi(e){let t;try{let n=ze.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let s=Math.min(r,ad),o=r-s;t=ze.openSync(e,"r");let i=Buffer.alloc(s);ze.readSync(t,i,0,s,o);let a=i.toString("utf-8");if(o>0){let l=Buffer.alloc(1);if(ze.readSync(t,l,0,1,o-1),l[0]!==10){let c=a.indexOf(`
96
- `);c>=0&&(a=a.slice(c+1))}}return a}catch{return null}finally{if(t!==void 0)try{ze.closeSync(t)}catch{}}}function pd(e){if(!e||typeof e!="object")return;let t=e,n=["file_path","path","notebook_path","pattern","command","url"];for(let r of n){let s=t[r];if(typeof s=="string"&&s.length>0){if(r.endsWith("_path")||r==="path"){let o=Me.basename(Me.dirname(s)),i=Me.basename(s);return o&&o!=="."&&o!=="/"?`${o}/${i}`:i}return s}}}function fd(e){let t=e.split(`
97
- `),n=[],r=new Set;for(let s=t.length-1;s>=0&&n.length<Ki*3;s-=1){let o=t[s].trim();if(!o)continue;let i;try{i=JSON.parse(o)}catch{continue}if(!i||typeof i!="object")continue;let l=i.message;if(!l||typeof l!="object")continue;let c=l.content;if(Array.isArray(c))for(let u of c){if(!u||typeof u!="object")continue;let 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:"",g=f.length>0?!r.has(f):!1;n.push({name:d.name,target:pd(d.input),running:g})}}}return n.reverse(),n.slice(Math.max(0,n.length-Ki))}function gd(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 hd(e){let t=e.running?x("\u25D0",S.visaGold):x("\u2713",S.green),n=e.running?S.visaGold:S.visaBlueSoft,r=x(Y(e.name),n),s=e.target?Y(e.target):"",o=s?`${x(":",S.dim)} ${x(s,S.dim)}`:"",i=e.count>1?` ${x(`\xD7${e.count}`,S.dim)}`:"";return o?`${t} ${r}${o}${i}`:`${t} ${r}${i}`}function yd(e){let t=` ${x("\u2502",S.dim)} `,n=Gi(t),r=e.slice();for(;r.length>0;){let l=r.join(t);if(Gi(l)<=qs)return l;r=r.slice(1)}if(e.length===0)return"";let s="\u2026",i=e[e.length-1].replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,""),a=i.length>qs-n-1?i.slice(0,qs-n-1)+s:i;return`${x(s,S.dim)}${t}${a}`}async function Wi(e){if(!e||typeof e!="string")return null;let t=Xi(e);if(!t)return null;let n;try{n=fd(t)}catch{return null}if(n.length===0)return null;let s=gd(n).map(hd);return yd(s)||null}async function Qi(e,t,n){return(await ta(e,t,n)).join(`
98
- `)}function ea(e,t,n){let r=!!t?.activeSession||e.includes("in session"),s=n?vd(n):!1;return{isActive:r||s,hasSession:r,hasToolActivity:s}}async function ta(e,t,n){let{isActive:r}=ea(e,n,t?.transcript_path),s=e.split(`
99
- `).filter(a=>a.length>0),i=t&&!r?s.map(a=>x(Fs(a),S.dim)):[...s];if(t){let a=ud(t);if(a){if(i.push(a.identity),t.transcript_path){let l=await Wi(t.transcript_path);l&&i.push(...l.split(`
100
- `))}i.push(a.metrics)}else{let l=ld(t);if(l&&i.push(...l.split(`
101
- `)),t.transcript_path){let c=await Wi(t.transcript_path);c&&i.push(...c.split(`
102
- `))}}}return i}var _d=["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 vd(e){let t=Xi(e);if(!t)return!1;let n=t.slice(-16384).toLowerCase();return _d.some(r=>n.includes(`"${r}"`))}async function na(e,t,n){let r=await ta(e,t,n),s=r.join(`
103
- `),{isActive:o}=ea(e,n,t?.transcript_path);return{schemaVersion:sd,client:t?oa(t):It.UNKNOWN,rendered:s,lines:r.map(Fs),visa:{spendLine:Fs(e),balanceCents:n?.balanceCents,balanceUsd:n?.amountUsd,sessionMode:n?.sessionMode,activeSession:n?.activeSession,isVisaActive:o},context:t?aa(t):{}}}function Y(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 xr(e){if(typeof e=="string")return Y(Me.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 Y(t?Me.basename(t):e.name)}function ra(e){return Y(e.app_name??e.appName??e.app??e.client)}function Sr(e){return Y(e.model?.display_name??e.model?.id??e.model_name??e.modelName)}function sa(e){return Y(e.cwd??e.current_dir??e.project_root)}function Ji(e){let t=Y(e.project);if(t)return t;let n=sa(e);if(n)return Y(Me.basename(n));let r=xr(e.workspace);return r||""}function Te(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function oa(e){let t=ra(e).toLowerCase();return t.includes("codex")?It.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?It.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||Te(e.context_used)!==void 0?It.CODEX:It.UNKNOWN}function ia(e){return oa(e)===It.CODEX}function aa(e){let t=ra(e),n=sa(e),r=xr(e.workspace),s=Te(e.context_used)??Te(e.context_window?.used_percentage??void 0),o=Te(e.context_remaining)??Te(e.context_window?.remaining_percentage??void 0);return{...t?{app:t}:{},...Sr(e)?{model:Sr(e)}:{},...Ji(e)?{project:Ji(e)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...Y(e.git_branch??e.branch)?{gitBranch:Y(e.git_branch??e.branch)}:{},...Y(e.status??e.run_state??e.runState)?{status:Y(e.status??e.run_state??e.runState)}:{},...Y(e.thread_title??e.threadTitle)?{threadTitle:Y(e.thread_title??e.threadTitle)}:{},...s!==void 0?{contextUsedPercent:s}:{},...o!==void 0?{contextRemainingPercent:o}:{},...Te(e.used_tokens)!==void 0?{usedTokens:Te(e.used_tokens)}:{},...Te(e.total_input_tokens)!==void 0?{totalInputTokens:Te(e.total_input_tokens)}:{},...Te(e.total_output_tokens)!==void 0?{totalOutputTokens:Te(e.total_output_tokens)}:{}}}function Fs(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}var la=R(require("path"));function ca(e){return e instanceof Error?e.message:String(e)}function Bs(e,t){let n=[],r=[],s=e??"claude",o=wr(s);if(s==="shell"||s==="prompt")try{let a=t.installShellHud();return a.installed?{ok:!0,messages:[a.message],errors:r}:{ok:!1,messages:n,errors:[a.message]}}catch(a){return{ok:!1,messages:n,errors:[`Failed to install shell HUD: ${ca(a)}`]}}if(!o)return{ok:!1,messages:n,errors:[`Unknown HUD surface: ${s}`,"Supported: claude (default), shell, all"]};let i=!0;if(o==="claude"||o==="claude-code"||o==="all"){let a=la.join(t.homeDir,".claude","settings.json");try{let l=t.installVisaStatusLine(a);n.push(l.message),(l.installed==="error"||l.installed==="malformed-json")&&(i=!1)}catch(l){i=!1,r.push(`Failed to install Claude HUD: ${ca(l)}`)}}return{ok:i,messages:n,errors:r}}async function $t(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,s=setTimeout(()=>r.abort(),n);try{let{timeoutMs:o,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(s)}}var Pt=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},ln=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}},Mt=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}},oe=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(t,n,r,s,o,i,a,l){super(t),this.name="CardDeclinedError",this.retryable=n,this.code=r,this.reason=s,this.paymentErrorClass=o,this.correlationId=i,this.transactionId=a,this.retryAfter=l}};var ua={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 Hs(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&&ua[n]?ua[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 bd=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function ma(e,t){let n=da(e),r=da(t);if(!n||!r)return!1;for(let s=0;s<3;s++)if(n.main[s]!==r.main[s])return n.main[s]>r.main[s];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:Sd(n.pre,r.pre)>0}function da(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(bd);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function Sd(e,t){let n=e.split("."),r=t.split("."),s=Math.max(n.length,r.length);for(let o=0;o<s;o++){if(o>=n.length)return-1;if(o>=r.length)return 1;let i=n[o],a=r[o],l=/^\d+$/.test(i),c=/^\d+$/.test(a);if(l&&c){let u=Number(i)-Number(a);if(u!==0)return u}else{if(l)return-1;if(c)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function Oe(){return!!(pa(process.env.VISA_CLI_NO_UPDATE_CHECK)||pa(process.env.CI)||process.env.NODE_ENV==="test")}function pa(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var pt=R(require("fs")),Zs=require("node:net"),_a=R(require("os")),va=R(require("path"));var Cr=R(require("fs")),fa=R(require("path")),ga=R(require("os"));var Ks=fa.join(ga.homedir(),".visa-mcp"),Un=class{static ensureConfigDir(){Cr.existsSync(Ks)||Cr.mkdirSync(Ks,{recursive:!0,mode:448})}static getConfigDir(){return Ks}static TOOL_STATES={login:!0,get_status:!0,get_cards:!0,add_card:!0,pay:!1,transaction_history:!0,update_spending_controls:!0,enroll_device:!1,verify_otp:!1,reset:!0,batch:!0,generate_x402_image:!1,browser_launch:!1,browser_navigate:!1,browser_snapshot:!1,browser_click:!1,browser_type:!1,browser_scroll:!1,generate_music_card:!1,generate_image_card:!1,query_onchain_prices_card:!1,generate_music_tempo_card:!1,check_music_status_tempo_card:!1,generate_image_fast_card:!1,generate_video_tempo_card:!1};static loadToolStates(){return{...this.TOOL_STATES}}static getDisabledTools(){let t=new Set;for(let[n,r]of Object.entries(this.TOOL_STATES))r||t.add(n);return t}static isToolDisabled(t){return this.TOOL_STATES[t]===!1}};var me=R(require("fs")),Ws=R(require("path")),ha=R(require("os")),zs=Ws.join(ha.homedir(),".visa-mcp"),jn=Ws.join(zs,"mcp-server.log"),wd=5*1024*1024,Gs=null;function xd(){me.existsSync(zs)||me.mkdirSync(zs,{recursive:!0,mode:448})}function Cd(){if(!Gs){if(xd(),me.existsSync(jn)&&me.statSync(jn).size>wd){let t=jn+".1";me.existsSync(t)&&me.unlinkSync(t),me.renameSync(jn,t)}Gs=me.createWriteStream(jn,{flags:"a"})}return Gs}function kd(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function kr(e,...t){let n=new Date().toISOString(),r=t.map(o=>typeof o=="string"?o:JSON.stringify(o,null,2)).join(" "),s=`[${n}] [${e}] ${r}
104
- `;kd(e)&&process.stderr.write(s),Cd().write(s)}var m={debug:(...e)=>kr("DEBUG",...e),info:(...e)=>kr("INFO",...e),warn:(...e)=>kr("WARN",...e),error:(...e)=>kr("ERROR",...e)};function ya(e){let t=_a.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}var Td="settings.json",Ed="must use https unless it points at localhost/loopback for local development";function qn(){return va.join(Un.getConfigDir(),Td)}function ba(e){if((0,Zs.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function Ad(e){let t=e.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!t)return!1;let n=Number.parseInt(t[1],16),r=Number.parseInt(t[2],16);if(!Number.isFinite(n)||!Number.isFinite(r))return!1;let s=[n>>8&255,n&255,r>>8&255,r&255].join(".");return ba(s)}function Rd(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,Zs.isIP)(t);return n===4?ba(t):n===6?t==="::1"||Ad(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:"&&Rd(n.hostname)))throw new Error(`${t} ${Ed}`)}var ft={"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(s=>s.trim()).filter(Boolean);for(let s of r)if(!n.test(s))throw new Error(`merchants.discover: "${s}" is not a valid merchant slug`)}},"credit.sessionCapCents":{type:"number",description:"Default cap (in cents) for start_session and pay-as-you-go one-shot approvals. Server clamps to [10, 10000] = $0.10\u2013$100. Default 500 ($5).",validate:e=>{if(typeof e!="number"||!Number.isFinite(e))throw new Error("credit.sessionCapCents must be a number");if(!Number.isInteger(e))throw new Error("credit.sessionCapCents must be a whole number of cents (no fractional cents)");if(e<10||e>1e4)throw new Error("credit.sessionCapCents must be between 10 ($0.10) and 10000 ($100)")}}},Xs=500,Tr={"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 Ot(){let e=qn();if(!pt.existsSync(e))return{};try{let t=pt.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?(m.warn("settings:corrupt",{path:ya(e),reason:"not_object"}),{}):n}catch(t){return m.warn("settings:corrupt",{path:ya(e),error:t?.message||String(t)}),{}}}function Ys(e){Un.ensureConfigDir();let t=qn(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
105
- `;pt.writeFileSync(n,r,{mode:384}),pt.renameSync(n,t)}function Qs(e){let t=Ot()[e];return typeof t=="string"?t:void 0}function Er(e){let t=Ot()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function eo(e){let t=Ot()[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 We=class extends Error{constructor(t){let n=Object.keys(ft).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"}},Je=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"}},mt=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+Tr[t]),this.name="RetiredSettingKeyError"}},Sa=["biometric.","spending.","account.","cards.","biometric"];function Ar(e,t){if(Sa.some(o=>e.startsWith(o)))throw new Je(e);if(e in Tr)throw new mt(e);let n=ft[e];if(!n)throw new We(e);let r;if(n.type==="boolean")if(typeof t=="boolean")r=t;else if(typeof t=="string"){let o=t.toLowerCase();if(o==="true")r=!0;else if(o==="false")r=!1;else throw new Error(`${e} expects true or false (got: ${JSON.stringify(t)})`)}else throw new Error(`${e} expects a boolean (got: ${typeof t})`);else if(n.type==="number")if(typeof t=="number")r=t;else if(typeof t=="string"&&t.trim().length>0){let o=Number(t);if(!Number.isFinite(o))throw new Error(`${e} expects a number (got: ${JSON.stringify(t)})`);r=o}else throw new Error(`${e} expects a number (got: ${typeof t})`);else{if(typeof t!="string"||t.length===0)throw new Error(`${e} expects a non-empty string`);r=t}n.validate&&n.validate(r);let s=Ot();return s[e]=r,Ys(s),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:qn()}}function Rr(e){if(Sa.some(o=>e.startsWith(o)))throw new Je(e);let t=ft[e];if(e in Tr){let o=Ot(),i=e in o;return i&&(delete o[e],Ys(o)),{key:e,removed:i,requiresRestart:!1,path:qn()}}if(!t)throw new We(e);let r=Ot(),s=e in r;return s&&(delete r[e],Ys(r)),{key:e,removed:s,requiresRestart:s&&!!t.requiresRestart,path:qn()}}function wa(){let e=Ot();return Object.entries(Tr).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}var Id="https://auth.visacli.sh",$d="https://auth-visa-code-preview.up.railway.app";function Pd(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function Md(){try{let e=dr();return Pd(e.version)}catch{return!1}}function Od(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?$d:Id}function we(){return Od({envVar:process.env.VISA_AUTH_URL,settingValue:Qs("auth.serverUrl"),isPrerelease:Md()})}function xa(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":Er("ui.suppressBrowser")??!1}function Ca(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":Er("ui.suppressFeed")??!1}function ka(){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=eo("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):Xs}var Nd="CARD_REENROLLMENT_REQUIRED",Ta="https://visacli.sh/enroll-card";function Ld(e){if(typeof e!="string")return Ta;try{let t=new URL(e),n=t.hostname==="localhost"||t.hostname==="127.0.0.1";if((t.protocol==="https:"&&(t.hostname==="visacli.sh"||t.hostname.endsWith(".visacli.sh"))||n)&&t.pathname==="/enroll-card")return t.toString()}catch{}return Ta}var Vn="2.1.1",Dd=/^vk_[A-Za-z0-9_-]{32,}$/;function Ud(e){if(typeof e!="string")return null;switch(e){case"BUDGET_CLOSED":case"BUDGET_NOT_FOUND":case"BUDGET_EXPIRED":return e;default:return null}}var jd="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function un(e){return typeof e=="string"?e.trim():""}function Ea(e){let t=e&&typeof e=="object"?e:{},n=un(t.error)||un(t.message);if(!n)return jd;let r=un(t.error_code),s=[["surface",un(t.disabled_surface)],["flag",un(t.flag)],["correlation_id",un(t.correlation_id)]].filter(([,i])=>i).map(([i,a])=>`${i}=${a}`),o=s.length?` (${s.join(" ")})`:"";return r?`503 [${r}] ${n}${o}`:`503 ${n}${o}`}function Aa(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?Dd.test(r)?(n.push("VISA_CLI_API_KEY is set, but MCP bearer tools currently require a local session from visa-cli setup."),n.push("For headless API-key use, call the /v1/api/* HTTP routes with X-Api-Key instead of MCP bearer tools.")):(n.push("VISA_CLI_API_KEY is set but has invalid format (expected vk_<32+ base64url chars>)."),n.push("Create a new token with: visa-cli tokens create <app-name>")):n.push("Run `visa-cli setup` in an interactive terminal to authenticate."),t===!1&&n.push("This process appears to be running without a TTY; complete setup in a normal terminal, then restart the MCP client."),n.join(`
106
- `)}var ye=class{constructor(t){this.getSessionToken=t;this.baseUrl=we()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!Oe()){let r=t.headers.get("X-Latest-Version");r&&ma(r,Vn)&&(this.lastSignals.updateAvailable={currentVersion:Vn,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return Vn}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new Pt(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(Ea(n))}async request(t,n,r,s,o,i){let a=await this.getSessionToken();if(!a)throw new Error(Aa());let l={Authorization:`Bearer ${a}`};o&&(t==="GET"?l["X-User-Context"]=encodeURIComponent(o.replace(/[\r\n\0]/g," ").slice(0,1e3)):r={...r||{},user_context:o}),i&&(l["X-Visa-Meta-Tool"]=i),r&&(l["Content-Type"]="application/json");let c;try{c=await $t(`${this.baseUrl}${n}`,{method:t,headers:{...l,"X-Visa-CLI-Version":Vn,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:s})}catch(d){throw new Error(Hs(d))}if(this.parseServerSignals(c),c.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(c.status===429){let d=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${d}s. Tip: use the batch tool to combine multiple requests into one.`)}c.status===503&&await this.throwServerUnavailable(c);let u;try{u=await c.json()}catch{throw c.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${n}. Try again.`)}if(!c.ok){if(c.status===500)throw new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(u),typeof u?.error_code=="string"&&u.error_code===Nd){let d=typeof u?.last4=="string"?u.last4:"",f=typeof u?.brand=="string"?u.brand:"card",g=Ld(u?.reenroll_url),w=d?`${f} ending in ${d}`:"your card";throw new Error(`Please re-add ${w} to keep payments running. Open: ${g}`)}if(u?.declined){let d=Number(u.retryAfter??c.headers.get("Retry-After"));throw new oe(u.error||"Your card was declined.",!!u.retryable,u.code,u.reason,u.payment_error_class,u.correlation_id,u.transactionId,Number.isFinite(d)&&d>0?d:void 0)}if(c.status===402){let d=u?.error||"Gateway returned 402",f=typeof u?.error_code=="string"?u.error_code:"";throw f==="SPENDING_LIMIT_EXCEEDED"||f==="DAILY_LIMIT_EXCEEDED"||f==="PER_TXN_LIMIT_EXCEEDED"?new Error(`${d}. Check your limits with get_status or run: visa-cli update-spending-controls`):new Error(d)}throw new Error(u?.error||`Request failed (${c.status}). Try again.`)}return u}async shortcut(t,n,r,s,o){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,s,o)}async shortcutWithSession(t,n,r,s,o,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,l=await this.getSessionToken();if(!l)throw new Error(Aa());let c={Authorization:`Bearer ${l}`,"X-Visa-CLI-Version":Vn,"X-Source":"cli","Content-Type":"application/json"};i&&(c["X-Visa-Meta-Tool"]=i);let u={...n,...r};o&&(u.user_context=o.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await $t(`${this.baseUrl}${a}`,{method:"POST",headers:c,body:JSON.stringify(u),timeoutMs:s})}catch(w){throw new Error(Hs(w))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let w=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${w}s. Tip: use the batch tool to combine multiple requests into one.`)}let f=d.headers.get("X-Voucher-Receipt"),g;try{g=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(g),d.status===503){if(g?.error_code==="SESSION_LOCK_CONTENDED"){let y=Number(d.headers.get("Retry-After"))||1;throw new Mt(g?.message||g?.error||"Session budget is being modified by another request. Retry shortly.",y,d.status)}throw new Error(Ea(g))}let w=Ud(g?.error_code);if(w||d.status===410){let y=w??"BUDGET_CLOSED";throw new ln(g?.message||g?.error||"Your session was invalidated by the server.",y,{budgetId:n.session_budget_id,status:d.status})}if(g?.declined){let y=Number(g.retryAfter??d.headers.get("Retry-After"));throw new oe(g.error||"Your card was declined.",!!g.retryable,g.code,g.reason,g.payment_error_class,g.correlation_id,g.transactionId,Number.isFinite(y)&&y>0?y:void 0)}throw new Error(g?.error||`Request failed (${d.status}). Try again.`)}return{data:g,voucherReceiptHeader:f}}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async catalogSearch(t,n,r,s){let o=r??"discover_tools",i=new URLSearchParams;t&&i.set("q",t),n&&i.set("category",n),s?.limit!=null&&i.set("limit",String(s.limit)),s?.offset!=null&&i.set("offset",String(s.offset));let a=i.toString();return this.request("GET",`/v1/catalog${a?`?${a}`:""}`,void 0,void 0,void 0,o)}async catalogTool(t,n){let r=n??"discover_tools";try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(t)}`,void 0,void 0,void 0,r)}catch{return null}}async discoverMerchantRoutes(t){try{return await this.request("GET",`/v1/platform/discover/${encodeURIComponent(t)}`)}catch{return null}}async listPublicMerchants(){try{let t=await $t(`${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 $t(`${this.baseUrl}/v1/platform/discover/${encodeURIComponent(t)}`,{method:"GET",timeoutMs:8e3});return n.ok?await n.json():null}catch{return null}}async paymentPreview(t,n){return this.request("POST","/v1/payment-preview",t,void 0,n)}async getBalance(){return this.request("GET","/v1/balance")}async topupBalance(t){return this.request("POST","/v1/balance/topup",t)}async createEnrollCode(){return this.request("POST","/v1/enroll-code")}async getAutoTopup(){let t=await this.getBalance();return{success:t.success,targetCents:t.autoTopupCents??null,thresholdCents:t.autoTopupThresholdCents??0}}async disableAutoTopup(){return this.request("PATCH","/v1/balance/auto-topup",{auto_topup_cents:null})}async createSessionBudget(t){return this.request("POST","/v1/session-budget/create",{...t,mode:"prepaid"})}async closeSession(t){return this.request("POST","/v1/session/close",{session_budget_id:t})}async getSessionBudget(t){return this.request("GET",`/v1/session-budget/${encodeURIComponent(t)}`)}async getSessionLedger(t){return this.request("GET",`/v1/session/${encodeURIComponent(t)}/ledger`)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getVisaSmi(t,n){return this.request("POST","/v1/visa/smi",t,6e4,n)}async getTransactions(t,n){let r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.offset!=null&&r.set("offset",String(t.offset));let s=r.toString(),o=s?`/v1/transactions?${s}`:"/v1/transactions";return this.request("GET",o,void 0,void 0,n)}async updateSpendingControls(t,n){return this.request("POST","/v1/spending-controls",t,void 0,n)}async removeCard(t,n,r){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(t))}`,n,void 0,r)}async setDefaultCard(t,n,r){return this.request("POST",`/v1/cards/${encodeURIComponent(String(t))}/default`,n,void 0,r)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t,n){return this.request("POST","/v1/attestation-key",{publicKey:t,...n?{attestation:n}:{}})}async startAttestationRecovery(t,n){return this.request("POST","/v1/attestation-key/recovery/start",{state:t},void 0,n)}async setBiometricPreference(t,n){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,n)}async logout(t,n){return this.request("POST","/v1/logout",t,void 0,n)}async feedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async createAppApiKey(t){return this.request("POST","/v1/api/keys",t)}async listAppApiKeys(){return this.request("GET","/v1/api/keys")}async revokeAppApiKey(t){return this.request("DELETE",`/v1/api/keys/${encodeURIComponent(String(t))}`)}async feedSubmit(t){return this.request("POST","/v1/feed",t)}async feedList(t){let n=new URLSearchParams;t?.tab&&n.set("tab",t.tab),t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset));let r=n.toString();return this.request("GET",`/v1/feed${r?"?"+r:""}`)}async feedVote(t,n){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/vote`,{direction:n})}async feedApprove(t){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/approve`)}async feedDelete(t){return this.request("DELETE",`/v1/feed/${encodeURIComponent(t)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async getFeedback(t,n){let r=new URLSearchParams;t&&r.set("limit",String(t));let s=r.toString();return this.request("GET",`/v1/feedback${s?"?"+s:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}};var p={};oi(p,{BRAND:()=>dm,DIRTY:()=>Nt,EMPTY_PATH:()=>Bd,INVALID:()=>E,NEVER:()=>Jm,OK:()=>ie,ParseStatus:()=>re,Schema:()=>M,ZodAny:()=>yt,ZodArray:()=>Qe,ZodBigInt:()=>Dt,ZodBoolean:()=>Ut,ZodBranded:()=>Bn,ZodCatch:()=>Jt,ZodDate:()=>jt,ZodDefault:()=>Wt,ZodDiscriminatedUnion:()=>Pr,ZodEffects:()=>ke,ZodEnum:()=>Gt,ZodError:()=>pe,ZodFirstPartyTypeKind:()=>A,ZodFunction:()=>Or,ZodIntersection:()=>Bt,ZodIssueCode:()=>h,ZodLazy:()=>Ht,ZodLiteral:()=>Kt,ZodMap:()=>hn,ZodNaN:()=>_n,ZodNativeEnum:()=>zt,ZodNever:()=>Ee,ZodNull:()=>Vt,ZodNullable:()=>De,ZodNumber:()=>Lt,ZodObject:()=>fe,ZodOptional:()=>xe,ZodParsedType:()=>v,ZodPipeline:()=>Hn,ZodPromise:()=>_t,ZodReadonly:()=>Yt,ZodRecord:()=>Mr,ZodSchema:()=>M,ZodSet:()=>yn,ZodString:()=>ht,ZodSymbol:()=>fn,ZodTransformer:()=>ke,ZodTuple:()=>Le,ZodType:()=>M,ZodUndefined:()=>qt,ZodUnion:()=>Ft,ZodUnknown:()=>Xe,ZodVoid:()=>gn,addIssueToContext:()=>_,any:()=>bm,array:()=>Cm,bigint:()=>gm,boolean:()=>ja,coerce:()=>Wm,custom:()=>La,date:()=>hm,datetimeRegex:()=>Oa,defaultErrorMap:()=>Ye,discriminatedUnion:()=>Am,effect:()=>qm,enum:()=>Dm,function:()=>Om,getErrorMap:()=>dn,getParsedType:()=>Ne,instanceof:()=>pm,intersection:()=>Rm,isAborted:()=>Ir,isAsync:()=>mn,isDirty:()=>$r,isValid:()=>gt,late:()=>mm,lazy:()=>Nm,literal:()=>Lm,makeIssue:()=>Fn,map:()=>Pm,nan:()=>fm,nativeEnum:()=>Um,never:()=>wm,null:()=>vm,nullable:()=>Fm,number:()=>Ua,object:()=>km,objectUtil:()=>to,oboolean:()=>zm,onumber:()=>Gm,optional:()=>Vm,ostring:()=>Km,pipeline:()=>Hm,preprocess:()=>Bm,promise:()=>jm,quotelessJson:()=>qd,record:()=>$m,set:()=>Mm,setErrorMap:()=>Fd,strictObject:()=>Tm,string:()=>Da,symbol:()=>ym,transformer:()=>qm,tuple:()=>Im,undefined:()=>_m,union:()=>Em,unknown:()=>Sm,util:()=>L,void:()=>xm});var L;(function(e){e.assertEqual=s=>{};function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{let o={};for(let i of s)o[i]=i;return o},e.getValidEnumValues=s=>{let o=e.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(let a of o)i[a]=s[a];return e.objectValues(i)},e.objectValues=s=>e.objectKeys(s).map(function(o){return s[o]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},e.find=(s,o)=>{for(let i of s)if(o(i))return i},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}e.joinValues=r,e.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(L||(L={}));var to;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(to||(to={}));var v=L.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ne=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=L.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),qd=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),pe=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(o){return o.message},r={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,l=0;for(;l<i.path.length;){let c=i.path[l];l===i.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(i))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return s(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,L.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];n[o]=n[o]||[],n[o].push(t(s))}else r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};pe.create=e=>new pe(e);var Vd=(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,L.jsonStringifyReplacer)}`;break;case h.unrecognized_keys:n=`Unrecognized key(s) in object: ${L.joinValues(e.keys,", ")}`;break;case h.invalid_union:n="Invalid input";break;case h.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${L.joinValues(e.options)}`;break;case h.invalid_enum_value:n=`Invalid enum value. Expected ${L.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}"`:L.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,L.assertNever(e)}return{message:n}},Ye=Vd;var Ra=Ye;function Fd(e){Ra=e}function dn(){return Ra}var Fn=e=>{let{data:t,path:n,errorMaps:r,issueData:s}=e,o=[...n,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)a=c(i,{data:t,defaultError:a}).message;return{...s,path:o,message:a}},Bd=[];function _(e,t){let n=dn(),r=Fn({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Ye?void 0:Ye].filter(s=>!!s)});e.common.issues.push(r)}var re=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let s of n){if(s.status==="aborted")return E;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let s of n){let o=await s.key,i=await s.value;r.push({key:o,value:i})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let s of n){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return E;o.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(r[o.value]=i.value)}return{status:t.value,value:r}}},E=Object.freeze({status:"aborted"}),Nt=e=>({status:"dirty",value:e}),ie=e=>({status:"valid",value:e}),Ir=e=>e.status==="aborted",$r=e=>e.status==="dirty",gt=e=>e.status==="valid",mn=e=>typeof Promise<"u"&&e instanceof Promise;var b;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(b||(b={}));var Ce=class{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Ia=(e,t)=>{if(gt(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 pe(e.common.issues);return this._error=n,this._error}}};function $(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(i,a)=>{let{message:l}=e;return i.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:s}}var M=class{get description(){return this._def.description}_getType(t){return Ne(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Ne(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new re,ctx:{common:t.parent.common,data:t.data,parsedType:Ne(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(mn(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:Ne(t)},s=this._parseSync({data:t,path:r.path,parent:r});return Ia(r,s)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Ne(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return gt(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=>gt(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:Ne(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(mn(s)?s:Promise.resolve(s));return Ia(r,o)}refine(t,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{let i=t(s),a=()=>o.addIssue({code:h.custom,...r(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new ke({schema:this,typeName:A.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 xe.create(this,this._def)}nullable(){return De.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Qe.create(this)}promise(){return _t.create(this,this._def)}or(t){return Ft.create([this,t],this._def)}and(t){return Bt.create(this,t,this._def)}transform(t){return new ke({...$(this._def),schema:this,typeName:A.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new Wt({...$(this._def),innerType:this,defaultValue:n,typeName:A.ZodDefault})}brand(){return new Bn({typeName:A.ZodBranded,type:this,...$(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new Jt({...$(this._def),innerType:this,catchValue:n,typeName:A.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Hn.create(this,t)}readonly(){return Yt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Hd=/^c[^\s-]{8,}$/i,Kd=/^[0-9a-z]+$/,Gd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,zd=/^[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,Wd=/^[a-z0-9_-]{21}$/i,Jd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Yd=/^[-+]?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)?)??$/,Zd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Xd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",no,Qd=/^(?:(?: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])$/,em=/^(?:(?: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])$/,tm=/^(([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]))$/,nm=/^(([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])$/,rm=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,sm=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Pa="((\\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])))",om=new RegExp(`^${Pa}$`);function Ma(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 im(e){return new RegExp(`^${Ma(e)}$`)}function Oa(e){let t=`${Pa}T${Ma(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 am(e,t){return!!((t==="v4"||!t)&&Qd.test(e)||(t==="v6"||!t)&&tm.test(e))}function cm(e,t){if(!Jd.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||t&&s.alg!==t)}catch{return!1}}function lm(e,t){return!!((t==="v4"||!t)&&em.test(e)||(t==="v6"||!t)&&nm.test(e))}var ht=class e extends M{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==v.string){let o=this._getOrReturnCtx(t);return _(o,{code:h.invalid_type,expected:v.string,received:o.parsedType}),E}let r=new re,s;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(s=this._getOrReturnCtx(t,s),_(s,{code:h.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")t.data.length>o.value&&(s=this._getOrReturnCtx(t,s),_(s,{code:h.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){let i=t.data.length>o.value,a=t.data.length<o.value;(i||a)&&(s=this._getOrReturnCtx(t,s),i?_(s,{code:h.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&_(s,{code:h.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")Zd.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"email",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")no||(no=new RegExp(Xd,"u")),no.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"emoji",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")zd.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"uuid",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")Wd.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"nanoid",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")Hd.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"cuid",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")Kd.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"cuid2",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")Gd.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"ulid",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),_(s,{validation:"url",code:h.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"regex",code:h.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(t,s),_(s,{code:h.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(s=this._getOrReturnCtx(t,s),_(s,{code:h.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(s=this._getOrReturnCtx(t,s),_(s,{code:h.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?Oa(o).test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{code:h.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?om.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{code:h.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?im(o).test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{code:h.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?Yd.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"duration",code:h.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?am(t.data,o.version)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"ip",code:h.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?cm(t.data,o.alg)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"jwt",code:h.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?lm(t.data,o.version)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"cidr",code:h.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?rm.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"base64",code:h.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?sm.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"base64url",code:h.invalid_string,message:o.message}),r.dirty()):L.assertNever(o);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:h.invalid_string,...b.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...b.errToObj(t)})}url(t){return this._addCheck({kind:"url",...b.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...b.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...b.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...b.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...b.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...b.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...b.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...b.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...b.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...b.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...b.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...b.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...b.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...b.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...b.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...b.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...b.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...b.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...b.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...b.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...b.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...b.errToObj(n)})}nonempty(t){return this.min(1,b.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};ht.create=e=>new ht({checks:[],typeName:A.ZodString,coerce:e?.coerce??!1,...$(e)});function um(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,o=Number.parseInt(e.toFixed(s).replace(".","")),i=Number.parseInt(t.toFixed(s).replace(".",""));return o%i/10**s}var Lt=class e extends M{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 o=this._getOrReturnCtx(t);return _(o,{code:h.invalid_type,expected:v.number,received:o.parsedType}),E}let r,s=new re;for(let o of this._def.checks)o.kind==="int"?L.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),_(r,{code:h.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),_(r,{code:h.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),_(r,{code:h.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?um(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),_(r,{code:h.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),_(r,{code:h.not_finite,message:o.message}),s.dirty()):L.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,b.toString(n))}gt(t,n){return this.setLimit("min",t,!1,b.toString(n))}lte(t,n){return this.setLimit("max",t,!0,b.toString(n))}lt(t,n){return this.setLimit("max",t,!1,b.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:b.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:b.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:b.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:b.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:b.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:b.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:b.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:b.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:b.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:b.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&L.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};Lt.create=e=>new Lt({checks:[],typeName:A.ZodNumber,coerce:e?.coerce||!1,...$(e)});var Dt=class e extends M{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,s=new re;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),_(r,{code:h.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),_(r,{code:h.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),_(r,{code:h.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):L.assertNever(o);return{status:s.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return _(n,{code:h.invalid_type,expected:v.bigint,received:n.parsedType}),E}gte(t,n){return this.setLimit("min",t,!0,b.toString(n))}gt(t,n){return this.setLimit("min",t,!1,b.toString(n))}lte(t,n){return this.setLimit("max",t,!0,b.toString(n))}lt(t,n){return this.setLimit("max",t,!1,b.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:b.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:b.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:b.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:b.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:b.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:b.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};Dt.create=e=>new Dt({checks:[],typeName:A.ZodBigInt,coerce:e?.coerce??!1,...$(e)});var Ut=class extends M{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==v.boolean){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:v.boolean,received:r.parsedType}),E}return ie(t.data)}};Ut.create=e=>new Ut({typeName:A.ZodBoolean,coerce:e?.coerce||!1,...$(e)});var jt=class e extends M{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==v.date){let o=this._getOrReturnCtx(t);return _(o,{code:h.invalid_type,expected:v.date,received:o.parsedType}),E}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return _(o,{code:h.invalid_date}),E}let r=new re,s;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(s=this._getOrReturnCtx(t,s),_(s,{code:h.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(s=this._getOrReturnCtx(t,s),_(s,{code:h.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):L.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:b.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:b.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};jt.create=e=>new jt({checks:[],coerce:e?.coerce||!1,typeName:A.ZodDate,...$(e)});var fn=class extends M{_parse(t){if(this._getType(t)!==v.symbol){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:v.symbol,received:r.parsedType}),E}return ie(t.data)}};fn.create=e=>new fn({typeName:A.ZodSymbol,...$(e)});var qt=class extends M{_parse(t){if(this._getType(t)!==v.undefined){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:v.undefined,received:r.parsedType}),E}return ie(t.data)}};qt.create=e=>new qt({typeName:A.ZodUndefined,...$(e)});var Vt=class extends M{_parse(t){if(this._getType(t)!==v.null){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:v.null,received:r.parsedType}),E}return ie(t.data)}};Vt.create=e=>new Vt({typeName:A.ZodNull,...$(e)});var yt=class extends M{constructor(){super(...arguments),this._any=!0}_parse(t){return ie(t.data)}};yt.create=e=>new yt({typeName:A.ZodAny,...$(e)});var Xe=class extends M{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ie(t.data)}};Xe.create=e=>new Xe({typeName:A.ZodUnknown,...$(e)});var Ee=class extends M{_parse(t){let n=this._getOrReturnCtx(t);return _(n,{code:h.invalid_type,expected:v.never,received:n.parsedType}),E}};Ee.create=e=>new Ee({typeName:A.ZodNever,...$(e)});var gn=class extends M{_parse(t){if(this._getType(t)!==v.undefined){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:v.void,received:r.parsedType}),E}return ie(t.data)}};gn.create=e=>new gn({typeName:A.ZodVoid,...$(e)});var Qe=class e extends M{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==v.array)return _(n,{code:h.invalid_type,expected:v.array,received:n.parsedType}),E;if(s.exactLength!==null){let i=n.data.length>s.exactLength.value,a=n.data.length<s.exactLength.value;(i||a)&&(_(n,{code:i?h.too_big:h.too_small,minimum:a?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(_(n,{code:h.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(_(n,{code:h.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>s.type._parseAsync(new Ce(n,i,n.path,a)))).then(i=>re.mergeArray(r,i));let o=[...n.data].map((i,a)=>s.type._parseSync(new Ce(n,i,n.path,a)));return re.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:b.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:b.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:b.toString(n)}})}nonempty(t){return this.min(1,t)}};Qe.create=(e,t)=>new Qe({type:e,minLength:null,maxLength:null,exactLength:null,typeName:A.ZodArray,...$(t)});function pn(e){if(e instanceof fe){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=xe.create(pn(r))}return new fe({...e._def,shape:()=>t})}else return e instanceof Qe?new Qe({...e._def,type:pn(e.element)}):e instanceof xe?xe.create(pn(e.unwrap())):e instanceof De?De.create(pn(e.unwrap())):e instanceof Le?Le.create(e.items.map(t=>pn(t))):e}var fe=class e extends M{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=L.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==v.object){let c=this._getOrReturnCtx(t);return _(c,{code:h.invalid_type,expected:v.object,received:c.parsedType}),E}let{status:r,ctx:s}=this._processInputParams(t),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ee&&this._def.unknownKeys==="strip"))for(let c in s.data)i.includes(c)||a.push(c);let l=[];for(let c of i){let u=o[c],d=s.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Ce(s,d,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Ee){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(c==="strict")a.length>0&&(_(s,{code:h.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let u of a){let d=s.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Ce(s,d,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of l){let d=await u.key,f=await u.value;c.push({key:d,value:f,alwaysSet:u.alwaysSet})}return c}).then(c=>re.mergeObjectSync(r,c)):re.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return b.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:b.errToObj(t).message??s}:{message:s}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:A.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of L.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let r of L.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return pn(this)}partial(t){let n={};for(let r of L.objectKeys(this.shape)){let s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let r of L.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof xe;)o=o._def.innerType;n[r]=o}return new e({...this._def,shape:()=>n})}keyof(){return Na(L.objectKeys(this.shape))}};fe.create=(e,t)=>new fe({shape:()=>e,unknownKeys:"strip",catchall:Ee.create(),typeName:A.ZodObject,...$(t)});fe.strictCreate=(e,t)=>new fe({shape:()=>e,unknownKeys:"strict",catchall:Ee.create(),typeName:A.ZodObject,...$(t)});fe.lazycreate=(e,t)=>new fe({shape:e,unknownKeys:"strip",catchall:Ee.create(),typeName:A.ZodObject,...$(t)});var Ft=class extends M{_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new pe(a.ctx.common.issues));return _(n,{code:h.invalid_union,unionErrors:i}),E}if(n.common.async)return Promise.all(r.map(async o=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let l of r){let c={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(l=>new pe(l));return _(n,{code:h.invalid_union,unionErrors:a}),E}}get options(){return this._def.options}};Ft.create=(e,t)=>new Ft({options:e,typeName:A.ZodUnion,...$(t)});var Ze=e=>e instanceof Ht?Ze(e.schema):e instanceof ke?Ze(e.innerType()):e instanceof Kt?[e.value]:e instanceof Gt?e.options:e instanceof zt?L.objectValues(e.enum):e instanceof Wt?Ze(e._def.innerType):e instanceof qt?[void 0]:e instanceof Vt?[null]:e instanceof xe?[void 0,...Ze(e.unwrap())]:e instanceof De?[null,...Ze(e.unwrap())]:e instanceof Bn||e instanceof Yt?Ze(e.unwrap()):e instanceof Jt?Ze(e._def.innerType):[],Pr=class e extends M{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==v.object)return _(n,{code:h.invalid_type,expected:v.object,received:n.parsedType}),E;let r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(_(n,{code:h.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),E)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let s=new Map;for(let o of n){let i=Ze(o.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of i){if(s.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);s.set(a,o)}}return new e({typeName:A.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...$(r)})}};function ro(e,t){let n=Ne(e),r=Ne(t);if(e===t)return{valid:!0,data:e};if(n===v.object&&r===v.object){let s=L.objectKeys(t),o=L.objectKeys(e).filter(a=>s.indexOf(a)!==-1),i={...e,...t};for(let a of o){let l=ro(e[a],t[a]);if(!l.valid)return{valid:!1};i[a]=l.data}return{valid:!0,data:i}}else if(n===v.array&&r===v.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let o=0;o<e.length;o++){let i=e[o],a=t[o],l=ro(i,a);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return n===v.date&&r===v.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Bt=class extends M{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=(o,i)=>{if(Ir(o)||Ir(i))return E;let a=ro(o.value,i.value);return a.valid?(($r(o)||$r(i))&&n.dirty(),{status:n.value,value:a.data}):(_(r,{code:h.invalid_intersection_types}),E)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Bt.create=(e,t,n)=>new Bt({left:e,right:t,typeName:A.ZodIntersection,...$(n)});var Le=class e extends M{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==v.array)return _(r,{code:h.invalid_type,expected:v.array,received:r.parsedType}),E;if(r.data.length<this._def.items.length)return _(r,{code:h.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),E;!this._def.rest&&r.data.length>this._def.items.length&&(_(r,{code:h.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...r.data].map((i,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Ce(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>re.mergeArray(n,i)):re.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Le.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Le({items:e,typeName:A.ZodTuple,rest:null,...$(t)})};var Mr=class e extends M{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 _(r,{code:h.invalid_type,expected:v.object,received:r.parsedType}),E;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in r.data)s.push({key:o._parse(new Ce(r,a,r.path,a)),value:i._parse(new Ce(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?re.mergeObjectAsync(n,s):re.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof M?new e({keyType:t,valueType:n,typeName:A.ZodRecord,...$(r)}):new e({keyType:ht.create(),valueType:t,typeName:A.ZodRecord,...$(n)})}},hn=class extends M{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 _(r,{code:h.invalid_type,expected:v.map,received:r.parsedType}),E;let s=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([a,l],c)=>({key:s._parse(new Ce(r,a,r.path,[c,"key"])),value:o._parse(new Ce(r,l,r.path,[c,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of i){let c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return E;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let l of i){let c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return E;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}}}};hn.create=(e,t,n)=>new hn({valueType:t,keyType:e,typeName:A.ZodMap,...$(n)});var yn=class e extends M{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==v.set)return _(r,{code:h.invalid_type,expected:v.set,received:r.parsedType}),E;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(_(r,{code:h.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(_(r,{code:h.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let o=this._def.valueType;function i(l){let c=new Set;for(let u of l){if(u.status==="aborted")return E;u.status==="dirty"&&n.dirty(),c.add(u.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((l,c)=>o._parse(new Ce(r,l,r.path,c)));return r.common.async?Promise.all(a).then(l=>i(l)):i(a)}min(t,n){return new e({...this._def,minSize:{value:t,message:b.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:b.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};yn.create=(e,t)=>new yn({valueType:e,minSize:null,maxSize:null,typeName:A.ZodSet,...$(t)});var Or=class e extends M{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==v.function)return _(n,{code:h.invalid_type,expected:v.function,received:n.parsedType}),E;function r(a,l){return Fn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,dn(),Ye].filter(c=>!!c),issueData:{code:h.invalid_arguments,argumentsError:l}})}function s(a,l){return Fn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,dn(),Ye].filter(c=>!!c),issueData:{code:h.invalid_return_type,returnTypeError:l}})}let o={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof _t){let a=this;return ie(async function(...l){let c=new pe([]),u=await a._def.args.parseAsync(l,o).catch(g=>{throw c.addIssue(r(l,g)),c}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,o).catch(g=>{throw c.addIssue(s(d,g)),c})})}else{let a=this;return ie(function(...l){let c=a._def.args.safeParse(l,o);if(!c.success)throw new pe([r(l,c.error)]);let u=Reflect.apply(i,this,c.data),d=a._def.returns.safeParse(u,o);if(!d.success)throw new pe([s(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Le.create(t).rest(Xe.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||Le.create([]).rest(Xe.create()),returns:n||Xe.create(),typeName:A.ZodFunction,...$(r)})}},Ht=class extends M{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})}};Ht.create=(e,t)=>new Ht({getter:e,typeName:A.ZodLazy,...$(t)});var Kt=class extends M{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return _(n,{received:n.data,code:h.invalid_literal,expected:this._def.value}),E}return{status:"valid",value:t.data}}get value(){return this._def.value}};Kt.create=(e,t)=>new Kt({value:e,typeName:A.ZodLiteral,...$(t)});function Na(e,t){return new Gt({values:e,typeName:A.ZodEnum,...$(t)})}var Gt=class e extends M{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return _(n,{expected:L.joinValues(r),received:n.parsedType,code:h.invalid_type}),E}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 _(n,{received:n.data,code:h.invalid_enum_value,options:r}),E}return ie(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};Gt.create=Na;var zt=class extends M{_parse(t){let n=L.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==v.string&&r.parsedType!==v.number){let s=L.objectValues(n);return _(r,{expected:L.joinValues(s),received:r.parsedType,code:h.invalid_type}),E}if(this._cache||(this._cache=new Set(L.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let s=L.objectValues(n);return _(r,{received:r.data,code:h.invalid_enum_value,options:s}),E}return ie(t.data)}get enum(){return this._def.values}};zt.create=(e,t)=>new zt({values:e,typeName:A.ZodNativeEnum,...$(t)});var _t=class extends M{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==v.promise&&n.common.async===!1)return _(n,{code:h.invalid_type,expected:v.promise,received:n.parsedType}),E;let r=n.parsedType===v.promise?n.data:Promise.resolve(n.data);return ie(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};_t.create=(e,t)=>new _t({type:e,typeName:A.ZodPromise,...$(t)});var ke=class extends M{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===A.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,o={addIssue:i=>{_(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(r.data,o);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return E;let l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?E:l.status==="dirty"?Nt(l.value):n.value==="dirty"?Nt(l.value):l});{if(n.value==="aborted")return E;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?E:a.status==="dirty"?Nt(a.value):n.value==="dirty"?Nt(a.value):a}}if(s.type==="refinement"){let i=a=>{let l=s.refinement(a,o);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?E:(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"?E:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(s.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!gt(i))return E;let a=s.transform(i.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>gt(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:n.value,value:a})):E);L.assertNever(s)}};ke.create=(e,t,n)=>new ke({schema:e,typeName:A.ZodEffects,effect:t,...$(n)});ke.createWithPreprocess=(e,t,n)=>new ke({schema:t,effect:{type:"preprocess",transform:e},typeName:A.ZodEffects,...$(n)});var xe=class extends M{_parse(t){return this._getType(t)===v.undefined?ie(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};xe.create=(e,t)=>new xe({innerType:e,typeName:A.ZodOptional,...$(t)});var De=class extends M{_parse(t){return this._getType(t)===v.null?ie(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};De.create=(e,t)=>new De({innerType:e,typeName:A.ZodNullable,...$(t)});var Wt=class extends M{_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}};Wt.create=(e,t)=>new Wt({innerType:e,typeName:A.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...$(t)});var Jt=class extends M{_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return mn(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new pe(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new pe(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Jt.create=(e,t)=>new Jt({innerType:e,typeName:A.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...$(t)});var _n=class extends M{_parse(t){if(this._getType(t)!==v.nan){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:v.nan,received:r.parsedType}),E}return{status:"valid",value:t.data}}};_n.create=e=>new _n({typeName:A.ZodNaN,...$(e)});var dm=Symbol("zod_brand"),Bn=class extends M{_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}},Hn=class e extends M{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?E:o.status==="dirty"?(n.dirty(),Nt(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?E:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:A.ZodPipeline})}},Yt=class extends M{_parse(t){let n=this._def.innerType._parse(t),r=s=>(gt(s)&&(s.value=Object.freeze(s.value)),s);return mn(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Yt.create=(e,t)=>new Yt({innerType:e,typeName:A.ZodReadonly,...$(t)});function $a(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function La(e,t={},n){return e?yt.create().superRefine((r,s)=>{let o=e(r);if(o instanceof Promise)return o.then(i=>{if(!i){let a=$a(t,r),l=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:l})}});if(!o){let i=$a(t,r),a=i.fatal??n??!0;s.addIssue({code:"custom",...i,fatal:a})}}):yt.create()}var mm={object:fe.lazycreate},A;(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"})(A||(A={}));var pm=(e,t={message:`Input not instance of ${e.name}`})=>La(n=>n instanceof e,t),Da=ht.create,Ua=Lt.create,fm=_n.create,gm=Dt.create,ja=Ut.create,hm=jt.create,ym=fn.create,_m=qt.create,vm=Vt.create,bm=yt.create,Sm=Xe.create,wm=Ee.create,xm=gn.create,Cm=Qe.create,km=fe.create,Tm=fe.strictCreate,Em=Ft.create,Am=Pr.create,Rm=Bt.create,Im=Le.create,$m=Mr.create,Pm=hn.create,Mm=yn.create,Om=Or.create,Nm=Ht.create,Lm=Kt.create,Dm=Gt.create,Um=zt.create,jm=_t.create,qm=ke.create,Vm=xe.create,Fm=De.create,Bm=ke.createWithPreprocess,Hm=Hn.create,Km=()=>Da().optional(),Gm=()=>Ua().optional(),zm=()=>ja().optional(),Wm={string:(e=>ht.create({...e,coerce:!0})),number:(e=>Lt.create({...e,coerce:!0})),boolean:(e=>Ut.create({...e,coerce:!0})),bigint:(e=>Dt.create({...e,coerce:!0})),date:(e=>jt.create({...e,coerce:!0}))};var Jm=E;var qa=["tempo","mpp_self","merchant_self"];var oo=p.object({inputPerMillion:p.number().positive(),outputPerMillion:p.number().positive(),contextWindow:p.number().int().positive().optional(),maxOutput:p.number().int().positive().optional(),perRequestFeeCents:p.number().nonnegative().optional()}),Ym=p.object({strategy:p.enum(["flat","token","band"]).optional(),pricingModel:p.enum(["per-call","per-token","band"]).optional(),priceCents:p.number().nonnegative().optional(),currency:p.string().optional(),display:p.string().optional(),estimate:p.boolean().optional(),source:p.string().optional(),priceBand:p.record(p.unknown()).optional(),tokenPricing:oo.optional()}).passthrough(),io=p.discriminatedUnion("type",[p.object({type:p.literal("shortcut"),routedPath:p.string().min(1).startsWith("/")}),p.object({type:p.literal("custom"),merchantSlug:p.string().min(1),subPath:p.string().optional()}),p.object({type:p.literal("local"),fn:p.string().min(1)}),p.object({type:p.literal("read")})]),ao=p.object({amount:p.number().nonnegative(),currency:p.string().length(3).optional(),display:p.string().optional(),free:p.boolean().optional(),batchDiscount:p.number().min(0).max(100).optional()}),Va=p.object({attestation:p.boolean().optional(),rateLimitMs:p.number().positive().optional()}),Fa=p.object({displayName:p.string().optional(),feedbackEligible:p.boolean().optional(),suggestionEligible:p.boolean().optional(),batchable:p.boolean().optional()}),Zm=p.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),Xm=120,Qm=120,ep=1200,tp=/^[^\u0000-\u001F\u007F]+$/;function so(e,t){return p.string().min(1).max(e).regex(tp,`${t} must not contain control characters`)}var co={id:p.string().min(1),name:so(Xm,"name"),description:so(ep,"description"),provider:p.string().min(1),model:p.string().min(1),category:Zm,priceCents:p.number().nonnegative(),inputSchema:p.record(p.unknown()),gatewayUrl:p.string().min(1),merchantName:so(Qm,"merchantName"),isAsync:p.boolean().optional(),pollUrl:p.string().optional(),pollInterval:p.number().positive().optional(),pollTimeout:p.number().positive().optional(),tags:p.array(p.string()).optional(),tokenPricing:oo.optional(),priceDisplay:p.string().optional(),pricingModel:p.enum(["per-call","per-token","band"]).optional(),pricingInfo:Ym.optional(),status:p.enum(["available","unavailable"]).optional(),handler:io.optional(),pricing:ao.optional(),security:Va.optional(),engagement:Fa.optional(),enabled:p.boolean().optional(),beta:p.boolean().optional(),deprecated:p.boolean().optional(),replacementTool:p.string().optional(),minCliVersion:p.string().optional(),sunsetAt:p.string().optional(),rail:p.enum(qa).optional(),pricingStrategy:p.enum(["flat","token","band"]).optional()},Ba=p.object({...co,dispatch:p.literal("routed"),routedPath:p.string().min(1).startsWith("/")}).strict(),Ha=p.object({...co,dispatch:p.literal("enveloped")}).strict(),Ka=p.object({...co,handler:io,pricing:ao}).strict(),Ga=p.union([p.discriminatedUnion("dispatch",[Ba,Ha]),Ka]);var lo=/^[a-z0-9][a-z0-9_-]*$/;var rp="https://fal.run",Ya="https://openrouter.mpp.tempo.xyz";function sp(e){let{attestation:t,tool_id:n,...r}=e;return r}var za={"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 Nr(e){let{attestation:t,tool_id:n,aspect_ratio:r,image_size:s,...o}=e,i={...o};return typeof s=="string"&&s.length>0?(i.image_size=s,i):(typeof r=="string"&&za[r]&&(i.image_size=za[r]),i)}function Wa(e){let t={chain:e.chain,token_address:e.token_address};if(e.start_timestamp){let n=e.end_timestamp||new Date().toISOString(),r=e.time_granularity;if(!r){let s=new Date(e.start_timestamp).getTime();(new Date(n).getTime()-s)/(1e3*60*60*24)<=2?r="1h":r="1d"}return{addresses:[t],start_timestamp:e.start_timestamp,end_timestamp:n,time_granularity:r}}return[t]}function op(e,t,n,r,s,o,i,a,l){return{id:e,name:t,description:n,provider:r,model:s.replace(/^\//,""),category:o,gatewayUrl:`https://${r}${s}`,merchantName:t,inputSchema:a,handler:{type:"custom",merchantSlug:r,subPath:s},pricing:{amount:i,currency:"USD",display:`$${(i/100).toFixed(2)}`},priceCents:i,tags:[],...l}}function ip(e,t,n,r,s,o,i,a){return op(e,t,n,"suno-ai",r,s,o,i,{merchantName:"Suno AI",...a})}function Z(e,t,n,r,s,o,i,a){return{dispatch:"routed",id:e,name:t,description:n,provider:"fal",model:r,category:s,priceCents:o,inputSchema:i,routedPath:`/api/v1/fal/${r}`,gatewayUrl:`${rp}/${r}`,merchantName:"fal.ai",buildBody:sp,tags:[],...a}}function ap(e){return t=>{let{attestation:n,tool_id:r,prompt:s,system_prompt:o,max_tokens:i,temperature:a,...l}=t;return{model:e,messages:[...o?[{role:"system",content:o}]:[],{role:"user",content:s}],max_tokens:i??1024,temperature:a??.7,...l}}}function cp(e){return t=>{let{attestation:n,tool_id:r,prompt:s,image_url:o,aspect_ratio:i,max_tokens:a,temperature:l,...c}=t,u=[{type:"text",text:s}];return typeof o=="string"&&o.length>0&&u.push({type:"image_url",image_url:{url:o}}),{model:e,messages:[{role:"user",content:u}],max_tokens:a??1024,temperature:l??.7,...typeof i=="string"&&i.length>0?{image_config:{aspect_ratio:i}}:{},...c}}}function X(e,t,n,r,s,o,i){let a=i?.perRequestFeeCents??0,l=500/1e6*s*100,c=500/1e6*o*100,u=Math.max(1,Math.ceil(l+c+a)),{perRequestFeeCents:d,...f}=i??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"llm",priceCents:u,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The prompt or question to send to the model"},system_prompt:{type:"string",description:"Optional system prompt to set model behavior"},max_tokens:{type:"integer",description:"Maximum tokens in response (default: 1024)",minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${Ya}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:ap(r),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:s,outputPerMillion:o,...a>0?{perRequestFeeCents:a}:{}},...f}}function uo(e,t,n,r,s,o){return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"image",priceCents:s,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate or edit"},image_url:{type:"string",description:"Optional source image URL for edits"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"1:1"},max_tokens:{type:"integer",description:"Maximum text tokens in response metadata (default: 1024)",minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${Ya}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:cp(r),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...o}}var mo=[Z("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"]}),Z("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:Nr}),Z("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:Nr}),Z("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:Nr}),Z("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"]}),uo("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),uo("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}}),uo("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}}),Z("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"]}),Z("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"]}),Z("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"]}),Z("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"]}),Z("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"]}),Z("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"]}),Z("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"]}),Z("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"]}),Z("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"]}),ip("suno-music","Suno Music","AI music generation. Create full songs with vocals or instrumentals.","/suno/generate-music","audio",10,{type:"object",properties:{prompt:{type:"string",description:"Description of the song (genre, mood, instruments)"},instrumental:{type:"boolean",description:"Instrumental only, no vocals",default:!1}},required:["prompt"]},{isAsync:!0,pollUrl:"https://api.sunoapi.org/suno/get-music-status",deprecated:!0,tags:["music","song","vocals","instrumental"],buildBody:e=>{let{attestation:t,tool_id:n,prompt:r,instrumental:s,...o}=e;return{prompt:r,customMode:!1,instrumental:typeof s=="boolean"?s:!1,model:"V4",...o}}}),Z("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"]}),Z("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"]}),Z("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"]}),Z("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-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-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",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:Wa,tags:["onchain","prices","allium","crypto"]},{dispatch:"enveloped",id:"generate_image_card",name:"Generate Image (Ultra)",description:"Generate a high-quality AI image (FLUX Pro Ultra, 2K, ~$0.06).",provider:"fal",model:"fal-ai/flux-pro/v1.1-ultra",category:"image",priceCents:6,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1-ultra",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro-ultra",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),t},tags:["image","flux","ultra","legacy"]},{dispatch:"enveloped",id:"generate_image_fast_card",name:"Generate Image (Fast)",description:"Generate an AI image (FLUX Pro v1.1, 1K, ~$0.04).",provider:"fal",model:"fal-ai/flux-pro/v1.1",category:"image",priceCents:4,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro",buildBody:e=>Nr({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"]},Z("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"}),Z("edit_image_seed_card","Edit Image (SeedEdit)","Inpaint/edit an image with a prompt using SeedEdit.","fal-ai/bytedance/seededit","image",5,{type:"object",properties:{image_url:{type:"string"},prompt:{type:"string"},seed:{type:"number"}},required:["image_url","prompt"]},{buildBody:e=>{let t={image_url:e.image_url,prompt:e.prompt};return e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","edit","inpaint","seededit"],deprecated:!0,replacementTool:"or-gemini-nano-banana"}),{dispatch:"enveloped",id:"generate_video_tempo_card",name:"Generate Video (Grok)",description:"Generate a video from a text prompt using Grok Imagine Video.",provider:"fal",model:"xai/grok-imagine-video/text-to-video",category:"video",priceCents:30,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/xai/grok-imagine-video/text-to-video",merchantName:"Grok Video via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),t},tags:["video","grok","legacy"]},{dispatch:"enveloped",id:"generate_video_kling_card",name:"Generate Video (Kling)",description:"Generate a video using Kling v1.6 (async, ~$0.40).",provider:"fal",model:"fal-ai/kling-video/v1.6/standard/text-to-video",category:"video",priceCents:40,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/kling-video/v1.6/standard/text-to-video",merchantName:"Kling via fal.ai",deprecated:!0,replacementTool:"fal-kling-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","kling","legacy"]},{dispatch:"enveloped",id:"generate_video_wan_card",name:"Generate Video (Wan)",description:"Generate a video using Wan T2V (async, ~$0.25).",provider:"fal",model:"fal-ai/wan/t2v-1.3b",category:"video",priceCents:25,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/wan/t2v-1.3b",merchantName:"Wan T2V via fal.ai",deprecated:!0,replacementTool:"fal-wan-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","wan","legacy"]},{dispatch:"enveloped",id:"generate_video_minimax_card",name:"Generate Video (MiniMax)",description:"Generate a video using MiniMax (async, ~$0.35).",provider:"fal",model:"fal-ai/minimax/video-01",category:"video",priceCents:35,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/minimax/video-01",merchantName:"MiniMax via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","minimax","legacy"]},{dispatch:"enveloped",id:"check_fal_status_card",name:"Check fal Async Job Status",description:"Poll an async fal.ai queue job for completion.",provider:"fal",model:"queue-status",category:"image",priceCents:0,inputSchema:{type:"object",properties:{model_path:{type:"string",description:"Model path (e.g. fal-ai/kling-video/v1.6/standard/text-to-video)"},request_id:{type:"string"}},required:["model_path","request_id"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue",merchantName:"fal.ai",buildUrl:e=>`https://fal.mpp.tempo.xyz/queue/${e.model_path}/requests/${e.request_id}`,buildBody:()=>({}),tags:["status","fal","async","legacy"]},{dispatch:"enveloped",id:"generate_3d_card",name:"Generate 3D Model",description:"Generate a 3D mesh from a text prompt using Meshy (async, ~$0.50).",provider:"fal",model:"fal-ai/meshy-ai/text-to-3d",category:"3d",priceCents:50,inputSchema:{type:"object",properties:{object_prompt:{type:"string"},style_prompt:{type:"string"},negative_prompt:{type:"string"},art_style:{type:"string"},seed:{type:"number"}},required:["object_prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/meshy-ai/text-to-3d",merchantName:"Meshy via fal.ai",deprecated:!0,replacementTool:"fal-trellis-3d",buildBody:e=>{let t={object_prompt:e.object_prompt};return e.style_prompt&&(t.style_prompt=e.style_prompt),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.art_style&&(t.art_style=e.art_style),e.seed!==void 0&&(t.seed=e.seed),t},tags:["3d","mesh","meshy","legacy"]},{dispatch:"enveloped",id:"generate_speech_card",name:"Generate Speech",description:"Text-to-speech using F5-TTS with optional voice cloning.",provider:"fal",model:"fal-ai/f5-tts",category:"tts",priceCents:3,inputSchema:{type:"object",properties:{gen_text:{type:"string",description:"Text to synthesize"},ref_audio_url:{type:"string",description:"Reference audio URL (for voice cloning)"},ref_text:{type:"string",description:"Transcription of ref audio"},remove_silence:{type:"boolean"}},required:["gen_text"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/f5-tts",merchantName:"fal.ai",buildBody:e=>{let t={gen_text:e.gen_text};return e.ref_audio_url&&(t.ref_audio_url=e.ref_audio_url),e.ref_text&&(t.ref_text=e.ref_text),e.remove_silence!==void 0&&(t.remove_silence=e.remove_silence),t},deprecated:!0,replacementTool:"fal-metavoice",tags:["tts","speech","f5-tts","legacy"]},{dispatch:"enveloped",id:"generate_music_tempo_card",name:"Generate Music (Suno)",description:"Generate a music track using Suno (async, ~$0.50).",provider:"suno",model:"suno-v4",category:"audio",priceCents:50,inputSchema:{type:"object",properties:{prompt:{type:"string"},instrumental:{type:"boolean"},model:{type:"string",default:"V4"}},required:["prompt"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/generate-music",merchantName:"Suno via Tempo",buildBody:e=>({prompt:e.prompt,customMode:!1,instrumental:e.instrumental??!1,model:e.model||"V4"}),isAsync:!0,pollUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",pollInterval:15e3,pollTimeout:3e5,deprecated:!0,replacementTool:"fal-ace-step-music",tags:["music","audio","suno","async","legacy"]},{dispatch:"enveloped",id:"check_music_status_tempo_card",name:"Check Music Status",description:"Poll a Suno music generation task for completion.",provider:"suno",model:"suno-status",category:"audio",priceCents:0,inputSchema:{type:"object",properties:{taskId:{type:"string"}},required:["taskId"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",merchantName:"Suno Status",buildBody:e=>({taskId:e.taskId}),deprecated:!0,tags:["music","status","suno","legacy"]},{dispatch:"enveloped",id:"query_onchain_prices_card",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly, daily, and weekly granularity.",provider:"allium",model:"allium-prices",category:"llm",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly), '1d' (daily), or '1w' (weekly). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",deprecated:!0,replacementTool:"query_onchain_prices",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:Wa,tags:["onchain","prices","allium","crypto","legacy"]}];function Kn(e){return mo.find(t=>t.id===e)}var Za=1,Xa=["pick_one","fan_out"],Qa=["concat","dedupe_by_url","top_k_by_score"],dp=8,mp=p.object({type:p.string().min(1),description:p.string().min(1),enum:p.array(p.string()).optional(),default:p.unknown().optional(),minimum:p.number().optional(),maximum:p.number().optional()}),pp=p.object({toolId:p.string().min(1),notes:p.string().min(1)}),fp=p.string().regex(/^[a-z0-9_-]{1,32}$/,"tier key must be 1-32 chars [a-z0-9_-]"),gp=p.object({providers:p.array(p.string().min(1)).min(1).max(dp),merge:p.enum(Qa),maxResults:p.number().int().positive().optional()}),ec=p.object({mode:p.enum(Xa).default("pick_one"),intro:p.string().min(1),defaultTier:p.string().min(1),tiers:p.record(fp,pp).refine(e=>Object.keys(e).length>0,{message:"must have at least one tier"}),fanOut:gp.optional(),guidance:p.string().min(1),inputProperties:p.record(p.string(),mp),required:p.array(p.string())}).refine(e=>e.tiers[e.defaultTier]!==void 0,{message:"defaultTier must exist in tiers",path:["defaultTier"]}).refine(e=>e.mode!=="fan_out"||e.fanOut!==void 0,{message:"fan_out mode requires fanOut config",path:["fanOut"]}).refine(e=>e.required.every(t=>t in e.inputProperties),{message:"required entries must exist in inputProperties",path:["required"]}),hp=p.object({version:p.literal(Za),generatedAt:p.string().datetime(),tools:p.record(p.string().regex(lo,"tool name must match MCP naming rules"),ec).refine(e=>Object.keys(e).length>0,{message:"manifest must have at least one tool"})});var Ur=require("child_process"),oc=require("util"),ic=R(require("crypto")),ae=R(require("fs")),ac=R(require("os")),Ue=R(require("path"));var vn=(0,oc.promisify)(Ur.execFile),jr=Ue.join(ac.homedir(),".visa-mcp","bin"),Zt=Ue.join(jr,"Visa CLI"),vp=Ue.join(__dirname,"..","native"),tc="6",nc=Ue.join(jr,"visa-keychain.version"),rc=Ue.join(jr,"visa-keychain.sha256");function sc(e){let t=ae.readFileSync(e);return ic.createHash("sha256").update(t).digest("hex")}async function fo(){try{if(ae.readFileSync(nc,"utf-8").trim()===tc&&ae.existsSync(Zt)){let r=ae.readFileSync(rc,"utf-8").trim();if(sc(Zt)!==r)m.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),ae.unlinkSync(Zt);else return Zt}}catch{}let e=Ue.join(vp,"visa-keychain.m");if(ae.existsSync(e)||(e=Ue.resolve(__dirname,"..","..","native","visa-keychain.m")),ae.existsSync(e)||(e=Ue.resolve(__dirname,"..","native","visa-keychain.m")),!ae.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");ae.mkdirSync(jr,{recursive:!0,mode:448});try{await vn("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",Zt,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=sc(Zt);return ae.writeFileSync(rc,t,{mode:384}),ae.writeFileSync(nc,tc,{mode:384}),Zt}async function cc(e){let t=await fo(),n;try{n=(await vn(t,e,{timeout:6e4})).stdout}catch(o){n=o.stdout||"";let i=n.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(o.stderr?.trim()||o.message||"Unknown error")}let r=n.trim();if(r.startsWith("OK:"))return r.slice(3);if(r==="OK")return;let s=r.startsWith("ERROR:")?r.slice(6):"Unknown error";throw new Error(s)}var po=null;function te(){return nn()?!0:process.platform!=="darwin"?!1:po!==null?po:(po=!0,!0)}var Lr="visa-cli",Dr="attestation-key";async function bp(e){try{await vn("security",["delete-generic-password","-s",Lr,"-a",Dr],{timeout:5e3})}catch{}await vn("security",["add-generic-password","-s",Lr,"-a",Dr,"-w",e],{timeout:5e3})}async function go(){try{let{stdout:e}=await vn("security",["find-generic-password","-s",Lr,"-a",Dr,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function qr(){let e=await cc(["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 bp(n),r}async function lc(){return await go()!==null}async function uc(){if(nn())return"mock-public-key-spki";let e=await go();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await fo();return new Promise((n,r)=>{let s=(0,Ur.execFile)(t,["public-key"],{timeout:6e4},(o,i)=>{let a=(i||"").trim();if(o){a.startsWith("ERROR:")?r(new Error(a.slice(6))):r(new Error(o.stderr?.trim()||o.message||"Unknown error"));return}a.startsWith("OK:")?n(a.slice(3)):r(new Error(a.startsWith("ERROR:")?a.slice(6):"Unknown error"))});s.stdin.write(e),s.stdin.end()})}async function bn(e,t){if(nn())return Promise.resolve(fi());let n=await go();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await fo(),s=["sign",e];return t&&s.push(t),new Promise((o,i)=>{let a=(0,Ur.execFile)(r,s,{timeout:6e4},(l,c)=>{let u=(c||"").trim();if(l){u.startsWith("ERROR:")?i(new Error(u.slice(6))):i(new Error(l.stderr?.trim()||l.message||"Unknown error"));return}u.startsWith("OK:")?o(u.slice(3)):i(new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error"))});a.stdin.write(n),a.stdin.end()})}async function Vr(){try{await vn("security",["delete-generic-password","-s",Lr,"-a",Dr],{timeout:5e3})}catch{}try{await cc(["delete-key"])}catch{}}var Sp=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],wp=[...Sp.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 yo(e,t=wp){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=ho(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(ho(r.match.provider)))&&r.match.keywords.every(s=>n.includes(ho(s))))return r.targetToolId;return null}function ho(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}var dc={generate_image:{intro:'Generate an AI image from a text prompt \u2014 useful for hero shots, marketing assets, social posts, blog covers, app mockups, or any time the user asks for art, a logo, an icon, a thumbnail, or "a picture of \u2026". From $0.01 (fast) to $0.06 (pro), returns a hosted PNG/JPG URL. Default tier: balanced ($0.04, 1K, ~10s).',tiers:{balanced:{toolId:"fal-flux-pro",notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",notes:"Recraft V3 \u2014 vector/flat/illustration styles"}},guidance:"If the user didn't specify a tier, pick 'balanced' unless the prompt clearly signals otherwise (text \u2192 text_heavy, logo/icon \u2192 vector, quick test \u2192 fast, hero/print \u2192 pro).",inputProperties:{prompt:{type:"string",description:"Text description of the image to generate."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9", "1:1", "9:16".',default:"16:9"}},required:["prompt"]},generate_video:{intro:'Generate a short AI video from a text prompt \u2014 useful for product demos, social clips, mood reels, ad concepts, or any "make me a video of \u2026" request. $0.10\u2013$0.40 per ~6s clip depending on tier. Async: returns a request_id; use execute_tool with tool_id "check_fal_status_card" to resolve it (60\u2013180s).',tiers:{balanced:{toolId:"fal-minimax-video",notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",notes:"Kling \u2014 highest quality, cinematic"}},guidance:'Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate and are processed asynchronously. The response includes a request_id and model_path. Poll with execute_tool using tool_id "check_fal_status_card" and params {request_id, model_path}. Do not poll more than once per 30 seconds.',inputProperties:{prompt:{type:"string",description:"Text description of the video scene."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9" or "9:16".',default:"16:9"}},required:["prompt"]},generate_music:{intro:'Generate an original music track from a prompt via ACE-Step. ~$0.02 for the default 60s track. Use for songs, backing tracks, jingles, vocal music, instrumental music, or any "make a song/music/track" request. Takes ~60-90s and may return a request_id to poll with check_fal_status_card. For SFX, chimes, ambient beds, or TTS, use generate_audio instead.',tiers:{ace_step:{toolId:"fal-ace-step-music",notes:"ACE-Step \u2014 prompt-to-music with vocals or instrumentals"}},guidance:"Use for songs and music tracks. Takes ~60-90s and may return a request_id to poll with check_fal_status_card. For sound effects, chimes, ambient beds, or TTS, use generate_audio instead.",inputProperties:{prompt:{type:"string",description:"Musical style, mood, instruments, subject, and lyrics direction."},instrumental:{type:"boolean",description:"True for instrumental music with no vocals; false for vocal tracks.",default:!1},duration:{type:"number",description:"Duration in seconds.",default:60}},required:["prompt"]},generate_audio:{intro:'Generate sound effects from a text prompt (sfx tier \u2014 default), or voice-cloned speech from text + a reference audio URL (tts tier). $0.03\u2013$0.04. Use for SFX, chimes, UI sounds, ambient audio (default sfx), or voice cloning when a reference audio URL is available (pass tier:"tts"). Default tier is sfx; pass tier:"tts" for voice cloning.',tiers:{sfx:{toolId:"fal-stable-audio",notes:"Stable Audio \u2014 sound effects and ambient from a prompt"},tts:{toolId:"fal-metavoice",notes:"MetaVoice \u2014 voice cloning TTS (requires a voice sample URL)"}},guidance:'Default tier is sfx: pass prompt describing the sound. For tts (voice cloning): pass tier:"tts" + text + audio_url.',inputProperties:{prompt:{type:"string",description:"Description of sound to generate (sfx tier, default)."},text:{type:"string",description:"Text to speak aloud (tts tier)."},audio_url:{type:"string",description:"URL of a voice sample to clone (tts tier, required for voice cloning)."}},required:[]},generate_3d:{intro:"Generate a 3D mesh (GLB) from an image URL via Trellis. ~$0.08, ~30\u201360s. Use when the user shares an image and asks for a 3D model, asset, AR-ready mesh, or game-ready GLB.",tiers:{trellis:{toolId:"fal-trellis-3d",notes:"Trellis \u2014 image-to-3D, returns a GLB mesh URL"}},guidance:"Pass an image URL. Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{image_url:{type:"string",description:"URL of the image to convert to a 3D model."}},required:["image_url"]},upscale_image:{intro:'Upscale an image to 4\xD7 resolution via Aura SR (preserves detail without hallucination). ~$0.03. Use whenever the user shares a low-res image and asks to "upscale", "make this higher resolution", "4x this", "enhance", or to print/export at larger size.',tiers:{aura:{toolId:"fal-aura-sr",notes:"Aura SR \u2014 default; preserves detail without hallucination"}},guidance:"Pass the existing image URL. Returns an upscaled version.",inputProperties:{image_url:{type:"string",description:"URL of the image to upscale."}},required:["image_url"]},transcribe_audio:{intro:'Transcribe speech in an audio or video file (URL) to text via OpenAI Whisper. ~$0.02 per file, multilingual, handles long files. Use whenever the user asks to "transcribe this", "what does this audio say", "make subtitles", "convert this to text", or shares an audio/video URL with no other clear intent.',tiers:{whisper:{toolId:"fal-whisper",notes:"OpenAI Whisper \u2014 fast, multilingual"}},guidance:"Pass the URL. Returns the transcript text.",inputProperties:{audio_url:{type:"string",description:"URL of the audio or video file to transcribe."}},required:["audio_url"]},run_llm:{intro:"Run a text prompt through a different LLM (GPT-4o-mini, Claude Sonnet, DeepSeek R1/V3, Perplexity Sonar with web search, or Llama 70B). Token-metered, typically ~$0.01\u2013$0.10 per call. Use for: web-grounded answers (search tier), second-opinion reasoning (reasoning tier), code generation in a different family (coding tier), deep math/logic (deep_reasoning tier), or fast cheap text cleanup (fast tier). Pair with batch for multi-model councils.",tiers:{fast:{toolId:"or-gpt-4o-mini",notes:"GPT-4o Mini. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",notes:"Claude Sonnet. Strong reasoning, long-context. Warn user it is materially pricier than `fast`."},deep_reasoning:{toolId:"or-deepseek-r1",notes:"DeepSeek R1. Deep chain-of-thought reasoning, mid-range pricing."},search:{toolId:"or-perplexity-sonar",notes:"Perplexity Sonar. Search-augmented, web-grounded with citations."},open_source:{toolId:"or-llama-70b",notes:"Llama 3.3 70B. Open-source large model."},coding:{toolId:"or-deepseek-chat",notes:"DeepSeek Chat V3. Strong at code generation."}},guidance:"Pick based on the user's need: fast (most questions, cheapest), reasoning (complex analysis; warn user it is materially pricier than fast), search (questions about current events), coding (code generation), deep_reasoning (hard math/logic problems).",inputProperties:{prompt:{type:"string",description:"The user query."},system_prompt:{type:"string",description:"Optional system prompt to set model behavior."},max_tokens:{type:"number",description:"Maximum output tokens.",default:1024,minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature \u2014 0 is deterministic, higher is more creative.",default:.7,minimum:0,maximum:2}},required:["prompt"]}};function _o(e,t,n){if(!pc(e))return Tp(e,n);let r=mc[e];if(!r)return e;let s=Object.keys(r.tiers),o=t||s[0],i=Ep(e,o,n);return i||Ap(e,r,o,s)}function Tp(e,t){return yo({requestedTool:e,intentText:t})??e}function Ep(e,t,n){return yo({requestedTool:e,metaTool:e,tier:t,intentText:n})}function Ap(e,t,n,r){let s=t.tiers[n];if(!s)throw new Error(`Unknown tier '${n}' for ${e}. Valid tiers: ${r.join(", ")}`);return s.toolId}var mc=dc;function pc(e){return e in mc}var Gn=Object.keys(dc);function vo(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function fc(e=process.env){return vo(e)!==null}var Zc=require("child_process"),ce=R(require("crypto")),Re=R(require("fs")),Yn=R(require("os")),ns=R(require("path"));var gc=!1;async function zn(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")||!te())throw r;if(m.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(gc)throw m.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;gc=!0,m.info("attestation:starting-browser-recovery");try{let o=await n();if(!o.success)throw m.error("attestation:browser-recovery-failed",{message:o.message}),r;let i=await qr();return await e.registerAttestationKey(i),await e.setBiometricPreference({required:!0}),m.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),m.info("attestation:key-reregistered-after-recovery"),await t()}catch(o){throw m.error("attestation:recovery-failure",{error:o.message}),r}}throw r}}var hc="2.1.1";function bo(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function Br(e,t,n){let r=process.env[e];if(r!==void 0)return{value:n==="opt-in"?r==="true":r!=="false",source:{kind:"env",var:e}};let s=Er(t);return s!==void 0?{value:s,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function _e(e){return e==null?"\u2014":e?"yes":"no"}function Hr(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function Rp(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function Ip(){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=eo("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:Xs,source:{kind:"default"}}}async function Kr(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(F){n=F?.message||"unknown error"}let r=[],s=process.env.VISA_AUTH_URL,o=Qs("auth.serverUrl"),i=we(),a=s!==void 0&&s!==""?{kind:"env",var:"VISA_AUTH_URL"}:o!==void 0?{kind:"settings"}:{kind:"default"};r.push({key:"auth.serverUrl",value:i,formatted:i,source:a,hint:a.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),r.push({key:"account.enrolled",value:t?.enrolled??null,formatted:_e(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),t?.githubUser&&r.push({key:"account.githubUser",value:t.githubUser,formatted:t.githubUser,source:{kind:"server"}});let l=t?t.attestationRequired!==!1:void 0;r.push({key:"biometric.required",value:l,formatted:_e(l),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"},hint:l===!1?"Touch ID prompts are suppressed. Re-enable with `visa-cli config biometric on`.":void 0}),r.push({key:"biometric.keyRegistered",value:t?.hasAttestationKey??null,formatted:_e(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:te(),formatted:_e(te()),source:{kind:"device"}});let c=t?.spendingControls,u=c?c.max_transaction_amount??c.maxTransactionAmount??null:null,d=c?c.daily_limit??c.dailyLimit??null:null;r.push({key:"spending.maxPerTxn",value:u,formatted:Hr(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:Hr(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:Hr(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:Hr(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(F=>F.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 g=Ip();r.push({key:"credit.sessionCapCents",value:g.value,formatted:Rp(g.value),source:g.source});let w=wa();w.length>0&&r.push({key:"settings.retired",value:w.map(F=>F.key),formatted:w.map(F=>F.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${w.map(F=>`visa-cli config unset ${F.key}`).join(" && ")}`});let y=Br("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:y.value,formatted:_e(y.value),source:y.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let k=Br("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:k.value,formatted:_e(k.value),source:k.source});let O=Oe(),N;process.env.VISA_CLI_NO_UPDATE_CHECK?N={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?N={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?N={kind:"env",var:"NODE_ENV"}:N={kind:"default"},r.push({key:"ui.updateCheck",value:!O,formatted:_e(!O),source:N});let C=Br("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:C.value,formatted:_e(C.value),source:C.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let T=Br("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:T.value,formatted:_e(T.value),source:T.source});let V=process.env.VISA_DRY_RUN,z=fc();if(r.push({key:"tools.dryRun",value:z,formatted:_e(z),source:V===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:hc,formatted:hc,source:{kind:"default"}}),e.includeDev){let F=process.env.VISA_MOCK_KEYCHAIN,ot=at();r.push({key:"dev.mockKeychain",value:ot,formatted:_e(ot),source:bo("VISA_MOCK_KEYCHAIN",!!F),hint:_s()});let ee=process.env.VISA_MOCK_TOUCHID,ue=nn();r.push({key:"dev.mockTouchid",value:ue,formatted:_e(ue),source:bo("VISA_MOCK_TOUCHID",!!ee),hint:_s()});let it=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!it,formatted:_e(!!it),source:bo("VISA_CLI_DEBUG",!!it)})}return{entries:r,statusError:n}}function $p(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 yc(e,t={}){if(e.length===0)return"";let n=Math.max(...e.map(o=>o.key.length)),r=Math.max(...e.map(o=>o.formatted.length)),s=[];for(let o of e){let i=o.key.padEnd(n+2),a=o.formatted.padEnd(r+2);s.push(`${i}${a}(${$p(o.source)})`),t.verbose&&o.hint&&s.push(` ${"\u21B3".padStart(n)} ${o.hint}`)}return s.join(`
107
- `)}function _c(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 vc(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 vt=require("fs"),Sc=require("os"),So=require("path"),Pp=(0,So.join)((0,Sc.homedir)(),".visa-mcp"),bc=(0,So.join)(Pp,"mcp-session-budget.json");function Gr(){try{(0,vt.existsSync)(bc)&&(0,vt.unlinkSync)(bc)}catch{}}var xo=require("crypto"),Ae=R(Wn()),Xt=null,ve=0,Sn=0,ge=0,bt=null,Co=null,ko=null,Wr=Promise.resolve();function Yp(e){return Number((0,Ae.fromCents)(e))}function Cc(e){return(0,Ae.toCents)((0,Ae.micros)(BigInt(e)))}function xc(e){return(0,Ae.toWire)((0,Ae.fromCents)(e))}function wo(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function zr(e){return typeof e=="string"&&/^\d+$/.test(e)}var Zp=43,Xp=new RegExp(`^[A-Za-z0-9_-]{${Zp}}$`);function Qp(e){return typeof e=="string"&&Xp.test(e)}function ef(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||Xt&&e.session_id!==Xt||typeof e.nonce!="string"||e.nonce.length===0||!Qp(e.server_signature)||!wo(e.cumulative)||!wo(e.remaining)||!wo(e.delta)||e.cumulative<ve||ge>0&&e.cumulative>ge||ge>0&&e.remaining>ge||e.cumulative_micros!==void 0&&!zr(e.cumulative_micros)||e.remaining_micros!==void 0&&!zr(e.remaining_micros)||e.delta_micros!==void 0&&!zr(e.delta_micros)||e.reserved_micros!==void 0&&!zr(e.reserved_micros))}function tt(e){Xt=e,ve=0,Sn=0,ge=0,bt=null,Co=null,ko=null,Wr=Promise.resolve()}function Jn(e){ge=Math.max(0,Math.floor(e))}function To(){return Xt}function Eo(e){if(!Xt)return null;let t=ve+Sn;return ge>0&&t>ge&&(t=ge),{session_budget_id:Xt,cumulative_micros:Yp(t),nonce:(0,xo.randomUUID)(),idempotency_key:e||(0,xo.randomUUID)()}}function Ao(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 ef(r)?(ve=Math.max(ve,r.cumulative),Sn=0,bt=r,r):null}function kc(){return bt}function Ro(e){let t=Cc(e.cumulative_micros);ve=Math.max(ve,t),Sn=0;let n={status:"accepted",session_id:e.session_budget_id,cumulative:ve,remaining:Math.max(0,ge-ve),delta:0,cumulative_micros:xc(ve),remaining_micros:xc(Math.max(0,ge-ve)),delta_micros:"0",nonce:e.nonce};return bt=n,n}function Io(e){if(!e||typeof e!="object")return;let t=e.cumulative_micros;if(typeof t!="string"||!/^\d+$/.test(t))return;let n;try{n=BigInt(t)}catch{return}if(n<0n)return;let r=(0,Ae.toCents)((0,Ae.micros)(n));if(!Number.isFinite(r)||r<0)return;Co=t;let s=e,o=typeof s.session_id=="string"?s.session_id:Xt??"";bt?(typeof s.remaining_micros=="string"&&/^\d+$/.test(s.remaining_micros)&&(bt.remaining_micros=s.remaining_micros),typeof s.charged_micros=="string"&&/^\d+$/.test(s.charged_micros)&&(bt.delta_micros=s.charged_micros)):bt={session_id:o,cumulative:r,remaining:0,delta:0,nonce:typeof s.transaction_id=="string"?s.transaction_id:"",remaining_micros:typeof s.remaining_micros=="string"&&/^\d+$/.test(s.remaining_micros)?s.remaining_micros:void 0,delta_micros:typeof s.charged_micros=="string"&&/^\d+$/.test(s.charged_micros)?s.charged_micros:void 0}}function Tc(e){let t=e.receipt??null;ko={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:Cc(e.voucher.cumulative_micros),estimatedCumulativeCents:Jr(),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 Ec(){return ko}function Ac(){return ve}function Rc(){return Co}function Jr(){let e=ve+Sn;return ge>0&&e>ge&&(e=ge),e}function Ic(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return Wr=Wr.then(()=>{Sn+=t}),Wr}var tf=10,nf=1,W=null,$c=Promise.resolve();function $o(e){let t=$c.catch(()=>{}).then(e);return $c=t.then(()=>{},()=>{}),t}var le=class extends Error{balanceCents;minRequiredCents;constructor(t,n){super(`Prepaid balance is $${(t/100).toFixed(2)}; at least $${(n/100).toFixed(2)} required to open a credit session. Top up via the buy_credits tool first.`),this.name="InsufficientBalanceError"}};async function Po(e,t,n){return $o(()=>Pc(e,t,n))}async function Pc(e,t,n){if(Gr(),W&&new Date(W.expiresAt).getTime()>Date.now())return To()!==W.budgetId&&(tt(W.budgetId),Jn(W.totalCents)),m.info("mcp-session:active-hit",{budgetId:W.budgetId,tool:n.toolName,remainingEstimatedCents:W.totalCents-Jr()}),{budgetId:W.budgetId,isFresh:!1,totalCents:W.totalCents,requestedCapCents:W.totalCents,appliedCapCents:W.totalCents,clampedReason:null};W&&(W=null,tt(null));let r=await e.getBalance();if(!r.success)throw new Error(`Could not read balance: ${r.error||"unknown error"}`);let s=n.sessionKind??"explicit",o=s==="one_shot"?nf:tf,i=Math.max(o,Math.ceil(n.minRequiredCents??o));if(r.balanceCents<i)throw new le(r.balanceCents,i);let a=n.capCentsOverride??ka(),l=Math.min(a,r.balanceCents),c=l<a?"balance":null,u=await t("session_create",l,"Visa CLI Session",`open credit-model session with $${(l/100).toFixed(2)} cap`,n.userContext),d=await e.createSessionBudget({total_cents:l,session_kind:s,...u?{attestation:u}:{}});if(!d.success||!d.budget){let g=d.error||"unknown error";throw new Error(`Failed to open credit session: ${g}`)}let f={budgetId:d.budget.id,expiresAt:d.budget.expiresAt,totalCents:d.budget.totalCents,createdAt:d.budget.createdAt};return W=f,tt(f.budgetId),Jn(f.totalCents),m.info("mcp-session:opened",{budgetId:f.budgetId,capCents:f.totalCents,requestedCapCents:a,clampedReason:c,sessionKind:s,expiresAt:f.expiresAt,tool:n.toolName}),{budgetId:f.budgetId,isFresh:!0,totalCents:f.totalCents,requestedCapCents:a,appliedCapCents:f.totalCents,clampedReason:c}}async function Mc(e,t,n){return $o(async()=>{let s=St()?await Oc(e):null,o=await Pc(e,t,n);return{budgetId:o.budgetId,totalCents:o.totalCents,closedPrevious:s,requestedCapCents:o.requestedCapCents,appliedCapCents:o.appliedCapCents,clampedReason:o.clampedReason}})}async function Oc(e){let n=St()?.budgetId??To(),r=!1,s,o;if(n)try{let i=await e.closeSession(n);r=!!i?.success,typeof i?.finalCumulativeCents=="number"&&(s=i.finalCumulativeCents),typeof i?.finalCumulativeMicros=="string"&&(o=i.finalCumulativeMicros)}catch(i){m.warn("mcp-session:close-server-failed",{budgetId:n,error:i?.message||String(i)})}return Gr(),W=null,tt(null),{closedServerSide:r,budgetId:n,finalCumulativeCents:s,finalCumulativeMicros:o}}async function Yr(e){return $o(()=>Oc(e))}function St(){return Gr(),W?new Date(W.expiresAt).getTime()<=Date.now()?(W=null,tt(null),null):{budgetId:W.budgetId,totalCents:W.totalCents,lastReceiptCumulative:Ac(),lastReceiptCumulativeMicros:kc()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:Rc(),estimatedCumulative:Jr(),lastToolSpend:Ec(),expiresAt:W.expiresAt}:null}var Lc=R(Wn()),Nc=10000n;function rf(e){return e<=0n?0:Number((e+Nc-1n)/Nc)}function Dc(e){return rf((0,Lc.fromUsd)(e))}var Zr="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.",Uc="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 jc=Promise.resolve(),qc=!1;function rs(e){let t=jc.catch(()=>{}).then(e);return jc=t.then(()=>{},()=>{}),t}async function Xc(e){let t=await Po(I,He,{toolName:e.toolId,userContext:e.userContext}),n=Eo(e.idempotencyKey);if(!n)throw new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await df(),s,o,i=async()=>I.shortcutWithSession(e.toolId,n,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);try{try{({data:s,voucherReceiptHeader:o}=await i())}catch(u){if(u instanceof Mt){let d=Math.min(Math.max(u.retryAfterSecs,0),5)*1e3;m.warn("mcp-session:lock-contended-retrying",{tool:e.toolId,retryAfterSecs:u.retryAfterSecs}),await new Promise(f=>setTimeout(f,d)),{data:s,voucherReceiptHeader:o}=await i()}else throw u}}catch(u){if(u instanceof ln){if(m.warn("mcp-session:server-invalidated-budget",{code:u.code,budgetId:u.budgetId??t.budgetId,tool:e.toolId}),await Yr(I),process.env.VISA_REQUIRE_EXPLICIT_SESSION==="true")throw new Error(`Your session was closed by another process (${u.code}). Restart MCP or run start_session again.`);return qc||(qc=!0,console.error(`[visa-cli] Your session was closed by another process; reopened automatically as pay-as-you-go.
108
- To require an explicit session approval instead, set VISA_REQUIRE_EXPLICIT_SESSION=true.`)),m.info("mcp-session:falling-back-to-payg",{code:u.code,tool:e.toolId}),Qc(e)}throw u instanceof Mt?(m.warn("mcp-session:lock-contended-give-up",{tool:e.toolId}),new Error("Another paid call is currently in progress on this session. Wait a moment and try again.")):u}let a=Ao(o)??(n?Ro(n):null);if(Io(s?.receipt_v2),await Ic(e.estimatedAmountCents),Tc({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),tl(s))return s;let l=await el();if(e.idempotencyKey&&nl(s,l,e.idempotencyKey))return s;let c=l?es(l):null;return rl(s,r,c)}function Ve(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function No(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(No).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${No(r)}`).join(",")}}`}function sf(e,t,n,r){let s=ce.createHash("sha256").update(`${n}:${No(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${s}`}function of(e,t){return`${e}:${t}`}function af(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 Vc(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,s=qe(r),o=s!==null?s.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=af(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),l=i!=null?String(i):a;return{batch_id:e,item_id:of(e,t),index:t,...l!==void 0?{transaction_id:l}:{},...a!==void 0?{ledger_id:a}:{},...o?{amountMicros:o,amount_micros:o,cost_micros:o}:{}}}async function Qc(e){let t=Math.max(1,Math.ceil(e.estimatedAmountCents)),n=await I.getBalance();if(!n.success)throw new Error(`Could not read balance: ${n.error||"unknown error"}`);if(n.balanceCents<t)throw new le(n.balanceCents,t);let r=t,s=es(n),o=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(r/100).toFixed(2)})`,i=await He("session_create",r,"Visa CLI Session",o,e.userContext),a=await I.createSessionBudget({total_cents:r,session_kind:"one_shot",...i?{attestation:i}:{}});if(!a.success||!a.budget)throw new Error(`Failed to open on-demand session: ${a.error||"unknown error"}`);let l=a.budget.id;tt(l),Jn(a.budget.totalCents),m.info("on-demand-session:opened",{budgetId:l,capCents:a.budget.totalCents,tool:e.toolId});try{let c=Eo(e.idempotencyKey);if(!c)throw new Error(`Internal: mintVoucher returned null after on-demand session-open ${l}`);let{data:u,voucherReceiptHeader:d}=await I.shortcutWithSession(e.toolId,c,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(Ao(d)||Ro(c),Io(u?.receipt_v2),tl(u))return u;let f=await el();if(e.idempotencyKey&&nl(u,f,e.idempotencyKey))return u;let g=f?es(f):null;return rl(u,s,g)}finally{try{await I.closeSession(l)}catch(c){m.warn("on-demand-session:close-failed",{budgetId:l,error:c?.message||String(c)})}tt(null),m.info("on-demand-session:closed",{budgetId:l,tool:e.toolId})}}async function xt(e){return rs(async()=>St()?Xc(e):Qc(e))}function ss(){return we()}var I=new ye(()=>U.getSessionToken());function qe(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function es(e){return qe(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function cf(e){if(e<0n&&(e=0n),e>=1000000n){let r=(e+5000n)/10000n,s=r/100n,o=r%100n;return`$${s.toString()}.${o.toString().padStart(2,"0")}`}let t=e%1000000n;return t===0n?"$0.00":`$0.${t.toString().padStart(6,"0").replace(/0+$/,"")}`}function lf(e){let t=qe(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=qe(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=qe(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function Xr(e,t="INVALID_TOOL_PARAMS"){return{success:!1,error_code:t,code:t,error:e,message:e}}function uf(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 df(){try{let e=await I.getBalance();return e.success?es(e):null}catch{return null}}async function el(){try{let e=await I.getBalance();return e.success?e:null}catch{return null}}function tl(e){if(!e||e.success===!1)return!1;let t=qe(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=qe(e.amountMicros??e.amount_micros??e.charged_micros),r=t??n;if(r===null||r<=0n)return!1;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,e.charged_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),!0}function nl(e,t,n){if(!e||e.success===!1||!t||!Array.isArray(t.ledger))return!1;let r=t.ledger.find(a=>a.idempotencyKey===n);if(!r)return!1;let s=qe(r.deltaMicros)??BigInt(r.deltaCents)*10000n,o=s<0n?-s:s;if(o<=0n)return!1;let i=o.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(o)/1e6),!0}function rl(e,t,n){if(!e||e.success===!1||t===null||n===null)return e;let r=t-n;if(r<=0n)return e;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),e}var mf="2.1.1",Rv=["","","You're ready to go! Try:","","Core:",'\u2022 "Show my account status" \u2192 get_status','\u2022 "List my enrolled cards" \u2192 get_cards','\u2022 "Show my paid tool use history" \u2192 transaction_history','\u2022 "Set my daily limit to $50" \u2192 update_spending_controls','\u2022 "Generate 3 variations in parallel" \u2192 batch',"","Category tools:",'\u2022 "Generate an image of a sunset over Tokyo" \u2192 generate_image','\u2022 "Make a 4-second video of a penguin juggling" \u2192 generate_video','\u2022 "Make a song about coding late at night" \u2192 generate_music','\u2022 "Create a sound effect for a checkout chime" \u2192 generate_audio','\u2022 "Create a 3D asset from this product sketch" \u2192 generate_3d','\u2022 "Upscale this product image" \u2192 upscale_image','\u2022 "Transcribe this meeting recording" \u2192 transcribe_audio','\u2022 "Run a reasoning model on this prompt" \u2192 run_llm',"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
109
- `);function Fe(e){if(!e||typeof e!="string"||xa())return;let t=In(e);if(!t)return;let n=Ts();if(n.headless){m.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`);return}let r=wi(t,ss());if(!r){m.info(`Browser auto-open skipped (non-internal host). URL: ${t}`);return}let s=Ci(r);if(!s){m.info(`No browser command for platform "${Yn.platform()}". URL: ${r}`);return}(0,Zc.execFile)(s.cmd,s.args,o=>{o&&m.warn(`Browser open failed: ${o.message}. URL: ${r}`)})}async function be(e){return zn(I,e,ul)}var sl="get_cards",ol="set_default_card";function pf(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 '${sl}' to see enrolled cards and '${ol}' to switch, then retry the original request.`}function ff(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 '${sl}' to see enrolled cards and '${ol}' to switch. Do not retry automatically.`}function Be(e,t){let n=e.retryable?pf(e.code,e.retryAfter):ff(e.code,t.merchantName);return{success:!1,declined:!0,retryable:e.retryable,code:e.code,reason:e.reason,payment_error_class:e.paymentErrorClass,correlation_id:e.correlationId,transactionId:e.transactionId,retryAfter:e.retryAfter,merchantName:t.merchantName,amount:t.amount,message:e.message,agent_guidance:n}}var wn=null,gf=3e4;function il(){wn=null}var wt=class extends Error{constructor(n){super(`${ts()} attestation is required for this action, but it is not available in this MCP process. `+Lo());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function os(e,t){return{success:!1,error:e.code,message:e.message,action:t,agent_guidance:`Biometric attestation is required for ${t}, but this MCP process cannot create a local attestation. `+Lo()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function hf(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:Zr,agent_guidance:Uc}}function ts(){return process.platform==="darwin"?"Touch ID":"local biometric"}function Lo(){return process.platform==="darwin"?"Run the action from an interactive terminal with Touch ID access, or use reset with confirm:true to clear stale server biometric state through GitHub re-authentication.":"This platform cannot create Visa CLI Touch ID attestations. Use reset with confirm:true to clear stale server biometric state through GitHub re-authentication."}function is(e){return typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0}async function yf(e){let t=Date.now();if(wn&&wn.expiresAt>t)return{required:wn.required,hasRegisteredKey:wn.hasRegisteredKey};try{let n=await I.getStatus(e),r=n.attestationRequired!==!1,s=is(n);return wn={required:r,hasRegisteredKey:s,expiresAt:t+gf},{required:r,hasRegisteredKey:s}}catch{return{required:!0,hasRegisteredKey:!0}}}async function He(e,t,n,r,s,o){if(!o?.forceRequired){let i=await yf(s);if(!i.required){m.info("attestation:skipped-by-server-policy",{context:e});return}if(!i.hasRegisteredKey){m.info("attestation:skipped-no-registered-key",{context:e});return}}if(!te())throw m.warn("attestation:unavailable",{context:e}),new wt(e);m.info("attestation:attempt",{context:e,amount:t,merchant:n});try{let{nonce:i}=await I.getAttestationChallenge(),a=Buffer.from(JSON.stringify({nonce:i,amount:t,merchant:n,context:e})).toString("base64");m.info("touchid:prompt",{context:e,amount:t,merchant:n});let l=await bn(a,r);return m.info("attestation:success",{context:e,amount:t,merchant:n}),{signature:l,nonce:i,amount:t,merchant:n}}catch(i){throw m.error("attestation:failure",{context:e,amount:t,merchant:n,error:i.message}),i}}var Fc="[dry-run] https://placeholder.visa-cli.dev/image.png",_f=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"]),vf=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 bf(e,t){return t==="run_llm"||e.startsWith("or-")?"llm":t==="generate_image"||_f.has(e)?"image":t==="generate_video"||vf.has(e)?"video":null}function Sf(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function wf(e){return e==="llm"?"OpenRouter":"fal.ai"}function xn(e,t,n,r){let s={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:wf(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${Sf(n)}`;return{...s,content:i,data:{content:i,model:t,dry_run:!0}}}return{...s,urls:[Fc],data:{[e==="video"?"videoUrl":"imageUrl"]:Fc,metadata:{dry_run:!0}}}}async function Mo(e){let t=e.mode??"mock",n=t==="preflight"?"/v1/telemetry/preflight":"/v1/telemetry/dry-run",r=t==="preflight"?"preflight":null;try{await I.emitTelemetry([{id:ce.randomUUID(),timestamp:new Date().toISOString(),tool_name:e.toolName,user_prompt:e.userContext??"",tool_params:JSON.stringify(e.toolParams),result_success:!0,result_error:null,result_json:JSON.stringify(e.result),payment_rail:r,payment_amount:0,payment_currency:"USD",merchant_name:e.result.merchantName,transaction_id:e.result.transactionId,tx_hash:null,protocol:null,http_status:200,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",event_kind:"mcp_tool",endpoint:n,resolved_model:e.resolvedModel,session_budget_id:null}])}catch(s){m.warn("dry_run:telemetry_failed",{tool:e.toolName,error:s?.message||String(s),mode:t})}}var xf="https://openrouter.ai/api/v1/chat/completions",Cf="openrouter/free",kf=50,Tf=15e3;function Ef(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 Af(e,t,n){let r=process.env.OPENROUTER_API_KEY;if(!r)return m.warn("preflight:no_openrouter_key_falling_back_to_mock",{tool:e}),{result:xn("llm",e,t,n),degraded:!0,resolvedModel:null};let s=Ef(t),o;try{o=await $t(xf,{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:Cf,messages:[{role:"user",content:s}],max_tokens:kf}),timeoutMs:Tf})}catch(u){return m.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:xn("llm",e,t,n),degraded:!0,resolvedModel:null}}if(!o.ok){let u=await o.text().catch(()=>"");return m.warn("preflight:openrouter_http_error_falling_back_to_mock",{tool:e,status:o.status,bodyExcerpt:u.slice(0,200)}),{result:xn("llm",e,t,n),degraded:!0,resolvedModel:null}}let i;try{i=await o.json()}catch(u){return m.warn("preflight:openrouter_invalid_json_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:xn("llm",e,t,n),degraded:!0,resolvedModel:null}}let a=typeof i?.choices?.[0]?.message?.content=="string"?i.choices[0].message.content:"",l=typeof i?.model=="string"?i.model:null;return{result:{success:!0,transactionId:`preflight:${n??e}`,amount:0,rail:"preflight",merchantName:"OpenRouter",dry_run:!0,preflight:!0,metadata:{dry_run:!0,preflight:!0,model_used:l},content:a,data:{content:a,model:l??e,dry_run:!0,preflight:!0}},degraded:!1,resolvedModel:l}}async function as(e,t,n,r){let s=vo();if(!s)return null;let o=bf(e,r);if(!o)return null;let i=Date.now();if(s==="mock"){let c=xn(o,e,t,r);return await Mo({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:c,userContext:n,startedAt:i,mode:"mock"}),m.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:o,mode:s}),c}if(o!=="llm"){m.warn("preflight:not_supported_for_kind_falling_back_to_mock",{tool:e,kind:o});let c=xn(o,e,t,r);return await Mo({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:c,userContext:n,startedAt:i,mode:"preflight"}),c}let{result:a,resolvedModel:l}=await Af(e,t,r);return await Mo({toolName:r??e,resolvedModel:l??(r&&r!==e?e:null),toolParams:t,result:a,userContext:n,startedAt:i,mode:"preflight"}),m.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:o,mode:s}),a}async function nt(e,t,n){let r=await I.paymentPreview({tool:e,url:t},n);if(!r||!r.merchantName||r.amount===void 0||r.amount===null||r.amount<0)throw new Error("Could not determine payment amount and merchant. Try again.");if(!Number.isFinite(r.amount)||r.amount<0||r.amount>999999)throw new Error(`Invalid payment amount: ${r.amount}. Payment rejected for safety.`);return r}function rt(e){return Dc(e.amount)}function Rf(){return ns.join(Yn.homedir(),".visa-mcp","allium-results")}var Iv=16*1024,$v=50*1024*1024;function If(){let e=Rf();try{if(!Re.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=Re.readdirSync(e),n=0,r=0;for(let s of t)try{let o=Re.statSync(ns.join(e,s));o.isFile()&&(n+=o.size,r++)}catch{}return{file_count:r,size_bytes:n,path:e}}catch(t){return m.warn("allium:disk_usage_error",{error:t.message}),{file_count:0,size_bytes:0,path:e}}}var Bc=3600*1e3,Oo=0;function $f(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function Zn(e){if(!Ca()&&!(Date.now()<Oo))try{if(!await U.getSessionToken())return;await I.feedSubmit({prompt:e.prompt,tool:e.tool,media_url:e.mediaUrl,media_type:e.mediaType,cost:e.cost,transaction_id:e.transactionId,auto:!0,...e.userContext&&{user_context:e.userContext}}),m.info("feed:submitted",{tool:e.tool,mediaType:e.mediaType,transactionId:e.transactionId})}catch(t){if($f(t)){let n=Oo===0;Oo=Date.now()+Bc,n&&m.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:Bc});return}m.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function Pf(e,t){let n=(e.state||"").trim().toUpperCase(),r=(e.county||"").trim(),s=(e.start_date||"").trim(),o=(e.end_date||s).trim();if(!/^[A-Z]{2}$/.test(n))throw new Error('state must be a 2-letter US state code (e.g. "VA").');if(!r)throw new Error("county is required.");if(!/^\d{4}-\d{2}$/.test(s))throw new Error('start_date must be YYYY-MM (e.g. "2025-08").');if(o&&!/^\d{4}-\d{2}$/.test(o))throw new Error("end_date must be YYYY-MM.");let i="Visa SMI",a=.1,l=`Pay $0.10 to ${i} for SMI data (${n} / ${r})`;m.info("payment:attempt",{tool:"get_visa_smi",amount:a,merchant:i});try{return await be(async()=>{let c=await He("get_visa_smi",a,i,l),u=await I.getVisaSmi({state:n,county:r,start_date:s,end_date:o,attestation:c,idempotencyKey:ce.randomUUID()},t);return u.success?m.info("payment:success",{tool:"get_visa_smi",merchant:i,charged_cents:u.charged_cents}):m.warn("payment:declined",{tool:"get_visa_smi",merchant:i,message:u.error}),u})}catch(c){if(c instanceof oe)return m.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:c.code,retryable:c.retryable}),Be(c,{amount:a,merchantName:i,description:"Visa SMI data"});throw m.error("payment:failure",{tool:"get_visa_smi",merchant:i,error:c.message}),c}}async function Mf(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 as("generate_image_card",e,t);if(n)return n;let r=await nt("generate_image_card",void 0,t),s=ce.randomUUID();m.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await be(async()=>{let o;try{o=await xt({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:rt(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof le)return Ve(i);throw i}return m.info("payment:success",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>Fe(i)),Zn({prompt:e.prompt,tool:"generate_image_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):m.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof oe)return m.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),Be(o,r);throw m.error("payment:failure",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,error:o.message}),o}}async function Of(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 as("generate_image_fast_card",e,t);if(n)return n;let r=await nt("generate_image_fast_card",void 0,t),s=ce.randomUUID();m.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await be(async()=>{let o;try{o=await xt({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:rt(r),userContext:t,timeoutMs:6e4,idempotencyKey:s})}catch(i){if(i instanceof le)return Ve(i);throw i}return m.info("payment:success",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>Fe(i)),Zn({prompt:e.prompt,tool:"generate_image_fast_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):m.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof oe)return m.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),Be(o,r);throw m.error("payment:failure",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,error:o.message}),o}}async function Nf(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 as("generate_video_tempo_card",e,t);if(n)return n;let r=await nt("generate_video_tempo_card",void 0,t),s=ce.randomUUID();m.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await be(async()=>{let o;try{o=await xt({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:rt(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof le)return Ve(i);throw i}return m.info("payment:success",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>Fe(i)),Zn({prompt:e.prompt,tool:"generate_video_tempo_card",mediaUrl:o.urls[0],mediaType:"video",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):m.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof oe)return m.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),Be(o,r);throw m.error("payment:failure",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,error:o.message}),o}}async function Lf(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 nt("generate_music_tempo_card",void 0,t),r=ce.randomUUID();m.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await be(async()=>{let s;try{s=await xt({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:rt(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(o){if(o instanceof le)return Ve(o);throw o}return m.info("payment:success",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),s.urls?.length&&s.status!=="processing"?(s.urls.forEach(o=>Fe(o)),Zn({prompt:e.prompt,tool:"generate_music_tempo_card",mediaUrl:s.urls[0],mediaType:"audio",cost:s.amount??n.amount,transactionId:s.transactionId,userContext:t})):s.urls?.length&&s.status==="processing"?(s._preliminary_urls=s.urls,delete s.urls,m.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):m.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof oe)return m.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),Be(s,n);throw m.error("payment:failure",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,error:s.message}),s}}async function Df(e,t){let n=await nt("check_music_status_tempo_card",void 0,t),r=ce.randomUUID();m.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await be(async()=>{let s;try{s=await xt({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:rt(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof le)return Ve(o);throw o}return m.info("payment:success",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),s.urls?.length&&s.urls.forEach(o=>Fe(o)),s})}catch(s){if(s instanceof oe)return m.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),Be(s,n);throw m.error("payment:failure",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,error:s.message}),s}}async function Uf(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 nt("query_onchain_prices",void 0,t),r=ce.randomUUID();m.info("payment:attempt",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName});try{return await be(async()=>{let s;try{s=await xt({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:rt(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof le)return Ve(o);throw o}if(m.info("payment:success",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,mode:"session"}),Array.isArray(s?.data))s.data=s.data.map(o=>{if("mint"in o&&!("address"in o)){let{mint:i,...a}=o;return{address:i,...a}}return o});else if(s&&"mint"in s&&!("address"in s)){let{mint:o,...i}=s;return{address:o,...i}}return s})}catch(s){if(s instanceof oe)return m.warn("payment:declined",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),Be(s,n);throw m.error("payment:failure",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,error:s.message}),s}}var jf=["generate_music_tempo_card"],Hc=10,Kc=5,Gc=new Map;function zc(e){let t=Gc.get(e);if(t!==void 0)return t;let r=Kn(e)?.isAsync===!0||jf.includes(e);return Gc.set(e,r),r}var qf=36e4,Vf=18e4,Ff=15e3,Bf=12e4,Hf=2e3;function Wc(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}async function Kf(e,t){let n;if(e.requests?.some(C=>C.tool||C.tool_id)&&e.requests)n=e.requests.map(C=>{let T=C.tool||C.tool_id||e.tool;if(!T)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let V=_o(T,C.tier||e.tier,C.prompt??t),{tool:z,tool_id:F,tier:ot,params:ee,...ue}=C,it=ee&&typeof ee=="object"?{...ee,...ue}:ue;return{resolvedTool:V,params:it}});else if(e.tool){let C=_o(e.tool,e.tier,e.params?.prompt??t);n=(e.requests||(e.count&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(V=>({resolvedTool:C,params:V}))}else return Wc("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return Wc("BATCH_EMPTY","Batch requires at least one item.");if(n.length>Hc)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${Hc} items. Please split into smaller batches.`};if([...new Set(n.map(C=>C.resolvedTool))].some(zc)&&n.length>Kc)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${Kc} items. Please use multiple batches for more.`};let i=[...new Set(n.map(C=>C.resolvedTool))],a=i.length===1,l={};for(let C of i)l[C]=await nt(C,void 0,t);let c=0;for(let C of n)c+=l[C.resolvedTool].amount;let u=[...new Set(Object.values(l).map(C=>C.merchantName))].join(", "),d=a?i[0]:"mixed";m.info("payment:attempt",{tool:"batch",batchTool:d,count:n.length,totalAmount:c,merchant:u,heterogeneous:!a});let f=n.some(C=>zc(C.resolvedTool)),g=n.some(C=>C.resolvedTool.startsWith("or-")||C.resolvedTool==="run_llm"||C.resolvedTool==="execute_tool"),w=f?qf:g?Vf+n.length*Ff:Bf+n.length*Hf,y=ce.randomUUID(),k=[],O=0,N=0n;return rs(async()=>{let C=!St();if(C)try{let T=Math.max(1,Math.ceil(c*100));await Po(I,He,{toolName:"batch",userContext:t,sessionKind:"one_shot",minRequiredCents:T,capCentsOverride:T})}catch(T){return T instanceof le?Ve(T):(m.warn("payment:batch-prewarm-failed",{batchTool:d,count:n.length,error:T?.message||String(T)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:T?.message||"Failed to authenticate batch session",tool:d,count:n.length,failedCount:n.length,results:[]})}try{for(let ee=0;ee<n.length;ee+=1){let ue=n[ee],it=l[ue.resolvedTool];try{let ne=await Xc({toolId:ue.resolvedTool,toolParams:ue.params,estimatedAmountCents:rt(it),userContext:t,metaTool:"batch",timeoutMs:w,idempotencyKey:sf(y,ee,ue.resolvedTool,ue.params)});if(k.push({success:ne?.success!==!1,tool:ue.resolvedTool,...ne,...Vc(y,ee,ne)}),ne?.success!==!1){let An=qe(ne?.amountMicros??ne?.amount_micros),ri=typeof ne?.amount=="number"?ne.amount:it.amount;An!==null&&An>0n?N+=An:N+=BigInt(Math.round(ri*1e6)),O+=ri}ne?.urls&&ne.urls.forEach(An=>Fe(An))}catch(ne){if(ne instanceof le&&k.length===0)return Ve(ne);m.warn("payment:batch-item-failed",{tool:ue.resolvedTool,index:ee,error:ne?.message||String(ne)}),k.push({success:!1,tool:ue.resolvedTool,...Vc(y,ee),error:ne?.message||String(ne)})}}let T=k.filter(ee=>ee?.success===!1).length,V=k.length-T,z=k.flatMap(ee=>Array.isArray(ee?.urls)?ee.urls:[]),F=N>0n?Number(N)/1e6:Math.round((O+Number.EPSILON)*100)/100,ot=V===0?"failure":T===0?"success":"partial";return m.info("payment:success",{tool:"batch",batchTool:d,count:n.length,totalAmount:c,totalCharged:F,merchant:u,successCount:V,failedCount:T,outcome:ot,mode:"session",batchId:y}),{success:V>0,outcome:ot,batch_id:y,tool:a?i[0]:d,count:n.length,successCount:V,failedCount:T,totalCharged:F,...N>0n?{totalChargedMicros:N.toString(),amountMicros:N.toString(),amount_micros:N.toString()}:{},merchantName:u,results:k,...z.length?{urls:z}:{}}}catch(T){if(T instanceof oe)return m.warn("payment:declined",{tool:"batch",batchTool:d,count:n.length,totalAmount:c,merchant:u,code:T.code,retryable:T.retryable}),Be(T,{amount:c,merchantName:u});throw m.error("payment:failure",{tool:"batch",batchTool:d,count:n.length,totalAmount:c,merchant:u,error:T.message}),T}finally{if(C){let T=await Yr(I);m.info("batch-session:closed",{budgetId:T.budgetId,closedServerSide:T.closedServerSide})}}})}function Gf(){let e=!1,t;try{let r=ns.join(Yn.homedir(),".claude","settings.json");if(Re.existsSync(r)){let s=JSON.parse(Re.readFileSync(r,"utf-8")),o=typeof s.statusLine=="object"?s.statusLine.command:"";e=Rt(o)}}catch{}let n=yr();return n||(t="visa-cli config hud enable"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function zf(e){let[t,n]=await Promise.all([I.getStatus(e),I.getBalance().catch(o=>(m.warn("get_status:balance_fetch_failed",{error:o?.message||String(o)}),null))]);typeof t?.dailyRemaining=="number"&&(t.dailyRemaining=Math.round(t.dailyRemaining*100)/100);let r=If();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=Gf(),t.version=mf,Array.isArray(t.cards)&&(t.cards=t.cards.map(o=>({...o,displayName:Do(o)})),t.cardIdGuidance="cardId values are opaque tool parameters only; refer to cards by brand and last four digits."),n&&n.success&&(t.balanceCents=n.balanceCents,t.amountUsd=n.amountUsd);let s=St();if(t.sessionMode=!!s,s){let o=Math.max(0,s.totalCents-s.estimatedCumulative);t.activeSession={budgetId:s.budgetId,capCents:s.totalCents,capUsd:s.totalCents/100,lastReceiptCumulativeCents:s.lastReceiptCumulative,estimatedCumulativeCents:s.estimatedCumulative,spentCents:s.estimatedCumulative,spentUsd:s.estimatedCumulative/100,estimatedRemainingCents:o,estimatedRemainingUsd:o/100,...s.lastToolSpend?{lastToolSpend:{toolName:s.lastToolSpend.toolName,resolvedToolId:s.lastToolSpend.resolvedToolId,estimatedAmountCents:s.lastToolSpend.estimatedAmountCents,estimatedAmountUsd:s.lastToolSpend.estimatedAmountCents/100,voucherCumulativeCents:s.lastToolSpend.voucherCumulativeCents,estimatedCumulativeCents:s.lastToolSpend.estimatedCumulativeCents,receiptDeltaCents:s.lastToolSpend.receiptDeltaCents,receiptCumulativeCents:s.lastToolSpend.receiptCumulativeCents,receiptRemainingCents:s.lastToolSpend.receiptRemainingCents,recordedAt:s.lastToolSpend.recordedAt}}:{},expiresAt:s.expiresAt}}return t}function Do(e){let t=typeof e.brand=="string"&&e.brand.trim().length>0?e.brand.trim():"card",n=t.charAt(0).toUpperCase()+t.slice(1).toLowerCase(),r=typeof e.last4=="string"&&e.last4.trim().length>0?e.last4.trim():"unknown",s=e.isDefault===!0?" (default)":"";return`${n} ending in ${r}${s}`}async function al(e,t){try{let r=((await I.getStatus(t)).cards||[]).find(s=>s?.id===e);if(r)return Do(r)}catch(n){m.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function Wf(e){let n=(await I.getStatus(e)).cards||[];return n.length===0?{cards:[],message:"No cards enrolled. Use the add_card tool to add a payment card."}:n.some(s=>!Number.isInteger(s?.id)||s.id<=0)?{success:!1,cards:[],message:"Card action handles are unavailable right now, so remove_card and set_default_card are temporarily disabled."}:{cards:n.map(s=>({...s,displayName:Do(s)})),message:"Use cardId only as an opaque tool parameter. When speaking to the user, refer to cards by brand and last four digits, not by card id."}}async function Jf(e,t){return await I.getTransactions({limit:e.limit,offset:e.offset},t)}async function Yf(e,t){return await I.feedback(e.message,e.transaction_id,t)}var Zf=100;async function Xf(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Qt("MISSING_CONFIRMATION","Please confirm by setting confirm: true to charge your enrolled card for credits.");if(!e.amount||!Number.isFinite(e.amount)||e.amount<=0)return{success:!1,error:"amount must be a positive number in USD (e.g. 5.00)"};let n=Math.round(e.amount*100);if(n<Zf)return{success:!1,error:"Minimum top-up is $1.00"};let r=ce.randomUUID();m.info("buy_credits:attempt",{amountCents:n});try{return await be(async()=>{let s=await He("balance-topup",e.amount,"Visa CLI Balance",`top up balance with $${e.amount.toFixed(2)}`,t,{forceRequired:!0}),o=await I.topupBalance({amount_cents:n,idempotency_key:r,attestation:s});if(o.success){m.info("buy_credits:success",{amountCents:n,balanceCents:o.balanceCents});let i=((o.balanceCents??0)/100).toFixed(2),a=(n/100).toFixed(2);return{...o,amount:n/100,amountMicros:String(n*1e4),merchantName:"Visa CLI Balance",message:`Added $${a} \u2014 balance is now $${i}`}}return m.warn("buy_credits:failed",{amountCents:n,error:o.error}),o})}catch(s){if(s instanceof wt)return hf();throw m.error("buy_credits:failure",{amountCents:n,error:s.message}),s}}function Qt(e,t){return{success:!1,error:t,code:e,message:t}}async function Qf(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Qt("MISSING_CONFIRMATION","Please confirm by setting confirm: true to update spending controls.");if(e.maxTransactionAmount!==void 0&&(typeof e.maxTransactionAmount!="number"||!Number.isFinite(e.maxTransactionAmount)||e.maxTransactionAmount<.01||e.maxTransactionAmount>100))return Qt("INVALID_VALUE","maxTransactionAmount must be between $0.01 and $100");if(e.dailyLimit!==void 0&&(typeof e.dailyLimit!="number"||!Number.isFinite(e.dailyLimit)||e.dailyLimit<1||e.dailyLimit>100))return Qt("INVALID_VALUE","dailyLimit must be between $1 and $100");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return Qt("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");m.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await be(async()=>{let n=await He("spending-controls",0,"","update spending controls"),r=await I.updateSpendingControls({maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit,confirm:!0,attestation:n},t);return m.info("spending_controls:success",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit}),r})}catch(n){if(m.error("spending_controls:failure",{error:n.message}),n instanceof wt)return os(n,"update_spending_controls");if(String(n?.message||n).includes("Attestation required"))return Qt("ATTESTATION_REQUIRED","Changing spending controls requires local attestation, even when payment biometric prompts are disabled.");throw n}}async function eg(e){let t=await Kr({api:I,includeDev:!!e.includeDev});return{config:t.entries.map(n=>({key:n.key,value:n.value,source:n.source,hint:n.hint})),statusError:t.statusError}}async function tg(e){if(!e.key||typeof e.key!="string")return{success:!1,error:"key is required. Call config_list first to see available keys."};if(e.value===void 0)return{success:!1,error:"value is required. Use config_unset to remove a setting."};m.info("config:set",{key:e.key});try{let t=Ar(e.key,e.value);return m.info("config:set:success",{key:t.key,requiresRestart:t.requiresRestart}),{success:!0,key:t.key,value:t.value,requiresRestart:t.requiresRestart,path:t.path,message:t.requiresRestart?`Saved ${t.key}. Restart Claude Code for the change to take effect.`:`Saved ${t.key}.`}}catch(t){let n=t instanceof We?"UNKNOWN_KEY":t instanceof Je?"SERVER_CONTROLLED":t instanceof mt?"RETIRED_KEY":"INVALID_VALUE";return m.warn("config:set:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(ft).sort()}}}async function ng(e){if(!e.key||typeof e.key!="string")return{success:!1,error:"key is required. Call config_list first to see which keys are currently set via settings.json."};m.info("config:unset",{key:e.key});try{let t=Rr(e.key);return m.info("config:unset:success",{key:t.key,removed:t.removed}),{success:!0,key:t.key,removed:t.removed,requiresRestart:t.requiresRestart,path:t.path,message:t.removed?t.requiresRestart?`Removed ${t.key}. Restart Claude Code for the change to take effect.`:`Removed ${t.key}.`:`${t.key} was not set in settings.json \u2014 nothing to remove.`}}catch(t){let n=t instanceof We?"UNKNOWN_KEY":t instanceof Je?"SERVER_CONTROLLED":t instanceof mt?"RETIRED_KEY":"INVALID_VALUE";return m.warn("config:unset:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(ft).sort()}}}async function rg(e){let t=await I.getStatus(e),n=t.attestationRequired!==!1,r=is(t),s=te(),o=n?r?s?`${ts()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${ts()} is not available in this process. ${Lo()}`:"Biometric attestation is enabled on the account, but no attestation key is registered. Payments on this device proceed without a biometric signature; processor declines such as INVALID_OR_MISSING_CONFIG are card/account configuration issues, not something biometric setup fixes.":"Biometric attestation is NOT required for payments. Payments will proceed without biometric confirmation.";return{required:n,hasAttestationKey:!!t.hasAttestationKey,hasTelegramAttestationKey:!!t.hasTelegramAttestationKey,hasAnyAttestationKey:r,touchIdAvailable:s,platform:process.platform,effectiveRequiredOnThisDevice:n&&r&&s,canDisableFromThisDevice:!n||!r||s,message:o}}async function sg(e){m.info("biometric:on");let t=await I.setBiometricPreference({required:!0},e);return t.success?(il(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:t.error||"unknown error"}}async function og(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return Qt("MISSING_CONFIRMATION","Please confirm by setting confirm: true. Disabling Touch ID is a security downgrade \u2014 the user will be prompted for one final Touch ID confirmation before the change takes effect.");m.info("biometric:off");try{return await be(async()=>{let n=await I.getStatus(t),r;if(is(n)&&(r=await He("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${ts()} confirmation required to disable \u2014 not available on this device.`);let s=await I.setBiometricPreference({required:!1,attestation:r},t);if(!s.success)throw new Error(s.error||"unknown error");return il(),{success:!0,required:!1,message:"Touch ID is no longer required for payments."}})}catch(n){if(m.error("biometric:off:failure",{error:n.message}),n instanceof wt)return os(n,"biometric_off");throw n}}var Jc=3e4,ig=3e5;async function cl(e,t,n="login"){let r=ce.randomUUID(),s=`${e}${e.includes("?")?"&":"?"}state=${r}`;return Fe(s),ll(r,t,n)}async function ll(e,t,n="login"){let r=Date.now()+ig;for(;Date.now()<r;)try{let o=await fetch(`${ss()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:Jc,...t&&{user_context:t}}),signal:AbortSignal.timeout(Jc+5e3)});if(!o.ok){await ut(o,a=>{m.warn("auth_status:retry_after_http_error",{status:o.status,delayMs:a})});continue}let i=await o.json();if(i.status==="pending")continue;if(i.status==="expired")return{success:!1,message:"Session expired. Please try again."};if(i.status==="error")return{success:!1,message:i.error||"Authentication failed. Please try again."};if(i.status==="complete"){if(n==="attestation-recovery"||i.attestationCleared)return m.info("auth:attestation_recovery_complete",{user:i.user||""}),{success:!0,message:"Server-side biometric state cleared. Run visa-cli setup to register a fresh key before reenabling Touch ID."};let a=i.welcomeBonusCents??0,l=vc(a);if(i.sessionToken){await U.saveSessionToken(i.sessionToken);let u=i.user||"",d=i.last4||"****";return m.info("auth:login_complete",{user:u,last4:d,bonusCents:a}),{success:!0,message:`Signed in as ${u}. Card ending in ${d} enrolled and ready for payments.`,...l||{}}}let c=i.last4||"****";return m.info("auth:card_added",{last4:c,bonusCents:a}),{success:!0,message:`Card ending in ${c} enrolled and ready for payments.`,...l||{}}}}catch{await ut(void 0,o=>{m.warn("auth_status:retry_after_network_error",{delayMs:o})})}return{success:!1,message:n==="enrollment"?"Card enrollment timed out. Please try again.":n==="attestation-recovery"?"Biometric reset timed out. Please try reset again.":"Login timed out. Please try again."}}async function ul(e){let t=ce.randomUUID(),n;try{n=await I.startAttestationRecovery(t,e)}catch(r){return{success:!1,message:`Could not start biometric reset: ${r?.message||"unknown error"}`}}return!n.success||!n.recoveryUrl?{success:!1,message:n.error||"Could not start biometric reset. Please try again."}:(Fe(n.recoveryUrl),ll(t,e,"attestation-recovery"))}async function ag(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to remove this card."};let n=e.cardId;if(!Number.isInteger(n)||n<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to get the opaque cardId for the card you want to remove."};m.info("cards:remove_attempt",{cardId:n});let r=`remove-card:${n}`,s=`remove ${await al(n,t)}`;try{return await be(async()=>{let o=await He(r,0,"",s,t,{forceRequired:!0}),i=await I.removeCard(n,{attestation:o},t);return m.info("cards:remove_success",{cardId:n,promotedId:i?.promotedId??null}),i})}catch(o){if(m.error("cards:remove_failure",{cardId:n,error:o.message}),o instanceof wt)return os(o,"remove_card");throw o}}async function cg(e,t){let n=e.cardId;if(!Number.isInteger(n)||n<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to get the opaque cardId for the card you want to make default."};m.info("cards:set_default_attempt",{cardId:n});let r=`set-default-card:${n}`,s=`set ${await al(n,t)} as default`;try{return await be(async()=>{let o=await He(r,0,"",s,t,{forceRequired:!0}),i=await I.setDefaultCard(n,{attestation:o},t);return m.info("cards:set_default_success",{cardId:n}),i})}catch(o){if(m.error("cards:set_default_failure",{cardId:n,error:o.message}),o instanceof wt)return os(o,"set_default_card");throw o}}async function lg(e){return m.info("auth:login_attempt"),cl(`${ss()}/login`,e)}function ug(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 dg(e={},t){let n;try{n=ug(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return rs(async()=>{let r=await Mc(I,He,{toolName:"start_session",userContext:t,capCentsOverride:n});m.info("session:started",{budgetId:r.budgetId,totalCents:r.totalCents,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious});let s=(r.appliedCapCents/100).toFixed(2),o=(r.requestedCapCents/100).toFixed(2),i=`Session started with a $${s} cap. Paid calls will use this approval window until you close it, it expires, or this MCP process restarts.`,a=r.clampedReason==="balance"?`${i} Note: requested cap of $${o} was clamped to your prepaid balance of $${s}. Run buy_credits to top up if you need a larger session.`:i;return{success:!0,budgetId:r.budgetId,totalCents:r.totalCents,amountUsd:r.totalCents/100,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious,message:a}})}async function mg(){let e=St();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 pg(){return rs(async()=>{let e=St();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 Yr(I);m.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=lf(e),r=qe(t.finalCumulativeMicros),s=r??(typeof t.finalCumulativeCents=="number"?BigInt(Math.max(0,t.finalCumulativeCents))*10000n:n.micros),o=Number(s/10000n);return m.info("session:closed:final-spend",{budgetId:t.budgetId,closedServerSide:t.closedServerSide,finalSpendMicros:s.toString(),finalSpendCents:o,finalSpendSource:r!==null?"server.finalCumulativeMicros":typeof t.finalCumulativeCents=="number"?"server.finalCumulativeCents":n.source,totalCents:e.totalCents}),{success:!0,closed:!0,closedServerSide:t.closedServerSide,budgetId:t.budgetId,finalEstimatedCumulativeCents:o,finalEstimatedCumulativeMicros:s.toString(),totalCents:e.totalCents,message:t.closedServerSide?`Explicit approval window closed. Spent ${cf(s)} of $${(e.totalCents/100).toFixed(2)} cap. Future paid calls are pay-as-you-go until you start a new explicit approval window.`:"Explicit approval window cleared locally; server-side close call did not succeed (likely already closed). Future paid calls are pay-as-you-go until you start a new explicit approval window."}})}async function fg(e){if(m.info("auth:add_card_attempt"),!await U.getSessionToken())return{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."};let{code:n}=await I.createEnrollCode();return cl(`${ss()}/enroll-card?code=${encodeURIComponent(n)}`,e,"enrollment")}async function gg(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};m.info("reset:attempt");let n=!1;try{let r=await I.getStatus(t);if(r&&is(r)){let s=await ul(t);if(!s.success)return s;n=!0}}catch(r){let s=r?.message||"unknown error";if(!/not logged in|session.*expired|no local credentials/i.test(s))return{success:!1,message:`Could not check server biometric state: ${s}`};m.warn("reset:server_attestation_status_unavailable",{error:s})}try{await I.logout(void 0,t)}catch{}if(await U.clearAll(),te())try{await Vr()}catch{}return m.info("reset:success"),{success:!0,message:n?"Device reset. Server-side biometric state and local credentials have been cleared. Use the login tool or visa-cli setup to re-enroll.":"Device reset. Local credentials and keys have been removed. Use the login tool or visa-cli setup to re-enroll."}}async function hg(e){let t=e.query?.trim()||void 0,n=e.category?.trim()||void 0,r=!t&&!n;m.info("catalog:discover",{query:t,category:n,browseAll:r});try{let o=(await I.catalogSearch(t,n)).tools||[];if(o.length===0)return{content:[{type:"text",text:r?"The tool catalog is currently empty.":`No tools found for "${t||n}". Try a different search term.`}]};if(r){let a={};for(let c of o){let u=c.category||"other";(a[u]??=[]).push(c)}let l=Object.keys(a).sort().map(c=>{let u=a[c].map((f,g)=>`${g+1}. **${f.name}** (${f.id})
84
+ `);return`${e}${i}`}function Ju(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 Ds(e,t){try{let n=H.dirname(mt());j.mkdirSync(n,{recursive:!0});let r=e.split(`
85
+ `).map(o=>We(o)).filter(o=>o.length>0).join(`
86
+ `),s={hudVersion:Ou,renderedAt:Date.now(),line:r,cwd:process.cwd(),status:t};cn(mt(),JSON.stringify(s)+`
87
+ `),cn(vr(),r+`
88
+ `)}catch{}}function Ui(e){try{let t=Nn();if(!t)return;let n=Math.max(Date.now(),t.renderedAt+1),r={...t,refreshFailedAt:n,refreshErrorReason:We(e).slice(0,200)};cn(mt(),JSON.stringify(r)+`
89
+ `)}catch{}}function ji(){try{let e=Nn();if(!e)return;let t={...e,renderedAt:0};cn(mt(),JSON.stringify(t)+`
90
+ `)}catch{}}function Pn(){try{j.unlinkSync(Oi())}catch{}}function Nn(){let e=mt();if(!j.existsSync(e))return null;try{let t=JSON.parse(j.readFileSync(e,"utf-8"));return typeof t?.line=="string"&&Vi(t.line)?null:t}catch{return null}}function Vi(e){let t=(e.split(`
91
+ `)[0]??"").trim();if(t.length===0)return!1;let n=t.replace(/\[[0-?]*[ -/]*[@-~]/g,"").trim();return!!(/^VISA\s*\|\s*loading\b/i.test(n)||/^VISA\s*\|\s*HUD\s+not\s+(ready|initialized)\b/i.test(n))}function qi(){return Nn()?.status??null}function Yu(){if(process.env.JEST_WORKER_ID)return;let e=Oi();try{if(j.mkdirSync(H.dirname(e),{recursive:!0}),!nd(e))return;let t=process.argv[1]?H.resolve(process.argv[1]):"";if(!t){Pn();return}let n=(0,Pi.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});n.once("error",Pn),n.unref()}catch{Pn()}}function We(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim()}function Zu(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${B(r||"",V.green)}${B(s||"",V.dim)}`}function on(e){return`$${e.toFixed(2)}`}function Xu(e){let t=e.cards?.find(a=>a.isDefault)??e.cards?.[0];if(!t)return"card none";let n=typeof t.brand=="string"?t.brand:"card",r=typeof t.last4=="string"?t.last4:"????",s=We(n.toUpperCase()),o=We(r);return`${t.isDefault?"default":"active"} ${s} ****${o}`}function Qu(){let e=(process.env.COLORTERM??"").toLowerCase();if(e==="truecolor"||e==="24bit")return!0;let t=(process.env.TERM??"").toLowerCase();return t.includes("truecolor")||t.includes("24bit")}var Ps=Qu(),V={reset:"\x1B[0m",visaBlue:Ps?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:Ps?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:Ps?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function B(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${V.reset}`}function $i(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Us(){let e=Rt.homedir();if(!e||!H.isAbsolute(e))throw new Error("unable to determine a valid home directory");return H.resolve(e)}function ed(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function td(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function nd(e){for(let t=0;t<2;t+=1){let n;try{return n=j.openSync(e,"wx"),j.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=j.statSync(e);if(Date.now()-s.mtimeMs<=ju)return!1;j.unlinkSync(e)}catch{}}finally{n!==void 0&&j.closeSync(n)}}return!1}function Ms(e){return e instanceof Error?e.message:"unknown file system error"}function cn(e,t){j.mkdirSync(H.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;j.writeFileSync(n,t),j.renameSync(n,e)}function Gi(e,t){de.mkdirSync(he.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Bi.randomBytes(8).toString("hex")}.tmp`;try{de.writeFileSync(n,JSON.stringify(t,null,2)+`
92
+ `),de.renameSync(n,e)}catch(r){try{de.unlinkSync(n)}catch{}throw r}}function Fi(e){return`'${e.replace(/'/g,"'\\''")}'`}var Vs="# visa-cli-hud-v1";function rd(e,t){if(!e&&!t&&sd())return`visa-cli config statusline ${Vs}`;let n=e??process.execPath,r=t??process.argv[1]??"",s=r?he.resolve(r):"";return`${s?`${Fi(n)} ${Fi(s)} config statusline`:"visa-cli config statusline"} ${Vs}`}function sd(){try{return(0,Hi.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function It(e){return typeof e!="string"?!1:e.includes(Vs)?!0:e.includes("visa-cli")&&e.includes("statusline")}function od(e){let t=he.dirname(he.resolve(e));return he.basename(t)===".claude"?he.dirname(t):Ki.homedir()}function id(e,t){let n=he.relative(t,e);return!n.startsWith("..")&&!he.isAbsolute(n)?`~/${n}`:e}function js(e,t){let n=od(t),r=On(n);if(r.length===0)return e;let s=r.map(o=>id(o,n)).join(", ");return`${e}
93
+ Note: a legacy shell-prompt HUD block was detected in ${s}. Remove it with: visa-cli config hud disable shell`}function Ln(e,t=rd){let n={},r=!1;if(de.existsSync(e)){r=!0;try{n=JSON.parse(de.readFileSync(e,"utf-8"))}catch(s){return{installed:"malformed-json",message:`~/.claude/settings.json is not valid JSON (${s.message}). Fix the file manually, then run: visa-cli config hud enable claude`}}}if(n.statusLine){let s=typeof n.statusLine=="object"?n.statusLine.command:"";return It(s)?{installed:"already-visa",message:js("Visa HUD already registered in ~/.claude/settings.json.",e)}:{installed:"other-hud-present",message:js("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()},Gi(e,n),{installed:"new",message:js(`Visa HUD registered in ~/.claude/settings.json${r?"":" (new file)"}. Restart Claude Code to see it pinned below the input.`,e)}}catch(s){return{installed:"error",message:`Failed to write settings: ${s.message}. Enable manually later with: visa-cli config hud enable claude`}}}function qs(e){if(!de.existsSync(e))return{removed:!1,message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(de.readFileSync(e,"utf-8"))}catch(r){return{removed:!1,message:`~/.claude/settings.json is not valid JSON: ${r.message}`}}if(!t.statusLine)return{removed:!1,message:"No statusLine configured."};let n=typeof t.statusLine=="object"?t.statusLine.command:"";return It(n)?(delete t.statusLine,Gi(e,t),{removed:!0,message:"Visa HUD removed from ~/.claude/settings.json. Restart Claude Code to take effect."}):{removed:!1,message:"statusLine is owned by another tool \u2014 leaving it alone."}}var Je=R(require("fs")),Oe=R(require("path")),ad=1,$t={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},cd=["terminal","claude","claude-code","all"];function kr(e){let t=e.toLowerCase();return cd.includes(t)?t:null}var ld=50,ud=64*1024,zi=10,Fs=80;function dd(){let e=(process.env.COLORTERM??"").toLowerCase();if(e==="truecolor"||e==="24bit")return!0;let t=(process.env.TERM??"").toLowerCase();return t.includes("truecolor")||t.includes("24bit")}var Bs=dd(),S={reset:"\x1B[0m",visaBlue:Bs?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:Bs?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:Bs?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function x(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${S.reset}`}function Wi(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function Xi(e=process.stdin){return e.isTTY?null:new Promise(t=>{let n=[],r=!1,s=()=>{e.removeListener("data",i),e.removeListener("end",a),e.removeListener("error",l),clearTimeout(c)},o=u=>{r||(r=!0,s(),t(u))},i=u=>{n.push(typeof u=="string"?Buffer.from(u):u)},a=()=>{let u=Buffer.concat(n).toString("utf-8").trim();if(!u)return o(null);try{let d=JSON.parse(u);o(d&&typeof d=="object"?d:null)}catch{o(null)}},l=()=>o(null),c=setTimeout(()=>{n.length>0?a():o(null)},ld);e.on("data",i),e.on("end",a),e.on("error",l)})}function Dn(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${x(r||"",S.visaBlueSoft)}${x(s||"",S.dim)}`}function Un(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 md(e){if(ca(e))return fd(e);let t=` ${x("\u2502",S.dim)} `,n=Cr(e)||"claude",r=e.cwd?Y(Oe.basename(e.cwd)):"",s=Tr(e.workspace),o=r||s,i=s&&s!==o?` ${x(`@${s}`,S.visaBlueSoft)}`:"",a=[x(`[${n}]`,S.visaBlueSoft)];o&&a.push(`${x(o,S.visaGold)}${i}`);let l=Y(e.git_branch??e.branch??"");l&&a.push(`${x("git:(",S.dim)}${x(l,S.visaBlueSoft)}${x(")",S.dim)}`);let c=a.join(t),u=Number(e.context_window?.context_window_size??0),d=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,f=e.context_window?.current_usage,g=[f?.input_tokens,f?.output_tokens,f?.cache_creation_input_tokens,f?.cache_read_input_tokens].filter(z=>typeof z=="number"&&Number.isFinite(z)),w=g.length>0?g.reduce((z,F)=>z+F,0):null,y=Number(e.context_window?.total_input_tokens??w??f?.input_tokens??0),k=d!==null?Math.max(0,Math.min(1,d/100)):u>0?Math.max(0,Math.min(1,y/u)):0,O=d!==null&&u>0?Math.round(k*u):y,N;if(u>0||d!==null){let z=`${String(Math.round(k*100)).padStart(2," ")}%`,F=u>0?` ${x(`(${Un(O)}/${Un(u)})`,S.dim)}`:"";N=`${x("Context",S.dim)} ${Dn(k)} ${x(z,S.green)}${F}`}else N=`${x("Context",S.dim)} ${x("-",S.dim)}`;let C=Qi(e.rate_limits),T=[N];C&&T.push(C);let q=T.join(t);return`${c}
94
+ ${q}`}function pd(e){if(ca(e))return null;let t=` ${x("\u2502",S.dim)} `,n=Cr(e)||"claude",r=e.cwd?Y(Oe.basename(e.cwd)):"",s=Tr(e.workspace),o=r||s,i=s&&s!==o?` ${x(`@${s}`,S.visaBlueSoft)}`:"",a=[x(`[${n}]`,S.visaBlueSoft)];o&&a.push(`${x(o,S.visaGold)}${i}`);let l=Y(e.git_branch??e.branch??"");l&&a.push(`${x("git:(",S.dim)}${x(l,S.visaBlueSoft)}${x(")",S.dim)}`);let c=Number(e.context_window?.context_window_size??0),u=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,d=e.context_window?.current_usage,f=[d?.input_tokens,d?.output_tokens,d?.cache_creation_input_tokens,d?.cache_read_input_tokens].filter(T=>typeof T=="number"&&Number.isFinite(T)),g=f.length>0?f.reduce((T,q)=>T+q,0):null,w=Number(e.context_window?.total_input_tokens??g??d?.input_tokens??0),y=u!==null?Math.max(0,Math.min(1,u/100)):c>0?Math.max(0,Math.min(1,w/c)):0,k=u!==null&&c>0?Math.round(y*c):w,O;if(c>0||u!==null){let T=`${String(Math.round(y*100)).padStart(2," ")}%`,q=c>0?` ${x(`(${Un(k)}/${Un(c)})`,S.dim)}`:"";O=`${x("Context",S.dim)} ${Dn(y)} ${x(T,S.green)}${q}`}else O=`${x("Context",S.dim)} ${x("-",S.dim)}`;let N=Qi(e.rate_limits),C=[O];return N&&C.push(N),{identity:a.join(t),metrics:C.join(t)}}function fd(e){let t=` ${x("\u2502",S.dim)} `,n=la(e),r=n.model||"codex",s=[x(`[${r}]`,S.visaBlueSoft)];n.project&&s.push(x(n.project,S.visaGold)),n.gitBranch&&s.push(`${x("git",S.dim)} ${x(n.gitBranch,S.visaGold)}`);let o=s.join(t),i=[];if(typeof n.contextUsedPercent=="number"){let l=Math.max(0,Math.min(1,n.contextUsedPercent/100));i.push(`${x("Context",S.dim)} ${Dn(l)} ${x(`${Math.round(n.contextUsedPercent)}%`,S.green)}`)}else if(typeof n.contextRemainingPercent=="number"){let l=100-n.contextRemainingPercent,c=Math.max(0,Math.min(1,l/100));i.push(`${x("Context",S.dim)} ${Dn(c)} ${x(`${Math.round(l)}%`,S.green)}`)}typeof n.usedTokens=="number"&&i.push(`${x("Tokens",S.dim)} ${Un(n.usedTokens)}`),n.status&&i.push(`${x("Status",S.dim)} ${x(n.status,S.visaBlueSoft)}`),n.threadTitle&&i.push(`${x("Thread",S.dim)} ${x(n.threadTitle,S.visaBlueSoft)}`);let a=i.length>0?i.join(t):`${x("Context",S.dim)} ${x("-",S.dim)}`;return`${o}
95
+ ${a}`}function gd(e){if(typeof e!="number"||e<=0)return"";let n=(e>1e12?e:e*1e3)-Date.now();if(n<=0||n>=10080*60*1e3)return"";let r=Math.floor(n/6e4),s=Math.floor(r/60),o=r%60;return s>0?`${s}h ${o}m`:`${o}m`}function Ji(e,t){if(!e||typeof e.used_percentage!="number")return null;let n=Math.max(0,Math.min(100,e.used_percentage)),r=n/100,s=Dn(r),o=n>=90?"\x1B[38;5;196m":n>=70?S.visaGold:S.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=gd(e.resets_at),l=a?` ${x(`(${a} / ${t})`,S.dim)}`:` ${x(`(${t})`,S.dim)}`;return`${s} ${x(i,o)}${l}`}function Qi(e){if(!e)return null;let t=Ji(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?Ji(e.seven_day,"7d"):null;if(!t&&!r)return null;let s=` ${x("\u2502",S.dim)} `,o=[t,r].filter(Boolean);return`${x("Usage",S.dim)} ${o.join(s)}`}function ea(e){let t;try{let n=Je.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let s=Math.min(r,ud),o=r-s;t=Je.openSync(e,"r");let i=Buffer.alloc(s);Je.readSync(t,i,0,s,o);let a=i.toString("utf-8");if(o>0){let l=Buffer.alloc(1);if(Je.readSync(t,l,0,1,o-1),l[0]!==10){let c=a.indexOf(`
96
+ `);c>=0&&(a=a.slice(c+1))}}return a}catch{return null}finally{if(t!==void 0)try{Je.closeSync(t)}catch{}}}function hd(e){if(!e||typeof e!="object")return;let t=e,n=["file_path","path","notebook_path","pattern","command","url"];for(let r of n){let s=t[r];if(typeof s=="string"&&s.length>0){if(r.endsWith("_path")||r==="path"){let o=Oe.basename(Oe.dirname(s)),i=Oe.basename(s);return o&&o!=="."&&o!=="/"?`${o}/${i}`:i}return s}}}function yd(e){let t=e.split(`
97
+ `),n=[],r=new Set;for(let s=t.length-1;s>=0&&n.length<zi*3;s-=1){let o=t[s].trim();if(!o)continue;let i;try{i=JSON.parse(o)}catch{continue}if(!i||typeof i!="object")continue;let l=i.message;if(!l||typeof l!="object")continue;let c=l.content;if(Array.isArray(c))for(let u of c){if(!u||typeof u!="object")continue;let 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:"",g=f.length>0?!r.has(f):!1;n.push({name:d.name,target:hd(d.input),running:g})}}}return n.reverse(),n.slice(Math.max(0,n.length-zi))}function _d(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 vd(e){let t=e.running?x("\u25D0",S.visaGold):x("\u2713",S.green),n=e.running?S.visaGold:S.visaBlueSoft,r=x(Y(e.name),n),s=e.target?Y(e.target):"",o=s?`${x(":",S.dim)} ${x(s,S.dim)}`:"",i=e.count>1?` ${x(`\xD7${e.count}`,S.dim)}`:"";return o?`${t} ${r}${o}${i}`:`${t} ${r}${i}`}function bd(e){let t=` ${x("\u2502",S.dim)} `,n=Wi(t),r=e.slice();for(;r.length>0;){let l=r.join(t);if(Wi(l)<=Fs)return l;r=r.slice(1)}if(e.length===0)return"";let s="\u2026",i=e[e.length-1].replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,""),a=i.length>Fs-n-1?i.slice(0,Fs-n-1)+s:i;return`${x(s,S.dim)}${t}${a}`}async function Yi(e){if(!e||typeof e!="string")return null;let t=ea(e);if(!t)return null;let n;try{n=yd(t)}catch{return null}if(n.length===0)return null;let s=_d(n).map(vd);return bd(s)||null}async function ta(e,t,n){return(await ra(e,t,n)).join(`
98
+ `)}function na(e,t,n){let r=!!t?.activeSession||e.includes("in session"),s=n?wd(n):!1;return{isActive:r||s,hasSession:r,hasToolActivity:s}}async function ra(e,t,n){let{isActive:r}=na(e,n,t?.transcript_path),s=e.split(`
99
+ `).filter(a=>a.length>0),i=t&&!r?s.map(a=>x(Hs(a),S.dim)):[...s];if(t){let a=pd(t);if(a){if(i.push(a.identity),t.transcript_path){let l=await Yi(t.transcript_path);l&&i.push(...l.split(`
100
+ `))}i.push(a.metrics)}else{let l=md(t);if(l&&i.push(...l.split(`
101
+ `)),t.transcript_path){let c=await Yi(t.transcript_path);c&&i.push(...c.split(`
102
+ `))}}}return i}var Sd=["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 wd(e){let t=ea(e);if(!t)return!1;let n=t.slice(-16384).toLowerCase();return Sd.some(r=>n.includes(`"${r}"`))}async function sa(e,t,n){let r=await ra(e,t,n),s=r.join(`
103
+ `),{isActive:o}=na(e,n,t?.transcript_path);return{schemaVersion:ad,client:t?aa(t):$t.UNKNOWN,rendered:s,lines:r.map(Hs),visa:{spendLine:Hs(e),balanceCents:n?.balanceCents,balanceUsd:n?.amountUsd,sessionMode:n?.sessionMode,activeSession:n?.activeSession,isVisaActive:o},context:t?la(t):{}}}function Y(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 Tr(e){if(typeof e=="string")return Y(Oe.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 Y(t?Oe.basename(t):e.name)}function oa(e){return Y(e.app_name??e.appName??e.app??e.client)}function Cr(e){return Y(e.model?.display_name??e.model?.id??e.model_name??e.modelName)}function ia(e){return Y(e.cwd??e.current_dir??e.project_root)}function Zi(e){let t=Y(e.project);if(t)return t;let n=ia(e);if(n)return Y(Oe.basename(n));let r=Tr(e.workspace);return r||""}function Te(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function aa(e){let t=oa(e).toLowerCase();return t.includes("codex")?$t.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?$t.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||Te(e.context_used)!==void 0?$t.CODEX:$t.UNKNOWN}function ca(e){return aa(e)===$t.CODEX}function la(e){let t=oa(e),n=ia(e),r=Tr(e.workspace),s=Te(e.context_used)??Te(e.context_window?.used_percentage??void 0),o=Te(e.context_remaining)??Te(e.context_window?.remaining_percentage??void 0);return{...t?{app:t}:{},...Cr(e)?{model:Cr(e)}:{},...Zi(e)?{project:Zi(e)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...Y(e.git_branch??e.branch)?{gitBranch:Y(e.git_branch??e.branch)}:{},...Y(e.status??e.run_state??e.runState)?{status:Y(e.status??e.run_state??e.runState)}:{},...Y(e.thread_title??e.threadTitle)?{threadTitle:Y(e.thread_title??e.threadTitle)}:{},...s!==void 0?{contextUsedPercent:s}:{},...o!==void 0?{contextRemainingPercent:o}:{},...Te(e.used_tokens)!==void 0?{usedTokens:Te(e.used_tokens)}:{},...Te(e.total_input_tokens)!==void 0?{totalInputTokens:Te(e.total_input_tokens)}:{},...Te(e.total_output_tokens)!==void 0?{totalOutputTokens:Te(e.total_output_tokens)}:{}}}function Hs(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}var da=R(require("path"));function ua(e){return e instanceof Error?e.message:String(e)}function Ks(e,t){let n=[],r=[],s=e??"claude",o=kr(s);if(s==="shell"||s==="prompt")try{let a=t.installShellHud();return a.installed?{ok:!0,messages:[a.message],errors:r}:{ok:!1,messages:n,errors:[a.message]}}catch(a){return{ok:!1,messages:n,errors:[`Failed to install shell HUD: ${ua(a)}`]}}if(!o)return{ok:!1,messages:n,errors:[`Unknown HUD surface: ${s}`,"Supported: claude (default), shell, all"]};let i=!0;if(o==="claude"||o==="claude-code"||o==="all"){let a=da.join(t.homeDir,".claude","settings.json");try{let l=t.installVisaStatusLine(a);n.push(l.message),(l.installed==="error"||l.installed==="malformed-json")&&(i=!1)}catch(l){i=!1,r.push(`Failed to install Claude HUD: ${ua(l)}`)}}return{ok:i,messages:n,errors:r}}function ma(e){if(!e||typeof e!="object")return"";let t=e;return Array.isArray(t.enum)&&t.enum.length>0?"enum":typeof t.type=="string"?t.type:Array.isArray(t.type)?t.type.filter(n=>typeof n=="string").join("|"):""}async function Pt(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,s=setTimeout(()=>r.abort(),n);try{let{timeoutMs:o,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(s)}}var Mt=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},un=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}},Ot=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}},oe=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(t,n,r,s,o,i,a,l){super(t),this.name="CardDeclinedError",this.retryable=n,this.code=r,this.reason=s,this.paymentErrorClass=o,this.correlationId=i,this.transactionId=a,this.retryAfter=l}};var pa={ENOTFOUND:"Cannot resolve the Visa CLI server hostname (DNS error). Check your internet connection or the auth.serverUrl setting.",EAI_AGAIN:"DNS lookup for the Visa CLI server failed temporarily. Check your internet connection and try again.",ECONNREFUSED:"The Visa CLI server refused the connection. The service may be down \u2014 check https://visacli.sh for status.",ECONNRESET:"The connection to the Visa CLI server was reset mid-request. Try again in a moment.",EHOSTUNREACH:"The Visa CLI server is unreachable from this network. Check your internet connection.",ETIMEDOUT:"The connection to the Visa CLI server timed out. Try again or check https://visacli.sh for status.",CERT_HAS_EXPIRED:"The Visa CLI server's TLS certificate is expired. Check https://visacli.sh for status; do not bypass the cert.",UND_ERR_CONNECT_TIMEOUT:"The connection to the Visa CLI server timed out before it could be established. Try again in a moment.",UND_ERR_SOCKET:"The connection to the Visa CLI server was interrupted. Try again in a moment."};function Gs(e){let t=e&&typeof e=="object"?e:{};if(t.name==="AbortError"||typeof t.message=="string"&&t.message.includes("aborted"))return"The request timed out. The server may be under heavy load. Please try again.";let n=(t.cause&&typeof t.cause=="object"?t.cause.code:void 0)??(typeof t.code=="string"?t.code:void 0);return n&&pa[n]?pa[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 xd=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function ga(e,t){let n=fa(e),r=fa(t);if(!n||!r)return!1;for(let s=0;s<3;s++)if(n.main[s]!==r.main[s])return n.main[s]>r.main[s];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:Cd(n.pre,r.pre)>0}function fa(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(xd);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function Cd(e,t){let n=e.split("."),r=t.split("."),s=Math.max(n.length,r.length);for(let o=0;o<s;o++){if(o>=n.length)return-1;if(o>=r.length)return 1;let i=n[o],a=r[o],l=/^\d+$/.test(i),c=/^\d+$/.test(a);if(l&&c){let u=Number(i)-Number(a);if(u!==0)return u}else{if(l)return-1;if(c)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function Ne(){return!!(ha(process.env.VISA_CLI_NO_UPDATE_CHECK)||ha(process.env.CI)||process.env.NODE_ENV==="test")}function ha(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var ft=R(require("fs")),Qs=require("node:net"),Sa=R(require("os")),wa=R(require("path"));var Er=R(require("fs")),ya=R(require("path")),_a=R(require("os"));var zs=ya.join(_a.homedir(),".visa-mcp"),jn=class{static ensureConfigDir(){Er.existsSync(zs)||Er.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}};var me=R(require("fs")),Ys=R(require("path")),va=R(require("os")),Js=Ys.join(va.homedir(),".visa-mcp"),Vn=Ys.join(Js,"mcp-server.log"),kd=5*1024*1024,Ws=null;function Td(){me.existsSync(Js)||me.mkdirSync(Js,{recursive:!0,mode:448})}function Ed(){if(!Ws){if(Td(),me.existsSync(Vn)&&me.statSync(Vn).size>kd){let t=Vn+".1";me.existsSync(t)&&me.unlinkSync(t),me.renameSync(Vn,t)}Ws=me.createWriteStream(Vn,{flags:"a"})}return Ws}function Ad(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function Ar(e,...t){let n=new Date().toISOString(),r=t.map(o=>typeof o=="string"?o:JSON.stringify(o,null,2)).join(" "),s=`[${n}] [${e}] ${r}
104
+ `;Ad(e)&&process.stderr.write(s),Ed().write(s)}var m={debug:(...e)=>Ar("DEBUG",...e),info:(...e)=>Ar("INFO",...e),warn:(...e)=>Ar("WARN",...e),error:(...e)=>Ar("ERROR",...e)};function ba(e){let t=Sa.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}var Rd="settings.json",Id="must use https unless it points at localhost/loopback for local development";function qn(){return wa.join(jn.getConfigDir(),Rd)}function xa(e){if((0,Qs.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function $d(e){let t=e.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!t)return!1;let n=Number.parseInt(t[1],16),r=Number.parseInt(t[2],16);if(!Number.isFinite(n)||!Number.isFinite(r))return!1;let s=[n>>8&255,n&255,r>>8&255,r&255].join(".");return xa(s)}function Pd(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,Qs.isIP)(t);return n===4?xa(t):n===6?t==="::1"||$d(t):!1}function Zs(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:"&&Pd(n.hostname)))throw new Error(`${t} ${Id}`)}var gt={"auth.serverUrl":{type:"string",description:"Auth server base URL. Override for staging / self-hosted backends.",requiresRestart:!0,validate:e=>{if(typeof e!="string")throw new Error("auth.serverUrl must be a string");Zs(e)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."},"ui.suppressFeed":{type:"boolean",description:"When true, generated images/music are not auto-submitted to the public Made-with-Visa feed."},"tools.meta":{type:"boolean",description:"Show category meta-tools (generate_image, generate_video, generate_music, run_llm, ...). Restart required.",requiresRestart:!0},"tools.discover":{type:"boolean",description:"Show the dynamic-catalog tools (discover_tools, execute_tool). Restart required.",requiresRestart:!0},"merchants.discover":{type:"string",description:'Platform-merchant JIT tool discovery: "all" = every live merchant, "off" = none, comma-separated slugs = exactly those. Equivalent to VISA_MERCHANT_DISCOVER / VISA_MERCHANT_SLUGS env. Restart required.',requiresRestart:!0,validate:e=>{if(typeof e!="string")throw new Error("merchants.discover must be a string");let t=e.trim().toLowerCase();if(t===""||t==="all"||t==="off"||t==="*")return;let n=/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/,r=e.split(",").map(s=>s.trim()).filter(Boolean);for(let s of r)if(!n.test(s))throw new Error(`merchants.discover: "${s}" is not a valid merchant slug`)}},"credit.sessionCapCents":{type:"number",description:"Default cap (in cents) for start_session and pay-as-you-go one-shot approvals. Server clamps to [10, 10000] = $0.10\u2013$100. Default 500 ($5).",validate:e=>{if(typeof e!="number"||!Number.isFinite(e))throw new Error("credit.sessionCapCents must be a number");if(!Number.isInteger(e))throw new Error("credit.sessionCapCents must be a whole number of cents (no fractional cents)");if(e<10||e>1e4)throw new Error("credit.sessionCapCents must be between 10 ($0.10) and 10000 ($100)")}}},eo=500,Rr={"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 Nt(){let e=qn();if(!ft.existsSync(e))return{};try{let t=ft.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?(m.warn("settings:corrupt",{path:ba(e),reason:"not_object"}),{}):n}catch(t){return m.warn("settings:corrupt",{path:ba(e),error:t?.message||String(t)}),{}}}function Xs(e){jn.ensureConfigDir();let t=qn(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
105
+ `;ft.writeFileSync(n,r,{mode:384}),ft.renameSync(n,t)}function to(e){let t=Nt()[e];return typeof t=="string"?t:void 0}function Ir(e){let t=Nt()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function no(e){let t=Nt()[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 Ye=class extends Error{constructor(t){let n=Object.keys(gt).sort().join(", ");super(`Unknown setting "${t}". Settable keys: ${n}. For server-controlled values (biometric.*, spending.*) use the dedicated tools (biometric_on/off, update_spending_controls).`),this.name="UnknownSettingKeyError"}},Ze=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"}},pt=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+Rr[t]),this.name="RetiredSettingKeyError"}},Ca=["biometric.","spending.","account.","cards.","biometric"];function $r(e,t){if(Ca.some(o=>e.startsWith(o)))throw new Ze(e);if(e in Rr)throw new pt(e);let n=gt[e];if(!n)throw new Ye(e);let r;if(n.type==="boolean")if(typeof t=="boolean")r=t;else if(typeof t=="string"){let o=t.toLowerCase();if(o==="true")r=!0;else if(o==="false")r=!1;else throw new Error(`${e} expects true or false (got: ${JSON.stringify(t)})`)}else throw new Error(`${e} expects a boolean (got: ${typeof t})`);else if(n.type==="number")if(typeof t=="number")r=t;else if(typeof t=="string"&&t.trim().length>0){let o=Number(t);if(!Number.isFinite(o))throw new Error(`${e} expects a number (got: ${JSON.stringify(t)})`);r=o}else throw new Error(`${e} expects a number (got: ${typeof t})`);else{if(typeof t!="string"||t.length===0)throw new Error(`${e} expects a non-empty string`);r=t}n.validate&&n.validate(r);let s=Nt();return s[e]=r,Xs(s),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:qn()}}function Pr(e){if(Ca.some(o=>e.startsWith(o)))throw new Ze(e);let t=gt[e];if(e in Rr){let o=Nt(),i=e in o;return i&&(delete o[e],Xs(o)),{key:e,removed:i,requiresRestart:!1,path:qn()}}if(!t)throw new Ye(e);let r=Nt(),s=e in r;return s&&(delete r[e],Xs(r)),{key:e,removed:s,requiresRestart:s&&!!t.requiresRestart,path:qn()}}function ka(){let e=Nt();return Object.entries(Rr).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}var Md="https://auth.visacli.sh",Od="https://auth-visa-code-preview.up.railway.app";function Nd(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function Ld(){try{let e=fr();return Nd(e.version)}catch{return!1}}function Dd(e){return e.envVar!==void 0&&e.envVar!==""?(Zs(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(Zs(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?Od:Md}function we(){return Dd({envVar:process.env.VISA_AUTH_URL,settingValue:to("auth.serverUrl"),isPrerelease:Ld()})}function Ta(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":Ir("ui.suppressBrowser")??!1}function Ea(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":Ir("ui.suppressFeed")??!1}function Aa(){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=no("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):eo}var Ud="CARD_REENROLLMENT_REQUIRED",Ra="https://visacli.sh/enroll-card";function jd(e){if(typeof e!="string")return Ra;try{let t=new URL(e),n=t.hostname==="localhost"||t.hostname==="127.0.0.1";if((t.protocol==="https:"&&(t.hostname==="visacli.sh"||t.hostname.endsWith(".visacli.sh"))||n)&&t.pathname==="/enroll-card")return t.toString()}catch{}return Ra}var Fn="2.1.2",Vd=/^vk_[A-Za-z0-9_-]{32,}$/;function qd(e){if(typeof e!="string")return null;switch(e){case"BUDGET_CLOSED":case"BUDGET_NOT_FOUND":case"BUDGET_EXPIRED":return e;default:return null}}var Fd="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function dn(e){return typeof e=="string"?e.trim():""}function Ia(e){let t=e&&typeof e=="object"?e:{},n=dn(t.error)||dn(t.message);if(!n)return Fd;let r=dn(t.error_code),s=[["surface",dn(t.disabled_surface)],["flag",dn(t.flag)],["correlation_id",dn(t.correlation_id)]].filter(([,i])=>i).map(([i,a])=>`${i}=${a}`),o=s.length?` (${s.join(" ")})`:"";return r?`503 [${r}] ${n}${o}`:`503 ${n}${o}`}function $a(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?Vd.test(r)?(n.push("VISA_CLI_API_KEY is set, but MCP bearer tools currently require a local session from visa-cli setup."),n.push("For headless API-key use, call the /v1/api/* HTTP routes with X-Api-Key instead of MCP bearer tools.")):(n.push("VISA_CLI_API_KEY is set but has invalid format (expected vk_<32+ base64url chars>)."),n.push("Create a new token with: visa-cli tokens create <app-name>")):n.push("Run `visa-cli setup` in an interactive terminal to authenticate."),t===!1&&n.push("This process appears to be running without a TTY; complete setup in a normal terminal, then restart the MCP client."),n.join(`
106
+ `)}var ye=class{constructor(t){this.getSessionToken=t;this.baseUrl=we()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!Ne()){let r=t.headers.get("X-Latest-Version");r&&ga(r,Fn)&&(this.lastSignals.updateAvailable={currentVersion:Fn,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return Fn}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new Mt(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(Ia(n))}async request(t,n,r,s,o,i){let a=await this.getSessionToken();if(!a)throw new Error($a());let l={Authorization:`Bearer ${a}`};o&&(t==="GET"?l["X-User-Context"]=encodeURIComponent(o.replace(/[\r\n\0]/g," ").slice(0,1e3)):r={...r||{},user_context:o}),i&&(l["X-Visa-Meta-Tool"]=i),r&&(l["Content-Type"]="application/json");let c;try{c=await Pt(`${this.baseUrl}${n}`,{method:t,headers:{...l,"X-Visa-CLI-Version":Fn,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:s})}catch(d){throw new Error(Gs(d))}if(this.parseServerSignals(c),c.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(c.status===429){let d=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${d}s. Tip: use the batch tool to combine multiple requests into one.`)}c.status===503&&await this.throwServerUnavailable(c);let u;try{u=await c.json()}catch{throw c.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${n}. Try again.`)}if(!c.ok){if(c.status===500)throw new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(u),typeof u?.error_code=="string"&&u.error_code===Ud){let d=typeof u?.last4=="string"?u.last4:"",f=typeof u?.brand=="string"?u.brand:"card",g=jd(u?.reenroll_url),w=d?`${f} ending in ${d}`:"your card";throw new Error(`Please re-add ${w} to keep payments running. Open: ${g}`)}if(u?.declined){let d=Number(u.retryAfter??c.headers.get("Retry-After"));throw new oe(u.error||"Your card was declined.",!!u.retryable,u.code,u.reason,u.payment_error_class,u.correlation_id,u.transactionId,Number.isFinite(d)&&d>0?d:void 0)}if(c.status===402){let d=u?.error||"Gateway returned 402",f=typeof u?.error_code=="string"?u.error_code:"";throw f==="SPENDING_LIMIT_EXCEEDED"||f==="DAILY_LIMIT_EXCEEDED"||f==="PER_TXN_LIMIT_EXCEEDED"?new Error(`${d}. Check your limits with get_status or run: visa-cli update-spending-controls`):new Error(d)}throw new Error(u?.error||`Request failed (${c.status}). Try again.`)}return u}async shortcut(t,n,r,s,o){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,s,o)}async shortcutWithSession(t,n,r,s,o,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,l=await this.getSessionToken();if(!l)throw new Error($a());let c={Authorization:`Bearer ${l}`,"X-Visa-CLI-Version":Fn,"X-Source":"cli","Content-Type":"application/json"};i&&(c["X-Visa-Meta-Tool"]=i);let u={...n,...r};o&&(u.user_context=o.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await Pt(`${this.baseUrl}${a}`,{method:"POST",headers:c,body:JSON.stringify(u),timeoutMs:s})}catch(w){throw new Error(Gs(w))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let w=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${w}s. Tip: use the batch tool to combine multiple requests into one.`)}let f=d.headers.get("X-Voucher-Receipt"),g;try{g=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(g),d.status===503){if(g?.error_code==="SESSION_LOCK_CONTENDED"){let y=Number(d.headers.get("Retry-After"))||1;throw new Ot(g?.message||g?.error||"Session budget is being modified by another request. Retry shortly.",y,d.status)}throw new Error(Ia(g))}let w=qd(g?.error_code);if(w||d.status===410){let y=w??"BUDGET_CLOSED";throw new un(g?.message||g?.error||"Your session was invalidated by the server.",y,{budgetId:n.session_budget_id,status:d.status})}if(g?.declined){let y=Number(g.retryAfter??d.headers.get("Retry-After"));throw new oe(g.error||"Your card was declined.",!!g.retryable,g.code,g.reason,g.payment_error_class,g.correlation_id,g.transactionId,Number.isFinite(y)&&y>0?y:void 0)}throw new Error(g?.error||`Request failed (${d.status}). Try again.`)}return{data:g,voucherReceiptHeader:f}}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async catalogSearch(t,n,r,s){let o=r??"discover_tools",i=new URLSearchParams;t&&i.set("q",t),n&&i.set("category",n),s?.limit!=null&&i.set("limit",String(s.limit)),s?.offset!=null&&i.set("offset",String(s.offset));let a=i.toString();return this.request("GET",`/v1/catalog${a?`?${a}`:""}`,void 0,void 0,void 0,o)}async catalogTool(t,n){let r=n??"discover_tools";try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(t)}`,void 0,void 0,void 0,r)}catch{return null}}async discoverMerchantRoutes(t){try{return await this.request("GET",`/v1/platform/discover/${encodeURIComponent(t)}`)}catch{return null}}async listPublicMerchants(){try{let t=await Pt(`${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 Pt(`${this.baseUrl}/v1/platform/discover/${encodeURIComponent(t)}`,{method:"GET",timeoutMs:8e3});return n.ok?await n.json():null}catch{return null}}async paymentPreview(t,n){return this.request("POST","/v1/payment-preview",t,void 0,n)}async getBalance(){return this.request("GET","/v1/balance")}async topupBalance(t){return this.request("POST","/v1/balance/topup",t)}async createEnrollCode(){return this.request("POST","/v1/enroll-code")}async getAutoTopup(){let t=await this.getBalance();return{success:t.success,targetCents:t.autoTopupCents??null,thresholdCents:t.autoTopupThresholdCents??0}}async disableAutoTopup(){return this.request("PATCH","/v1/balance/auto-topup",{auto_topup_cents:null})}async createSessionBudget(t){return this.request("POST","/v1/session-budget/create",{...t,mode:"prepaid"})}async closeSession(t){return this.request("POST","/v1/session/close",{session_budget_id:t})}async getSessionBudget(t){return this.request("GET",`/v1/session-budget/${encodeURIComponent(t)}`)}async getSessionLedger(t){return this.request("GET",`/v1/session/${encodeURIComponent(t)}/ledger`)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getVisaSmi(t,n){return this.request("POST","/v1/visa/smi",t,6e4,n)}async getTransactions(t,n){let r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.offset!=null&&r.set("offset",String(t.offset));let s=r.toString(),o=s?`/v1/transactions?${s}`:"/v1/transactions";return this.request("GET",o,void 0,void 0,n)}async updateSpendingControls(t,n){return this.request("POST","/v1/spending-controls",t,void 0,n)}async removeCard(t,n,r){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(t))}`,n,void 0,r)}async setDefaultCard(t,n,r){return this.request("POST",`/v1/cards/${encodeURIComponent(String(t))}/default`,n,void 0,r)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t,n){return this.request("POST","/v1/attestation-key",{publicKey:t,...n?{attestation:n}:{}})}async startAttestationRecovery(t,n){return this.request("POST","/v1/attestation-key/recovery/start",{state:t},void 0,n)}async setBiometricPreference(t,n){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,n)}async logout(t,n){return this.request("POST","/v1/logout",t,void 0,n)}async feedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async createAppApiKey(t){return this.request("POST","/v1/api/keys",t)}async listAppApiKeys(){return this.request("GET","/v1/api/keys")}async revokeAppApiKey(t){return this.request("DELETE",`/v1/api/keys/${encodeURIComponent(String(t))}`)}async feedSubmit(t){return this.request("POST","/v1/feed",t)}async feedList(t){let n=new URLSearchParams;t?.tab&&n.set("tab",t.tab),t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset));let r=n.toString();return this.request("GET",`/v1/feed${r?"?"+r:""}`)}async feedVote(t,n){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/vote`,{direction:n})}async feedApprove(t){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/approve`)}async feedDelete(t){return this.request("DELETE",`/v1/feed/${encodeURIComponent(t)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async getFeedback(t,n){let r=new URLSearchParams;t&&r.set("limit",String(t));let s=r.toString();return this.request("GET",`/v1/feedback${s?"?"+s:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}};var p={};_s(p,{BRAND:()=>fm,DIRTY:()=>Lt,EMPTY_PATH:()=>Gd,INVALID:()=>E,NEVER:()=>Xm,OK:()=>ie,ParseStatus:()=>se,Schema:()=>M,ZodAny:()=>_t,ZodArray:()=>tt,ZodBigInt:()=>Ut,ZodBoolean:()=>jt,ZodBranded:()=>Hn,ZodCatch:()=>Yt,ZodDate:()=>Vt,ZodDefault:()=>Jt,ZodDiscriminatedUnion:()=>Nr,ZodEffects:()=>ke,ZodEnum:()=>zt,ZodError:()=>pe,ZodFirstPartyTypeKind:()=>A,ZodFunction:()=>Dr,ZodIntersection:()=>Ht,ZodIssueCode:()=>h,ZodLazy:()=>Kt,ZodLiteral:()=>Gt,ZodMap:()=>yn,ZodNaN:()=>vn,ZodNativeEnum:()=>Wt,ZodNever:()=>Ee,ZodNull:()=>Ft,ZodNullable:()=>Ue,ZodNumber:()=>Dt,ZodObject:()=>fe,ZodOptional:()=>xe,ZodParsedType:()=>v,ZodPipeline:()=>Kn,ZodPromise:()=>vt,ZodReadonly:()=>Zt,ZodRecord:()=>Lr,ZodSchema:()=>M,ZodSet:()=>_n,ZodString:()=>yt,ZodSymbol:()=>gn,ZodTransformer:()=>ke,ZodTuple:()=>De,ZodType:()=>M,ZodUndefined:()=>qt,ZodUnion:()=>Bt,ZodUnknown:()=>et,ZodVoid:()=>hn,addIssueToContext:()=>_,any:()=>xm,array:()=>Em,bigint:()=>_m,boolean:()=>Fa,coerce:()=>Zm,custom:()=>ja,date:()=>vm,datetimeRegex:()=>Da,defaultErrorMap:()=>Xe,discriminatedUnion:()=>$m,effect:()=>Bm,enum:()=>Vm,function:()=>Dm,getErrorMap:()=>mn,getParsedType:()=>Le,instanceof:()=>hm,intersection:()=>Pm,isAborted:()=>Mr,isAsync:()=>pn,isDirty:()=>Or,isValid:()=>ht,late:()=>gm,lazy:()=>Um,literal:()=>jm,makeIssue:()=>Bn,map:()=>Nm,nan:()=>ym,nativeEnum:()=>qm,never:()=>km,null:()=>wm,nullable:()=>Km,number:()=>qa,object:()=>Am,objectUtil:()=>ro,oboolean:()=>Ym,onumber:()=>Jm,optional:()=>Hm,ostring:()=>Wm,pipeline:()=>zm,preprocess:()=>Gm,promise:()=>Fm,quotelessJson:()=>Bd,record:()=>Om,set:()=>Lm,setErrorMap:()=>Kd,strictObject:()=>Rm,string:()=>Va,symbol:()=>bm,transformer:()=>Bm,tuple:()=>Mm,undefined:()=>Sm,union:()=>Im,unknown:()=>Cm,util:()=>L,void:()=>Tm});var L;(function(e){e.assertEqual=s=>{};function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{let o={};for(let i of s)o[i]=i;return o},e.getValidEnumValues=s=>{let o=e.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(let a of o)i[a]=s[a];return e.objectValues(i)},e.objectValues=s=>e.objectKeys(s).map(function(o){return s[o]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},e.find=(s,o)=>{for(let i of s)if(o(i))return i},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}e.joinValues=r,e.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(L||(L={}));var ro;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(ro||(ro={}));var v=L.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Le=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=L.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Bd=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),pe=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(o){return o.message},r={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,l=0;for(;l<i.path.length;){let c=i.path[l];l===i.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(i))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return s(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,L.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];n[o]=n[o]||[],n[o].push(t(s))}else r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};pe.create=e=>new pe(e);var Hd=(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,L.jsonStringifyReplacer)}`;break;case h.unrecognized_keys:n=`Unrecognized key(s) in object: ${L.joinValues(e.keys,", ")}`;break;case h.invalid_union:n="Invalid input";break;case h.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${L.joinValues(e.options)}`;break;case h.invalid_enum_value:n=`Invalid enum value. Expected ${L.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}"`:L.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,L.assertNever(e)}return{message:n}},Xe=Hd;var Pa=Xe;function Kd(e){Pa=e}function mn(){return Pa}var Bn=e=>{let{data:t,path:n,errorMaps:r,issueData:s}=e,o=[...n,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)a=c(i,{data:t,defaultError:a}).message;return{...s,path:o,message:a}},Gd=[];function _(e,t){let n=mn(),r=Bn({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Xe?void 0:Xe].filter(s=>!!s)});e.common.issues.push(r)}var se=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let s of n){if(s.status==="aborted")return E;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let s of n){let o=await s.key,i=await s.value;r.push({key:o,value:i})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let s of n){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return E;o.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(r[o.value]=i.value)}return{status:t.value,value:r}}},E=Object.freeze({status:"aborted"}),Lt=e=>({status:"dirty",value:e}),ie=e=>({status:"valid",value:e}),Mr=e=>e.status==="aborted",Or=e=>e.status==="dirty",ht=e=>e.status==="valid",pn=e=>typeof Promise<"u"&&e instanceof Promise;var b;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(b||(b={}));var Ce=class{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Ma=(e,t)=>{if(ht(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 pe(e.common.issues);return this._error=n,this._error}}};function $(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(i,a)=>{let{message:l}=e;return i.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:s}}var M=class{get description(){return this._def.description}_getType(t){return Le(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Le(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new se,ctx:{common:t.parent.common,data:t.data,parsedType:Le(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(pn(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:Le(t)},s=this._parseSync({data:t,path:r.path,parent:r});return Ma(r,s)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Le(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return ht(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=>ht(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:Le(t)},s=this._parse({data:t,path:r.path,parent:r}),o=await(pn(s)?s:Promise.resolve(s));return Ma(r,o)}refine(t,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{let i=t(s),a=()=>o.addIssue({code:h.custom,...r(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new ke({schema:this,typeName:A.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 xe.create(this,this._def)}nullable(){return Ue.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return tt.create(this)}promise(){return vt.create(this,this._def)}or(t){return Bt.create([this,t],this._def)}and(t){return Ht.create(this,t,this._def)}transform(t){return new ke({...$(this._def),schema:this,typeName:A.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new Jt({...$(this._def),innerType:this,defaultValue:n,typeName:A.ZodDefault})}brand(){return new Hn({typeName:A.ZodBranded,type:this,...$(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new Yt({...$(this._def),innerType:this,catchValue:n,typeName:A.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Kn.create(this,t)}readonly(){return Zt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},zd=/^c[^\s-]{8,}$/i,Wd=/^[0-9a-z]+$/,Jd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Yd=/^[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,Zd=/^[a-z0-9_-]{21}$/i,Xd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Qd=/^[-+]?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)?)??$/,em=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,tm="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",so,nm=/^(?:(?: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])$/,rm=/^(?:(?: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])$/,sm=/^(([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]))$/,om=/^(([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])$/,im=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,am=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Na="((\\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])))",cm=new RegExp(`^${Na}$`);function La(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 lm(e){return new RegExp(`^${La(e)}$`)}function Da(e){let t=`${Na}T${La(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 um(e,t){return!!((t==="v4"||!t)&&nm.test(e)||(t==="v6"||!t)&&sm.test(e))}function dm(e,t){if(!Xd.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||t&&s.alg!==t)}catch{return!1}}function mm(e,t){return!!((t==="v4"||!t)&&rm.test(e)||(t==="v6"||!t)&&om.test(e))}var yt=class e extends M{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==v.string){let o=this._getOrReturnCtx(t);return _(o,{code:h.invalid_type,expected:v.string,received:o.parsedType}),E}let r=new se,s;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(s=this._getOrReturnCtx(t,s),_(s,{code:h.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")t.data.length>o.value&&(s=this._getOrReturnCtx(t,s),_(s,{code:h.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){let i=t.data.length>o.value,a=t.data.length<o.value;(i||a)&&(s=this._getOrReturnCtx(t,s),i?_(s,{code:h.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&_(s,{code:h.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")em.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"email",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")so||(so=new RegExp(tm,"u")),so.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"emoji",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")Yd.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"uuid",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")Zd.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"nanoid",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")zd.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"cuid",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")Wd.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"cuid2",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")Jd.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"ulid",code:h.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),_(s,{validation:"url",code:h.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"regex",code:h.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(t,s),_(s,{code:h.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(s=this._getOrReturnCtx(t,s),_(s,{code:h.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(s=this._getOrReturnCtx(t,s),_(s,{code:h.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?Da(o).test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{code:h.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?cm.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{code:h.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?lm(o).test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{code:h.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?Qd.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"duration",code:h.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?um(t.data,o.version)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"ip",code:h.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?dm(t.data,o.alg)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"jwt",code:h.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?mm(t.data,o.version)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"cidr",code:h.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?im.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"base64",code:h.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?am.test(t.data)||(s=this._getOrReturnCtx(t,s),_(s,{validation:"base64url",code:h.invalid_string,message:o.message}),r.dirty()):L.assertNever(o);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:h.invalid_string,...b.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...b.errToObj(t)})}url(t){return this._addCheck({kind:"url",...b.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...b.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...b.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...b.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...b.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...b.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...b.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...b.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...b.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...b.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...b.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...b.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...b.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...b.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...b.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...b.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...b.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...b.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...b.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...b.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...b.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...b.errToObj(n)})}nonempty(t){return this.min(1,b.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};yt.create=e=>new yt({checks:[],typeName:A.ZodString,coerce:e?.coerce??!1,...$(e)});function pm(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,o=Number.parseInt(e.toFixed(s).replace(".","")),i=Number.parseInt(t.toFixed(s).replace(".",""));return o%i/10**s}var Dt=class e extends M{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 o=this._getOrReturnCtx(t);return _(o,{code:h.invalid_type,expected:v.number,received:o.parsedType}),E}let r,s=new se;for(let o of this._def.checks)o.kind==="int"?L.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),_(r,{code:h.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),_(r,{code:h.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),_(r,{code:h.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?pm(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),_(r,{code:h.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),_(r,{code:h.not_finite,message:o.message}),s.dirty()):L.assertNever(o);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,b.toString(n))}gt(t,n){return this.setLimit("min",t,!1,b.toString(n))}lte(t,n){return this.setLimit("max",t,!0,b.toString(n))}lt(t,n){return this.setLimit("max",t,!1,b.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:b.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:b.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:b.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:b.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:b.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:b.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:b.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:b.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:b.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:b.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&L.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};Dt.create=e=>new Dt({checks:[],typeName:A.ZodNumber,coerce:e?.coerce||!1,...$(e)});var Ut=class e extends M{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,s=new se;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),_(r,{code:h.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),_(r,{code:h.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),_(r,{code:h.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):L.assertNever(o);return{status:s.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return _(n,{code:h.invalid_type,expected:v.bigint,received:n.parsedType}),E}gte(t,n){return this.setLimit("min",t,!0,b.toString(n))}gt(t,n){return this.setLimit("min",t,!1,b.toString(n))}lte(t,n){return this.setLimit("max",t,!0,b.toString(n))}lt(t,n){return this.setLimit("max",t,!1,b.toString(n))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:b.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:b.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:b.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:b.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:b.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:b.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};Ut.create=e=>new Ut({checks:[],typeName:A.ZodBigInt,coerce:e?.coerce??!1,...$(e)});var jt=class extends M{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==v.boolean){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:v.boolean,received:r.parsedType}),E}return ie(t.data)}};jt.create=e=>new jt({typeName:A.ZodBoolean,coerce:e?.coerce||!1,...$(e)});var Vt=class e extends M{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==v.date){let o=this._getOrReturnCtx(t);return _(o,{code:h.invalid_type,expected:v.date,received:o.parsedType}),E}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return _(o,{code:h.invalid_date}),E}let r=new se,s;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(s=this._getOrReturnCtx(t,s),_(s,{code:h.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(s=this._getOrReturnCtx(t,s),_(s,{code:h.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):L.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:b.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:b.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};Vt.create=e=>new Vt({checks:[],coerce:e?.coerce||!1,typeName:A.ZodDate,...$(e)});var gn=class extends M{_parse(t){if(this._getType(t)!==v.symbol){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:v.symbol,received:r.parsedType}),E}return ie(t.data)}};gn.create=e=>new gn({typeName:A.ZodSymbol,...$(e)});var qt=class extends M{_parse(t){if(this._getType(t)!==v.undefined){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:v.undefined,received:r.parsedType}),E}return ie(t.data)}};qt.create=e=>new qt({typeName:A.ZodUndefined,...$(e)});var Ft=class extends M{_parse(t){if(this._getType(t)!==v.null){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:v.null,received:r.parsedType}),E}return ie(t.data)}};Ft.create=e=>new Ft({typeName:A.ZodNull,...$(e)});var _t=class extends M{constructor(){super(...arguments),this._any=!0}_parse(t){return ie(t.data)}};_t.create=e=>new _t({typeName:A.ZodAny,...$(e)});var et=class extends M{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ie(t.data)}};et.create=e=>new et({typeName:A.ZodUnknown,...$(e)});var Ee=class extends M{_parse(t){let n=this._getOrReturnCtx(t);return _(n,{code:h.invalid_type,expected:v.never,received:n.parsedType}),E}};Ee.create=e=>new Ee({typeName:A.ZodNever,...$(e)});var hn=class extends M{_parse(t){if(this._getType(t)!==v.undefined){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:v.void,received:r.parsedType}),E}return ie(t.data)}};hn.create=e=>new hn({typeName:A.ZodVoid,...$(e)});var tt=class e extends M{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==v.array)return _(n,{code:h.invalid_type,expected:v.array,received:n.parsedType}),E;if(s.exactLength!==null){let i=n.data.length>s.exactLength.value,a=n.data.length<s.exactLength.value;(i||a)&&(_(n,{code:i?h.too_big:h.too_small,minimum:a?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(_(n,{code:h.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(_(n,{code:h.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>s.type._parseAsync(new Ce(n,i,n.path,a)))).then(i=>se.mergeArray(r,i));let o=[...n.data].map((i,a)=>s.type._parseSync(new Ce(n,i,n.path,a)));return se.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:b.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:b.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:b.toString(n)}})}nonempty(t){return this.min(1,t)}};tt.create=(e,t)=>new tt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:A.ZodArray,...$(t)});function fn(e){if(e instanceof fe){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=xe.create(fn(r))}return new fe({...e._def,shape:()=>t})}else return e instanceof tt?new tt({...e._def,type:fn(e.element)}):e instanceof xe?xe.create(fn(e.unwrap())):e instanceof Ue?Ue.create(fn(e.unwrap())):e instanceof De?De.create(e.items.map(t=>fn(t))):e}var fe=class e extends M{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=L.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==v.object){let c=this._getOrReturnCtx(t);return _(c,{code:h.invalid_type,expected:v.object,received:c.parsedType}),E}let{status:r,ctx:s}=this._processInputParams(t),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ee&&this._def.unknownKeys==="strip"))for(let c in s.data)i.includes(c)||a.push(c);let l=[];for(let c of i){let u=o[c],d=s.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Ce(s,d,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Ee){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(c==="strict")a.length>0&&(_(s,{code:h.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let u of a){let d=s.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Ce(s,d,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of l){let d=await u.key,f=await u.value;c.push({key:d,value:f,alwaysSet:u.alwaysSet})}return c}).then(c=>se.mergeObjectSync(r,c)):se.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return b.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:b.errToObj(t).message??s}:{message:s}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:A.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of L.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let r of L.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return fn(this)}partial(t){let n={};for(let r of L.objectKeys(this.shape)){let s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let r of L.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof xe;)o=o._def.innerType;n[r]=o}return new e({...this._def,shape:()=>n})}keyof(){return Ua(L.objectKeys(this.shape))}};fe.create=(e,t)=>new fe({shape:()=>e,unknownKeys:"strip",catchall:Ee.create(),typeName:A.ZodObject,...$(t)});fe.strictCreate=(e,t)=>new fe({shape:()=>e,unknownKeys:"strict",catchall:Ee.create(),typeName:A.ZodObject,...$(t)});fe.lazycreate=(e,t)=>new fe({shape:e,unknownKeys:"strip",catchall:Ee.create(),typeName:A.ZodObject,...$(t)});var Bt=class extends M{_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new pe(a.ctx.common.issues));return _(n,{code:h.invalid_union,unionErrors:i}),E}if(n.common.async)return Promise.all(r.map(async o=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let l of r){let c={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(l=>new pe(l));return _(n,{code:h.invalid_union,unionErrors:a}),E}}get options(){return this._def.options}};Bt.create=(e,t)=>new Bt({options:e,typeName:A.ZodUnion,...$(t)});var Qe=e=>e instanceof Kt?Qe(e.schema):e instanceof ke?Qe(e.innerType()):e instanceof Gt?[e.value]:e instanceof zt?e.options:e instanceof Wt?L.objectValues(e.enum):e instanceof Jt?Qe(e._def.innerType):e instanceof qt?[void 0]:e instanceof Ft?[null]:e instanceof xe?[void 0,...Qe(e.unwrap())]:e instanceof Ue?[null,...Qe(e.unwrap())]:e instanceof Hn||e instanceof Zt?Qe(e.unwrap()):e instanceof Yt?Qe(e._def.innerType):[],Nr=class e extends M{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==v.object)return _(n,{code:h.invalid_type,expected:v.object,received:n.parsedType}),E;let r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(_(n,{code:h.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),E)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let s=new Map;for(let o of n){let i=Qe(o.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of i){if(s.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);s.set(a,o)}}return new e({typeName:A.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...$(r)})}};function oo(e,t){let n=Le(e),r=Le(t);if(e===t)return{valid:!0,data:e};if(n===v.object&&r===v.object){let s=L.objectKeys(t),o=L.objectKeys(e).filter(a=>s.indexOf(a)!==-1),i={...e,...t};for(let a of o){let l=oo(e[a],t[a]);if(!l.valid)return{valid:!1};i[a]=l.data}return{valid:!0,data:i}}else if(n===v.array&&r===v.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let o=0;o<e.length;o++){let i=e[o],a=t[o],l=oo(i,a);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return n===v.date&&r===v.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Ht=class extends M{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=(o,i)=>{if(Mr(o)||Mr(i))return E;let a=oo(o.value,i.value);return a.valid?((Or(o)||Or(i))&&n.dirty(),{status:n.value,value:a.data}):(_(r,{code:h.invalid_intersection_types}),E)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Ht.create=(e,t,n)=>new Ht({left:e,right:t,typeName:A.ZodIntersection,...$(n)});var De=class e extends M{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==v.array)return _(r,{code:h.invalid_type,expected:v.array,received:r.parsedType}),E;if(r.data.length<this._def.items.length)return _(r,{code:h.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),E;!this._def.rest&&r.data.length>this._def.items.length&&(_(r,{code:h.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...r.data].map((i,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Ce(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>se.mergeArray(n,i)):se.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};De.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new De({items:e,typeName:A.ZodTuple,rest:null,...$(t)})};var Lr=class e extends M{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 _(r,{code:h.invalid_type,expected:v.object,received:r.parsedType}),E;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in r.data)s.push({key:o._parse(new Ce(r,a,r.path,a)),value:i._parse(new Ce(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?se.mergeObjectAsync(n,s):se.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof M?new e({keyType:t,valueType:n,typeName:A.ZodRecord,...$(r)}):new e({keyType:yt.create(),valueType:t,typeName:A.ZodRecord,...$(n)})}},yn=class extends M{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 _(r,{code:h.invalid_type,expected:v.map,received:r.parsedType}),E;let s=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([a,l],c)=>({key:s._parse(new Ce(r,a,r.path,[c,"key"])),value:o._parse(new Ce(r,l,r.path,[c,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of i){let c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return E;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let l of i){let c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return E;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}}}};yn.create=(e,t,n)=>new yn({valueType:t,keyType:e,typeName:A.ZodMap,...$(n)});var _n=class e extends M{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==v.set)return _(r,{code:h.invalid_type,expected:v.set,received:r.parsedType}),E;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(_(r,{code:h.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(_(r,{code:h.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let o=this._def.valueType;function i(l){let c=new Set;for(let u of l){if(u.status==="aborted")return E;u.status==="dirty"&&n.dirty(),c.add(u.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((l,c)=>o._parse(new Ce(r,l,r.path,c)));return r.common.async?Promise.all(a).then(l=>i(l)):i(a)}min(t,n){return new e({...this._def,minSize:{value:t,message:b.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:b.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};_n.create=(e,t)=>new _n({valueType:e,minSize:null,maxSize:null,typeName:A.ZodSet,...$(t)});var Dr=class e extends M{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==v.function)return _(n,{code:h.invalid_type,expected:v.function,received:n.parsedType}),E;function r(a,l){return Bn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,mn(),Xe].filter(c=>!!c),issueData:{code:h.invalid_arguments,argumentsError:l}})}function s(a,l){return Bn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,mn(),Xe].filter(c=>!!c),issueData:{code:h.invalid_return_type,returnTypeError:l}})}let o={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof vt){let a=this;return ie(async function(...l){let c=new pe([]),u=await a._def.args.parseAsync(l,o).catch(g=>{throw c.addIssue(r(l,g)),c}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,o).catch(g=>{throw c.addIssue(s(d,g)),c})})}else{let a=this;return ie(function(...l){let c=a._def.args.safeParse(l,o);if(!c.success)throw new pe([r(l,c.error)]);let u=Reflect.apply(i,this,c.data),d=a._def.returns.safeParse(u,o);if(!d.success)throw new pe([s(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:De.create(t).rest(et.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||De.create([]).rest(et.create()),returns:n||et.create(),typeName:A.ZodFunction,...$(r)})}},Kt=class extends M{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})}};Kt.create=(e,t)=>new Kt({getter:e,typeName:A.ZodLazy,...$(t)});var Gt=class extends M{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return _(n,{received:n.data,code:h.invalid_literal,expected:this._def.value}),E}return{status:"valid",value:t.data}}get value(){return this._def.value}};Gt.create=(e,t)=>new Gt({value:e,typeName:A.ZodLiteral,...$(t)});function Ua(e,t){return new zt({values:e,typeName:A.ZodEnum,...$(t)})}var zt=class e extends M{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return _(n,{expected:L.joinValues(r),received:n.parsedType,code:h.invalid_type}),E}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 _(n,{received:n.data,code:h.invalid_enum_value,options:r}),E}return ie(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};zt.create=Ua;var Wt=class extends M{_parse(t){let n=L.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==v.string&&r.parsedType!==v.number){let s=L.objectValues(n);return _(r,{expected:L.joinValues(s),received:r.parsedType,code:h.invalid_type}),E}if(this._cache||(this._cache=new Set(L.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let s=L.objectValues(n);return _(r,{received:r.data,code:h.invalid_enum_value,options:s}),E}return ie(t.data)}get enum(){return this._def.values}};Wt.create=(e,t)=>new Wt({values:e,typeName:A.ZodNativeEnum,...$(t)});var vt=class extends M{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==v.promise&&n.common.async===!1)return _(n,{code:h.invalid_type,expected:v.promise,received:n.parsedType}),E;let r=n.parsedType===v.promise?n.data:Promise.resolve(n.data);return ie(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};vt.create=(e,t)=>new vt({type:e,typeName:A.ZodPromise,...$(t)});var ke=class extends M{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===A.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,o={addIssue:i=>{_(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(r.data,o);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return E;let l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?E:l.status==="dirty"?Lt(l.value):n.value==="dirty"?Lt(l.value):l});{if(n.value==="aborted")return E;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?E:a.status==="dirty"?Lt(a.value):n.value==="dirty"?Lt(a.value):a}}if(s.type==="refinement"){let i=a=>{let l=s.refinement(a,o);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?E:(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"?E:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(s.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ht(i))return E;let a=s.transform(i.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>ht(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:n.value,value:a})):E);L.assertNever(s)}};ke.create=(e,t,n)=>new ke({schema:e,typeName:A.ZodEffects,effect:t,...$(n)});ke.createWithPreprocess=(e,t,n)=>new ke({schema:t,effect:{type:"preprocess",transform:e},typeName:A.ZodEffects,...$(n)});var xe=class extends M{_parse(t){return this._getType(t)===v.undefined?ie(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};xe.create=(e,t)=>new xe({innerType:e,typeName:A.ZodOptional,...$(t)});var Ue=class extends M{_parse(t){return this._getType(t)===v.null?ie(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ue.create=(e,t)=>new Ue({innerType:e,typeName:A.ZodNullable,...$(t)});var Jt=class extends M{_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}};Jt.create=(e,t)=>new Jt({innerType:e,typeName:A.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...$(t)});var Yt=class extends M{_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return pn(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new pe(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new pe(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Yt.create=(e,t)=>new Yt({innerType:e,typeName:A.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...$(t)});var vn=class extends M{_parse(t){if(this._getType(t)!==v.nan){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:v.nan,received:r.parsedType}),E}return{status:"valid",value:t.data}}};vn.create=e=>new vn({typeName:A.ZodNaN,...$(e)});var fm=Symbol("zod_brand"),Hn=class extends M{_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}},Kn=class e extends M{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?E:o.status==="dirty"?(n.dirty(),Lt(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?E:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:A.ZodPipeline})}},Zt=class extends M{_parse(t){let n=this._def.innerType._parse(t),r=s=>(ht(s)&&(s.value=Object.freeze(s.value)),s);return pn(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Zt.create=(e,t)=>new Zt({innerType:e,typeName:A.ZodReadonly,...$(t)});function Oa(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function ja(e,t={},n){return e?_t.create().superRefine((r,s)=>{let o=e(r);if(o instanceof Promise)return o.then(i=>{if(!i){let a=Oa(t,r),l=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:l})}});if(!o){let i=Oa(t,r),a=i.fatal??n??!0;s.addIssue({code:"custom",...i,fatal:a})}}):_t.create()}var gm={object:fe.lazycreate},A;(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"})(A||(A={}));var hm=(e,t={message:`Input not instance of ${e.name}`})=>ja(n=>n instanceof e,t),Va=yt.create,qa=Dt.create,ym=vn.create,_m=Ut.create,Fa=jt.create,vm=Vt.create,bm=gn.create,Sm=qt.create,wm=Ft.create,xm=_t.create,Cm=et.create,km=Ee.create,Tm=hn.create,Em=tt.create,Am=fe.create,Rm=fe.strictCreate,Im=Bt.create,$m=Nr.create,Pm=Ht.create,Mm=De.create,Om=Lr.create,Nm=yn.create,Lm=_n.create,Dm=Dr.create,Um=Kt.create,jm=Gt.create,Vm=zt.create,qm=Wt.create,Fm=vt.create,Bm=ke.create,Hm=xe.create,Km=Ue.create,Gm=ke.createWithPreprocess,zm=Kn.create,Wm=()=>Va().optional(),Jm=()=>qa().optional(),Ym=()=>Fa().optional(),Zm={string:(e=>yt.create({...e,coerce:!0})),number:(e=>Dt.create({...e,coerce:!0})),boolean:(e=>jt.create({...e,coerce:!0})),bigint:(e=>Ut.create({...e,coerce:!0})),date:(e=>Vt.create({...e,coerce:!0}))};var Xm=E;var Ba=["tempo","mpp_self","merchant_self"];var ao=p.object({inputPerMillion:p.number().positive(),outputPerMillion:p.number().positive(),contextWindow:p.number().int().positive().optional(),maxOutput:p.number().int().positive().optional(),perRequestFeeCents:p.number().nonnegative().optional()}),Qm=p.object({strategy:p.enum(["flat","token","band"]).optional(),pricingModel:p.enum(["per-call","per-token","band"]).optional(),priceCents:p.number().nonnegative().optional(),currency:p.string().optional(),display:p.string().optional(),estimate:p.boolean().optional(),source:p.string().optional(),priceBand:p.record(p.unknown()).optional(),tokenPricing:ao.optional()}).passthrough(),co=p.discriminatedUnion("type",[p.object({type:p.literal("shortcut"),routedPath:p.string().min(1).startsWith("/")}),p.object({type:p.literal("custom"),merchantSlug:p.string().min(1),subPath:p.string().optional()}),p.object({type:p.literal("local"),fn:p.string().min(1)}),p.object({type:p.literal("read")})]),lo=p.object({amount:p.number().nonnegative(),currency:p.string().length(3).optional(),display:p.string().optional(),free:p.boolean().optional(),batchDiscount:p.number().min(0).max(100).optional()}),Ha=p.object({attestation:p.boolean().optional(),rateLimitMs:p.number().positive().optional()}),Ka=p.object({displayName:p.string().optional(),feedbackEligible:p.boolean().optional(),suggestionEligible:p.boolean().optional(),batchable:p.boolean().optional()}),ep=p.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),tp=120,np=120,rp=1200,sp=/^[^\u0000-\u001F\u007F]+$/;function io(e,t){return p.string().min(1).max(e).regex(sp,`${t} must not contain control characters`)}var uo={id:p.string().min(1),name:io(tp,"name"),description:io(rp,"description"),provider:p.string().min(1),model:p.string().min(1),category:ep,priceCents:p.number().nonnegative(),inputSchema:p.record(p.unknown()),gatewayUrl:p.string().min(1),merchantName:io(np,"merchantName"),isAsync:p.boolean().optional(),pollUrl:p.string().optional(),pollInterval:p.number().positive().optional(),pollTimeout:p.number().positive().optional(),tags:p.array(p.string()).optional(),tokenPricing:ao.optional(),priceDisplay:p.string().optional(),pricingModel:p.enum(["per-call","per-token","band"]).optional(),pricingInfo:Qm.optional(),status:p.enum(["available","unavailable"]).optional(),handler:co.optional(),pricing:lo.optional(),security:Ha.optional(),engagement:Ka.optional(),enabled:p.boolean().optional(),beta:p.boolean().optional(),deprecated:p.boolean().optional(),replacementTool:p.string().optional(),minCliVersion:p.string().optional(),sunsetAt:p.string().optional(),rail:p.enum(Ba).optional(),pricingStrategy:p.enum(["flat","token","band"]).optional()},Ga=p.object({...uo,dispatch:p.literal("routed"),routedPath:p.string().min(1).startsWith("/")}).strict(),za=p.object({...uo,dispatch:p.literal("enveloped")}).strict(),Wa=p.object({...uo,handler:co,pricing:lo}).strict(),Ja=p.union([p.discriminatedUnion("dispatch",[Ga,za]),Wa]);var mo=/^[a-z0-9][a-z0-9_-]*$/;var ip="https://fal.run",Qa="https://openrouter.mpp.tempo.xyz";function ap(e){let{attestation:t,tool_id:n,...r}=e;return r}var Ya={"1:1":"square_hd","16:9":"landscape_16_9","9:16":"portrait_16_9","4:3":"landscape_4_3","3:4":"portrait_4_3"};function Ur(e){let{attestation:t,tool_id:n,aspect_ratio:r,image_size:s,...o}=e,i={...o};return typeof s=="string"&&s.length>0?(i.image_size=s,i):(typeof r=="string"&&Ya[r]&&(i.image_size=Ya[r]),i)}function Za(e){let t={chain:e.chain,token_address:e.token_address};if(e.start_timestamp){let n=e.end_timestamp||new Date().toISOString(),r=e.time_granularity;if(!r){let s=new Date(e.start_timestamp).getTime();(new Date(n).getTime()-s)/(1e3*60*60*24)<=2?r="1h":r="1d"}return{addresses:[t],start_timestamp:e.start_timestamp,end_timestamp:n,time_granularity:r}}return[t]}function cp(e,t,n,r,s,o,i,a,l){return{id:e,name:t,description:n,provider:r,model:s.replace(/^\//,""),category:o,gatewayUrl:`https://${r}${s}`,merchantName:t,inputSchema:a,handler:{type:"custom",merchantSlug:r,subPath:s},pricing:{amount:i,currency:"USD",display:`$${(i/100).toFixed(2)}`},priceCents:i,tags:[],...l}}function lp(e,t,n,r,s,o,i,a){return cp(e,t,n,"suno-ai",r,s,o,i,{merchantName:"Suno AI",...a})}function Z(e,t,n,r,s,o,i,a){return{dispatch:"routed",id:e,name:t,description:n,provider:"fal",model:r,category:s,priceCents:o,inputSchema:i,routedPath:`/api/v1/fal/${r}`,gatewayUrl:`${ip}/${r}`,merchantName:"fal.ai",buildBody:ap,tags:[],...a}}function up(e){return t=>{let{attestation:n,tool_id:r,prompt:s,system_prompt:o,max_tokens:i,temperature:a,...l}=t;return{model:e,messages:[...o?[{role:"system",content:o}]:[],{role:"user",content:s}],max_tokens:i??1024,temperature:a??.7,...l}}}function dp(e){return t=>{let{attestation:n,tool_id:r,prompt:s,image_url:o,aspect_ratio:i,max_tokens:a,temperature:l,...c}=t,u=[{type:"text",text:s}];return typeof o=="string"&&o.length>0&&u.push({type:"image_url",image_url:{url:o}}),{model:e,messages:[{role:"user",content:u}],max_tokens:a??1024,temperature:l??.7,...typeof i=="string"&&i.length>0?{image_config:{aspect_ratio:i}}:{},...c}}}function X(e,t,n,r,s,o,i){let a=i?.perRequestFeeCents??0,l=500/1e6*s*100,c=500/1e6*o*100,u=Math.max(1,Math.ceil(l+c+a)),{perRequestFeeCents:d,...f}=i??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"llm",priceCents:u,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The prompt or question to send to the model"},system_prompt:{type:"string",description:"Optional system prompt to set model behavior"},max_tokens:{type:"integer",description:"Maximum tokens in response (default: 1024)",minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${Qa}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:up(r),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:s,outputPerMillion:o,...a>0?{perRequestFeeCents:a}:{}},...f}}function po(e,t,n,r,s,o){return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"image",priceCents:s,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate or edit"},image_url:{type:"string",description:"Optional source image URL for edits"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"1:1"},max_tokens:{type:"integer",description:"Maximum text tokens in response metadata (default: 1024)",minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${Qa}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:dp(r),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...o}}var fo=[Z("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"]}),Z("fal-flux-pro","FLUX Pro","Fast, high-quality image generation. Good balance of speed and quality.","fal-ai/flux-pro/v1.1","image",4,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},{tags:["image","flux","fast"],buildBody:Ur}),Z("fal-flux-dev","FLUX Dev","Open-source image generation. Cheaper, good for experimentation.","fal-ai/flux/dev","image",3,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["image","flux","open-source","cheap"],buildBody:Ur}),Z("fal-flux-schnell","FLUX Schnell","Fastest image generation. Ultra-cheap, great for drafts and iteration.","fal-ai/flux/schnell","image",1,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["image","flux","fast","cheap","draft"],buildBody:Ur}),Z("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"]}),po("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),po("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}}),po("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}}),Z("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"]}),Z("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"]}),Z("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"]}),Z("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"]}),Z("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"]}),Z("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"]}),Z("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"]}),Z("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"]}),Z("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"]}),lp("suno-music","Suno Music","AI music generation. Create full songs with vocals or instrumentals.","/suno/generate-music","audio",10,{type:"object",properties:{prompt:{type:"string",description:"Description of the song (genre, mood, instruments)"},instrumental:{type:"boolean",description:"Instrumental only, no vocals",default:!1}},required:["prompt"]},{isAsync:!0,pollUrl:"https://api.sunoapi.org/suno/get-music-status",deprecated:!0,tags:["music","song","vocals","instrumental"],buildBody:e=>{let{attestation:t,tool_id:n,prompt:r,instrumental:s,...o}=e;return{prompt:r,customMode:!1,instrumental:typeof s=="boolean"?s:!1,model:"V4",...o}}}),Z("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"]}),Z("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"]}),Z("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"]}),Z("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-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-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",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:Za,tags:["onchain","prices","allium","crypto"]},{dispatch:"enveloped",id:"generate_image_card",name:"Generate Image (Ultra)",description:"Generate a high-quality AI image (FLUX Pro Ultra, 2K, ~$0.06).",provider:"fal",model:"fal-ai/flux-pro/v1.1-ultra",category:"image",priceCents:6,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1-ultra",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro-ultra",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),t},tags:["image","flux","ultra","legacy"]},{dispatch:"enveloped",id:"generate_image_fast_card",name:"Generate Image (Fast)",description:"Generate an AI image (FLUX Pro v1.1, 1K, ~$0.04).",provider:"fal",model:"fal-ai/flux-pro/v1.1",category:"image",priceCents:4,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro",buildBody:e=>Ur({prompt:e.prompt,aspect_ratio:e.aspect_ratio}),tags:["image","flux","legacy"]},{dispatch:"enveloped",id:"generate_image_schnell_card",name:"Generate Image (Cheap)",description:"Cheap, fast FLUX image generation (~$0.01).",provider:"fal",model:"fal-ai/flux/schnell",category:"image",priceCents:1,inputSchema:{type:"object",properties:{prompt:{type:"string"},image_size:{type:"string"},num_inference_steps:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux/schnell",merchantName:"fal.ai",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"]},Z("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"}),Z("edit_image_seed_card","Edit Image (SeedEdit)","Inpaint/edit an image with a prompt using SeedEdit.","fal-ai/bytedance/seededit","image",5,{type:"object",properties:{image_url:{type:"string"},prompt:{type:"string"},seed:{type:"number"}},required:["image_url","prompt"]},{buildBody:e=>{let t={image_url:e.image_url,prompt:e.prompt};return e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","edit","inpaint","seededit"],deprecated:!0,replacementTool:"or-gemini-nano-banana"}),{dispatch:"enveloped",id:"generate_video_tempo_card",name:"Generate Video (Grok)",description:"Generate a video from a text prompt using Grok Imagine Video.",provider:"fal",model:"xai/grok-imagine-video/text-to-video",category:"video",priceCents:30,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/xai/grok-imagine-video/text-to-video",merchantName:"Grok Video via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),t},tags:["video","grok","legacy"]},{dispatch:"enveloped",id:"generate_video_kling_card",name:"Generate Video (Kling)",description:"Generate a video using Kling v1.6 (async, ~$0.40).",provider:"fal",model:"fal-ai/kling-video/v1.6/standard/text-to-video",category:"video",priceCents:40,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/kling-video/v1.6/standard/text-to-video",merchantName:"Kling via fal.ai",deprecated:!0,replacementTool:"fal-kling-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","kling","legacy"]},{dispatch:"enveloped",id:"generate_video_wan_card",name:"Generate Video (Wan)",description:"Generate a video using Wan T2V (async, ~$0.25).",provider:"fal",model:"fal-ai/wan/t2v-1.3b",category:"video",priceCents:25,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/wan/t2v-1.3b",merchantName:"Wan T2V via fal.ai",deprecated:!0,replacementTool:"fal-wan-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","wan","legacy"]},{dispatch:"enveloped",id:"generate_video_minimax_card",name:"Generate Video (MiniMax)",description:"Generate a video using MiniMax (async, ~$0.35).",provider:"fal",model:"fal-ai/minimax/video-01",category:"video",priceCents:35,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/minimax/video-01",merchantName:"MiniMax via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","minimax","legacy"]},{dispatch:"enveloped",id:"check_fal_status_card",name:"Check fal Async Job Status",description:"Poll an async fal.ai queue job for completion.",provider:"fal",model:"queue-status",category:"image",priceCents:0,inputSchema:{type:"object",properties:{model_path:{type:"string",description:"Model path (e.g. fal-ai/kling-video/v1.6/standard/text-to-video)"},request_id:{type:"string"}},required:["model_path","request_id"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue",merchantName:"fal.ai",buildUrl:e=>`https://fal.mpp.tempo.xyz/queue/${e.model_path}/requests/${e.request_id}`,buildBody:()=>({}),tags:["status","fal","async","legacy"]},{dispatch:"enveloped",id:"generate_3d_card",name:"Generate 3D Model",description:"Generate a 3D mesh from a text prompt using Meshy (async, ~$0.50).",provider:"fal",model:"fal-ai/meshy-ai/text-to-3d",category:"3d",priceCents:50,inputSchema:{type:"object",properties:{object_prompt:{type:"string"},style_prompt:{type:"string"},negative_prompt:{type:"string"},art_style:{type:"string"},seed:{type:"number"}},required:["object_prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/meshy-ai/text-to-3d",merchantName:"Meshy via fal.ai",deprecated:!0,replacementTool:"fal-trellis-3d",buildBody:e=>{let t={object_prompt:e.object_prompt};return e.style_prompt&&(t.style_prompt=e.style_prompt),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.art_style&&(t.art_style=e.art_style),e.seed!==void 0&&(t.seed=e.seed),t},tags:["3d","mesh","meshy","legacy"]},{dispatch:"enveloped",id:"generate_speech_card",name:"Generate Speech",description:"Text-to-speech using F5-TTS with optional voice cloning.",provider:"fal",model:"fal-ai/f5-tts",category:"tts",priceCents:3,inputSchema:{type:"object",properties:{gen_text:{type:"string",description:"Text to synthesize"},ref_audio_url:{type:"string",description:"Reference audio URL (for voice cloning)"},ref_text:{type:"string",description:"Transcription of ref audio"},remove_silence:{type:"boolean"}},required:["gen_text"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/f5-tts",merchantName:"fal.ai",buildBody:e=>{let t={gen_text:e.gen_text};return e.ref_audio_url&&(t.ref_audio_url=e.ref_audio_url),e.ref_text&&(t.ref_text=e.ref_text),e.remove_silence!==void 0&&(t.remove_silence=e.remove_silence),t},deprecated:!0,replacementTool:"fal-metavoice",tags:["tts","speech","f5-tts","legacy"]},{dispatch:"enveloped",id:"generate_music_tempo_card",name:"Generate Music (Suno)",description:"Generate a music track using Suno (async, ~$0.50).",provider:"suno",model:"suno-v4",category:"audio",priceCents:50,inputSchema:{type:"object",properties:{prompt:{type:"string"},instrumental:{type:"boolean"},model:{type:"string",default:"V4"}},required:["prompt"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/generate-music",merchantName:"Suno via Tempo",buildBody:e=>({prompt:e.prompt,customMode:!1,instrumental:e.instrumental??!1,model:e.model||"V4"}),isAsync:!0,pollUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",pollInterval:15e3,pollTimeout:3e5,deprecated:!0,replacementTool:"fal-ace-step-music",tags:["music","audio","suno","async","legacy"]},{dispatch:"enveloped",id:"check_music_status_tempo_card",name:"Check Music Status",description:"Poll a Suno music generation task for completion.",provider:"suno",model:"suno-status",category:"audio",priceCents:0,inputSchema:{type:"object",properties:{taskId:{type:"string"}},required:["taskId"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",merchantName:"Suno Status",buildBody:e=>({taskId:e.taskId}),deprecated:!0,tags:["music","status","suno","legacy"]},{dispatch:"enveloped",id:"query_onchain_prices_card",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly, daily, and weekly granularity.",provider:"allium",model:"allium-prices",category:"llm",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly), '1d' (daily), or '1w' (weekly). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",deprecated:!0,replacementTool:"query_onchain_prices",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:Za,tags:["onchain","prices","allium","crypto","legacy"]}];function Gn(e){return fo.find(t=>t.id===e)}var ec=1,tc=["pick_one","fan_out"],nc=["concat","dedupe_by_url","top_k_by_score"],fp=8,gp=p.object({type:p.string().min(1),description:p.string().min(1),enum:p.array(p.string()).optional(),default:p.unknown().optional(),minimum:p.number().optional(),maximum:p.number().optional()}),hp=p.object({toolId:p.string().min(1),notes:p.string().min(1)}),yp=p.string().regex(/^[a-z0-9_-]{1,32}$/,"tier key must be 1-32 chars [a-z0-9_-]"),_p=p.object({providers:p.array(p.string().min(1)).min(1).max(fp),merge:p.enum(nc),maxResults:p.number().int().positive().optional()}),rc=p.object({mode:p.enum(tc).default("pick_one"),intro:p.string().min(1),defaultTier:p.string().min(1),tiers:p.record(yp,hp).refine(e=>Object.keys(e).length>0,{message:"must have at least one tier"}),fanOut:_p.optional(),guidance:p.string().min(1),inputProperties:p.record(p.string(),gp),required:p.array(p.string())}).refine(e=>e.tiers[e.defaultTier]!==void 0,{message:"defaultTier must exist in tiers",path:["defaultTier"]}).refine(e=>e.mode!=="fan_out"||e.fanOut!==void 0,{message:"fan_out mode requires fanOut config",path:["fanOut"]}).refine(e=>e.required.every(t=>t in e.inputProperties),{message:"required entries must exist in inputProperties",path:["required"]}),vp=p.object({version:p.literal(ec),generatedAt:p.string().datetime(),tools:p.record(p.string().regex(mo,"tool name must match MCP naming rules"),rc).refine(e=>Object.keys(e).length>0,{message:"manifest must have at least one tool"})});var qr=require("child_process"),cc=require("util"),lc=R(require("crypto")),ae=R(require("fs")),uc=R(require("os")),je=R(require("path"));var bn=(0,cc.promisify)(qr.execFile),Fr=je.join(uc.homedir(),".visa-mcp","bin"),Xt=je.join(Fr,"Visa CLI"),wp=je.join(__dirname,"..","native"),sc="6",oc=je.join(Fr,"visa-keychain.version"),ic=je.join(Fr,"visa-keychain.sha256");function ac(e){let t=ae.readFileSync(e);return lc.createHash("sha256").update(t).digest("hex")}async function ho(){try{if(ae.readFileSync(oc,"utf-8").trim()===sc&&ae.existsSync(Xt)){let r=ae.readFileSync(ic,"utf-8").trim();if(ac(Xt)!==r)m.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),ae.unlinkSync(Xt);else return Xt}}catch{}let e=je.join(wp,"visa-keychain.m");if(ae.existsSync(e)||(e=je.resolve(__dirname,"..","..","native","visa-keychain.m")),ae.existsSync(e)||(e=je.resolve(__dirname,"..","native","visa-keychain.m")),!ae.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");ae.mkdirSync(Fr,{recursive:!0,mode:448});try{await bn("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",Xt,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=ac(Xt);return ae.writeFileSync(ic,t,{mode:384}),ae.writeFileSync(oc,sc,{mode:384}),Xt}async function dc(e){let t=await ho(),n;try{n=(await bn(t,e,{timeout:6e4})).stdout}catch(o){n=o.stdout||"";let i=n.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(o.stderr?.trim()||o.message||"Unknown error")}let r=n.trim();if(r.startsWith("OK:"))return r.slice(3);if(r==="OK")return;let s=r.startsWith("ERROR:")?r.slice(6):"Unknown error";throw new Error(s)}var go=null;function te(){return rn()?!0:process.platform!=="darwin"?!1:go!==null?go:(go=!0,!0)}var jr="visa-cli",Vr="attestation-key";async function xp(e){try{await bn("security",["delete-generic-password","-s",jr,"-a",Vr],{timeout:5e3})}catch{}await bn("security",["add-generic-password","-s",jr,"-a",Vr,"-w",e],{timeout:5e3})}async function yo(){try{let{stdout:e}=await bn("security",["find-generic-password","-s",jr,"-a",Vr,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Br(){let e=await dc(["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 xp(n),r}async function mc(){return await yo()!==null}async function pc(){if(rn())return"mock-public-key-spki";let e=await yo();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await ho();return new Promise((n,r)=>{let s=(0,qr.execFile)(t,["public-key"],{timeout:6e4},(o,i)=>{let a=(i||"").trim();if(o){a.startsWith("ERROR:")?r(new Error(a.slice(6))):r(new Error(o.stderr?.trim()||o.message||"Unknown error"));return}a.startsWith("OK:")?n(a.slice(3)):r(new Error(a.startsWith("ERROR:")?a.slice(6):"Unknown error"))});s.stdin.write(e),s.stdin.end()})}async function Sn(e,t){if(rn())return Promise.resolve(hi());let n=await yo();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await ho(),s=["sign",e];return t&&s.push(t),new Promise((o,i)=>{let a=(0,qr.execFile)(r,s,{timeout:6e4},(l,c)=>{let u=(c||"").trim();if(l){u.startsWith("ERROR:")?i(new Error(u.slice(6))):i(new Error(l.stderr?.trim()||l.message||"Unknown error"));return}u.startsWith("OK:")?o(u.slice(3)):i(new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error"))});a.stdin.write(n),a.stdin.end()})}async function Hr(){try{await bn("security",["delete-generic-password","-s",jr,"-a",Vr],{timeout:5e3})}catch{}try{await dc(["delete-key"])}catch{}}var Cp=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],kp=[...Cp.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 vo(e,t=kp){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=_o(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(_o(r.match.provider)))&&r.match.keywords.every(s=>n.includes(_o(s))))return r.targetToolId;return null}function _o(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}var fc={generate_image:{intro:'Generate an AI image from a text prompt \u2014 useful for hero shots, marketing assets, social posts, blog covers, app mockups, or any time the user asks for art, a logo, an icon, a thumbnail, or "a picture of \u2026". From $0.01 (fast) to $0.06 (pro), returns a hosted PNG/JPG URL. Default tier: balanced ($0.04, 1K, ~10s).',tiers:{balanced:{toolId:"fal-flux-pro",notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",notes:"Recraft V3 \u2014 vector/flat/illustration styles"}},guidance:"If the user didn't specify a tier, pick 'balanced' unless the prompt clearly signals otherwise (text \u2192 text_heavy, logo/icon \u2192 vector, quick test \u2192 fast, hero/print \u2192 pro).",inputProperties:{prompt:{type:"string",description:"Text description of the image to generate."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9", "1:1", "9:16".',default:"16:9"}},required:["prompt"]},generate_video:{intro:'Generate a short AI video from a text prompt \u2014 useful for product demos, social clips, mood reels, ad concepts, or any "make me a video of \u2026" request. $0.10\u2013$0.40 per ~6s clip depending on tier. Async: returns a request_id; use execute_tool with tool_id "check_fal_status_card" to resolve it (60\u2013180s).',tiers:{balanced:{toolId:"fal-minimax-video",notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",notes:"Kling \u2014 highest quality, cinematic"}},guidance:'Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate and are processed asynchronously. The response includes a request_id and model_path. Poll with execute_tool using tool_id "check_fal_status_card" and params {request_id, model_path}. Do not poll more than once per 30 seconds.',inputProperties:{prompt:{type:"string",description:"Text description of the video scene."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9" or "9:16".',default:"16:9"}},required:["prompt"]},generate_music:{intro:'Generate an original music track from a prompt via ACE-Step. ~$0.02 for the default 60s track. Use for songs, backing tracks, jingles, vocal music, instrumental music, or any "make a song/music/track" request. Takes ~60-90s and may return a request_id to poll with check_fal_status_card. For SFX, chimes, ambient beds, or TTS, use generate_audio instead.',tiers:{ace_step:{toolId:"fal-ace-step-music",notes:"ACE-Step \u2014 prompt-to-music with vocals or instrumentals"}},guidance:"Use for songs and music tracks. Takes ~60-90s and may return a request_id to poll with check_fal_status_card. For sound effects, chimes, ambient beds, or TTS, use generate_audio instead.",inputProperties:{prompt:{type:"string",description:"Musical style, mood, instruments, subject, and lyrics direction."},instrumental:{type:"boolean",description:"True for instrumental music with no vocals; false for vocal tracks.",default:!1},duration:{type:"number",description:"Duration in seconds.",default:60}},required:["prompt"]},generate_audio:{intro:'Generate sound effects from a text prompt (sfx tier \u2014 default), or voice-cloned speech from text + a reference audio URL (tts tier). $0.03\u2013$0.04. Use for SFX, chimes, UI sounds, ambient audio (default sfx), or voice cloning when a reference audio URL is available (pass tier:"tts"). Default tier is sfx; pass tier:"tts" for voice cloning.',tiers:{sfx:{toolId:"fal-stable-audio",notes:"Stable Audio \u2014 sound effects and ambient from a prompt"},tts:{toolId:"fal-metavoice",notes:"MetaVoice \u2014 voice cloning TTS (requires a voice sample URL)"}},guidance:'Default tier is sfx: pass prompt describing the sound. For tts (voice cloning): pass tier:"tts" + text + audio_url.',inputProperties:{prompt:{type:"string",description:"Description of sound to generate (sfx tier, default)."},text:{type:"string",description:"Text to speak aloud (tts tier)."},audio_url:{type:"string",description:"URL of a voice sample to clone (tts tier, required for voice cloning)."}},required:[]},generate_3d:{intro:"Generate a 3D mesh (GLB) from an image URL via Trellis. ~$0.08, ~30\u201360s. Use when the user shares an image and asks for a 3D model, asset, AR-ready mesh, or game-ready GLB.",tiers:{trellis:{toolId:"fal-trellis-3d",notes:"Trellis \u2014 image-to-3D, returns a GLB mesh URL"}},guidance:"Pass an image URL. Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{image_url:{type:"string",description:"URL of the image to convert to a 3D model."}},required:["image_url"]},upscale_image:{intro:'Upscale an image to 4\xD7 resolution via Aura SR (preserves detail without hallucination). ~$0.03. Use whenever the user shares a low-res image and asks to "upscale", "make this higher resolution", "4x this", "enhance", or to print/export at larger size.',tiers:{aura:{toolId:"fal-aura-sr",notes:"Aura SR \u2014 default; preserves detail without hallucination"}},guidance:"Pass the existing image URL. Returns an upscaled version.",inputProperties:{image_url:{type:"string",description:"URL of the image to upscale."}},required:["image_url"]},transcribe_audio:{intro:'Transcribe speech in an audio or video file (URL) to text via OpenAI Whisper. ~$0.02 per file, multilingual, handles long files. Use whenever the user asks to "transcribe this", "what does this audio say", "make subtitles", "convert this to text", or shares an audio/video URL with no other clear intent.',tiers:{whisper:{toolId:"fal-whisper",notes:"OpenAI Whisper \u2014 fast, multilingual"}},guidance:"Pass the URL. Returns the transcript text.",inputProperties:{audio_url:{type:"string",description:"URL of the audio or video file to transcribe."}},required:["audio_url"]},run_llm:{intro:"Run a text prompt through a different LLM (GPT-4o-mini, Claude Sonnet, DeepSeek R1/V3, Perplexity Sonar with web search, or Llama 70B). Token-metered, typically ~$0.01\u2013$0.10 per call. Use for: web-grounded answers (search tier), second-opinion reasoning (reasoning tier), code generation in a different family (coding tier), deep math/logic (deep_reasoning tier), or fast cheap text cleanup (fast tier). Pair with batch for multi-model councils.",tiers:{fast:{toolId:"or-gpt-4o-mini",notes:"GPT-4o Mini. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",notes:"Claude Sonnet. Strong reasoning, long-context. Warn user it is materially pricier than `fast`."},deep_reasoning:{toolId:"or-deepseek-r1",notes:"DeepSeek R1. Deep chain-of-thought reasoning, mid-range pricing."},search:{toolId:"or-perplexity-sonar",notes:"Perplexity Sonar. Search-augmented, web-grounded with citations."},open_source:{toolId:"or-llama-70b",notes:"Llama 3.3 70B. Open-source large model."},coding:{toolId:"or-deepseek-chat",notes:"DeepSeek Chat V3. Strong at code generation."}},guidance:"Pick based on the user's need: fast (most questions, cheapest), reasoning (complex analysis; warn user it is materially pricier than fast), search (questions about current events), coding (code generation), deep_reasoning (hard math/logic problems).",inputProperties:{prompt:{type:"string",description:"The user query."},system_prompt:{type:"string",description:"Optional system prompt to set model behavior."},max_tokens:{type:"number",description:"Maximum output tokens.",default:1024,minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature \u2014 0 is deterministic, higher is more creative.",default:.7,minimum:0,maximum:2}},required:["prompt"]}};function bo(e,t,n){if(!hc(e))return Rp(e,n);let r=gc[e];if(!r)return e;let s=Object.keys(r.tiers),o=t||s[0],i=Ip(e,o,n);return i||$p(e,r,o,s)}function Rp(e,t){return vo({requestedTool:e,intentText:t})??e}function Ip(e,t,n){return vo({requestedTool:e,metaTool:e,tier:t,intentText:n})}function $p(e,t,n,r){let s=t.tiers[n];if(!s)throw new Error(`Unknown tier '${n}' for ${e}. Valid tiers: ${r.join(", ")}`);return s.toolId}var gc=fc;function hc(e){return e in gc}var zn=Object.keys(fc);function So(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function yc(e=process.env){return So(e)!==null}var el=require("child_process"),ce=R(require("crypto")),Re=R(require("fs")),Xn=R(require("os")),ss=R(require("path"));var _c=!1;async function Wn(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")||!te())throw r;if(m.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(_c)throw m.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;_c=!0,m.info("attestation:starting-browser-recovery");try{let o=await n();if(!o.success)throw m.error("attestation:browser-recovery-failed",{message:o.message}),r;let i=await Br();return await e.registerAttestationKey(i),await e.setBiometricPreference({required:!0}),m.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),m.info("attestation:key-reregistered-after-recovery"),await t()}catch(o){throw m.error("attestation:recovery-failure",{error:o.message}),r}}throw r}}var vc="2.1.2";function wo(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function Gr(e,t,n){let r=process.env[e];if(r!==void 0)return{value:n==="opt-in"?r==="true":r!=="false",source:{kind:"env",var:e}};let s=Ir(t);return s!==void 0?{value:s,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function _e(e){return e==null?"\u2014":e?"yes":"no"}function zr(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function Pp(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function Mp(){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=no("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:eo,source:{kind:"default"}}}async function Jn(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(F){n=F?.message||"unknown error"}let r=[],s=process.env.VISA_AUTH_URL,o=to("auth.serverUrl"),i=we(),a=s!==void 0&&s!==""?{kind:"env",var:"VISA_AUTH_URL"}:o!==void 0?{kind:"settings"}:{kind:"default"};r.push({key:"auth.serverUrl",value:i,formatted:i,source:a,hint:a.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),r.push({key:"account.enrolled",value:t?.enrolled??null,formatted:_e(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),t?.githubUser&&r.push({key:"account.githubUser",value:t.githubUser,formatted:t.githubUser,source:{kind:"server"}});let l=t?t.attestationRequired!==!1:void 0;r.push({key:"biometric.required",value:l,formatted:_e(l),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"},hint:l===!1?"Touch ID prompts are suppressed. Re-enable with `visa-cli config biometric on`.":void 0}),r.push({key:"biometric.keyRegistered",value:t?.hasAttestationKey??null,formatted:_e(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:te(),formatted:_e(te()),source:{kind:"device"}});let c=t?.spendingControls,u=c?c.max_transaction_amount??c.maxTransactionAmount??null:null,d=c?c.daily_limit??c.dailyLimit??null:null;r.push({key:"spending.maxPerTxn",value:u,formatted:zr(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:zr(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:zr(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:zr(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(F=>F.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 g=Mp();r.push({key:"credit.sessionCapCents",value:g.value,formatted:Pp(g.value),source:g.source});let w=ka();w.length>0&&r.push({key:"settings.retired",value:w.map(F=>F.key),formatted:w.map(F=>F.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${w.map(F=>`visa-cli config unset ${F.key}`).join(" && ")}`});let y=Gr("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:y.value,formatted:_e(y.value),source:y.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let k=Gr("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:k.value,formatted:_e(k.value),source:k.source});let O=Ne(),N;process.env.VISA_CLI_NO_UPDATE_CHECK?N={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?N={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?N={kind:"env",var:"NODE_ENV"}:N={kind:"default"},r.push({key:"ui.updateCheck",value:!O,formatted:_e(!O),source:N});let C=Gr("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:C.value,formatted:_e(C.value),source:C.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let T=Gr("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:T.value,formatted:_e(T.value),source:T.source});let q=process.env.VISA_DRY_RUN,z=yc();if(r.push({key:"tools.dryRun",value:z,formatted:_e(z),source:q===void 0?{kind:"default"}:{kind:"env",var:"VISA_DRY_RUN"},hint:"VISA_DRY_RUN=true|1|mock returns deterministic paid-tool fixtures (no card, no upstream). VISA_DRY_RUN=preflight makes a real zero-cost OpenRouter call for LLM tools (image/video still mocked)."}),r.push({key:"client.version",value:vc,formatted:vc,source:{kind:"default"}}),e.includeDev){let F=process.env.VISA_MOCK_KEYCHAIN,it=ct();r.push({key:"dev.mockKeychain",value:it,formatted:_e(it),source:wo("VISA_MOCK_KEYCHAIN",!!F),hint:bs()});let ee=process.env.VISA_MOCK_TOUCHID,ue=rn();r.push({key:"dev.mockTouchid",value:ue,formatted:_e(ue),source:wo("VISA_MOCK_TOUCHID",!!ee),hint:bs()});let at=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!at,formatted:_e(!!at),source:wo("VISA_CLI_DEBUG",!!at)})}return{entries:r,statusError:n}}function Op(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 bc(e,t={}){if(e.length===0)return"";let n=Math.max(...e.map(o=>o.key.length)),r=Math.max(...e.map(o=>o.formatted.length)),s=[];for(let o of e){let i=o.key.padEnd(n+2),a=o.formatted.padEnd(r+2);s.push(`${i}${a}(${Op(o.source)})`),t.verbose&&o.hint&&s.push(` ${"\u21B3".padStart(n)} ${o.hint}`)}return s.join(`
107
+ `)}function Sc(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 wc(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 bt=require("fs"),Cc=require("os"),xo=require("path"),Np=(0,xo.join)((0,Cc.homedir)(),".visa-mcp"),xc=(0,xo.join)(Np,"mcp-session-budget.json");function Wr(){try{(0,bt.existsSync)(xc)&&(0,bt.unlinkSync)(xc)}catch{}}var ko=require("crypto"),Ae=R(Yn()),Qt=null,ve=0,wn=0,ge=0,St=null,To=null,Eo=null,Yr=Promise.resolve();function Qp(e){return Number((0,Ae.fromCents)(e))}function Ec(e){return(0,Ae.toCents)((0,Ae.micros)(BigInt(e)))}function Tc(e){return(0,Ae.toWire)((0,Ae.fromCents)(e))}function Co(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Jr(e){return typeof e=="string"&&/^\d+$/.test(e)}var ef=43,tf=new RegExp(`^[A-Za-z0-9_-]{${ef}}$`);function nf(e){return typeof e=="string"&&tf.test(e)}function rf(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||Qt&&e.session_id!==Qt||typeof e.nonce!="string"||e.nonce.length===0||!nf(e.server_signature)||!Co(e.cumulative)||!Co(e.remaining)||!Co(e.delta)||e.cumulative<ve||ge>0&&e.cumulative>ge||ge>0&&e.remaining>ge||e.cumulative_micros!==void 0&&!Jr(e.cumulative_micros)||e.remaining_micros!==void 0&&!Jr(e.remaining_micros)||e.delta_micros!==void 0&&!Jr(e.delta_micros)||e.reserved_micros!==void 0&&!Jr(e.reserved_micros))}function rt(e){Qt=e,ve=0,wn=0,ge=0,St=null,To=null,Eo=null,Yr=Promise.resolve()}function Zn(e){ge=Math.max(0,Math.floor(e))}function Ao(){return Qt}function Ro(e){if(!Qt)return null;let t=ve+wn;return ge>0&&t>ge&&(t=ge),{session_budget_id:Qt,cumulative_micros:Qp(t),nonce:(0,ko.randomUUID)(),idempotency_key:e||(0,ko.randomUUID)()}}function Io(e){if(!e)return null;let t;try{t=Buffer.from(e,"base64").toString("utf-8")}catch{return null}let n;try{n=JSON.parse(t)}catch{return null}if(!n||typeof n!="object")return null;let r=n;return rf(r)?(ve=Math.max(ve,r.cumulative),wn=0,St=r,r):null}function Ac(){return St}function $o(e){let t=Ec(e.cumulative_micros);ve=Math.max(ve,t),wn=0;let n={status:"accepted",session_id:e.session_budget_id,cumulative:ve,remaining:Math.max(0,ge-ve),delta:0,cumulative_micros:Tc(ve),remaining_micros:Tc(Math.max(0,ge-ve)),delta_micros:"0",nonce:e.nonce};return St=n,n}function Po(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,Ae.toCents)((0,Ae.micros)(n));if(!Number.isFinite(r)||r<0)return;To=t;let s=e,o=typeof s.session_id=="string"?s.session_id:Qt??"";St?(typeof s.remaining_micros=="string"&&/^\d+$/.test(s.remaining_micros)&&(St.remaining_micros=s.remaining_micros),typeof s.charged_micros=="string"&&/^\d+$/.test(s.charged_micros)&&(St.delta_micros=s.charged_micros)):St={session_id:o,cumulative:r,remaining:0,delta:0,nonce:typeof s.transaction_id=="string"?s.transaction_id:"",remaining_micros:typeof s.remaining_micros=="string"&&/^\d+$/.test(s.remaining_micros)?s.remaining_micros:void 0,delta_micros:typeof s.charged_micros=="string"&&/^\d+$/.test(s.charged_micros)?s.charged_micros:void 0}}function Rc(e){let t=e.receipt??null;Eo={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:Ec(e.voucher.cumulative_micros),estimatedCumulativeCents:Zr(),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 Ic(){return Eo}function $c(){return ve}function Pc(){return To}function Zr(){let e=ve+wn;return ge>0&&e>ge&&(e=ge),e}function Mc(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return Yr=Yr.then(()=>{wn+=t}),Yr}var sf=10,of=1,W=null,Oc=Promise.resolve();function Mo(e){let t=Oc.catch(()=>{}).then(e);return Oc=t.then(()=>{},()=>{}),t}var le=class extends Error{balanceCents;minRequiredCents;constructor(t,n){super(`Prepaid balance is $${(t/100).toFixed(2)}; at least $${(n/100).toFixed(2)} required to open a credit session. Top up via the buy_credits tool first.`),this.name="InsufficientBalanceError"}};async function Oo(e,t,n){return Mo(()=>Nc(e,t,n))}async function Nc(e,t,n){if(Wr(),W&&new Date(W.expiresAt).getTime()>Date.now())return Ao()!==W.budgetId&&(rt(W.budgetId),Zn(W.totalCents)),m.info("mcp-session:active-hit",{budgetId:W.budgetId,tool:n.toolName,remainingEstimatedCents:W.totalCents-Zr()}),{budgetId:W.budgetId,isFresh:!1,totalCents:W.totalCents,requestedCapCents:W.totalCents,appliedCapCents:W.totalCents,clampedReason:null};W&&(W=null,rt(null));let r=await e.getBalance();if(!r.success)throw new Error(`Could not read balance: ${r.error||"unknown error"}`);let s=n.sessionKind??"explicit",o=s==="one_shot"?of:sf,i=Math.max(o,Math.ceil(n.minRequiredCents??o));if(r.balanceCents<i)throw new le(r.balanceCents,i);let a=n.capCentsOverride??Aa(),l=Math.min(a,r.balanceCents),c=l<a?"balance":null,u=await t("session_create",l,"Visa CLI Session",`open credit-model session with $${(l/100).toFixed(2)} cap`,n.userContext),d=await e.createSessionBudget({total_cents:l,session_kind:s,...u?{attestation:u}:{}});if(!d.success||!d.budget){let g=d.error||"unknown error";throw new Error(`Failed to open credit session: ${g}`)}let f={budgetId:d.budget.id,expiresAt:d.budget.expiresAt,totalCents:d.budget.totalCents,createdAt:d.budget.createdAt};return W=f,rt(f.budgetId),Zn(f.totalCents),m.info("mcp-session:opened",{budgetId:f.budgetId,capCents:f.totalCents,requestedCapCents:a,clampedReason:c,sessionKind:s,expiresAt:f.expiresAt,tool:n.toolName}),{budgetId:f.budgetId,isFresh:!0,totalCents:f.totalCents,requestedCapCents:a,appliedCapCents:f.totalCents,clampedReason:c}}async function Lc(e,t,n){return Mo(async()=>{let s=wt()?await Dc(e):null,o=await Nc(e,t,n);return{budgetId:o.budgetId,totalCents:o.totalCents,closedPrevious:s,requestedCapCents:o.requestedCapCents,appliedCapCents:o.appliedCapCents,clampedReason:o.clampedReason}})}async function Dc(e){let n=wt()?.budgetId??Ao(),r=!1,s,o;if(n)try{let i=await e.closeSession(n);r=!!i?.success,typeof i?.finalCumulativeCents=="number"&&(s=i.finalCumulativeCents),typeof i?.finalCumulativeMicros=="string"&&(o=i.finalCumulativeMicros)}catch(i){m.warn("mcp-session:close-server-failed",{budgetId:n,error:i?.message||String(i)})}return Wr(),W=null,rt(null),{closedServerSide:r,budgetId:n,finalCumulativeCents:s,finalCumulativeMicros:o}}async function Xr(e){return Mo(()=>Dc(e))}function wt(){return Wr(),W?new Date(W.expiresAt).getTime()<=Date.now()?(W=null,rt(null),null):{budgetId:W.budgetId,totalCents:W.totalCents,lastReceiptCumulative:$c(),lastReceiptCumulativeMicros:Ac()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:Pc(),estimatedCumulative:Zr(),lastToolSpend:Ic(),expiresAt:W.expiresAt}:null}var jc=R(Yn()),Uc=10000n;function af(e){return e<=0n?0:Number((e+Uc-1n)/Uc)}function Vc(e){return af((0,jc.fromUsd)(e))}var Qr="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.",qc="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 Fc=Promise.resolve(),Bc=!1;function os(e){let t=Fc.catch(()=>{}).then(e);return Fc=t.then(()=>{},()=>{}),t}async function tl(e){let t=await Oo(I,Ke,{toolName:e.toolId,userContext:e.userContext}),n=Ro(e.idempotencyKey);if(!n)throw new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await ff(),s,o,i=async()=>I.shortcutWithSession(e.toolId,n,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);try{try{({data:s,voucherReceiptHeader:o}=await i())}catch(u){if(u instanceof Ot){let d=Math.min(Math.max(u.retryAfterSecs,0),5)*1e3;m.warn("mcp-session:lock-contended-retrying",{tool:e.toolId,retryAfterSecs:u.retryAfterSecs}),await new Promise(f=>setTimeout(f,d)),{data:s,voucherReceiptHeader:o}=await i()}else throw u}}catch(u){if(u instanceof un){if(m.warn("mcp-session:server-invalidated-budget",{code:u.code,budgetId:u.budgetId??t.budgetId,tool:e.toolId}),await Xr(I),process.env.VISA_REQUIRE_EXPLICIT_SESSION==="true")throw new Error(`Your session was closed by another process (${u.code}). Restart MCP or run start_session again.`);return Bc||(Bc=!0,console.error(`[visa-cli] Your session was closed by another process; reopened automatically as pay-as-you-go.
108
+ To require an explicit session approval instead, set VISA_REQUIRE_EXPLICIT_SESSION=true.`)),m.info("mcp-session:falling-back-to-payg",{code:u.code,tool:e.toolId}),nl(e)}throw u instanceof Ot?(m.warn("mcp-session:lock-contended-give-up",{tool:e.toolId}),new Error("Another paid call is currently in progress on this session. Wait a moment and try again.")):u}let a=Io(o)??(n?$o(n):null);if(Po(s?.receipt_v2),await Mc(e.estimatedAmountCents),Rc({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),sl(s))return s;let l=await rl();if(e.idempotencyKey&&ol(s,l,e.idempotencyKey))return s;let c=l?ns(l):null;return il(s,r,c)}function Fe(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function Do(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(Do).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${Do(r)}`).join(",")}}`}function cf(e,t,n,r){let s=ce.createHash("sha256").update(`${n}:${Do(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${s}`}function lf(e,t){return`${e}:${t}`}function uf(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 Hc(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,s=qe(r),o=s!==null?s.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=uf(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),l=i!=null?String(i):a;return{batch_id:e,item_id:lf(e,t),index:t,...l!==void 0?{transaction_id:l}:{},...a!==void 0?{ledger_id:a}:{},...o?{amountMicros:o,amount_micros:o,cost_micros:o}:{}}}async function nl(e){let t=Math.max(1,Math.ceil(e.estimatedAmountCents)),n=await I.getBalance();if(!n.success)throw new Error(`Could not read balance: ${n.error||"unknown error"}`);if(n.balanceCents<t)throw new le(n.balanceCents,t);let r=t,s=ns(n),o=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(r/100).toFixed(2)})`,i=await Ke("session_create",r,"Visa CLI Session",o,e.userContext),a=await I.createSessionBudget({total_cents:r,session_kind:"one_shot",...i?{attestation:i}:{}});if(!a.success||!a.budget)throw new Error(`Failed to open on-demand session: ${a.error||"unknown error"}`);let l=a.budget.id;rt(l),Zn(a.budget.totalCents),m.info("on-demand-session:opened",{budgetId:l,capCents:a.budget.totalCents,tool:e.toolId});try{let c=Ro(e.idempotencyKey);if(!c)throw new Error(`Internal: mintVoucher returned null after on-demand session-open ${l}`);let{data:u,voucherReceiptHeader:d}=await I.shortcutWithSession(e.toolId,c,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(Io(d)||$o(c),Po(u?.receipt_v2),sl(u))return u;let f=await rl();if(e.idempotencyKey&&ol(u,f,e.idempotencyKey))return u;let g=f?ns(f):null;return il(u,s,g)}finally{try{await I.closeSession(l)}catch(c){m.warn("on-demand-session:close-failed",{budgetId:l,error:c?.message||String(c)})}rt(null),m.info("on-demand-session:closed",{budgetId:l,tool:e.toolId})}}async function Ct(e){return os(async()=>wt()?tl(e):nl(e))}function is(){return we()}var I=new ye(()=>U.getSessionToken());function qe(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function ns(e){return qe(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function df(e){if(e<0n&&(e=0n),e>=1000000n){let r=(e+5000n)/10000n,s=r/100n,o=r%100n;return`$${s.toString()}.${o.toString().padStart(2,"0")}`}let t=e%1000000n;return t===0n?"$0.00":`$0.${t.toString().padStart(6,"0").replace(/0+$/,"")}`}function mf(e){let t=qe(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=qe(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=qe(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function es(e,t="INVALID_TOOL_PARAMS"){return{success:!1,error_code:t,code:t,error:e,message:e}}function pf(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 ff(){try{let e=await I.getBalance();return e.success?ns(e):null}catch{return null}}async function rl(){try{let e=await I.getBalance();return e.success?e:null}catch{return null}}function sl(e){if(!e||e.success===!1)return!1;let t=qe(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=qe(e.amountMicros??e.amount_micros??e.charged_micros),r=t??n;if(r===null||r<=0n)return!1;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,e.charged_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),!0}function ol(e,t,n){if(!e||e.success===!1||!t||!Array.isArray(t.ledger))return!1;let r=t.ledger.find(a=>a.idempotencyKey===n);if(!r)return!1;let s=qe(r.deltaMicros)??BigInt(r.deltaCents)*10000n,o=s<0n?-s:s;if(o<=0n)return!1;let i=o.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(o)/1e6),!0}function il(e,t,n){if(!e||e.success===!1||t===null||n===null)return e;let r=t-n;if(r<=0n)return e;let s=r.toString();return e.amountMicros??=s,e.amount_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),e}var gf="2.1.2",Ov=["","","You're ready to go! Try:","","Core:",'\u2022 "Show my account status" \u2192 get_status','\u2022 "List my enrolled cards" \u2192 get_cards','\u2022 "Show my paid tool use history" \u2192 transaction_history','\u2022 "Set my daily limit to $50" \u2192 update_spending_controls','\u2022 "Generate 3 variations in parallel" \u2192 batch',"","Category tools:",'\u2022 "Generate an image of a sunset over Tokyo" \u2192 generate_image','\u2022 "Make a 4-second video of a penguin juggling" \u2192 generate_video','\u2022 "Make a song about coding late at night" \u2192 generate_music','\u2022 "Create a sound effect for a checkout chime" \u2192 generate_audio','\u2022 "Create a 3D asset from this product sketch" \u2192 generate_3d','\u2022 "Upscale this product image" \u2192 upscale_image','\u2022 "Transcribe this meeting recording" \u2192 transcribe_audio','\u2022 "Run a reasoning model on this prompt" \u2192 run_llm',"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
109
+ `);function Be(e){if(!e||typeof e!="string"||Ta())return;let t=$n(e);if(!t)return;let n=As();if(n.headless){m.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`);return}let r=Ci(t,is());if(!r){m.info(`Browser auto-open skipped (non-internal host). URL: ${t}`);return}let s=Ti(r);if(!s){m.info(`No browser command for platform "${Xn.platform()}". URL: ${r}`);return}(0,el.execFile)(s.cmd,s.args,o=>{o&&m.warn(`Browser open failed: ${o.message}. URL: ${r}`)})}async function be(e){return Wn(I,e,pl)}var al="get_cards",cl="set_default_card";function hf(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 '${al}' to see enrolled cards and '${cl}' to switch, then retry the original request.`}function yf(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 '${al}' to see enrolled cards and '${cl}' to switch. Do not retry automatically.`}function He(e,t){let n=e.retryable?hf(e.code,e.retryAfter):yf(e.code,t.merchantName);return{success:!1,declined:!0,retryable:e.retryable,code:e.code,reason:e.reason,payment_error_class:e.paymentErrorClass,correlation_id:e.correlationId,transactionId:e.transactionId,retryAfter:e.retryAfter,merchantName:t.merchantName,amount:t.amount,message:e.message,agent_guidance:n}}var xn=null,_f=3e4;function ll(){xn=null}var xt=class extends Error{constructor(n){super(`${rs()} attestation is required for this action, but it is not available in this MCP process. `+Uo());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function as(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. `+Uo()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function vf(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:Qr,agent_guidance:qc}}function rs(){return process.platform==="darwin"?"Touch ID":"local biometric"}function Uo(){return process.platform==="darwin"?"Run the action from an interactive terminal with Touch ID access, or use reset with confirm:true to clear stale server biometric state through GitHub re-authentication.":"This platform cannot create Visa CLI Touch ID attestations. Use reset with confirm:true to clear stale server biometric state through GitHub re-authentication."}function cs(e){return typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0}async function bf(e){let t=Date.now();if(xn&&xn.expiresAt>t)return{required:xn.required,hasRegisteredKey:xn.hasRegisteredKey};try{let n=await I.getStatus(e),r=n.attestationRequired!==!1,s=cs(n);return xn={required:r,hasRegisteredKey:s,expiresAt:t+_f},{required:r,hasRegisteredKey:s}}catch{return{required:!0,hasRegisteredKey:!0}}}async function Ke(e,t,n,r,s,o){if(!o?.forceRequired){let i=await bf(s);if(!i.required){m.info("attestation:skipped-by-server-policy",{context:e});return}if(!i.hasRegisteredKey){m.info("attestation:skipped-no-registered-key",{context:e});return}}if(!te())throw m.warn("attestation:unavailable",{context:e}),new xt(e);m.info("attestation:attempt",{context:e,amount:t,merchant:n});try{let{nonce:i}=await I.getAttestationChallenge(),a=Buffer.from(JSON.stringify({nonce:i,amount:t,merchant:n,context:e})).toString("base64");m.info("touchid:prompt",{context:e,amount:t,merchant:n});let l=await Sn(a,r);return m.info("attestation:success",{context:e,amount:t,merchant:n}),{signature:l,nonce:i,amount:t,merchant:n}}catch(i){throw m.error("attestation:failure",{context:e,amount:t,merchant:n,error:i.message}),i}}var Kc="[dry-run] https://placeholder.visa-cli.dev/image.png",Sf=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"]),wf=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 xf(e,t){return t==="run_llm"||e.startsWith("or-")?"llm":t==="generate_image"||Sf.has(e)?"image":t==="generate_video"||wf.has(e)?"video":null}function Cf(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function kf(e){return e==="llm"?"OpenRouter":"fal.ai"}function Cn(e,t,n,r){let s={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:kf(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${Cf(n)}`;return{...s,content:i,data:{content:i,model:t,dry_run:!0}}}return{...s,urls:[Kc],data:{[e==="video"?"videoUrl":"imageUrl"]:Kc,metadata:{dry_run:!0}}}}async function No(e){let t=e.mode??"mock",n=t==="preflight"?"/v1/telemetry/preflight":"/v1/telemetry/dry-run",r=t==="preflight"?"preflight":null;try{await I.emitTelemetry([{id:ce.randomUUID(),timestamp:new Date().toISOString(),tool_name:e.toolName,user_prompt:e.userContext??"",tool_params:JSON.stringify(e.toolParams),result_success:!0,result_error:null,result_json:JSON.stringify(e.result),payment_rail:r,payment_amount:0,payment_currency:"USD",merchant_name:e.result.merchantName,transaction_id:e.result.transactionId,tx_hash:null,protocol:null,http_status:200,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",event_kind:"mcp_tool",endpoint:n,resolved_model:e.resolvedModel,session_budget_id:null}])}catch(s){m.warn("dry_run:telemetry_failed",{tool:e.toolName,error:s?.message||String(s),mode:t})}}var Tf="https://openrouter.ai/api/v1/chat/completions",Ef="openrouter/free",Af=50,Rf=15e3;function If(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 $f(e,t,n){let r=process.env.OPENROUTER_API_KEY;if(!r)return m.warn("preflight:no_openrouter_key_falling_back_to_mock",{tool:e}),{result:Cn("llm",e,t,n),degraded:!0,resolvedModel:null};let s=If(t),o;try{o=await Pt(Tf,{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:Ef,messages:[{role:"user",content:s}],max_tokens:Af}),timeoutMs:Rf})}catch(u){return m.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:Cn("llm",e,t,n),degraded:!0,resolvedModel:null}}if(!o.ok){let u=await o.text().catch(()=>"");return m.warn("preflight:openrouter_http_error_falling_back_to_mock",{tool:e,status:o.status,bodyExcerpt:u.slice(0,200)}),{result:Cn("llm",e,t,n),degraded:!0,resolvedModel:null}}let i;try{i=await o.json()}catch(u){return m.warn("preflight:openrouter_invalid_json_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:Cn("llm",e,t,n),degraded:!0,resolvedModel:null}}let a=typeof i?.choices?.[0]?.message?.content=="string"?i.choices[0].message.content:"",l=typeof i?.model=="string"?i.model:null;return{result:{success:!0,transactionId:`preflight:${n??e}`,amount:0,rail:"preflight",merchantName:"OpenRouter",dry_run:!0,preflight:!0,metadata:{dry_run:!0,preflight:!0,model_used:l},content:a,data:{content:a,model:l??e,dry_run:!0,preflight:!0}},degraded:!1,resolvedModel:l}}async function ls(e,t,n,r){let s=So();if(!s)return null;let o=xf(e,r);if(!o)return null;let i=Date.now();if(s==="mock"){let c=Cn(o,e,t,r);return await No({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:c,userContext:n,startedAt:i,mode:"mock"}),m.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:o,mode:s}),c}if(o!=="llm"){m.warn("preflight:not_supported_for_kind_falling_back_to_mock",{tool:e,kind:o});let c=Cn(o,e,t,r);return await No({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:c,userContext:n,startedAt:i,mode:"preflight"}),c}let{result:a,resolvedModel:l}=await $f(e,t,r);return await No({toolName:r??e,resolvedModel:l??(r&&r!==e?e:null),toolParams:t,result:a,userContext:n,startedAt:i,mode:"preflight"}),m.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:o,mode:s}),a}async function st(e,t,n){let r=await I.paymentPreview({tool:e,url:t},n);if(!r||!r.merchantName||r.amount===void 0||r.amount===null||r.amount<0)throw new Error("Could not determine payment amount and merchant. Try again.");if(!Number.isFinite(r.amount)||r.amount<0||r.amount>999999)throw new Error(`Invalid payment amount: ${r.amount}. Payment rejected for safety.`);return r}function ot(e){return Vc(e.amount)}function Pf(){return ss.join(Xn.homedir(),".visa-mcp","allium-results")}var Nv=16*1024,Lv=50*1024*1024;function Mf(){let e=Pf();try{if(!Re.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=Re.readdirSync(e),n=0,r=0;for(let s of t)try{let o=Re.statSync(ss.join(e,s));o.isFile()&&(n+=o.size,r++)}catch{}return{file_count:r,size_bytes:n,path:e}}catch(t){return m.warn("allium:disk_usage_error",{error:t.message}),{file_count:0,size_bytes:0,path:e}}}var Gc=3600*1e3,Lo=0;function Of(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function Qn(e){if(!Ea()&&!(Date.now()<Lo))try{if(!await U.getSessionToken())return;await I.feedSubmit({prompt:e.prompt,tool:e.tool,media_url:e.mediaUrl,media_type:e.mediaType,cost:e.cost,transaction_id:e.transactionId,auto:!0,...e.userContext&&{user_context:e.userContext}}),m.info("feed:submitted",{tool:e.tool,mediaType:e.mediaType,transactionId:e.transactionId})}catch(t){if(Of(t)){let n=Lo===0;Lo=Date.now()+Gc,n&&m.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:Gc});return}m.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function Nf(e,t){let n=(e.state||"").trim().toUpperCase(),r=(e.county||"").trim(),s=(e.start_date||"").trim(),o=(e.end_date||s).trim();if(!/^[A-Z]{2}$/.test(n))throw new Error('state must be a 2-letter US state code (e.g. "VA").');if(!r)throw new Error("county is required.");if(!/^\d{4}-\d{2}$/.test(s))throw new Error('start_date must be YYYY-MM (e.g. "2025-08").');if(o&&!/^\d{4}-\d{2}$/.test(o))throw new Error("end_date must be YYYY-MM.");let i="Visa SMI",a=.1,l=`Pay $0.10 to ${i} for SMI data (${n} / ${r})`;m.info("payment:attempt",{tool:"get_visa_smi",amount:a,merchant:i});try{return await be(async()=>{let c=await Ke("get_visa_smi",a,i,l),u=await I.getVisaSmi({state:n,county:r,start_date:s,end_date:o,attestation:c,idempotencyKey:ce.randomUUID()},t);return u.success?m.info("payment:success",{tool:"get_visa_smi",merchant:i,charged_cents:u.charged_cents}):m.warn("payment:declined",{tool:"get_visa_smi",merchant:i,message:u.error}),u})}catch(c){if(c instanceof oe)return m.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:c.code,retryable:c.retryable}),He(c,{amount:a,merchantName:i,description:"Visa SMI data"});throw m.error("payment:failure",{tool:"get_visa_smi",merchant:i,error:c.message}),c}}async function Lf(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 ls("generate_image_card",e,t);if(n)return n;let r=await st("generate_image_card",void 0,t),s=ce.randomUUID();m.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await be(async()=>{let o;try{o=await Ct({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:ot(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof le)return Fe(i);throw i}return m.info("payment:success",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>Be(i)),Qn({prompt:e.prompt,tool:"generate_image_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):m.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof oe)return m.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),He(o,r);throw m.error("payment:failure",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,error:o.message}),o}}async function Df(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 ls("generate_image_fast_card",e,t);if(n)return n;let r=await st("generate_image_fast_card",void 0,t),s=ce.randomUUID();m.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await be(async()=>{let o;try{o=await Ct({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:ot(r),userContext:t,timeoutMs:6e4,idempotencyKey:s})}catch(i){if(i instanceof le)return Fe(i);throw i}return m.info("payment:success",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>Be(i)),Qn({prompt:e.prompt,tool:"generate_image_fast_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):m.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof oe)return m.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),He(o,r);throw m.error("payment:failure",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,error:o.message}),o}}async function Uf(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 ls("generate_video_tempo_card",e,t);if(n)return n;let r=await st("generate_video_tempo_card",void 0,t),s=ce.randomUUID();m.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await be(async()=>{let o;try{o=await Ct({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:ot(r),userContext:t,timeoutMs:12e4,idempotencyKey:s})}catch(i){if(i instanceof le)return Fe(i);throw i}return m.info("payment:success",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(i=>Be(i)),Qn({prompt:e.prompt,tool:"generate_video_tempo_card",mediaUrl:o.urls[0],mediaType:"video",cost:o.amount??r.amount,transactionId:o.transactionId,userContext:t})):m.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof oe)return m.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:o.code,retryable:o.retryable}),He(o,r);throw m.error("payment:failure",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,error:o.message}),o}}async function jf(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 st("generate_music_tempo_card",void 0,t),r=ce.randomUUID();m.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await be(async()=>{let s;try{s=await Ct({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:ot(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(o){if(o instanceof le)return Fe(o);throw o}return m.info("payment:success",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),s.urls?.length&&s.status!=="processing"?(s.urls.forEach(o=>Be(o)),Qn({prompt:e.prompt,tool:"generate_music_tempo_card",mediaUrl:s.urls[0],mediaType:"audio",cost:s.amount??n.amount,transactionId:s.transactionId,userContext:t})):s.urls?.length&&s.status==="processing"?(s._preliminary_urls=s.urls,delete s.urls,m.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):m.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof oe)return m.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),He(s,n);throw m.error("payment:failure",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,error:s.message}),s}}async function Vf(e,t){let n=await st("check_music_status_tempo_card",void 0,t),r=ce.randomUUID();m.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await be(async()=>{let s;try{s=await Ct({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:ot(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof le)return Fe(o);throw o}return m.info("payment:success",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),s.urls?.length&&s.urls.forEach(o=>Be(o)),s})}catch(s){if(s instanceof oe)return m.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),He(s,n);throw m.error("payment:failure",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,error:s.message}),s}}async function qf(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 st("query_onchain_prices",void 0,t),r=ce.randomUUID();m.info("payment:attempt",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName});try{return await be(async()=>{let s;try{s=await Ct({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:ot(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(o){if(o instanceof le)return Fe(o);throw o}if(m.info("payment:success",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,mode:"session"}),Array.isArray(s?.data))s.data=s.data.map(o=>{if("mint"in o&&!("address"in o)){let{mint:i,...a}=o;return{address:i,...a}}return o});else if(s&&"mint"in s&&!("address"in s)){let{mint:o,...i}=s;return{address:o,...i}}return s})}catch(s){if(s instanceof oe)return m.warn("payment:declined",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,code:s.code,retryable:s.retryable}),He(s,n);throw m.error("payment:failure",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,error:s.message}),s}}var Ff=["generate_music_tempo_card"],zc=10,Wc=5,Jc=new Map;function Yc(e){let t=Jc.get(e);if(t!==void 0)return t;let r=Gn(e)?.isAsync===!0||Ff.includes(e);return Jc.set(e,r),r}var Bf=36e4,Hf=18e4,Kf=15e3,Gf=12e4,zf=2e3;function Zc(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}async function Wf(e,t){let n;if(e.requests?.some(C=>C.tool||C.tool_id)&&e.requests)n=e.requests.map(C=>{let T=C.tool||C.tool_id||e.tool;if(!T)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let q=bo(T,C.tier||e.tier,C.prompt??t),{tool:z,tool_id:F,tier:it,params:ee,...ue}=C,at=ee&&typeof ee=="object"?{...ee,...ue}:ue;return{resolvedTool:q,params:at}});else if(e.tool){let C=bo(e.tool,e.tier,e.params?.prompt??t);n=(e.requests||(e.count&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(q=>({resolvedTool:C,params:q}))}else return Zc("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return Zc("BATCH_EMPTY","Batch requires at least one item.");if(n.length>zc)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${zc} items. Please split into smaller batches.`};if([...new Set(n.map(C=>C.resolvedTool))].some(Yc)&&n.length>Wc)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${Wc} items. Please use multiple batches for more.`};let i=[...new Set(n.map(C=>C.resolvedTool))],a=i.length===1,l={};for(let C of i)l[C]=await st(C,void 0,t);let c=0;for(let C of n)c+=l[C.resolvedTool].amount;let u=[...new Set(Object.values(l).map(C=>C.merchantName))].join(", "),d=a?i[0]:"mixed";m.info("payment:attempt",{tool:"batch",batchTool:d,count:n.length,totalAmount:c,merchant:u,heterogeneous:!a});let f=n.some(C=>Yc(C.resolvedTool)),g=n.some(C=>C.resolvedTool.startsWith("or-")||C.resolvedTool==="run_llm"||C.resolvedTool==="execute_tool"),w=f?Bf:g?Hf+n.length*Kf:Gf+n.length*zf,y=ce.randomUUID(),k=[],O=0,N=0n;return os(async()=>{let C=!wt();if(C)try{let T=Math.max(1,Math.ceil(c*100));await Oo(I,Ke,{toolName:"batch",userContext:t,sessionKind:"one_shot",minRequiredCents:T,capCentsOverride:T})}catch(T){return T instanceof le?Fe(T):(m.warn("payment:batch-prewarm-failed",{batchTool:d,count:n.length,error:T?.message||String(T)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:T?.message||"Failed to authenticate batch session",tool:d,count:n.length,failedCount:n.length,results:[]})}try{for(let ee=0;ee<n.length;ee+=1){let ue=n[ee],at=l[ue.resolvedTool];try{let re=await tl({toolId:ue.resolvedTool,toolParams:ue.params,estimatedAmountCents:ot(at),userContext:t,metaTool:"batch",timeoutMs:w,idempotencyKey:cf(y,ee,ue.resolvedTool,ue.params)});if(k.push({success:re?.success!==!1,tool:ue.resolvedTool,...re,...Hc(y,ee,re)}),re?.success!==!1){let Rn=qe(re?.amountMicros??re?.amount_micros),oi=typeof re?.amount=="number"?re.amount:at.amount;Rn!==null&&Rn>0n?N+=Rn:N+=BigInt(Math.round(oi*1e6)),O+=oi}re?.urls&&re.urls.forEach(Rn=>Be(Rn))}catch(re){if(re instanceof le&&k.length===0)return Fe(re);m.warn("payment:batch-item-failed",{tool:ue.resolvedTool,index:ee,error:re?.message||String(re)}),k.push({success:!1,tool:ue.resolvedTool,...Hc(y,ee),error:re?.message||String(re)})}}let T=k.filter(ee=>ee?.success===!1).length,q=k.length-T,z=k.flatMap(ee=>Array.isArray(ee?.urls)?ee.urls:[]),F=N>0n?Number(N)/1e6:Math.round((O+Number.EPSILON)*100)/100,it=q===0?"failure":T===0?"success":"partial";return m.info("payment:success",{tool:"batch",batchTool:d,count:n.length,totalAmount:c,totalCharged:F,merchant:u,successCount:q,failedCount:T,outcome:it,mode:"session",batchId:y}),{success:q>0,outcome:it,batch_id:y,tool:a?i[0]:d,count:n.length,successCount:q,failedCount:T,totalCharged:F,...N>0n?{totalChargedMicros:N.toString(),amountMicros:N.toString(),amount_micros:N.toString()}:{},merchantName:u,results:k,...z.length?{urls:z}:{}}}catch(T){if(T instanceof oe)return m.warn("payment:declined",{tool:"batch",batchTool:d,count:n.length,totalAmount:c,merchant:u,code:T.code,retryable:T.retryable}),He(T,{amount:c,merchantName:u});throw m.error("payment:failure",{tool:"batch",batchTool:d,count:n.length,totalAmount:c,merchant:u,error:T.message}),T}finally{if(C){let T=await Xr(I);m.info("batch-session:closed",{budgetId:T.budgetId,closedServerSide:T.closedServerSide})}}})}function Jf(){let e=!1,t;try{let r=ss.join(Xn.homedir(),".claude","settings.json");if(Re.existsSync(r)){let s=JSON.parse(Re.readFileSync(r,"utf-8")),o=typeof s.statusLine=="object"?s.statusLine.command:"";e=It(o)}}catch{}let n=br();return n||(t="visa-cli config hud enable"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function Yf(e){let[t,n]=await Promise.all([I.getStatus(e),I.getBalance().catch(o=>(m.warn("get_status:balance_fetch_failed",{error:o?.message||String(o)}),null))]);typeof t?.dailyRemaining=="number"&&(t.dailyRemaining=Math.round(t.dailyRemaining*100)/100);let r=Mf();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=Jf(),t.version=gf,Array.isArray(t.cards)&&(t.cards=t.cards.map(o=>({...o,displayName:jo(o)})),t.cardIdGuidance="cardId values are opaque tool parameters only; refer to cards by brand and last four digits."),n&&n.success&&(t.balanceCents=n.balanceCents,t.amountUsd=n.amountUsd);let s=wt();if(t.sessionMode=!!s,s){let o=Math.max(0,s.totalCents-s.estimatedCumulative);t.activeSession={budgetId:s.budgetId,capCents:s.totalCents,capUsd:s.totalCents/100,lastReceiptCumulativeCents:s.lastReceiptCumulative,estimatedCumulativeCents:s.estimatedCumulative,spentCents:s.estimatedCumulative,spentUsd:s.estimatedCumulative/100,estimatedRemainingCents:o,estimatedRemainingUsd:o/100,...s.lastToolSpend?{lastToolSpend:{toolName:s.lastToolSpend.toolName,resolvedToolId:s.lastToolSpend.resolvedToolId,estimatedAmountCents:s.lastToolSpend.estimatedAmountCents,estimatedAmountUsd:s.lastToolSpend.estimatedAmountCents/100,voucherCumulativeCents:s.lastToolSpend.voucherCumulativeCents,estimatedCumulativeCents:s.lastToolSpend.estimatedCumulativeCents,receiptDeltaCents:s.lastToolSpend.receiptDeltaCents,receiptCumulativeCents:s.lastToolSpend.receiptCumulativeCents,receiptRemainingCents:s.lastToolSpend.receiptRemainingCents,recordedAt:s.lastToolSpend.recordedAt}}:{},expiresAt:s.expiresAt}}return t}function jo(e){let t=typeof e.brand=="string"&&e.brand.trim().length>0?e.brand.trim():"card",n=t.charAt(0).toUpperCase()+t.slice(1).toLowerCase(),r=typeof e.last4=="string"&&e.last4.trim().length>0?e.last4.trim():"unknown",s=e.isDefault===!0?" (default)":"";return`${n} ending in ${r}${s}`}async function ul(e,t){try{let r=((await I.getStatus(t)).cards||[]).find(s=>s?.id===e);if(r)return jo(r)}catch(n){m.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function Zf(e){let n=(await I.getStatus(e)).cards||[];return n.length===0?{cards:[],message:"No cards enrolled. Use the add_card tool to add a payment card."}:n.some(s=>!Number.isInteger(s?.id)||s.id<=0)?{success:!1,cards:[],message:"Card action handles are unavailable right now, so remove_card and set_default_card are temporarily disabled."}:{cards:n.map(s=>({...s,displayName:jo(s)})),message:"Use cardId only as an opaque tool parameter. When speaking to the user, refer to cards by brand and last four digits, not by card id."}}async function Xf(e,t){return await I.getTransactions({limit:e.limit,offset:e.offset},t)}async function Qf(e,t){return await I.feedback(e.message,e.transaction_id,t)}var eg=100;async function tg(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return en("MISSING_CONFIRMATION","Please confirm by setting confirm: true to charge your enrolled card for credits.");if(!e.amount||!Number.isFinite(e.amount)||e.amount<=0)return{success:!1,error:"amount must be a positive number in USD (e.g. 5.00)"};let n=Math.round(e.amount*100);if(n<eg)return{success:!1,error:"Minimum top-up is $1.00"};let r=ce.randomUUID();m.info("buy_credits:attempt",{amountCents:n});try{return await be(async()=>{let s=await Ke("balance-topup",e.amount,"Visa CLI Balance",`top up balance with $${e.amount.toFixed(2)}`,t,{forceRequired:!0}),o=await I.topupBalance({amount_cents:n,idempotency_key:r,attestation:s});if(o.success){m.info("buy_credits:success",{amountCents:n,balanceCents:o.balanceCents});let i=((o.balanceCents??0)/100).toFixed(2),a=(n/100).toFixed(2);return{...o,amount:n/100,amountMicros:String(n*1e4),merchantName:"Visa CLI Balance",message:`Added $${a} \u2014 balance is now $${i}`}}return m.warn("buy_credits:failed",{amountCents:n,error:o.error}),o})}catch(s){if(s instanceof xt)return vf();throw m.error("buy_credits:failure",{amountCents:n,error:s.message}),s}}function en(e,t){return{success:!1,error:t,code:e,message:t}}async function ng(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return en("MISSING_CONFIRMATION","Please confirm by setting confirm: true to update spending controls.");if(e.maxTransactionAmount!==void 0&&(typeof e.maxTransactionAmount!="number"||!Number.isFinite(e.maxTransactionAmount)||e.maxTransactionAmount<.01||e.maxTransactionAmount>100))return en("INVALID_VALUE","maxTransactionAmount must be between $0.01 and $100");if(e.dailyLimit!==void 0&&(typeof e.dailyLimit!="number"||!Number.isFinite(e.dailyLimit)||e.dailyLimit<1||e.dailyLimit>100))return en("INVALID_VALUE","dailyLimit must be between $1 and $100");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return en("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");m.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await be(async()=>{let n=await Ke("spending-controls",0,"","update spending controls"),r=await I.updateSpendingControls({maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit,confirm:!0,attestation:n},t);return m.info("spending_controls:success",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit}),r})}catch(n){if(m.error("spending_controls:failure",{error:n.message}),n instanceof xt)return as(n,"update_spending_controls");if(String(n?.message||n).includes("Attestation required"))return en("ATTESTATION_REQUIRED","Changing spending controls requires local attestation, even when payment biometric prompts are disabled.");throw n}}async function rg(e){let t=await Jn({api:I,includeDev:!!e.includeDev});return{config:t.entries.map(n=>({key:n.key,value:n.value,source:n.source,hint:n.hint})),statusError:t.statusError}}async function sg(e){if(!e.key||typeof e.key!="string")return{success:!1,error:"key is required. Call config_list first to see available keys."};if(e.value===void 0)return{success:!1,error:"value is required. Use config_unset to remove a setting."};m.info("config:set",{key:e.key});try{let t=$r(e.key,e.value);return m.info("config:set:success",{key:t.key,requiresRestart:t.requiresRestart}),{success:!0,key:t.key,value:t.value,requiresRestart:t.requiresRestart,path:t.path,message:t.requiresRestart?`Saved ${t.key}. Restart Claude Code for the change to take effect.`:`Saved ${t.key}.`}}catch(t){let n=t instanceof Ye?"UNKNOWN_KEY":t instanceof Ze?"SERVER_CONTROLLED":t instanceof pt?"RETIRED_KEY":"INVALID_VALUE";return m.warn("config:set:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(gt).sort()}}}async function og(e){if(!e.key||typeof e.key!="string")return{success:!1,error:"key is required. Call config_list first to see which keys are currently set via settings.json."};m.info("config:unset",{key:e.key});try{let t=Pr(e.key);return m.info("config:unset:success",{key:t.key,removed:t.removed}),{success:!0,key:t.key,removed:t.removed,requiresRestart:t.requiresRestart,path:t.path,message:t.removed?t.requiresRestart?`Removed ${t.key}. Restart Claude Code for the change to take effect.`:`Removed ${t.key}.`:`${t.key} was not set in settings.json \u2014 nothing to remove.`}}catch(t){let n=t instanceof Ye?"UNKNOWN_KEY":t instanceof Ze?"SERVER_CONTROLLED":t instanceof pt?"RETIRED_KEY":"INVALID_VALUE";return m.warn("config:unset:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(gt).sort()}}}async function ig(e){let t=await I.getStatus(e),n=t.attestationRequired!==!1,r=cs(t),s=te(),o=n?r?s?`${rs()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${rs()} is not available in this process. ${Uo()}`:"Biometric attestation is enabled on the account, but no attestation key is registered. Payments on this device proceed without a biometric signature; processor declines such as INVALID_OR_MISSING_CONFIG are card/account configuration issues, not something biometric setup fixes.":"Biometric attestation is NOT required for payments. Payments will proceed without biometric confirmation.";return{required:n,hasAttestationKey:!!t.hasAttestationKey,hasTelegramAttestationKey:!!t.hasTelegramAttestationKey,hasAnyAttestationKey:r,touchIdAvailable:s,platform:process.platform,effectiveRequiredOnThisDevice:n&&r&&s,canDisableFromThisDevice:!n||!r||s,message:o}}async function ag(e){m.info("biometric:on");let t=await I.setBiometricPreference({required:!0},e);return t.success?(ll(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:t.error||"unknown error"}}async function cg(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return en("MISSING_CONFIRMATION","Please confirm by setting confirm: true. Disabling Touch ID is a security downgrade \u2014 the user will be prompted for one final Touch ID confirmation before the change takes effect.");m.info("biometric:off");try{return await be(async()=>{let n=await I.getStatus(t),r;if(cs(n)&&(r=await Ke("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${rs()} confirmation required to disable \u2014 not available on this device.`);let s=await I.setBiometricPreference({required:!1,attestation:r},t);if(!s.success)throw new Error(s.error||"unknown error");return ll(),{success:!0,required:!1,message:"Touch ID is no longer required for payments."}})}catch(n){if(m.error("biometric:off:failure",{error:n.message}),n instanceof xt)return as(n,"biometric_off");throw n}}var Xc=3e4,lg=3e5;async function dl(e,t,n="login"){let r=ce.randomUUID(),s=`${e}${e.includes("?")?"&":"?"}state=${r}`;return Be(s),ml(r,t,n)}async function ml(e,t,n="login"){let r=Date.now()+lg;for(;Date.now()<r;)try{let o=await fetch(`${is()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:Xc,...t&&{user_context:t}}),signal:AbortSignal.timeout(Xc+5e3)});if(!o.ok){await dt(o,a=>{m.warn("auth_status:retry_after_http_error",{status:o.status,delayMs:a})});continue}let i=await o.json();if(i.status==="pending")continue;if(i.status==="expired")return{success:!1,message:"Session expired. Please try again."};if(i.status==="error")return{success:!1,message:i.error||"Authentication failed. Please try again."};if(i.status==="complete"){if(n==="attestation-recovery"||i.attestationCleared)return m.info("auth:attestation_recovery_complete",{user:i.user||""}),{success:!0,message:"Server-side biometric state cleared. Run visa-cli setup to register a fresh key before reenabling Touch ID."};let a=i.welcomeBonusCents??0,l=wc(a);if(i.sessionToken){await U.saveSessionToken(i.sessionToken);let u=i.user||"",d=i.last4||"****";return m.info("auth:login_complete",{user:u,last4:d,bonusCents:a}),{success:!0,message:`Signed in as ${u}. Card ending in ${d} enrolled and ready for payments.`,...l||{}}}let c=i.last4||"****";return m.info("auth:card_added",{last4:c,bonusCents:a}),{success:!0,message:`Card ending in ${c} enrolled and ready for payments.`,...l||{}}}}catch{await dt(void 0,o=>{m.warn("auth_status:retry_after_network_error",{delayMs:o})})}return{success:!1,message:n==="enrollment"?"Card enrollment timed out. Please try again.":n==="attestation-recovery"?"Biometric reset timed out. Please try reset again.":"Login timed out. Please try again."}}async function pl(e){let t=ce.randomUUID(),n;try{n=await I.startAttestationRecovery(t,e)}catch(r){return{success:!1,message:`Could not start biometric reset: ${r?.message||"unknown error"}`}}return!n.success||!n.recoveryUrl?{success:!1,message:n.error||"Could not start biometric reset. Please try again."}:(Be(n.recoveryUrl),ml(t,e,"attestation-recovery"))}async function ug(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to remove this card."};let n=e.cardId;if(!Number.isInteger(n)||n<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to get the opaque cardId for the card you want to remove."};m.info("cards:remove_attempt",{cardId:n});let r=`remove-card:${n}`,s=`remove ${await ul(n,t)}`;try{return await be(async()=>{let o=await Ke(r,0,"",s,t,{forceRequired:!0}),i=await I.removeCard(n,{attestation:o},t);return m.info("cards:remove_success",{cardId:n,promotedId:i?.promotedId??null}),i})}catch(o){if(m.error("cards:remove_failure",{cardId:n,error:o.message}),o instanceof xt)return as(o,"remove_card");throw o}}async function dg(e,t){let n=e.cardId;if(!Number.isInteger(n)||n<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to get the opaque cardId for the card you want to make default."};m.info("cards:set_default_attempt",{cardId:n});let r=`set-default-card:${n}`,s=`set ${await ul(n,t)} as default`;try{return await be(async()=>{let o=await Ke(r,0,"",s,t,{forceRequired:!0}),i=await I.setDefaultCard(n,{attestation:o},t);return m.info("cards:set_default_success",{cardId:n}),i})}catch(o){if(m.error("cards:set_default_failure",{cardId:n,error:o.message}),o instanceof xt)return as(o,"set_default_card");throw o}}async function mg(e){return m.info("auth:login_attempt"),dl(`${is()}/login`,e)}function pg(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 fg(e={},t){let n;try{n=pg(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return os(async()=>{let r=await Lc(I,Ke,{toolName:"start_session",userContext:t,capCentsOverride:n});m.info("session:started",{budgetId:r.budgetId,totalCents:r.totalCents,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious});let s=(r.appliedCapCents/100).toFixed(2),o=(r.requestedCapCents/100).toFixed(2),i=`Session started with a $${s} cap. Paid calls will use this approval window until you close it, it expires, or this MCP process restarts.`,a=r.clampedReason==="balance"?`${i} Note: requested cap of $${o} was clamped to your prepaid balance of $${s}. Run buy_credits to top up if you need a larger session.`:i;return{success:!0,budgetId:r.budgetId,totalCents:r.totalCents,amountUsd:r.totalCents/100,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious,message:a}})}async function gg(){let e=wt();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 hg(){return os(async()=>{let e=wt();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 Xr(I);m.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=mf(e),r=qe(t.finalCumulativeMicros),s=r??(typeof t.finalCumulativeCents=="number"?BigInt(Math.max(0,t.finalCumulativeCents))*10000n:n.micros),o=Number(s/10000n);return m.info("session:closed:final-spend",{budgetId:t.budgetId,closedServerSide:t.closedServerSide,finalSpendMicros:s.toString(),finalSpendCents:o,finalSpendSource:r!==null?"server.finalCumulativeMicros":typeof t.finalCumulativeCents=="number"?"server.finalCumulativeCents":n.source,totalCents:e.totalCents}),{success:!0,closed:!0,closedServerSide:t.closedServerSide,budgetId:t.budgetId,finalEstimatedCumulativeCents:o,finalEstimatedCumulativeMicros:s.toString(),totalCents:e.totalCents,message:t.closedServerSide?`Explicit approval window closed. Spent ${df(s)} of $${(e.totalCents/100).toFixed(2)} cap. Future paid calls are pay-as-you-go until you start a new explicit approval window.`:"Explicit approval window cleared locally; server-side close call did not succeed (likely already closed). Future paid calls are pay-as-you-go until you start a new explicit approval window."}})}async function yg(e){if(m.info("auth:add_card_attempt"),!await U.getSessionToken())return{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."};let{code:n}=await I.createEnrollCode();return dl(`${is()}/enroll-card?code=${encodeURIComponent(n)}`,e,"enrollment")}async function _g(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};m.info("reset:attempt");let n=!1;try{let r=await I.getStatus(t);if(r&&cs(r)){let s=await pl(t);if(!s.success)return s;n=!0}}catch(r){let s=r?.message||"unknown error";if(!/not logged in|session.*expired|no local credentials/i.test(s))return{success:!1,message:`Could not check server biometric state: ${s}`};m.warn("reset:server_attestation_status_unavailable",{error:s})}try{await I.logout(void 0,t)}catch{}if(await U.clearAll(),te())try{await Hr()}catch{}return m.info("reset:success"),{success:!0,message:n?"Device reset. Server-side biometric state and local credentials have been cleared. Use the login tool or visa-cli setup to re-enroll.":"Device reset. Local credentials and keys have been removed. Use the login tool or visa-cli setup to re-enroll."}}async function vg(e){let t=e.query?.trim()||void 0,n=e.category?.trim()||void 0,r=!t&&!n;m.info("catalog:discover",{query:t,category:n,browseAll:r});try{let o=(await I.catalogSearch(t,n)).tools||[];if(o.length===0)return{content:[{type:"text",text:r?"The tool catalog is currently empty.":`No tools found for "${t||n}". Try a different search term.`}]};if(r){let a={};for(let c of o){let u=c.category||"other";(a[u]??=[]).push(c)}let l=Object.keys(a).sort().map(c=>{let u=a[c].map((f,g)=>`${g+1}. **${f.name}** (${f.id})
110
110
  ${f.description}
111
- Provider: ${f.provider} | Price: ${Yc(f)}
111
+ Provider: ${f.provider} | Price: ${Qc(f)}
112
112
  Params: ${Object.keys(f.inputSchema?.properties||f.inputSchema||{}).join(", ")||"none"}`).join(`
113
113
 
114
114
  `);return`## ${c.length<=3?c.toUpperCase():c.charAt(0).toUpperCase()+c.slice(1)}
@@ -121,47 +121,47 @@ ${l}
121
121
 
122
122
  Use execute_tool with the tool id and required params to run any of these.`}],_tools:o}}let i=o.map((a,l)=>`${l+1}. **${a.name}** (${a.id})
123
123
  ${a.description}
124
- Provider: ${a.provider} | Category: ${a.category} | Price: ${Yc(a)}
124
+ Provider: ${a.provider} | Category: ${a.category} | Price: ${Qc(a)}
125
125
  Params: ${Object.keys(a.inputSchema?.properties||a.inputSchema||{}).join(", ")||"none"}`).join(`
126
126
 
127
127
  `);return m.info("catalog:discovered",{count:o.length}),{content:[{type:"text",text:`Found ${o.length} tool(s):
128
128
 
129
129
  ${i}
130
130
 
131
- Use execute_tool with the tool id and required params to run any of these.`}],_tools:o}}catch(s){throw m.error("catalog:discover:error",{error:s.message}),new Error(`Failed to search tool catalog: ${s.message}`)}}function Yc(e){return e.priceDisplay??`$${(e.priceCents/100).toFixed(2)}`}function yg(e,t){return t==="image"||t==="video"||t==="audio"?t:e?.match(/\.(mp4|webm|mov)/)?"video":"image"}function Qr(e,t){return Array.isArray(e.type)?e.type.includes(t):e.type===t}function _g(e,t,n){let r=e.inputSchema;if(!r||r.type!=="object")return null;let s=r.properties??{},o=n??e.id;for(let a of Object.keys(t))if(!Object.prototype.hasOwnProperty.call(s,a)){let l=Object.keys(s),c=l.length>0?` Expected: ${l.join(", ")}.`:"";return`Unknown parameter "${a}" for ${o}.${c}`}let i=(r.required??[]).filter(a=>!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0);if(i.length>1)return`${i.join(", ")} are required for ${o}.`;for(let a of r.required??[]){if(!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0)return`${a} is required for ${o}.`;if(t[a]===null)return`${a} cannot be null.`;if(typeof t[a]=="string"&&t[a].trim()==="")return`${a} cannot be empty.`}for(let[a,l]of Object.entries(t)){let c=s[a];if(!(!c||l===void 0||l===null)){if(c.enum&&!c.enum.includes(l))return`${a} must be one of: ${c.enum.map(String).join(", ")}.`;if(Qr(c,"integer")){if(typeof l!="number"||!Number.isInteger(l))return`${a} must be an integer.`}else if(Qr(c,"number")){if(typeof l!="number"||!Number.isFinite(l))return`${a} must be a number.`}else if(Qr(c,"string")){if(typeof l!="string")return`${a} must be a string.`;if(l.trim()==="")return`${a} cannot be empty.`;if(c.minLength!==void 0&&l.length<c.minLength)return`${a} is too short.`;if(c.maxLength!==void 0&&l.length>c.maxLength)return`${a} is too long.`}else if(Qr(c,"boolean")&&typeof l!="boolean")return`${a} must be a boolean.`;if(typeof l=="number"){if(c.minimum!==void 0&&l<c.minimum)return`${a} must be at least ${c.minimum}.`;if(c.maximum!==void 0&&l>c.maximum)return`${a} must be at most ${c.maximum}.`}}}return null}async function vg(e){let t=Kn(e);if(t)return t;try{return await I.catalogTool(e)}catch(n){return m.warn("catalog:resolve:error",{tool:e,error:n?.message||String(n)}),null}}async function bg(e,t,n="execute_tool"){let{tool_id:r,params:s,...o}=e,i=s||o;if(!r)return Xr("tool_id is required. Use discover_tools first to find available tools.","MISSING_TOOL_ID");m.info("catalog:execute",{tool:r,metaTool:n});let a=await vg(r);if(!a)return Xr(`Unknown tool: '${r}'. Use discover_tools first to find available tools.`,"UNKNOWN_TOOL");if(a.deprecated){let g=a.replacementTool?` Use '${a.replacementTool}' instead.`:"";return Xr(`Tool '${r}' is deprecated and is no longer available for new paid calls.${g}`,"DEPRECATED_TOOL")}let c=_g(a,i,n&&n!=="execute_tool"?n:void 0);if(c)return m.info("catalog:execute:validation_failed",{tool:r,metaTool:n,error:c}),Xr(c);let u=await as(r,i,t,n);if(u)return u;if(a.executionMode==="free_authenticated"||a.accessMode==="free"){m.info("catalog:execute:free",{tool:r,metaTool:n});let g=await I.shortcut(r,i,6e4,t,n);return g&&typeof g=="object"&&!Array.isArray(g)&&g.merchantName==null&&(g.merchantName=a.name??r),g}let d=await nt(r,void 0,t),f=ce.randomUUID();m.info("payment:attempt",{tool:r,amount:d.amount,merchant:d.merchantName});try{return await be(async()=>{let g;try{g=await xt({toolId:r,toolParams:i,estimatedAmountCents:rt(d),userContext:t,metaTool:n,timeoutMs:12e4,idempotencyKey:f})}catch(w){if(w instanceof le)return Ve(w);throw w}if(m.info("payment:success",{tool:r,amount:d.amount,merchant:d.merchantName,mode:"session"}),g&&typeof g=="object"&&!Array.isArray(g)&&g.merchantName==null&&(g.merchantName=a?.name??r),g.urls?.length){g.urls.forEach(y=>Fe(y));let w=yg(g.urls[0],g.mediaType);Zn({prompt:i.prompt||`${r} execution`,tool:r,mediaUrl:g.urls[0],mediaType:w,cost:g.amount??d.amount,transactionId:g.transactionId,userContext:t})}return g})}catch(g){return g instanceof oe?(m.warn("payment:declined",{tool:r,amount:d.amount,merchant:d.merchantName,code:g.code,retryable:g.retryable}),Be(g,d)):(m.error("payment:failure",{tool:r,amount:d.amount,merchant:d.merchantName,error:g.message}),uf({toolId:r,surface:n,merchantName:d.merchantName,amount:d.amount,message:g?.message||"Tool execution failed."}))}}var je=class{static async getStatus(t){return zf(t)}static async getVisaSmi(t,n){return Pf(t,n)}static async getCards(t){return Wf(t)}static async transactionHistory(t,n){return Jf(t||{},n)}static async feedback(t,n){return Yf(t,n)}static async updateSpendingControls(t,n){return Qf(t,n)}static async configList(t){return eg(t||{})}static async configSet(t){return tg(t||{})}static async configUnset(t){return ng(t||{})}static async biometricStatus(t){return rg(t)}static async biometricOn(t){return sg(t)}static async biometricOff(t,n){return og(t,n)}static async reset(t,n){return gg(t,n)}static async login(t){return lg(t)}static async closeSession(t){return pg()}static async startSession(t,n){return dg(t||{},n)}static async getSessionStatus(t){return mg()}static async addCard(t){return fg(t)}static async removeCard(t,n){return ag(t,n)}static async setDefaultCard(t,n){return cg(t,n)}static async buyCredits(t,n){return Xf(t,n)}static async batch(t,n){return Kf(t,n)}static async discoverTools(t){return hg(t)}static async executeTool(t,n,r="execute_tool"){return bg(t,n,r)}static async shortcut(t,n,r){switch(t){case"generate_image_card":return Mf(n,r);case"generate_image_fast_card":return Of(n,r);case"generate_video_tempo_card":return Nf(n,r);case"generate_music_tempo_card":return Lf(n,r);case"check_music_status_tempo_card":return Df(n,r);case"query_onchain_prices_card":return Uf(n,r);default:{let s=await nt(t,void 0,r);m.info("payment:attempt",{tool:t});try{let o=await xt({toolId:t,toolParams:n,estimatedAmountCents:rt(s),userContext:r,timeoutMs:6e4});return m.info("payment:success",{tool:t,mode:"session"}),o.urls?.length&&o.urls.forEach(i=>Fe(i)),o}catch(o){if(o instanceof le)return Ve(o);if(o instanceof oe)return m.warn("payment:declined",{tool:t,code:o.code,retryable:o.retryable}),Be(o,s);throw m.error("payment:failure",{tool:t,error:o.message}),o}}}}static async submitFeedback(t,n,r){m.info("feedback:submit",{length:t.length,transactionId:n,hasContext:!!r});try{let s=await I.submitFeedback(t,n,r);return m.info("feedback:submitted",{transactionId:n}),s}catch(s){let o=s instanceof Error?s.message:"Unknown error";throw m.error("feedback:error",{error:o,transactionId:n}),s}}static async getFeedback(t,n){m.info("feedback:list",{limit:t||20});try{let r=await I.getFeedback(t,n);return m.info("feedback:listed",{count:r?.feedback?.length||0}),r}catch(r){let s=r instanceof Error?r.message:"Unknown error";throw m.error("feedback:error",{error:s}),r}}};function dl(e,t=process.stderr){if(Oe()||!e?.updateAvailable)return!1;let{latestVersion:n}=e.updateAvailable;if(!n)return!1;let r=`Update available: v${n}. Run: ${rn(n)}`;return t.write(`
131
+ Use execute_tool with the tool id and required params to run any of these.`}],_tools:o}}catch(s){throw m.error("catalog:discover:error",{error:s.message}),new Error(`Failed to search tool catalog: ${s.message}`)}}function Qc(e){return e.priceDisplay??`$${(e.priceCents/100).toFixed(2)}`}function bg(e,t){return t==="image"||t==="video"||t==="audio"?t:e?.match(/\.(mp4|webm|mov)/)?"video":"image"}function ts(e,t){return Array.isArray(e.type)?e.type.includes(t):e.type===t}function Sg(e,t,n){let r=e.inputSchema;if(!r||r.type!=="object")return null;let s=r.properties??{},o=n??e.id;for(let a of Object.keys(t))if(!Object.prototype.hasOwnProperty.call(s,a)){let l=Object.keys(s),c=l.length>0?` Expected: ${l.join(", ")}.`:"";return`Unknown parameter "${a}" for ${o}.${c}`}let i=(r.required??[]).filter(a=>!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0);if(i.length>1)return`${i.join(", ")} are required for ${o}.`;for(let a of r.required??[]){if(!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0)return`${a} is required for ${o}.`;if(t[a]===null)return`${a} cannot be null.`;if(typeof t[a]=="string"&&t[a].trim()==="")return`${a} cannot be empty.`}for(let[a,l]of Object.entries(t)){let c=s[a];if(!(!c||l===void 0||l===null)){if(c.enum&&!c.enum.includes(l))return`${a} must be one of: ${c.enum.map(String).join(", ")}.`;if(ts(c,"integer")){if(typeof l!="number"||!Number.isInteger(l))return`${a} must be an integer.`}else if(ts(c,"number")){if(typeof l!="number"||!Number.isFinite(l))return`${a} must be a number.`}else if(ts(c,"string")){if(typeof l!="string")return`${a} must be a string.`;if(l.trim()==="")return`${a} cannot be empty.`;if(c.minLength!==void 0&&l.length<c.minLength)return`${a} is too short.`;if(c.maxLength!==void 0&&l.length>c.maxLength)return`${a} is too long.`}else if(ts(c,"boolean")&&typeof l!="boolean")return`${a} must be a boolean.`;if(typeof l=="number"){if(c.minimum!==void 0&&l<c.minimum)return`${a} must be at least ${c.minimum}.`;if(c.maximum!==void 0&&l>c.maximum)return`${a} must be at most ${c.maximum}.`}}}return null}async function wg(e){let t=Gn(e);if(t)return t;try{return await I.catalogTool(e)}catch(n){return m.warn("catalog:resolve:error",{tool:e,error:n?.message||String(n)}),null}}async function xg(e,t,n="execute_tool"){let{tool_id:r,params:s,...o}=e,i=s||o;if(!r)return es("tool_id is required. Use discover_tools first to find available tools.","MISSING_TOOL_ID");m.info("catalog:execute",{tool:r,metaTool:n});let a=await wg(r);if(!a)return es(`Unknown tool: '${r}'. Use discover_tools first to find available tools.`,"UNKNOWN_TOOL");if(a.deprecated){let g=a.replacementTool?` Use '${a.replacementTool}' instead.`:"";return es(`Tool '${r}' is deprecated and is no longer available for new paid calls.${g}`,"DEPRECATED_TOOL")}let c=Sg(a,i,n&&n!=="execute_tool"?n:void 0);if(c)return m.info("catalog:execute:validation_failed",{tool:r,metaTool:n,error:c}),es(c);let u=await ls(r,i,t,n);if(u)return u;if(a.executionMode==="free_authenticated"||a.accessMode==="free"){m.info("catalog:execute:free",{tool:r,metaTool:n});let g=await I.shortcut(r,i,6e4,t,n);return g&&typeof g=="object"&&!Array.isArray(g)&&g.merchantName==null&&(g.merchantName=a.name??r),g}let d=await st(r,void 0,t),f=ce.randomUUID();m.info("payment:attempt",{tool:r,amount:d.amount,merchant:d.merchantName});try{return await be(async()=>{let g;try{g=await Ct({toolId:r,toolParams:i,estimatedAmountCents:ot(d),userContext:t,metaTool:n,timeoutMs:12e4,idempotencyKey:f})}catch(w){if(w instanceof le)return Fe(w);throw w}if(m.info("payment:success",{tool:r,amount:d.amount,merchant:d.merchantName,mode:"session"}),g&&typeof g=="object"&&!Array.isArray(g)&&g.merchantName==null&&(g.merchantName=a?.name??r),g.urls?.length){g.urls.forEach(y=>Be(y));let w=bg(g.urls[0],g.mediaType);Qn({prompt:i.prompt||`${r} execution`,tool:r,mediaUrl:g.urls[0],mediaType:w,cost:g.amount??d.amount,transactionId:g.transactionId,userContext:t})}return g})}catch(g){return g instanceof oe?(m.warn("payment:declined",{tool:r,amount:d.amount,merchant:d.merchantName,code:g.code,retryable:g.retryable}),He(g,d)):(m.error("payment:failure",{tool:r,amount:d.amount,merchant:d.merchantName,error:g.message}),pf({toolId:r,surface:n,merchantName:d.merchantName,amount:d.amount,message:g?.message||"Tool execution failed."}))}}var Ve=class{static async getStatus(t){return Yf(t)}static async getVisaSmi(t,n){return Nf(t,n)}static async getCards(t){return Zf(t)}static async transactionHistory(t,n){return Xf(t||{},n)}static async feedback(t,n){return Qf(t,n)}static async updateSpendingControls(t,n){return ng(t,n)}static async configList(t){return rg(t||{})}static async configSet(t){return sg(t||{})}static async configUnset(t){return og(t||{})}static async biometricStatus(t){return ig(t)}static async biometricOn(t){return ag(t)}static async biometricOff(t,n){return cg(t,n)}static async reset(t,n){return _g(t,n)}static async login(t){return mg(t)}static async closeSession(t){return hg()}static async startSession(t,n){return fg(t||{},n)}static async getSessionStatus(t){return gg()}static async addCard(t){return yg(t)}static async removeCard(t,n){return ug(t,n)}static async setDefaultCard(t,n){return dg(t,n)}static async buyCredits(t,n){return tg(t,n)}static async batch(t,n){return Wf(t,n)}static async discoverTools(t){return vg(t)}static async executeTool(t,n,r="execute_tool"){return xg(t,n,r)}static async shortcut(t,n,r){switch(t){case"generate_image_card":return Lf(n,r);case"generate_image_fast_card":return Df(n,r);case"generate_video_tempo_card":return Uf(n,r);case"generate_music_tempo_card":return jf(n,r);case"check_music_status_tempo_card":return Vf(n,r);case"query_onchain_prices_card":return qf(n,r);default:{let s=await st(t,void 0,r);m.info("payment:attempt",{tool:t});try{let o=await Ct({toolId:t,toolParams:n,estimatedAmountCents:ot(s),userContext:r,timeoutMs:6e4});return m.info("payment:success",{tool:t,mode:"session"}),o.urls?.length&&o.urls.forEach(i=>Be(i)),o}catch(o){if(o instanceof le)return Fe(o);if(o instanceof oe)return m.warn("payment:declined",{tool:t,code:o.code,retryable:o.retryable}),He(o,s);throw m.error("payment:failure",{tool:t,error:o.message}),o}}}}static async submitFeedback(t,n,r){m.info("feedback:submit",{length:t.length,transactionId:n,hasContext:!!r});try{let s=await I.submitFeedback(t,n,r);return m.info("feedback:submitted",{transactionId:n}),s}catch(s){let o=s instanceof Error?s.message:"Unknown error";throw m.error("feedback:error",{error:o,transactionId:n}),s}}static async getFeedback(t,n){m.info("feedback:list",{limit:t||20});try{let r=await I.getFeedback(t,n);return m.info("feedback:listed",{count:r?.feedback?.length||0}),r}catch(r){let s=r instanceof Error?r.message:"Unknown error";throw m.error("feedback:error",{error:s}),r}}};function fl(e,t=process.stderr){if(Ne()||!e?.updateAvailable)return!1;let{latestVersion:n}=e.updateAvailable;if(!n)return!1;let r=`Update available: v${n}. Run: ${sn(n)}`;return t.write(`
132
132
  \x1B[33m\u2191 ${r}\x1B[0m
133
- `),!0}function ml(e){let t=Array.isArray(e.inputSchema?.required)?e.inputSchema.required.filter(s=>typeof s=="string"):[],n=e.inputSchema?.properties&&typeof e.inputSchema.properties=="object"?e.inputSchema.properties:{};if(t.length===0)return{prompt:"a lobster"};let r={};for(let s of t)r[s]=Sg(s,n[s]?.description);return r}function Sg(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"}var wg=20;function fl(e,t,n,r){let s=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=Rg(e.spendingControls).dailyLimit,a=Math.max(0,Xn(e.dailySpent)),l=i>0?Math.min(i,Math.max(0,Xn(e.dailyRemaining??i-a))):0,c=i>0?Math.min(1,a/i):0,d=(Array.isArray(t)?t:[]).filter(kg),f=d.slice(0,3),g=Tg(d,3),w=(e.cards??[]).slice(0,3),y=r.latestVersion?Ct(r.latestVersion):"",k=r.updateCheckDisabled?"update checks disabled":y?`update ready: v${y}`:"up to date",O=Math.round(c*100),N=kt(e.status,e.enrolled?"approved":"not enrolled"),T=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${N} | touch id: ${n?"ready":"unavailable"}`,`Version: v${s} | ${k}`,`Spend meter: ${pl(c)} ${String(O).padStart(3," ")}% | remaining ${Cn(l)}/day | daily cap ${Cn(i)}`,"","Spend",` Remaining ${Cn(l)} / ${Cn(i)}`,` Usage ${pl(c)} ${O}%`,` Spent today ${Cn(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...w.length>0?w.map(V=>` ${Ag(V)}`):[" No cards enrolled"],"","Last 3 services",...g.length>0?g.map((V,z)=>` ${z+1}. ${V}`):[" No paid services yet"],"","Recent receipts",...f.length>0?f.map(V=>` ${Eg(V)}`):[" No receipts yet"]];if(y&&!r.updateCheckDisabled){let V=Ct(rn(y));T.push("",`Update: v${y} ready \u2014 run \`${V}\``),r.updateMessage&&T.push(` ${Ct(r.updateMessage)}`)}else r.updateMessage&&T.push("",`Update: ${Ct(r.updateMessage)}`);return`${T.join(`
133
+ `),!0}function gl(e){let t=Array.isArray(e.inputSchema?.required)?e.inputSchema.required.filter(s=>typeof s=="string"):[],n=e.inputSchema?.properties&&typeof e.inputSchema.properties=="object"?e.inputSchema.properties:{};if(t.length===0)return{prompt:"a lobster"};let r={};for(let s of t)r[s]=Cg(s,n[s]?.description);return r}function Cg(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"}var kg=20;function yl(e,t,n,r){let s=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=Pg(e.spendingControls).dailyLimit,a=Math.max(0,er(e.dailySpent)),l=i>0?Math.min(i,Math.max(0,er(e.dailyRemaining??i-a))):0,c=i>0?Math.min(1,a/i):0,d=(Array.isArray(t)?t:[]).filter(Ag),f=d.slice(0,3),g=Rg(d,3),w=(e.cards??[]).slice(0,3),y=r.latestVersion?kt(r.latestVersion):"",k=r.updateCheckDisabled?"update checks disabled":y?`update ready: v${y}`:"up to date",O=Math.round(c*100),N=Tt(e.status,e.enrolled?"approved":"not enrolled"),T=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${N} | touch id: ${n?"ready":"unavailable"}`,`Version: v${s} | ${k}`,`Spend meter: ${hl(c)} ${String(O).padStart(3," ")}% | remaining ${kn(l)}/day | daily cap ${kn(i)}`,"","Spend",` Remaining ${kn(l)} / ${kn(i)}`,` Usage ${hl(c)} ${O}%`,` Spent today ${kn(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...w.length>0?w.map(q=>` ${$g(q)}`):[" No cards enrolled"],"","Last 3 services",...g.length>0?g.map((q,z)=>` ${z+1}. ${q}`):[" No paid services yet"],"","Recent receipts",...f.length>0?f.map(q=>` ${Ig(q)}`):[" No receipts yet"]];if(y&&!r.updateCheckDisabled){let q=kt(sn(y));T.push("",`Update: v${y} ready \u2014 run \`${q}\``),r.updateMessage&&T.push(` ${kt(r.updateMessage)}`)}else r.updateMessage&&T.push("",`Update: ${kt(r.updateMessage)}`);return`${T.join(`
134
134
  `)}
135
- `}function xg(e){return e.tool_name!=null}function Cg(e){return Xn(e.amount)===0&&e.status==="failed"}function kg(e){return xg(e)&&!Cg(e)}function Tg(e,t=1/0){let n=new Set,r=[];for(let s of e){if(r.length>=t)break;let o=kt(s.merchant_name,"Unknown merchant"),i=kt(s.tool_name,"unknown_tool"),a=`${o} :: ${i}`;n.has(a)||(n.add(a),r.push(`${o} [${i}]`))}return r}function Eg(e){let t=kt(e.merchant_name,"Unknown merchant"),n=kt(e.tool_name,"unknown_tool"),r=Cn(Xn(e.amount)),s=kt(e.status,"unknown"),o=Ig(e.created_at);return`${r} ${s.padEnd(9)} ${t} [${n}] ${o}`}function Ag(e){let t=kt(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function Rg(e){return{dailyLimit:Xn(e?.daily_limit??e?.dailyLimit??0)}}function Xn(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function Cn(e){return`$${e.toFixed(2)}`}function pl(e,t=wg){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function kt(e,t){let n=Ct(e??"").trim();return n.length>0?n:t}function Ig(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?kt(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}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," ")}var $g=/^[1-9]\d{0,9}$/;function Uo(e){if(!$g.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 gl(e){let t=Ct(e.brand||"Visa"),n=Ct(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 ps=R(Wn());var Pg=["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 Mg(){let e=new Set;for(let t of Pg)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of Gn)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var zv=Mg();var jo=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 Xv=new Set(Gn),Qv=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...jo,...Gn]);var Tt=R(Wn()),Og=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;function hl(e,t,n){if(typeof e!="string"||!Og.test(e))return{ok:!1,error:"amount must be a USD amount with at most two decimal places"};let[r,s=""]=e.split("."),o=BigInt(r)*100n+BigInt(s.padEnd(2,"0"));if(o>BigInt(Number.MAX_SAFE_INTEGER))return{ok:!1,error:"amount is too large"};let i=Number(o);return i<t?{ok:!1,error:`minimum top-up is ${(0,Tt.toDisplay)((0,Tt.fromCents)(t))}`}:i>n?{ok:!1,error:`maximum top-up is ${(0,Tt.toDisplay)((0,Tt.fromCents)(n))}`}:{ok:!0,cents:i,displayUsd:(0,Tt.toDisplay)((0,Tt.fromCents)(i),{symbol:""})}}var D=R(require("fs")),P=R(require("path")),yl=R(require("os")),J=yl.homedir(),Ng=["Claude_","Anthropic.ClaudeDesktop_"],kn=class extends Error{constructor(n,r,s){super(Dg(n,r,s));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function _l(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
136
- `)}function Lg(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=_l(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function Dg(e,t,n){let r=t.replace(J,"~"),s=_l(n).split(`
137
- `).find(Boolean),o=s?` (${s})`:"";return e.id==="codex"?`Could not update Codex MCP config at ${r}: filesystem access was denied${o}. In Codex, rerun with elevated filesystem access or run \`visa-cli install codex\` outside the sandbox.`:`Could not update ${e.displayName} MCP config at ${r}: filesystem access was denied${o}.`}function Qn(){return process.env.APPDATA||P.join(J,"AppData","Roaming")}function Ug(){return process.env.LOCALAPPDATA||P.join(J,"AppData","Local")}function qo(e){return process.platform==="win32"?e.win32:e.posix}function vl(){if(process.platform!=="win32")return;let e=P.join(Ug(),"Packages");if(D.existsSync(e))try{let t=D.readdirSync(e,"utf-8");for(let n of Ng){let r=t.filter(s=>s.startsWith(n)).sort()[0];if(r)return P.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function bl(){if(process.platform==="win32"){let e=vl();return e?P.join(e,"claude_desktop_config.json"):P.join(Qn(),"Claude","claude_desktop_config.json")}return P.join(J,"Library","Application Support","Claude","claude_desktop_config.json")}function Sl(){if(process.platform!=="win32")return[P.join(J,"Library","Application Support","Claude")];let e=[P.join(Qn(),"Claude")],t=vl();return t&&e.push(t),e}function cs(e){return e.id==="claude-desktop"?bl():e.globalConfigPath}function jg(e){return e.id==="claude-desktop"?Sl():e.detectPaths}var Ie=[{id:"claude",displayName:"Claude Code",globalConfigPath:P.join(J,".claude.json"),configKey:"mcpServers",detectPaths:[P.join(J,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:bl(),configKey:"mcpServers",detectPaths:Sl(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:P.join(J,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[P.join(J,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:P.join(J,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[P.join(J,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:P.join(J,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[P.join(J,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:qo({win32:P.join(Qn(),"Roo","mcp_settings.json"),posix:P.join(J,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[P.join(J,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:P.join(J,".vscode","mcp.json"),configKey:"servers",detectPaths:[P.join(J,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:qo({win32:P.join(Qn(),"Zed","settings.json"),posix:P.join(J,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:qo({win32:[P.join(Qn(),"Zed")],posix:[P.join(J,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:P.join(J,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[P.join(J,".codex")],postInstallHint:"Restart Codex to connect."}];function Vo(e){return Ie.find(t=>t.id===e)}function er(e){return jg(e).some(t=>{if(t.includes("*")){let n=P.dirname(t),r=P.basename(t).replaceAll("*","");if(!D.existsSync(n))return!1;try{return D.readdirSync(n).some(s=>s.startsWith(r))}catch{return!1}}return D.existsSync(t)})}function wl(){return{command:"node",args:[P.resolve(__dirname,"mcp-server/index.js")]}}function Fo(e,t){return t==="project"?"json":e.configFormat??"json"}function qg(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 Bo(e,t){let n=`[mcp_servers.${t}]`,r=e.findIndex(o=>o.trim()===n);if(r===-1)return;let s=r+1;for(;s<e.length&&!e[s].trim().startsWith("[");)s++;return{start:r,end:s}}function Ho(e,t){let n=e.split(`
138
- `),r=Bo(n,t);if(!r)return;let s={};for(let o=r.start+1;o<r.end;o++){let i=n[o].trim().match(/^(\w+)\s*=\s*(.+)$/);i&&(s[i[1]]=qg(i[2]))}return Object.keys(s).length>0?s:void 0}function Vg(e,t,n){let r=`[${n.args.map(l=>`"${l}"`).join(", ")}]`,s=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],o=e.split(`
139
- `),i=Bo(o,t);if(i){o.splice(i.start,i.end-i.start,...s);let l=o.join(`
135
+ `}function Tg(e){return e.tool_name!=null}function Eg(e){return er(e.amount)===0&&e.status==="failed"}function Ag(e){return Tg(e)&&!Eg(e)}function Rg(e,t=1/0){let n=new Set,r=[];for(let s of e){if(r.length>=t)break;let o=Tt(s.merchant_name,"Unknown merchant"),i=Tt(s.tool_name,"unknown_tool"),a=`${o} :: ${i}`;n.has(a)||(n.add(a),r.push(`${o} [${i}]`))}return r}function Ig(e){let t=Tt(e.merchant_name,"Unknown merchant"),n=Tt(e.tool_name,"unknown_tool"),r=kn(er(e.amount)),s=Tt(e.status,"unknown"),o=Mg(e.created_at);return`${r} ${s.padEnd(9)} ${t} [${n}] ${o}`}function $g(e){let t=Tt(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function Pg(e){return{dailyLimit:er(e?.daily_limit??e?.dailyLimit??0)}}function er(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function kn(e){return`$${e.toFixed(2)}`}function hl(e,t=kg){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function Tt(e,t){let n=kt(e??"").trim();return n.length>0?n:t}function Mg(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?Tt(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function kt(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 Og=/^[1-9]\d{0,9}$/;function Vo(e){if(!Og.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 _l(e){let t=kt(e.brand||"Visa"),n=kt(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 gs=R(Yn());var Ng=["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 Lg(){let e=new Set;for(let t of Ng)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of zn)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var Xv=Lg();var qo=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 rb=new Set(zn),sb=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...qo,...zn]);var Et=R(Yn()),Dg=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;function vl(e,t,n){if(typeof e!="string"||!Dg.test(e))return{ok:!1,error:"amount must be a USD amount with at most two decimal places"};let[r,s=""]=e.split("."),o=BigInt(r)*100n+BigInt(s.padEnd(2,"0"));if(o>BigInt(Number.MAX_SAFE_INTEGER))return{ok:!1,error:"amount is too large"};let i=Number(o);return i<t?{ok:!1,error:`minimum top-up is ${(0,Et.toDisplay)((0,Et.fromCents)(t))}`}:i>n?{ok:!1,error:`maximum top-up is ${(0,Et.toDisplay)((0,Et.fromCents)(n))}`}:{ok:!0,cents:i,displayUsd:(0,Et.toDisplay)((0,Et.fromCents)(i),{symbol:""})}}var D=R(require("fs")),P=R(require("path")),bl=R(require("os")),J=bl.homedir(),Ug=["Claude_","Anthropic.ClaudeDesktop_"],Tn=class extends Error{constructor(n,r,s){super(Vg(n,r,s));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function Sl(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
136
+ `)}function jg(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=Sl(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function Vg(e,t,n){let r=t.replace(J,"~"),s=Sl(n).split(`
137
+ `).find(Boolean),o=s?` (${s})`:"";return e.id==="codex"?`Could not update Codex MCP config at ${r}: filesystem access was denied${o}. In Codex, rerun with elevated filesystem access or run \`visa-cli install codex\` outside the sandbox.`:`Could not update ${e.displayName} MCP config at ${r}: filesystem access was denied${o}.`}function tr(){return process.env.APPDATA||P.join(J,"AppData","Roaming")}function qg(){return process.env.LOCALAPPDATA||P.join(J,"AppData","Local")}function Fo(e){return process.platform==="win32"?e.win32:e.posix}function wl(){if(process.platform!=="win32")return;let e=P.join(qg(),"Packages");if(D.existsSync(e))try{let t=D.readdirSync(e,"utf-8");for(let n of Ug){let r=t.filter(s=>s.startsWith(n)).sort()[0];if(r)return P.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function xl(){if(process.platform==="win32"){let e=wl();return e?P.join(e,"claude_desktop_config.json"):P.join(tr(),"Claude","claude_desktop_config.json")}return P.join(J,"Library","Application Support","Claude","claude_desktop_config.json")}function Cl(){if(process.platform!=="win32")return[P.join(J,"Library","Application Support","Claude")];let e=[P.join(tr(),"Claude")],t=wl();return t&&e.push(t),e}function us(e){return e.id==="claude-desktop"?xl():e.globalConfigPath}function Fg(e){return e.id==="claude-desktop"?Cl():e.detectPaths}var Ie=[{id:"claude",displayName:"Claude Code",globalConfigPath:P.join(J,".claude.json"),configKey:"mcpServers",detectPaths:[P.join(J,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:xl(),configKey:"mcpServers",detectPaths:Cl(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:P.join(J,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[P.join(J,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:P.join(J,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[P.join(J,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:P.join(J,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[P.join(J,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:Fo({win32:P.join(tr(),"Roo","mcp_settings.json"),posix:P.join(J,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[P.join(J,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:P.join(J,".vscode","mcp.json"),configKey:"servers",detectPaths:[P.join(J,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:Fo({win32:P.join(tr(),"Zed","settings.json"),posix:P.join(J,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:Fo({win32:[P.join(tr(),"Zed")],posix:[P.join(J,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:P.join(J,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[P.join(J,".codex")],postInstallHint:"Restart Codex to connect."}];function Bo(e){return Ie.find(t=>t.id===e)}function nr(e){return Fg(e).some(t=>{if(t.includes("*")){let n=P.dirname(t),r=P.basename(t).replaceAll("*","");if(!D.existsSync(n))return!1;try{return D.readdirSync(n).some(s=>s.startsWith(r))}catch{return!1}}return D.existsSync(t)})}function kl(){return{command:"node",args:[P.resolve(__dirname,"mcp-server/index.js")]}}function Ho(e,t){return t==="project"?"json":e.configFormat??"json"}function Bg(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 Ko(e,t){let n=`[mcp_servers.${t}]`,r=e.findIndex(o=>o.trim()===n);if(r===-1)return;let s=r+1;for(;s<e.length&&!e[s].trim().startsWith("[");)s++;return{start:r,end:s}}function Go(e,t){let n=e.split(`
138
+ `),r=Ko(n,t);if(!r)return;let s={};for(let o=r.start+1;o<r.end;o++){let i=n[o].trim().match(/^(\w+)\s*=\s*(.+)$/);i&&(s[i[1]]=Bg(i[2]))}return Object.keys(s).length>0?s:void 0}function Hg(e,t,n){let r=`[${n.args.map(l=>`"${l}"`).join(", ")}]`,s=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],o=e.split(`
139
+ `),i=Ko(o,t);if(i){o.splice(i.start,i.end-i.start,...s);let l=o.join(`
140
140
  `);return l.endsWith(`
141
141
  `)?l:l+`
142
142
  `}let a=e.trimEnd();return a+(a.length>0?`
143
143
 
144
144
  `:"")+s.join(`
145
145
  `)+`
146
- `}function Fg(e,t){let n=e.split(`
147
- `),r=Bo(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
146
+ `}function Kg(e,t){let n=e.split(`
147
+ `),r=Ko(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
148
148
  `).replace(/\n{3,}/g,`
149
149
 
150
- `)):e}function tr(e,t="global"){let n=t==="project"?P.join(process.cwd(),".mcp.json"):cs(e);try{let r=P.dirname(n);D.existsSync(r)||D.mkdirSync(r,{recursive:!0});let s=Fo(e,t),o=wl();if(s==="toml"){let i=D.existsSync(n)?D.readFileSync(n,"utf-8"):"",a=Vg(i,"visa-cli",o);D.writeFileSync(n,a)}else{let i={};if(D.existsSync(n))try{i=JSON.parse(D.readFileSync(n,"utf-8"))}catch{i={}}i[e.configKey]=i[e.configKey]||{},i[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(o):o,D.writeFileSync(n,JSON.stringify(i,null,2)+`
151
- `)}}catch(r){throw Lg(r)?new kn(e,n,r):r}return{installed:!0,configPath:n,message:e.postInstallHint}}function Ko(e,t="global"){let n=t==="project"?P.join(process.cwd(),".mcp.json"):cs(e);if(!D.existsSync(n))return{removed:!1,configPath:n};if(Fo(e,t)==="toml"){let i=D.readFileSync(n,"utf-8");return Ho(i,"visa-cli")?(D.writeFileSync(n,Fg(i,"visa-cli")),{removed:!0,configPath:n}):{removed:!1,configPath:n}}let s;try{s=JSON.parse(D.readFileSync(n,"utf-8"))}catch{return{removed:!1,configPath:n}}let o=s[e.configKey];return!o||!o["visa-cli"]?{removed:!1,configPath:n}:(delete o["visa-cli"],D.writeFileSync(n,JSON.stringify(s,null,2)+`
152
- `),{removed:!0,configPath:n})}function xl(e,t="global"){let n=t==="project"?P.join(process.cwd(),".mcp.json"):cs(e);if(!D.existsSync(n))return!1;if(Fo(e,t)==="toml")try{let s=D.readFileSync(n,"utf-8");return!!Ho(s,"visa-cli")}catch{return!1}try{return!!JSON.parse(D.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function Bg(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 Hg(e,t){if(e===t)return!0;let n=P.resolve(e),r=P.resolve(t);if(n===r)return!0;try{let s=D.realpathSync(n),o=D.realpathSync(r);return s===o}catch{return!1}}function nr(){let e=wl(),t=e.args[e.args.length-1],n=[];for(let r of Ie){let s=cs(r);if(!D.existsSync(s))continue;let o=r.configFormat??"json",i;if(o==="toml")try{let c=D.readFileSync(s,"utf-8");i=Ho(c,"visa-cli")}catch{continue}else{let c;try{c=JSON.parse(D.readFileSync(s,"utf-8"))}catch{continue}i=c?.[r.configKey]?.["visa-cli"]}if(!i)continue;let a=Bg(i);if(!a||Hg(a,t))continue;let l=D.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:s,currentPath:a,expectedPath:t,staleReason:l})}return n}function Go(e){return{configPath:tr(e.client,"global").configPath}}var Jo=(0,Pl.promisify)(Il.execFile);function Wg(e){let t=K.homedir(),n=s=>s.replace(t,"~"),r=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
153
- ${r}: ${n(e.currentPath)}`}function Ml(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(Wg(n))}function Cl(e){console.log(` ! ${e.client.displayName} skipped: ${e.message}`)}var G=new Rl.Command,Jg=new Set(["pay",...jo]),ds=null,rr=!1;function se(){return ds=new ye(()=>U.getSessionToken()),ds}function Ol(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function kl(e){if(e instanceof Pt)return!0;let t=e instanceof Error?e.message:"";return/attestation required|invalid signature|rotate biometric key|biometric key/i.test(t)}var Tl=0,El="",Yg="attestation-key-rotation";async function Zg(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:Tl,merchant:El,context:Yg})).toString("base64");return{signature:await bn(n,"verify Visa CLI Touch ID setup"),nonce:t,amount:Tl,merchant:El}}async function Xg(e){let t=await uc(),n=await Zg(e);await e.registerAttestationKey(t,n)}async function Nl(e,t,n=!1){let r=await qr();console.log(" Attestation key generated."),await e.registerAttestationKey(r),console.log(" Attestation key registered with server."),t&&(await e.setBiometricPreference({required:!0}),n&&m.info("attestation:requirement-restored-after-recovery",{surface:"setup"}),console.log(n?" Touch ID requirement re-enabled after biometric recovery.":" Touch ID requirement enabled."))}async function zo(e){if(!await Zo(e))throw new Error("Could not clear stale server biometric state. Run `visa-cli config reset`, then `visa-cli setup`.");await Nl(e,!0,!0)}function Ll(e){return async()=>{let t=await Zo(e);return{success:t,...t?{}:{message:"Biometric recovery was not completed."}}}}async function Qg(e){let r=Date.now()+3e5;for(;Date.now()<r;)try{let s=await globalThis.fetch(`${we()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:3e4}),signal:AbortSignal.timeout(35e3)});if(!s.ok){await ut(s,i=>{m.warn("auth_status:retry_after_http_error",{status:s.status,delayMs:i})});continue}let o=await s.json();if(o.status==="pending")continue;if(o.status==="complete"&&o.attestationCleared)return;if(o.status==="expired")throw new Error("Biometric reset session expired. Please run visa-cli config reset again.");if(o.status==="error")throw new Error(o.error||"Biometric reset failed. Please try again.")}catch(s){if(s?.message&&!/fetch failed|network|abort/i.test(s.message))throw s;await ut(void 0,o=>{m.warn("auth_status:retry_after_network_error",{delayMs:o})})}throw new Error("Biometric reset timed out after 5 minutes. Please run visa-cli config reset again.")}async function Zo(e){let t;try{t=await e.getStatus()}catch(s){let o=s?.message||"";if(/not logged in|session.*expired|no local credentials/i.test(o))return!1;throw new Error(`Could not check server biometric state: ${o||"unknown error"}`)}if(!Ol(t))return!1;let n=ms.randomUUID(),r=await e.startAttestationRecovery(n);if(!r.success||!r.recoveryUrl)throw new Error(r.error||"Could not start biometric reset.");return console.log(" Server biometric key found. Opening GitHub to confirm reset..."),await Es(r.recoveryUrl),await Qg(n),console.log(" Server biometric state cleared."),!0}function sr(e){return`$${(e/100).toFixed(2)}`}function Yo(e,t,n=!1){if(!e){let i=sr(t);return n&&t>=0?`+${i}`:i}let r=(0,ps.fromWire)(e),s=r%10000n===0n?2:6,o=(0,ps.toDisplay)(r,{decimals:s});return n&&r>=0n?`+${o}`:o}function eh(e){return Yo(e,0)}function th(e){let t=`visa-cli-${K.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 nh(e){if(!e)return;let t=e.split(",").map(o=>o.trim()).filter(Boolean),n=Array.from(new Set(t)),r=n.find(o=>o.length>64);if(r)throw new Error(`Tool id is too long: ${r}`);let s=n.find(o=>Jg.has(o));if(s)throw new Error(`Tool id "${s}" is retired for direct API-key access. Use category meta-tools or discover/execute instead.`);return n}function rh(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 Dl(e){return e&&e.length>0?e.join(", "):"all tools"}function Xo(e,t){return t||(typeof e!="number"||!Number.isFinite(e)?"price unknown":`$${(e/100).toFixed(2)}`)}function sh(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 Ul(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 Wo(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function oh(e){let t=new Map;for(let n of e){let r=n.category||"other",s=t.get(r)??[];s.push(n),t.set(r,s)}return new Map([...t.entries()].sort(([n],[r])=>n.localeCompare(r)))}function ih(e){let t=Math.max(4,Math.min(28,e.reduce((s,o)=>Math.max(s,o.id.length),0))),n=7,r=Math.max(8,Math.min(12,e.reduce((s,o)=>Math.max(s,(o.category||"").length),0)));console.log(`
150
+ `)):e}function rr(e,t="global"){let n=t==="project"?P.join(process.cwd(),".mcp.json"):us(e);try{let r=P.dirname(n);D.existsSync(r)||D.mkdirSync(r,{recursive:!0});let s=Ho(e,t),o=kl();if(s==="toml"){let i=D.existsSync(n)?D.readFileSync(n,"utf-8"):"",a=Hg(i,"visa-cli",o);D.writeFileSync(n,a)}else{let i={};if(D.existsSync(n))try{i=JSON.parse(D.readFileSync(n,"utf-8"))}catch{i={}}i[e.configKey]=i[e.configKey]||{},i[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(o):o,D.writeFileSync(n,JSON.stringify(i,null,2)+`
151
+ `)}}catch(r){throw jg(r)?new Tn(e,n,r):r}return{installed:!0,configPath:n,message:e.postInstallHint}}function zo(e,t="global"){let n=t==="project"?P.join(process.cwd(),".mcp.json"):us(e);if(!D.existsSync(n))return{removed:!1,configPath:n};if(Ho(e,t)==="toml"){let i=D.readFileSync(n,"utf-8");return Go(i,"visa-cli")?(D.writeFileSync(n,Kg(i,"visa-cli")),{removed:!0,configPath:n}):{removed:!1,configPath:n}}let s;try{s=JSON.parse(D.readFileSync(n,"utf-8"))}catch{return{removed:!1,configPath:n}}let o=s[e.configKey];return!o||!o["visa-cli"]?{removed:!1,configPath:n}:(delete o["visa-cli"],D.writeFileSync(n,JSON.stringify(s,null,2)+`
152
+ `),{removed:!0,configPath:n})}function Tl(e,t="global"){let n=t==="project"?P.join(process.cwd(),".mcp.json"):us(e);if(!D.existsSync(n))return!1;if(Ho(e,t)==="toml")try{let s=D.readFileSync(n,"utf-8");return!!Go(s,"visa-cli")}catch{return!1}try{return!!JSON.parse(D.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function Gg(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 zg(e,t){if(e===t)return!0;let n=P.resolve(e),r=P.resolve(t);if(n===r)return!0;try{let s=D.realpathSync(n),o=D.realpathSync(r);return s===o}catch{return!1}}function sr(){let e=kl(),t=e.args[e.args.length-1],n=[];for(let r of Ie){let s=us(r);if(!D.existsSync(s))continue;let o=r.configFormat??"json",i;if(o==="toml")try{let c=D.readFileSync(s,"utf-8");i=Go(c,"visa-cli")}catch{continue}else{let c;try{c=JSON.parse(D.readFileSync(s,"utf-8"))}catch{continue}i=c?.[r.configKey]?.["visa-cli"]}if(!i)continue;let a=Gg(i);if(!a||zg(a,t))continue;let l=D.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:s,currentPath:a,expectedPath:t,staleReason:l})}return n}function Wo(e){return{configPath:rr(e.client,"global").configPath}}var Zo=(0,Nl.promisify)(Ml.execFile);function Zg(e){let t=K.homedir(),n=s=>s.replace(t,"~"),r=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
153
+ ${r}: ${n(e.currentPath)}`}function Ll(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(Zg(n))}function El(e){console.log(` ! ${e.client.displayName} skipped: ${e.message}`)}function Pe(){this.help({error:!1})}var G=new Pl.Command,Xg=new Set(["pay",...qo]),ps=null,or=!1;function ne(){return ps=new ye(()=>U.getSessionToken()),ps}function Dl(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function Al(e){if(e instanceof Mt)return!0;let t=e instanceof Error?e.message:"";return/attestation required|invalid signature|rotate biometric key|biometric key/i.test(t)}var Rl=0,Il="",Qg="attestation-key-rotation";async function eh(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:Rl,merchant:Il,context:Qg})).toString("base64");return{signature:await Sn(n,"verify Visa CLI Touch ID setup"),nonce:t,amount:Rl,merchant:Il}}async function th(e){let t=await pc(),n=await eh(e);await e.registerAttestationKey(t,n)}async function Ul(e,t,n=!1){let r=await Br();console.log(" Attestation key generated."),await e.registerAttestationKey(r),console.log(" Attestation key registered with server."),t&&(await e.setBiometricPreference({required:!0}),n&&m.info("attestation:requirement-restored-after-recovery",{surface:"setup"}),console.log(n?" Touch ID requirement re-enabled after biometric recovery.":" Touch ID requirement enabled."))}async function Jo(e){if(!await Qo(e))throw new Error("Could not clear stale server biometric state. Run `visa-cli config reset`, then `visa-cli setup`.");await Ul(e,!0,!0)}function jl(e){return async()=>{let t=await Qo(e);return{success:t,...t?{}:{message:"Biometric recovery was not completed."}}}}async function nh(e){let r=Date.now()+3e5;for(;Date.now()<r;)try{let s=await globalThis.fetch(`${we()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:3e4}),signal:AbortSignal.timeout(35e3)});if(!s.ok){await dt(s,i=>{m.warn("auth_status:retry_after_http_error",{status:s.status,delayMs:i})});continue}let o=await s.json();if(o.status==="pending")continue;if(o.status==="complete"&&o.attestationCleared)return;if(o.status==="expired")throw new Error("Biometric reset session expired. Please run visa-cli config reset again.");if(o.status==="error")throw new Error(o.error||"Biometric reset failed. Please try again.")}catch(s){if(s?.message&&!/fetch failed|network|abort/i.test(s.message))throw s;await dt(void 0,o=>{m.warn("auth_status:retry_after_network_error",{delayMs:o})})}throw new Error("Biometric reset timed out after 5 minutes. Please run visa-cli config reset again.")}async function Qo(e){let t;try{t=await e.getStatus()}catch(s){let o=s?.message||"";if(/not logged in|session.*expired|no local credentials/i.test(o))return!1;throw new Error(`Could not check server biometric state: ${o||"unknown error"}`)}if(!Dl(t))return!1;let n=fs.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 Rs(r.recoveryUrl),await nh(n),console.log(" Server biometric state cleared."),!0}function ir(e){return`$${(e/100).toFixed(2)}`}function Xo(e,t,n=!1){if(!e){let i=ir(t);return n&&t>=0?`+${i}`:i}let r=(0,gs.fromWire)(e),s=r%10000n===0n?2:6,o=(0,gs.toDisplay)(r,{decimals:s});return n&&r>=0n?`+${o}`:o}function rh(e){return Xo(e,0)}function sh(e){let t=`visa-cli-${K.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 oh(e){if(!e)return;let t=e.split(",").map(o=>o.trim()).filter(Boolean),n=Array.from(new Set(t)),r=n.find(o=>o.length>64);if(r)throw new Error(`Tool id is too long: ${r}`);let s=n.find(o=>Xg.has(o));if(s)throw new Error(`Tool id "${s}" is retired for direct API-key access. Use category meta-tools or discover/execute instead.`);return n}function ih(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 Vl(e){return e&&e.length>0?e.join(", "):"all tools"}function ei(e,t){return t||(typeof e!="number"||!Number.isFinite(e)?"price unknown":`$${(e/100).toFixed(2)}`)}function ah(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 ql(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 Yo(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function ch(e){let t=new Map;for(let n of e){let r=n.category||"other",s=t.get(r)??[];s.push(n),t.set(r,s)}return new Map([...t.entries()].sort(([n],[r])=>n.localeCompare(r)))}function lh(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))),s=typeof process.stdout.columns=="number"&&process.stdout.columns>0?process.stdout.columns:100,o=Math.max(40,s-(t+n+r+10));console.log(`
154
154
  Merchant tools
155
- `),console.log(` ${"Tool".padEnd(t)} ${"Price".padEnd(n)} ${"Category".padEnd(r)} Params`),console.log(` ${"\u2500".repeat(t)} ${"\u2500".repeat(n)} ${"\u2500".repeat(r)} ${"\u2500".repeat(28)}`);for(let s of e)console.log(` ${Wo(s.id,t).padEnd(t)} ${Xo(s.priceCents,s.priceDisplay).padEnd(n)} ${Wo(s.category||"other",r).padEnd(r)} ${Wo(Ul(s),42)}`);console.log("\nUse `visa-cli merchants describe <tool>` for full details."),console.log('Shortcut: `visa-cli generate image "a lobster"`\n')}function ah(e){console.log(`
155
+ `),console.log(` ${"Tool".padEnd(t)} ${"Price".padEnd(n)} ${"Category".padEnd(r)} Params`),console.log(` ${"\u2500".repeat(t)} ${"\u2500".repeat(n)} ${"\u2500".repeat(r)} ${"\u2500".repeat(Math.min(o,32))}`);for(let i of e)console.log(` ${Yo(i.id,t).padEnd(t)} ${ei(i.priceCents,i.priceDisplay).padEnd(n)} ${Yo(i.category||"other",r).padEnd(r)} ${Yo(ql(i),o)}`);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 uh(e){console.log(`
156
156
  Merchant tools
157
- `);for(let[t,n]of oh(e)){console.log(t[0]?.toUpperCase()+t.slice(1));for(let r of n)console.log(` ${r.id.padEnd(28)} ${Xo(r.priceCents,r.priceDisplay).padEnd(8)} ${r.description}`),console.log(` Params: ${Ul(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"
158
- `)}function jl(e){if(e?.content?.[0]?.text&&typeof e.content[0].text=="string"){console.log(e.content[0].text);return}let t=Array.isArray(e?.urls)?e.urls:Array.isArray(e?.receipt?.urls)?e.receipt.urls:[];if(e?.success===!1){let r=JSON.stringify(e,null,2);console.log("Result:"),console.log(r);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}`),t.length>0){console.log(`
157
+ `);for(let[t,n]of ch(e)){console.log(t[0]?.toUpperCase()+t.slice(1));for(let r of n)console.log(` ${r.id.padEnd(28)} ${ei(r.priceCents,r.priceDisplay).padEnd(8)} ${r.description}`),console.log(` Params: ${ql(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"
158
+ `)}function Fl(e){if(e?.content?.[0]?.text&&typeof e.content[0].text=="string"){console.log(e.content[0].text);return}let t=Array.isArray(e?.urls)?e.urls:Array.isArray(e?.receipt?.urls)?e.receipt.urls:[];if(e?.success===!1){let r=JSON.stringify(e,null,2);console.log("Result:"),console.log(r);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}`),t.length>0){console.log(`
159
159
  Result URLs:`);for(let r of t)console.log(` ${r}`);return}let n=JSON.stringify(e,null,2);n&&n!=="{}"&&(console.log(`
160
- Result:`),console.log(n))}var ch=new Set(["INVALID_TOOL_PARAMS","MISSING_TOOL_ID","UNKNOWN_TOOL"]),ql=0,lh=1,uh=2;function dh(e){if(e?.success!==!1)return ql;let n=(typeof e?.error_code=="string"?e.error_code:typeof e?.code=="string"?e.code:"").toUpperCase();return ch.has(n)?uh:lh}function Vl(e){let t=dh(e);t!==ql&&(process.exitCode=t)}async function mh(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 Fl=100,Bl=200;function Al(e){let t=Number.parseInt(e,10);return Number.isNaN(t)?Number.NaN:t}function ph(e){let t=typeof e.limit=="number"&&Number.isInteger(e.limit)?Math.max(1,Math.min(e.limit,Bl)):Fl,n=typeof e.offset=="number"&&Number.isInteger(e.offset)?Math.max(0,e.offset):0;return{limit:t,offset:n}}function fh(e){let t=`
160
+ Result:`),console.log(n))}var dh=new Set(["INVALID_TOOL_PARAMS","MISSING_TOOL_ID","UNKNOWN_TOOL"]),Bl=0,mh=1,ph=2;function fh(e){if(e?.success!==!1)return Bl;let n=(typeof e?.error_code=="string"?e.error_code:typeof e?.code=="string"?e.code:"").toUpperCase();return dh.has(n)?ph:mh}function Hl(e){let t=fh(e);t!==Bl&&(process.exitCode=t)}async function gh(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 Kl=100,Gl=200;function $l(e){let t=Number.parseInt(e,10);return Number.isNaN(t)?Number.NaN:t}function hh(e){let t=typeof e.limit=="number"&&Number.isInteger(e.limit)?Math.max(1,Math.min(e.limit,Gl)):Kl,n=typeof e.offset=="number"&&Number.isInteger(e.offset)?Math.max(0,e.offset):0;return{limit:t,offset:n}}function yh(e){let t=`
161
161
  Options:
162
162
  `,n=`
163
163
  Commands:
164
- `,r=e.indexOf(t),s=e.indexOf(n);if(r===-1||s===-1||r>s)return e;let o=f=>{let w=e.slice(f+1).search(/\n[A-Z][A-Za-z ]+:\n/);return w===-1?e.length:f+1+w},i=o(r),a=o(s),l=e.slice(0,r),c=e.slice(r,i),u=e.slice(s,a),d=e.slice(a);return`${l}${u}${c}${d}`}function gh(e){if(!e.startsWith("Usage: "))return e;let t=e.indexOf(`
164
+ `,r=e.indexOf(t),s=e.indexOf(n);if(r===-1||s===-1||r>s)return e;let o=f=>{let w=e.slice(f+1).search(/\n[A-Z][A-Za-z ]+:\n/);return w===-1?e.length:f+1+w},i=o(r),a=o(s),l=e.slice(0,r),c=e.slice(r,i),u=e.slice(s,a),d=e.slice(a);return`${l}${u}${c}${d}`}function _h(e){if(!e.startsWith("Usage: "))return e;let t=e.indexOf(`
165
165
 
166
166
  `);if(t===-1)return e;let n=e.slice(0,t),r=e.slice(t+2),s=r.indexOf(`
167
167
 
@@ -169,13 +169,13 @@ Commands:
169
169
 
170
170
  ${n}
171
171
 
172
- ${i}`:e}function hh(e){return e.replace(/(^|\n)(Commands:\n)([\s\S]*?)(?=\n[A-Z][A-Za-z ]+:\n|$)/g,(t,n,r,s)=>{let o=s.split(`
173
- `).map(yh).join(`
174
- `);return`${n}${r}${o}`})}function yh(e){if(!e.startsWith(" "))return e;let n=2,r=n;for(;r<e.length&&e[r]!==" "&&e[r]!==" ";)r+=1;if(r===n)return e;let s=-1;for(let l=r;l<e.length-1;l+=1){if(e[l]!==" "||e[l+1]!==" ")continue;let c=l+2;for(;c<e.length&&e[c]===" ";)c+=1;if(c<e.length){s=c;break}}if(s===-1)return e;let o=e.slice(n,r),i=e.slice(s),a=Math.max(2,s-2-o.length);return` ${o}${" ".repeat(a)}${i}`}function _h(e){return e.replace(/^(Usage: .+?) \[options\](?= |$)/gm,"$1")}function vh(e){return e.replace(/^Options:$/gm,"Flags:")}function Hl(e){let t=e.helpInformation.bind(e);e.helpInformation=()=>vh(_h(hh(fh(gh(t())))));for(let n of e.commands)Hl(n)}function bh(e){let t=new Map(e.map((r,s)=>[r,s]));G.commands.sort((r,s)=>{let o=t.get(r.name())??Number.MAX_SAFE_INTEGER,i=t.get(s.name())??Number.MAX_SAFE_INTEGER;return o-i})}G.name("visa-cli").description("Visa CLI - set up MCP payments, manage credentials, and monitor AI spend").version(dr().version).addHelpCommand(!1);G.hook("preAction",async()=>{await vi()});G.command("setup").description("Register MCP server, authenticate, and generate attestation key").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--yes","Accept setup prompts without asking \u2014 for CI/agent use").option("--hud","Also enable the Visa HUD (Claude Code statusLine)").option("--no-hud","Do not install the Visa HUD during setup (default)").action(async e=>{try{if(e.check){let y=nr();Ml(y,"MCP config check:"),y.length>0&&(console.log("\nRun `visa-cli setup` (or `visa-cli install --repair`) to rewrite these entries."),process.exit(1));return}console.log("Step 1: Registering MCP server...");let t=nr(),n=new Map(t.map(y=>[y.client.id,y])),r=new Set,s=new Set,o=new Set;for(let y of Ie)if(er(y)){let k;try{k=tr(y)}catch(C){if(C instanceof kn){Cl(C),s.add(y.displayName),o.add(y.id);continue}throw C}let O=n.get(y.id),N=O?` \u2014 repaired stale ${O.staleReason} entry`:"";console.log(` \u2713 ${y.displayName} (${k.configPath.replace(K.homedir(),"~")})${N}`),O&&r.add(y.id)}let i=t.filter(y=>!r.has(y.client.id)&&!o.has(y.client.id)),a=0;for(let y of i){try{Go(y)}catch(k){if(k instanceof kn){Cl(k),s.add(y.client.displayName),o.add(y.client.id);continue}throw k}console.log(` \u2713 ${y.client.displayName} (${y.configPath.replace(K.homedir(),"~")}) \u2014 repaired stale ${y.staleReason} entry`),a++}let l=r.size+a;l===0&&s.size===0?console.log(" \u2713 MCP config verified \u2014 nothing to repair."):l>0&&console.log(` \u2713 Repaired ${l} stale MCP config ${l===1?"entry":"entries"}.`),s.size>0&&console.log(` ! Skipped MCP registration for: ${Array.from(s).join(", ")}. Rerun with access to those config files to complete registration.`),console.log(`
175
- Step 2: Checking authentication...`);let c=await U.getSessionToken();if(c)try{await new ye(()=>Promise.resolve(c)).getStatus(),console.log(" Already authenticated.")}catch(y){let k=y instanceof Error?y.message:"";k.includes("session has expired")||k.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await U.clearAll(),c=null):console.log(` Couldn't verify session (${k||"unknown error"}) \u2014 continuing with existing token.`)}if(!c){let y=null;try{let{stdout:k}=await Jo("gh",["auth","token"],{timeout:5e3});y=k.trim()}catch{}if(y||(y=process.env.GITHUB_TOKEN||null),y)try{console.log(" Found GitHub token \u2014 attempting headless login...");let k=await globalThis.fetch(`${we()}/v1/auth/token-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({github_token:y}),signal:AbortSignal.timeout(1e4)});if(k.ok){let O=await k.json();if(O.success&&O.sessionToken){let N=O.sessionToken;c=N,await U.saveSessionToken(N),console.log(` Signed in as ${O.user} (headless).`)}}else(await k.json().catch(()=>({}))).hint==="card_required"&&console.log(" GitHub token valid but no card on file \u2014 opening browser for card enrollment...")}catch{}}if(c||(console.log(" No session found. Opening browser for GitHub login..."),c=await new Promise(async(y,k)=>{let O=ms.randomUUID(),N=`${we()}/login?state=${O}`;await Es(N);let C=3e4,T=300*1e3,V=Date.now()+T;for(;Date.now()<V;)try{let z=await globalThis.fetch(`${we()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:O,timeout:C}),signal:AbortSignal.timeout(C+5e3)});if(!z.ok){await ut(z,ot=>{m.warn("auth_status:retry_after_http_error",{status:z.status,delayMs:ot})});continue}let F=await z.json();if(F.status==="pending")continue;if(F.status==="expired"){k(new Error("Session expired. Please run setup again."));return}if(F.status==="complete"&&F.sessionToken){console.log(` Signed in as ${F.user}.`),y(F.sessionToken);return}}catch{await ut(void 0,z=>{m.warn("auth_status:retry_after_network_error",{delayMs:z})})}k(new Error("Login timed out after 5 minutes. Please run setup again."))}),await U.saveSessionToken(c),console.log(" Session token saved.")),console.log(`
176
- Step 3: Setting up authentication...`),!te())console.log(" Not macOS \u2014 skipping biometric setup.");else{try{await Jo("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 y=se();try{let k=await y.getStatus(),O=!0;if(Ol(k))if(await lc())try{await Xg(y),console.log(" Attestation key already registered with server."),console.log(" Existing local Touch ID key verified and preserved."),O=!1}catch(N){if(!kl(N))throw N;console.log(" Existing local Touch ID key does not match server biometric state."),await zo(y),O=!1}else console.log(" Server already has a biometric key, but this device has no local key."),await zo(y),O=!1;O&&await Nl(y,k.attestationRequired===!1)}catch(k){let O=k?.message||"unknown error";if(kl(k)){console.log(" Server already has a biometric key for this account, but this device cannot prove access to it.");let N=!1;try{await zo(y),N=!0}catch(C){console.error(` Biometric recovery failed: ${C?.message||"unknown error"}`)}if(!N){let C=k instanceof Pt&&k.hint?k.hint:"Run `visa-cli config reset` to clear server-side biometric state through GitHub, then run `visa-cli setup` again.";console.error(` ${C}`),process.exit(1)}}else console.error(` Biometric setup failed: ${O}`),process.exit(1)}}let u=Et.join(K.homedir(),".claude","settings.json"),d=$e.existsSync(Et.join(K.homedir(),".claude.json"));if(e.hud===!0)if(!d)console.log(`
172
+ ${i}`:e}function vh(e){return e.replace(/(^|\n)(Commands:\n)([\s\S]*?)(?=\n[A-Z][A-Za-z ]+:\n|$)/g,(t,n,r,s)=>{let o=s.split(`
173
+ `).map(bh).join(`
174
+ `);return`${n}${r}${o}`})}function bh(e){if(!e.startsWith(" "))return e;let n=2,r=n;for(;r<e.length&&e[r]!==" "&&e[r]!==" ";)r+=1;if(r===n)return e;let s=-1;for(let l=r;l<e.length-1;l+=1){if(e[l]!==" "||e[l+1]!==" ")continue;let c=l+2;for(;c<e.length&&e[c]===" ";)c+=1;if(c<e.length){s=c;break}}if(s===-1)return e;let o=e.slice(n,r),i=e.slice(s),a=Math.max(2,s-2-o.length);return` ${o}${" ".repeat(a)}${i}`}function Sh(e){return e.replace(/^(Usage: .+?) \[options\](?= |$)/gm,"$1")}function wh(e){return e.replace(/^Options:$/gm,"Flags:")}function zl(e){let t=e.helpInformation.bind(e);e.helpInformation=()=>wh(Sh(vh(yh(_h(t())))));for(let n of e.commands)zl(n)}function xh(e){let t=new Map(e.map((r,s)=>[r,s]));G.commands.sort((r,s)=>{let o=t.get(r.name())??Number.MAX_SAFE_INTEGER,i=t.get(s.name())??Number.MAX_SAFE_INTEGER;return o-i})}G.name("visa-cli").description("Visa CLI - set up MCP payments, manage credentials, and monitor AI spend").version(fr().version).addHelpCommand(!1).action(Pe);G.hook("preAction",async()=>{await Si()});G.command("setup").description("Register MCP server, authenticate, and generate attestation key").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--yes","Accept setup prompts without asking \u2014 for CI/agent use").option("--hud","Also enable the Visa HUD (Claude Code statusLine)").option("--no-hud","Do not install the Visa HUD during setup (default)").action(async e=>{try{if(e.check){let y=sr();Ll(y,"MCP config check:"),y.length>0&&(console.log("\nRun `visa-cli setup` (or `visa-cli install --repair`) to rewrite these entries."),process.exit(1));return}console.log("Step 1: Registering MCP server...");let t=sr(),n=new Map(t.map(y=>[y.client.id,y])),r=new Set,s=new Set,o=new Set;for(let y of Ie)if(nr(y)){let k;try{k=rr(y)}catch(C){if(C instanceof Tn){El(C),s.add(y.displayName),o.add(y.id);continue}throw C}let O=n.get(y.id),N=O?` \u2014 repaired stale ${O.staleReason} entry`:"";console.log(` \u2713 ${y.displayName} (${k.configPath.replace(K.homedir(),"~")})${N}`),O&&r.add(y.id)}let i=t.filter(y=>!r.has(y.client.id)&&!o.has(y.client.id)),a=0;for(let y of i){try{Wo(y)}catch(k){if(k instanceof Tn){El(k),s.add(y.client.displayName),o.add(y.client.id);continue}throw k}console.log(` \u2713 ${y.client.displayName} (${y.configPath.replace(K.homedir(),"~")}) \u2014 repaired stale ${y.staleReason} entry`),a++}let l=r.size+a;l===0&&s.size===0?console.log(" \u2713 MCP config verified \u2014 nothing to repair."):l>0&&console.log(` \u2713 Repaired ${l} stale MCP config ${l===1?"entry":"entries"}.`),s.size>0&&console.log(` ! Skipped MCP registration for: ${Array.from(s).join(", ")}. Rerun with access to those config files to complete registration.`),console.log(`
175
+ Step 2: Checking authentication...`);let c=await U.getSessionToken();if(c)try{await new ye(()=>Promise.resolve(c)).getStatus(),console.log(" Already authenticated.")}catch(y){let k=y instanceof Error?y.message:"";k.includes("session has expired")||k.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await U.clearAll(),c=null):console.log(` Couldn't verify session (${k||"unknown error"}) \u2014 continuing with existing token.`)}if(!c){let y=null;try{let{stdout:k}=await Zo("gh",["auth","token"],{timeout:5e3});y=k.trim()}catch{}if(y||(y=process.env.GITHUB_TOKEN||null),y)try{console.log(" Found GitHub token \u2014 attempting headless login...");let k=await globalThis.fetch(`${we()}/v1/auth/token-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({github_token:y}),signal:AbortSignal.timeout(1e4)});if(k.ok){let O=await k.json();if(O.success&&O.sessionToken){let N=O.sessionToken;c=N,await U.saveSessionToken(N),console.log(` Signed in as ${O.user} (headless).`)}}else(await k.json().catch(()=>({}))).hint==="card_required"&&console.log(" GitHub token valid but no card on file \u2014 opening browser for card enrollment...")}catch{}}if(c||(console.log(" No session found. Opening browser for GitHub login..."),c=await new Promise(async(y,k)=>{let O=fs.randomUUID(),N=`${we()}/login?state=${O}`;await Rs(N);let C=3e4,T=300*1e3,q=Date.now()+T;for(;Date.now()<q;)try{let z=await globalThis.fetch(`${we()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:O,timeout:C}),signal:AbortSignal.timeout(C+5e3)});if(!z.ok){await dt(z,it=>{m.warn("auth_status:retry_after_http_error",{status:z.status,delayMs:it})});continue}let F=await z.json();if(F.status==="pending")continue;if(F.status==="expired"){k(new Error("Session expired. Please run setup again."));return}if(F.status==="complete"&&F.sessionToken){console.log(` Signed in as ${F.user}.`),y(F.sessionToken);return}}catch{await dt(void 0,z=>{m.warn("auth_status:retry_after_network_error",{delayMs:z})})}k(new Error("Login timed out after 5 minutes. Please run setup again."))}),await U.saveSessionToken(c),console.log(" Session token saved.")),console.log(`
176
+ Step 3: Setting up authentication...`),!te())console.log(" Not macOS \u2014 skipping biometric setup.");else{try{await Zo("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 y=ne();try{let k=await y.getStatus(),O=!0;if(Dl(k))if(await mc())try{await th(y),console.log(" Attestation key already registered with server."),console.log(" Existing local Touch ID key verified and preserved."),O=!1}catch(N){if(!Al(N))throw N;console.log(" Existing local Touch ID key does not match server biometric state."),await Jo(y),O=!1}else console.log(" Server already has a biometric key, but this device has no local key."),await Jo(y),O=!1;O&&await Ul(y,k.attestationRequired===!1)}catch(k){let O=k?.message||"unknown error";if(Al(k)){console.log(" Server already has a biometric key for this account, but this device cannot prove access to it.");let N=!1;try{await Jo(y),N=!0}catch(C){console.error(` Biometric recovery failed: ${C?.message||"unknown error"}`)}if(!N){let C=k instanceof Mt&&k.hint?k.hint:"Run `visa-cli config reset` to clear server-side biometric state through GitHub, then run `visa-cli setup` again.";console.error(` ${C}`),process.exit(1)}}else console.error(` Biometric setup failed: ${O}`),process.exit(1)}}let u=At.join(K.homedir(),".claude","settings.json"),d=$e.existsSync(At.join(K.homedir(),".claude.json"));if(e.hud===!0)if(!d)console.log(`
177
177
  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(`
178
- Step 4: Enabling the Visa spend HUD...`);let y=Nn(u),k=y.installed==="new"||y.installed==="already-visa"||y.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${k}${y.message}`);try{let O=se(),N=await O.getStatus(),C={currentVersion:O.getClientVersion(),latestVersion:O.lastSignals?.updateAvailable?.latestVersion,updateCheckDisabled:Oe()},T=Os(N,C);Ns(T,N),console.log(` Preview: ${T.split(`
178
+ Step 4: Enabling the Visa spend HUD...`);let y=Ln(u),k=y.installed==="new"||y.installed==="already-visa"||y.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${k}${y.message}`);try{let O=ne(),N=await O.getStatus(),C={currentVersion:O.getClientVersion(),latestVersion:O.lastSignals?.updateAvailable?.latestVersion,updateCheckDisabled:Ne()},T=Ls(N,C);Ds(T,N),console.log(` Preview: ${T.split(`
179
179
  `)[0]}`)}catch{}}let f="\x1B[1m",g="\x1B[2m",w="\x1B[0m";console.log(`
180
180
  \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
181
181
  \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
@@ -204,56 +204,56 @@ Step 4: Enabling the Visa spend HUD...`);let y=Nn(u),k=y.installed==="new"||y.in
204
204
 
205
205
  ${f}Verify:${w} visa-cli status
206
206
  ${f}Docs:${w} https://visacli.sh
207
- `)}catch(t){console.error("Error:",t.message),process.exit(1)}});G.command("install [client]",{hidden:!0}).description("Register MCP server with an AI client (claude, cursor, windsurf, cline, zed, ...)").option("--all","Install for all detected clients").option("--list","Show supported clients and install status").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--repair","Repair stale MCP client configs without re-running the full setup flow").option("--scope <scope>","Install scope: global or project","global").action(async(e,t)=>{try{if(t.check){let o=nr();Ml(o,"MCP config check:"),o.length>0&&process.exit(1);return}if(t.repair){let o=nr();if(o.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of o)Go(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(K.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
207
+ `)}catch(t){console.error("Error:",t.message),process.exit(1)}});G.command("install [client]",{hidden:!0}).description("Register MCP server with an AI client (claude, cursor, windsurf, cline, zed, ...)").option("--all","Install for all detected clients").option("--list","Show supported clients and install status").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--repair","Repair stale MCP client configs without re-running the full setup flow").option("--scope <scope>","Install scope: global or project","global").action(async(e,t)=>{try{if(t.check){let o=sr();Ll(o,"MCP config check:"),o.length>0&&process.exit(1);return}if(t.repair){let o=sr();if(o.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of o)Wo(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(K.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
208
208
  Repaired ${o.length} stale MCP config ${o.length===1?"entry":"entries"}.`);return}if(t.list){console.log(`
209
209
  \x1B[1mSupported MCP Clients\x1B[0m
210
- `),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 Ie){let l=er(a),c=xl(a),u=l?"Yes":"No",d=c?"Yes":"No",f=a.globalConfigPath.replace(K.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 o=[],i=[];for(let a of Ie){if(!er(a)){i.push(a.displayName);continue}tr(a,n),o.push(a.displayName)}o.length>0&&console.log(`Installed for: ${o.join(", ")}.`),i.length>0&&console.log(`Skipped: ${i.map(a=>`${a} (not detected)`).join(", ")}.`),o.length===0&&i.length===0&&console.log("No supported clients found.");return}e||(console.error("Usage: visa-cli install <client>"),console.error(" visa-cli install --all"),console.error(" visa-cli install --list"),console.error(`
211
- Supported clients: ${Ie.map(o=>o.id).join(", ")}`),process.exit(1));let r=Vo(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${Ie.map(o=>o.id).join(", ")}`),process.exit(1)),n==="global"&&!er(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let s=tr(r,n);console.log(`Registered visa-cli MCP server in ${s.configPath}`),console.log(s.message)}catch(n){console.error("Error:",n.message),process.exit(1)}});G.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{rr=!1;try{let e=se(),[t,n]=await Promise.all([e.getStatus(),e.getTransactions().catch(s=>{if(process.env.VISA_CLI_DEBUG){let o=s instanceof Error?s.message:String(s);process.stderr.write(`[visa-cli] getTransactions failed (HUD will omit): ${o}
212
- `)}return{transactions:[]}})]),r={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:Oe()};process.stdout.write(fl(t,Array.isArray(n?.transactions)?n.transactions:[],te(),r)),rr=!0}catch(e){rr=!1,console.error("Error:",e.message),process.exit(1)}});function Sh(e){let t=e.map(gl),n=Math.max(2,...t.map(i=>i.id.length)),r=Math.max(5,...t.map(i=>i.brand.length)),s=Math.max(4,...t.map(i=>i.card.length)),o=7;console.log(`
210
+ `),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 Ie){let l=nr(a),c=Tl(a),u=l?"Yes":"No",d=c?"Yes":"No",f=a.globalConfigPath.replace(K.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 o=[],i=[];for(let a of Ie){if(!nr(a)){i.push(a.displayName);continue}rr(a,n),o.push(a.displayName)}o.length>0&&console.log(`Installed for: ${o.join(", ")}.`),i.length>0&&console.log(`Skipped: ${i.map(a=>`${a} (not detected)`).join(", ")}.`),o.length===0&&i.length===0&&console.log("No supported clients found.");return}e||(console.error("Usage: visa-cli install <client>"),console.error(" visa-cli install --all"),console.error(" visa-cli install --list"),console.error(`
211
+ Supported clients: ${Ie.map(o=>o.id).join(", ")}`),process.exit(1));let r=Bo(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${Ie.map(o=>o.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 s=rr(r,n);console.log(`Registered visa-cli MCP server in ${s.configPath}`),console.log(s.message)}catch(n){console.error("Error:",n.message),process.exit(1)}});G.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{or=!1;try{let e=ne(),[t,n]=await Promise.all([e.getStatus(),e.getTransactions().catch(s=>{if(process.env.VISA_CLI_DEBUG){let o=s instanceof Error?s.message:String(s);process.stderr.write(`[visa-cli] getTransactions failed (HUD will omit): ${o}
212
+ `)}return{transactions:[]}})]),r={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:Ne()};process.stdout.write(yl(t,Array.isArray(n?.transactions)?n.transactions:[],te(),r)),or=!0}catch(e){or=!1,console.error("Error:",e.message),process.exit(1)}});function Ch(e){let t=e.map(_l),n=Math.max(2,...t.map(i=>i.id.length)),r=Math.max(5,...t.map(i=>i.brand.length)),s=Math.max(4,...t.map(i=>i.card.length)),o=7;console.log(`
213
213
  Cards
214
214
  `),console.log(` ${"ID".padEnd(n)} ${"Brand".padEnd(r)} ${"Card".padEnd(s)} Default`),console.log(` ${"\u2500".repeat(n)} ${"\u2500".repeat(r)} ${"\u2500".repeat(s)} ${"\u2500".repeat(o)}`);for(let i of t)console.log(` ${i.id.padEnd(n)} ${i.brand.padEnd(r)} ${i.card.padEnd(s)} ${i.default}`);console.log(`
215
215
  Use:`),console.log(" visa-cli cards default <id>"),console.log(` visa-cli cards remove <id>
216
- `)}async function wh(e,t){if(t.yes)return"confirmed";if(!process.stdin.isTTY)return"refused-non-tty";let n=$l.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 fs=G.command("cards").description("Manage enrolled payment cards").addHelpCommand(!1);fs.command("list").description("List enrolled payment cards").action(async()=>{try{let e=await je.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}Sh(t)}catch(e){console.error("Error:",e.message),process.exit(1)}});fs.command("add").description("Add a new Visa card").action(async()=>{try{let e=await je.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)}});fs.command("remove <card-id>").description("Remove an enrolled card").option("-y, --yes","Skip the interactive confirmation prompt").action(async(e,t)=>{try{let n=Uo(e),r=await wh(`Remove card ${n}? This cannot be undone.`,t);if(r==="refused-non-tty"&&(console.error("Refusing to remove card without --yes in a non-interactive shell."),process.exit(1)),r==="declined"){console.log("Aborted.");return}let s=await je.removeCard({cardId:n,confirm:!0},"visa-cli cards remove");s?.success===!1&&(console.error(s.error||s.message||"Failed to remove card."),process.exit(1)),console.log(s?.message||`Removed card ${n}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});fs.command("default <card-id>").alias("set-default").description("Set the default payment card").action(async e=>{try{let t=Uo(e),n=await je.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 Qo=G.command("tokens").description("Create and manage API tokens for apps and agents").addHelpCommand(!1);function ei(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)}Qo.command("create [label]").description("Create an API token for the authenticated approved user").option("--tools <ids>","Comma-separated allowed tool ids (default: all tools)").option("--daily-cap <usd>","Daily cap in USD, between 1 and 100 (default: server default)").option("--json","Output raw JSON").action(async(e,t)=>{try{let r=await se().createAppApiKey({label:th(e),allowed_tools:nh(t.tools),daily_cap_cents:rh(t.dailyCap)});if(t.json){console.log(JSON.stringify(r,null,2));return}console.log("API token created."),console.log(""),console.log(`Key: ${r.key}`),console.log(`Label: ${r.label}`),console.log(`Owner: ${r.owner}`),console.log(`Allowed tools: ${Dl(r.allowed_tools)}`),console.log(`Daily cap: ${sr(r.daily_cap_cents)}/day`),console.log(""),console.log("Store this key now. It will not be shown again."),console.log(""),r.biometric_enabled?(console.log("---------------------------------------------------------------"),console.log("Biometric (Touch ID) is currently ON for this account."),console.log("This API token can still be used headlessly. Per-call Touch ID is"),console.log("not required; spending is bounded by the token daily cap and tools."),console.log("---------------------------------------------------------------"),console.log("")):r.biometric_warning&&(console.log("Note: API tokens bypass per-call biometric verification."),console.log("Keep daily caps and allowed tools scoped for headless use."),console.log("")),console.log("Example:"),console.log(` curl -X POST ${we()}/v1/api/shortcuts/or-gpt-4o-mini \\`),console.log(` -H "X-Api-Key: ${r.key}" \\`),console.log(' -H "Content-Type: application/json" \\'),console.log(` -d '{"prompt":"Say hello in one sentence."}'`)}catch(n){ei(n)}});Qo.command("list").description("List API tokens for the authenticated user").option("--json","Output raw JSON").action(async e=>{try{let n=await se().listAppApiKeys();if(e.json){console.log(JSON.stringify(n,null,2));return}let r=n.keys||[];if(r.length===0){console.log("No API tokens found. Create one with: visa-cli tokens create");return}console.log("API tokens"),console.log("");for(let s of r)console.log(`${s.id}. ${s.label} (${s.key_prefix})`),console.log(` Status: ${s.status}`),console.log(` Owner: ${s.owner}`),console.log(` Allowed tools: ${Dl(s.allowed_tools)}`),console.log(` Daily cap: ${sr(s.daily_cap_cents)}/day`),console.log(` Last used: ${s.last_used_at||"never"}`)}catch(t){ei(t)}});Qo.command("revoke <id>").alias("delete").description("Revoke (or delete) an API token by id").action(async e=>{try{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Error("API token id must be a positive integer. Run `visa-cli tokens list` first.");let r=await se().revokeAppApiKey(t);console.log(`Revoked API token ${r.revoked}.`)}catch(t){ei(t)}});async function Kl(){try{console.log(`Resetting Visa CLI...
217
- `);let e=se();await Zo(e);try{await e.logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}if(await U.clearAll(),console.log(" Keychain credentials cleared."),te())try{await Vr(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}console.log(`
218
- Reset complete.`)}catch(e){console.error("Error:",e.message),process.exit(1)}}G.command("reset",{hidden:!0}).description("Deprecated alias for `config reset`").action(Kl);var xh=100,Ch=1e4,ti=G.command("balance").description("Manage prepaid balance").addHelpCommand(!1);ti.command("show").description("Show prepaid balance + recent ledger entries").action(async()=>{try{let t=await new ye(()=>U.getSessionToken()).getBalance();if(console.log(`
219
- Balance: ${Yo(t.balanceMicros,t.balanceCents)}
216
+ `)}async function kh(e,t){if(t.yes)return"confirmed";if(!process.stdin.isTTY)return"refused-non-tty";let n=Ol.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 hs=G.command("cards").description("Manage enrolled payment cards").addHelpCommand(!1).action(Pe);hs.command("list").description("List enrolled payment cards").action(async()=>{try{let e=await Ve.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}Ch(t)}catch(e){console.error("Error:",e.message),process.exit(1)}});hs.command("add").description("Add a new Visa card").action(async()=>{try{let e=await Ve.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)}});hs.command("remove <card-id>").description("Remove an enrolled card").option("-y, --yes","Skip the interactive confirmation prompt").action(async(e,t)=>{try{let n=Vo(e),r=await kh(`Remove card ${n}? This cannot be undone.`,t);if(r==="refused-non-tty"&&(console.error("Refusing to remove card without --yes in a non-interactive shell."),process.exit(1)),r==="declined"){console.log("Aborted.");return}let s=await Ve.removeCard({cardId:n,confirm:!0},"visa-cli cards remove");s?.success===!1&&(console.error(s.error||s.message||"Failed to remove card."),process.exit(1)),console.log(s?.message||`Removed card ${n}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});hs.command("default <card-id>").alias("set-default").description("Set the default payment card").action(async e=>{try{let t=Vo(e),n=await Ve.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 ti=G.command("tokens").description("Create and manage API tokens for apps and agents").addHelpCommand(!1).action(Pe);function ni(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)}ti.command("create [label]").description("Create an API token for the authenticated approved user").option("--tools <ids>","Comma-separated allowed tool ids (default: all tools)").option("--daily-cap <usd>","Daily cap in USD, between 1 and 100 (default: server default)").option("--json","Output raw JSON").action(async(e,t)=>{try{let r=await ne().createAppApiKey({label:sh(e),allowed_tools:oh(t.tools),daily_cap_cents:ih(t.dailyCap)});if(t.json){console.log(JSON.stringify(r,null,2));return}console.log("API token created."),console.log(""),console.log(`Key: ${r.key}`),console.log(`Label: ${r.label}`),console.log(`Owner: ${r.owner}`),console.log(`Allowed tools: ${Vl(r.allowed_tools)}`),console.log(`Daily cap: ${ir(r.daily_cap_cents)}/day`),console.log(""),console.log("Store this key now. It will not be shown again."),console.log(""),r.biometric_enabled?(console.log("---------------------------------------------------------------"),console.log("Biometric (Touch ID) is currently ON for this account."),console.log("This API token can still be used headlessly. Per-call Touch ID is"),console.log("not required; spending is bounded by the token daily cap and tools."),console.log("---------------------------------------------------------------"),console.log("")):r.biometric_warning&&(console.log("Note: API tokens bypass per-call biometric verification."),console.log("Keep daily caps and allowed tools scoped for headless use."),console.log("")),console.log("Example:"),console.log(` curl -X POST ${we()}/v1/api/shortcuts/or-gpt-4o-mini \\`),console.log(` -H "X-Api-Key: ${r.key}" \\`),console.log(' -H "Content-Type: application/json" \\'),console.log(` -d '{"prompt":"Say hello in one sentence."}'`)}catch(n){ni(n)}});ti.command("list").description("List API tokens for the authenticated user").option("--json","Output raw JSON").action(async e=>{try{let n=await ne().listAppApiKeys();if(e.json){console.log(JSON.stringify(n,null,2));return}let r=n.keys||[];if(r.length===0){console.log("No API tokens found. Create one with: visa-cli tokens create");return}console.log("API tokens"),console.log("");for(let s of r)console.log(`${s.id}. ${s.label} (${s.key_prefix})`),console.log(` Status: ${s.status}`),console.log(` Owner: ${s.owner}`),console.log(` Allowed tools: ${Vl(s.allowed_tools)}`),console.log(` Daily cap: ${ir(s.daily_cap_cents)}/day`),console.log(` Last used: ${s.last_used_at||"never"}`)}catch(t){ni(t)}});ti.command("revoke <id>").alias("delete").description("Revoke (or delete) an API token by id").action(async e=>{try{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Error("API token id must be a positive integer. Run `visa-cli tokens list` first.");let r=await ne().revokeAppApiKey(t);console.log(`Revoked API token ${r.revoked}.`)}catch(t){ni(t)}});async function Wl(){try{console.log(`Resetting Visa CLI...
217
+ `);let e=ne();await Qo(e);try{await e.logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}if(await U.clearAll(),console.log(" Keychain credentials cleared."),te())try{await Hr(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}console.log(`
218
+ Reset complete.`)}catch(e){console.error("Error:",e.message),process.exit(1)}}G.command("reset",{hidden:!0}).description("Deprecated alias for `config reset`").action(Wl);var Th=100,Eh=1e4,ri=G.command("balance").description("Manage prepaid balance").addHelpCommand(!1).action(Pe);ri.command("show").description("Show prepaid balance + recent ledger entries").action(async()=>{try{let t=await new ye(()=>U.getSessionToken()).getBalance();if(console.log(`
219
+ Balance: ${Xo(t.balanceMicros,t.balanceCents)}
220
220
  `),t.ledger.length===0){console.log(` (no ledger entries \u2014 top up to begin: visa-cli balance topup --amount 5)
221
- `);return}let n=t.ledger.slice(0,20),r=[],s=t.balanceCents,o=t.balanceMicros?BigInt(t.balanceMicros):null;for(let u of n)r.push(o!=null?o.toString():String(s*1e4)),o!=null&&u.deltaMicros?o-=BigInt(u.deltaMicros):(o=null,s-=u.deltaCents);let i=19,a=11,l=13,c=18;console.log(` ${"TIMESTAMP".padEnd(i)} ${"DELTA".padStart(a)} ${"BALANCE".padStart(l)} ${"REASON".padEnd(c)} TOOL`),console.log(` ${"\u2500".repeat(i)} ${"\u2500".repeat(a)} ${"\u2500".repeat(l)} ${"\u2500".repeat(c)} ${"\u2500".repeat(20)}`),n.forEach((u,d)=>{let f=(u.createdAt||"").slice(0,19),g=Yo(u.deltaMicros,u.deltaCents,!0),w=eh(r[d]),y=(u.reason??"").slice(0,c),k=u.toolName??"";console.log(` ${f.padEnd(i)} ${g.padStart(a)} ${w.padStart(l)} ${y.padEnd(c)} ${k}`)}),console.log()}catch(e){console.error("Error:",e.message),process.exit(1)}});ti.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=hl(e.amount,xh,Ch);if(!t.ok)throw new Error(t.error);let n=t.cents,r=n/100,s=new ye(()=>U.getSessionToken());if(!te())throw new Error(Zr);let o=ms.randomUUID(),i=await zn(s,async()=>{let a;if(te()){let{nonce:l}=await s.getAttestationChallenge(),c=Buffer.from(JSON.stringify({nonce:l,amount:r,merchant:"Visa CLI Balance",context:"balance-topup"})).toString("base64");a={signature:await bn(c,`top up balance with $${t.displayUsd}`),nonce:l,amount:r,merchant:"Visa CLI Balance"}}return s.topupBalance({amount_cents:n,idempotency_key:o,attestation:a})},Ll(s));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}`),Di();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 Gl=ti.command("auto-topup").description("Show or disable automatic balance top-ups (read/disable only \u2014 re-enabling is retired pending mandate model)").addHelpCommand(!1);Gl.command("show").description("Show current auto-topup configuration").action(async()=>{try{let t=await new ye(()=>U.getSessionToken()).getAutoTopup();if(t.targetCents==null||t.targetCents===0){console.log(`
221
+ `);return}let n=t.ledger.slice(0,20),r=[],s=t.balanceCents,o=t.balanceMicros?BigInt(t.balanceMicros):null;for(let u of n)r.push(o!=null?o.toString():String(s*1e4)),o!=null&&u.deltaMicros?o-=BigInt(u.deltaMicros):(o=null,s-=u.deltaCents);let i=19,a=11,l=13,c=18;console.log(` ${"TIMESTAMP".padEnd(i)} ${"DELTA".padStart(a)} ${"BALANCE".padStart(l)} ${"REASON".padEnd(c)} TOOL`),console.log(` ${"\u2500".repeat(i)} ${"\u2500".repeat(a)} ${"\u2500".repeat(l)} ${"\u2500".repeat(c)} ${"\u2500".repeat(20)}`),n.forEach((u,d)=>{let f=(u.createdAt||"").slice(0,19),g=Xo(u.deltaMicros,u.deltaCents,!0),w=rh(r[d]),y=(u.reason??"").slice(0,c),k=u.toolName??"";console.log(` ${f.padEnd(i)} ${g.padStart(a)} ${w.padStart(l)} ${y.padEnd(c)} ${k}`)}),console.log()}catch(e){console.error("Error:",e.message),process.exit(1)}});ri.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=vl(e.amount,Th,Eh);if(!t.ok)throw new Error(t.error);let n=t.cents,r=n/100,s=new ye(()=>U.getSessionToken());if(!te())throw new Error(Qr);let o=fs.randomUUID(),i=await Wn(s,async()=>{let a;if(te()){let{nonce:l}=await s.getAttestationChallenge(),c=Buffer.from(JSON.stringify({nonce:l,amount:r,merchant:"Visa CLI Balance",context:"balance-topup"})).toString("base64");a={signature:await Sn(c,`top up balance with $${t.displayUsd}`),nonce:l,amount:r,merchant:"Visa CLI Balance"}}return s.topupBalance({amount_cents:n,idempotency_key:o,attestation:a})},jl(s));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}`),ji();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 Jl=ri.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(Pe);Jl.command("show").description("Show current auto-topup configuration").action(async()=>{try{let t=await new ye(()=>U.getSessionToken()).getAutoTopup();if(t.targetCents==null||t.targetCents===0){console.log(`
222
222
  Auto-topup: disabled
223
- `);return}let n=sr(t.targetCents),r=sr(t.thresholdCents),s=12,o=13;console.log(),console.log(` ${"STATE".padEnd(s)} enabled`),console.log(` ${"TARGET".padEnd(s)} ${n.padStart(o)} (refill balance to this amount)`),console.log(` ${"THRESHOLD".padEnd(s)} ${r.padStart(o)} (trigger refill when balance drops below this)`),console.log(),console.log(" Disable with: visa-cli balance auto-topup disable"),console.log()}catch(e){console.error("Error:",e.message),process.exit(1)}});Gl.command("disable").description("Disable auto-topup").action(async()=>{try{let t=await new ye(()=>U.getSessionToken()).disableAutoTopup();t.success||(console.error(`Auto-topup disable failed: ${t.error||"Unknown error"}`),process.exit(1)),console.log("Auto-topup disabled. Your balance will no longer refill automatically.")}catch(e){console.error("Error:",e.message),process.exit(1)}});var kh=G.command("session",{hidden:!0}).description("Inspect session budgets");kh.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 ye(()=>U.getSessionToken()),[n,r]=await Promise.allSettled([t.getSessionBudget(e),t.getSessionLedger(e)]),s=n.status==="fulfilled"?n.value.budget:void 0,o=r.status==="fulfilled"?r.value:void 0;if(!s&&!o?.ledger?.length&&(console.error(`Session not found: ${e}`),process.exit(1)),console.log(`
223
+ `);return}let n=ir(t.targetCents),r=ir(t.thresholdCents),s=12,o=13;console.log(),console.log(` ${"STATE".padEnd(s)} enabled`),console.log(` ${"TARGET".padEnd(s)} ${n.padStart(o)} (refill balance to this amount)`),console.log(` ${"THRESHOLD".padEnd(s)} ${r.padStart(o)} (trigger refill when balance drops below this)`),console.log(),console.log(" Disable with: visa-cli balance auto-topup disable"),console.log()}catch(e){console.error("Error:",e.message),process.exit(1)}});Jl.command("disable").description("Disable auto-topup").action(async()=>{try{let t=await new ye(()=>U.getSessionToken()).disableAutoTopup();t.success||(console.error(`Auto-topup disable failed: ${t.error||"Unknown error"}`),process.exit(1)),console.log("Auto-topup disabled. Your balance will no longer refill automatically.")}catch(e){console.error("Error:",e.message),process.exit(1)}});var Ah=G.command("session",{hidden:!0}).description("Inspect session budgets");Ah.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 ye(()=>U.getSessionToken()),[n,r]=await Promise.allSettled([t.getSessionBudget(e),t.getSessionLedger(e)]),s=n.status==="fulfilled"?n.value.budget:void 0,o=r.status==="fulfilled"?r.value:void 0;if(!s&&!o?.ledger?.length&&(console.error(`Session not found: ${e}`),process.exit(1)),console.log(`
224
224
  Session: ${e}`),s){let i=(s.totalCents/100).toFixed(2),a=(s.cumulativeCents/100).toFixed(2),l=(s.remainingCents/100).toFixed(2);console.log(` Status: ${s.status}${s.expired?" (expired)":""}`),console.log(` Budget: $${i} \xB7 spent $${a} \xB7 remaining $${l}`),console.log(` Created: ${s.createdAt}`),console.log(` Expires: ${s.expiresAt}`)}if(o?.ledger?.length){console.log(`
225
225
  PSP References (CyberSource activity):`);let i=8,a=9,l=36;console.log(` ${"TYPE".padEnd(i)} ${"AMOUNT".padStart(a)} ${"CYBERSOURCE TX ID".padEnd(l)} CREATED`),console.log(` ${"\u2500".repeat(i)} ${"\u2500".repeat(a)} ${"\u2500".repeat(l)} ${"\u2500".repeat(19)}`);for(let c of o.ledger){let u=`$${(c.amountCents/100).toFixed(2)}`;console.log(` ${c.type.padEnd(i)} ${u.padStart(a)} ${(c.transactionId||"").padEnd(l)} ${(c.createdAt||"").slice(0,19)}`)}}else s&&console.log(`
226
- (no PSP references yet \u2014 no holds placed)`);console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});async function zl(e){(!e||e.trim().length===0)&&(console.log('Usage: visa-cli feedback "your message"'),process.exit(1));try{await U.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await se().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}}G.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action(zl);G.command("update").description("Update Visa CLI to the latest stable version").action(async()=>{let e=Rs();try{console.log(`Updating Visa CLI with ${e.packageManager}: ${e.display}`);let{stdout:t,stderr:n}=await Jo(e.command,e.args,{timeout:5*6e4,maxBuffer:10*1024*1024});t.trim()&&process.stdout.write(t),n.trim()&&process.stderr.write(n),console.log("Visa CLI update complete. Restart any running MCP clients to use the new version.")}catch(t){console.error(`Update failed while running: ${e.display}`),console.error(t?.message??String(t)),process.exit(1)}});var st=G.command("config").description("Manage CLI configuration and local integrations").addHelpCommand(!1);st.command("feedback",{hidden:!0}).description("Deprecated alias for `feedback`").argument("[message]","Your feedback message").action(zl);st.command("list").description("Show resolved config values (env vars, server state, defaults) with their source").option("--json","Output as JSON for scripting / agent consumption").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").option("--verbose","Show one-line hints beneath entries that have them").action(async e=>{try{let t=se(),n=await Kr({api:t,includeDev:!!e.dev});if(e.json){console.log(_c(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(yc(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});function Th(){return Object.entries(ft).map(([e,t])=>` ${e.padEnd(22)} (${t.type}) ${t.description}`).join(`
227
- `)}st.command("set <key> <value>").description("Persist a CLI setting to ~/.visa-mcp/settings.json").addHelpText("after",`
226
+ (no PSP references yet \u2014 no holds placed)`);console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});async function Yl(e){(!e||e.trim().length===0)&&(console.log('Usage: visa-cli feedback "your message"'),process.exit(1));try{await U.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await ne().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}}G.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action(Yl);G.command("update").description("Update Visa CLI to the latest stable version").action(async()=>{let e=$s();try{console.log(`Updating Visa CLI with ${e.packageManager}: ${e.display}`);let{stdout:t,stderr:n}=await Zo(e.command,e.args,{timeout:5*6e4,maxBuffer:10*1024*1024});t.trim()&&process.stdout.write(t),n.trim()&&process.stderr.write(n),console.log("Visa CLI update complete. Restart any running MCP clients to use the new version.")}catch(t){console.error(`Update failed while running: ${e.display}`),console.error(t?.message??String(t)),process.exit(1)}});var Ge=G.command("config").description("Manage CLI configuration and local integrations").addHelpCommand(!1).action(Pe);Ge.command("feedback",{hidden:!0}).description("Deprecated alias for `feedback`").argument("[message]","Your feedback message").action(Yl);Ge.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=ne(),n=await Jn({api:t,includeDev:!!e.dev});if(e.json){console.log(Sc(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(bc(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});Ge.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=ne(),s=(await Jn({api:n,includeDev:!!t.dev})).entries.find(o=>o.key===e);s||(console.error(`Error: unknown config key '${e}'. Run 'visa-cli config list' to see available keys.`),process.exit(1)),t.raw?console.log(JSON.stringify(s.value)):console.log(s.formatted)}catch(n){console.error("Error:",n.message),process.exit(1)}});function Rh(){return Object.entries(gt).map(([e,t])=>` ${e.padEnd(22)} (${t.type}) ${t.description}`).join(`
227
+ `)}Ge.command("set <key> <value>").description("Persist a CLI setting to ~/.visa-mcp/settings.json").addHelpText("after",`
228
228
  Settable keys:
229
- ${Th()}`).action((e,t)=>{try{let n=Ar(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 We||n instanceof Je||n instanceof mt?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});st.command("unset <key>").description("Remove a CLI setting from ~/.visa-mcp/settings.json (falls back to env var or default)").action(e=>{try{let t=Rr(e);t.removed?(console.log(`Removed ${t.key} from ${t.path}`),t.requiresRestart&&console.log("Restart Claude Code (or your MCP-enabled client) for the change to take effect.")):console.log(`No-op: ${t.key} was not set in ${t.path}.`)}catch(t){console.error(`Error: ${t.message}`),process.exit(1)}});st.command("reset").description("Log out and clear all credentials").action(Kl);var ni=st.command("biometric").description("Manage Touch ID / biometric attestation enforcement");ni.command("status").description("Show current biometric enforcement state").action(async()=>{try{await U.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let n=await se().getStatus(),r=n.attestationRequired!==!1,s=!!n.hasAttestationKey,o=te();console.log(`Server policy: Touch ID ${r?"REQUIRED":"NOT required"}`),console.log(`Attestation key registered: ${s?"yes":"no"}`),console.log(`Touch ID available on this device: ${o?"yes":"no"}`)}catch(e){console.error("Error:",e.message),process.exit(1)}});ni.command("on").description("Require Touch ID for payments (security upgrade \u2014 no Touch ID needed)").action(async()=>{try{await U.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=se(),n=await t.setBiometricPreference({required:!0});n.success||(console.error(`Failed: ${n.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is now REQUIRED for payments."),(await t.getStatus()).hasAttestationKey||console.warn("Note: no attestation key is registered yet. Run `visa-cli setup` to enroll Touch ID.")}catch(e){console.error("Error:",e.message),process.exit(1)}});ni.command("off").description("Disable Touch ID requirement (security downgrade \u2014 one Touch ID confirmation required)").action(async()=>{try{await U.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=se(),n=await t.getStatus();if(n.attestationRequired===!1){console.log("Touch ID is already disabled.");return}n.hasAttestationKey&&!te()&&(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 zn(t,async()=>{let s;if(n.hasAttestationKey&&te())try{let{nonce:o}=await t.getAttestationChallenge(),i=0,a="",l=Buffer.from(JSON.stringify({nonce:o,amount:i,merchant:a,context:"biometric-preference"})).toString("base64");s={signature:await bn(l,"disable Touch ID requirement"),nonce:o,amount:i,merchant:a}}catch(o){throw new Error(`Touch ID confirmation failed: ${o?.message||"cancelled"}`)}return t.setBiometricPreference({required:!1,attestation:s})},Ll(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 en=st.command("shell-hud").description("Manage the shell prompt HUD (opt-in \u2014 prefer: visa-cli config hud enable)").addHelpCommand(!1);function Wl(){let e=_r();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function Jl(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 Eh(){Jl(Bs(void 0,{homeDir:K.homedir(),installVisaStatusLine:Nn,installShellHud:_r}))}function Yl(){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"),Eh()}function gs(){let e=vr();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}en.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Wl);en.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(Yl);en.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(gs);en.command("disable").description("Disable the persistent shell HUD").action(gs);en.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${br()}
230
- `)});en.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,r=(d,f,g)=>{console.log(` ${f?"\u2713":"\u2717"} ${d}: ${g}`),f||(n=!1)};console.log(`Shell HUD Doctor
231
- `);let s=cn();if(r("Shell detected",!!s,s??"none (zsh, bash, or PowerShell required)"),s){let d=Pn(s),f=e(d);if(r("RC file exists",f,d.replace(K.homedir(),"~")),f){let w=t(d,"utf-8").includes("visa-cli shell hud v2");r("HUD block installed",!!w,w?"found in rc file":"missing \u2014 run: visa-cli config hud enable shell")}}let o=dt(),i=e(o);if(r("Cache file",i,i?o.replace(K.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let d=JSON.parse(t(o,"utf-8")),f=Date.now()-(d.renderedAt??0),g=Math.round(f/1e3),w=g<=30;console.log(` ${w?"\u2713":"\u26A0"} Cache freshness: ${g}s old${w?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{r("Cache readable",!1,"corrupt JSON")}let a=hr(),l=e(a),c="missing";if(l)try{c=t(a,"utf-8").trim().slice(0,80)}catch{c="unreadable"}r("Line file",l,c);let u=!1;try{u=!!await U.getSessionToken()}catch{}if(r("Auth token",u,u?"found in keychain":"missing \u2014 run: visa-cli setup"),u)try{await se().getStatus(),r("API connectivity",!0,"GET /v1/status OK")}catch(d){let f=d instanceof Error?d.message:"unknown error";r("API connectivity",!1,f)}console.log(n?`
229
+ ${Rh()}`).action((e,t)=>{try{let n=$r(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 Ye||n instanceof Ze||n instanceof pt?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});Ge.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=Pr(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)}});Ge.command("reset").description("Log out and clear all credentials").action(Wl);var si=Ge.command("biometric").description("Manage Touch ID / biometric attestation enforcement").addHelpCommand(!1).action(Pe);si.command("status").description("Show current biometric enforcement state").action(async()=>{try{await U.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let n=await ne().getStatus(),r=n.attestationRequired!==!1,s=!!n.hasAttestationKey,o=te();console.log(`Server policy: Touch ID ${r?"REQUIRED":"NOT required"}`),console.log(`Attestation key registered: ${s?"yes":"no"}`),console.log(`Touch ID available on this device: ${o?"yes":"no"}`)}catch(e){console.error("Error:",e.message),process.exit(1)}});si.command("on").description("Require Touch ID for payments (security upgrade \u2014 no Touch ID needed)").action(async()=>{try{await U.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=ne(),n=await t.setBiometricPreference({required:!0});n.success||(console.error(`Failed: ${n.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is now REQUIRED for payments."),(await t.getStatus()).hasAttestationKey||console.warn("Note: no attestation key is registered yet. Run `visa-cli setup` to enroll Touch ID.")}catch(e){console.error("Error:",e.message),process.exit(1)}});si.command("off").description("Disable Touch ID requirement (security downgrade \u2014 one Touch ID confirmation required)").action(async()=>{try{await U.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=ne(),n=await t.getStatus();if(n.attestationRequired===!1){console.log("Touch ID is already disabled.");return}n.hasAttestationKey&&!te()&&(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 Wn(t,async()=>{let s;if(n.hasAttestationKey&&te())try{let{nonce:o}=await t.getAttestationChallenge(),i=0,a="",l=Buffer.from(JSON.stringify({nonce:o,amount:i,merchant:a,context:"biometric-preference"})).toString("base64");s={signature:await Sn(l,"disable Touch ID requirement"),nonce:o,amount:i,merchant:a}}catch(o){throw new Error(`Touch ID confirmation failed: ${o?.message||"cancelled"}`)}return t.setBiometricPreference({required:!1,attestation:s})},jl(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 tn=Ge.command("shell-hud").description("Manage the shell prompt HUD (opt-in \u2014 prefer: visa-cli config hud enable)").addHelpCommand(!1).action(Pe);function Zl(){let e=Sr();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function Xl(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 Ih(){Xl(Ks(void 0,{homeDir:K.homedir(),installVisaStatusLine:Ln,installShellHud:Sr}))}function Ql(){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"),Ih()}function ys(){let e=wr();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}tn.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Zl);tn.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(Ql);tn.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(ys);tn.command("disable").description("Disable the persistent shell HUD").action(ys);tn.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${xr()}
230
+ `)});tn.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,r=(d,f,g)=>{console.log(` ${f?"\u2713":"\u2717"} ${d}: ${g}`),f||(n=!1)};console.log(`Shell HUD Doctor
231
+ `);let s=ln();if(r("Shell detected",!!s,s??"none (zsh, bash, or PowerShell required)"),s){let d=Mn(s),f=e(d);if(r("RC file exists",f,d.replace(K.homedir(),"~")),f){let w=t(d,"utf-8").includes("visa-cli shell hud v2");r("HUD block installed",!!w,w?"found in rc file":"missing \u2014 run: visa-cli config hud enable shell")}}let o=mt(),i=e(o);if(r("Cache file",i,i?o.replace(K.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let d=JSON.parse(t(o,"utf-8")),f=Date.now()-(d.renderedAt??0),g=Math.round(f/1e3),w=g<=30;console.log(` ${w?"\u2713":"\u26A0"} Cache freshness: ${g}s old${w?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{r("Cache readable",!1,"corrupt JSON")}let a=vr(),l=e(a),c="missing";if(l)try{c=t(a,"utf-8").trim().slice(0,80)}catch{c="unreadable"}r("Line file",l,c);let u=!1;try{u=!!await U.getSessionToken()}catch{}if(r("Auth token",u,u?"found in keychain":"missing \u2014 run: visa-cli setup"),u)try{await ne().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?`
232
232
  All checks passed.`:`
233
- Some checks failed \u2014 see above.`),n||process.exit(1)});async function Zl(e){if(!(!e.force&&Ni()))try{let t=se(),[n,r,s,o]=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),s.status==="fulfilled"&&s.value.success&&(i.apiKeyCount=Array.isArray(s.value.keys)?s.value.keys.length:0),o.status==="fulfilled"){let u=o.value,f=(Array.isArray(u)?u:Array.isArray(u.transactions)?u.transactions:[]).find(g=>g&&typeof g.tool_name=="string"&&g.tool_name.length>0);f&&f.created_at&&(i.lastService={toolName:f.tool_name,createdAt:f.created_at})}let l={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:Oe()},c=Os(i,l);Ns(c,i)}catch(t){let n=t instanceof Error?t.message:"unknown refresh failure";Li(n)}finally{$n()}}en.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(Zl);var tn=G.command("shell-hud",{hidden:!0}).description("Deprecated alias for `config shell-hud`");tn.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Wl);tn.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(Yl);tn.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(gs);tn.command("disable").description("Disable the persistent shell HUD").action(gs);tn.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${br()}
234
- `)});tn.command("doctor").description("Show the new shell HUD doctor command").action(()=>{console.log("Run: visa-cli config shell-hud doctor")});tn.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(Zl);async function Xl(e){try{let t=await Yi(),n=br(),r=n,s=n.split(`
235
- `)[0],o=ji();if(!t&&s.includes("loading")){process.stdout.write(`VISA | HUD not initialized \u2014 run: visa-cli config hud enable
236
- `);return}if(e.json){let a=await na(r,t,o);process.stdout.write(`${JSON.stringify(a,null,2)}
237
- `);return}let i=await Qi(r,t,o);process.stdout.write(`${i}
238
- `)}catch(t){let n=t instanceof Error?t.message:"unknown error";console.error(`Failed to render Visa HUD: ${n}`),process.exit(1)}}st.command("statusline").description("Output the Visa HUD for agent statusline integrations").option("--json","Output structured JSON for clients that render their own HUD").action(Xl);G.command("statusline",{hidden:!0}).description("Deprecated alias for `config statusline`").option("--json","Output structured JSON for clients that render their own HUD").action(Xl);var Tn=st.command("hud").description("Manage the Visa spend HUD \u2014 one command for all surfaces").addHelpCommand(!1);Tn.description("Show which HUD surfaces are currently enabled").action(()=>{let e="\x1B[1m",t="\x1B[2m",n="\x1B[32m",r="\x1B[33m",s="\x1B[0m";console.log(`
233
+ Some checks failed \u2014 see above.`),n||process.exit(1)});async function eu(e){if(!(!e.force&&Di()))try{let t=ne(),[n,r,s,o]=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),s.status==="fulfilled"&&s.value.success&&(i.apiKeyCount=Array.isArray(s.value.keys)?s.value.keys.length:0),o.status==="fulfilled"){let u=o.value,f=(Array.isArray(u)?u:Array.isArray(u.transactions)?u.transactions:[]).find(g=>g&&typeof g.tool_name=="string"&&g.tool_name.length>0);f&&f.created_at&&(i.lastService={toolName:f.tool_name,createdAt:f.created_at})}let l={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:Ne()},c=Ls(i,l);Ds(c,i)}catch(t){let n=t instanceof Error?t.message:"unknown refresh failure";Ui(n)}finally{Pn()}}tn.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(eu);var nn=G.command("shell-hud",{hidden:!0}).description("Deprecated alias for `config shell-hud`");nn.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(Zl);nn.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(Ql);nn.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(ys);nn.command("disable").description("Disable the persistent shell HUD").action(ys);nn.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${xr()}
234
+ `)});nn.command("doctor").description("Show the new shell HUD doctor command").action(()=>{console.log("Run: visa-cli config shell-hud doctor")});nn.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(eu);async function tu(e){try{let t=await Xi(),n=xr(),r=n,s=n.split(`
235
+ `)[0],o=qi();if(!t&&s.includes("loading")){process.stdout.write(`VISA | HUD not initialized \u2014 run: visa-cli config hud enable
236
+ `);return}if(e.json){let a=await sa(r,t,o);process.stdout.write(`${JSON.stringify(a,null,2)}
237
+ `);return}let i=await ta(r,t,o);process.stdout.write(`${i}
238
+ `)}catch(t){let n=t instanceof Error?t.message:"unknown error";console.error(`Failed to render Visa HUD: ${n}`),process.exit(1)}}Ge.command("statusline").description("Output the Visa HUD for agent statusline integrations").option("--json","Output structured JSON for clients that render their own HUD").action(tu);G.command("statusline",{hidden:!0}).description("Deprecated alias for `config statusline`").option("--json","Output structured JSON for clients that render their own HUD").action(tu);var En=Ge.command("hud").description("Manage the Visa spend HUD \u2014 one command for all surfaces").addHelpCommand(!1);En.description("Show which HUD surfaces are currently enabled").action(()=>{let e="\x1B[1m",t="\x1B[2m",n="\x1B[32m",r="\x1B[33m",s="\x1B[0m";console.log(`
239
239
  ${e}Visa HUD Status${s}
240
- `);let o=Et.join(K.homedir(),".claude","settings.json"),i=!1,a=!1;try{if($e.existsSync(o)){let w=JSON.parse($e.readFileSync(o,"utf-8")),y=typeof w.statusLine=="object"?w.statusLine.command:"";i=Rt(y),a=!!w.statusLine&&!i}}catch{}let l=i?`${n}\u2713${s}`:`${t}\u2717${s}`,c=i?"registered in ~/.claude/settings.json":a?`${r}another HUD is configured${s} \u2014 edit settings.json to switch`:"not enabled";console.log(` ${l} ${e}Claude Code${s} (statusLine) ${c}`);let u=Mn(K.homedir()),d=u.length>0||yr(),f=d?`${n}\u2713${s}`:`${t}\u2717${s}`,g=d?`installed in shell rc file${u.length>0?` (${u.map(w=>w.replace(K.homedir(),"~")).join(", ")})`:""}`:"not installed (opt-in)";console.log(` ${f} ${e}Shell prompt${s} ${g}`),i&&d&&console.log(` ${r}!${s} ${e}Overlap${s} Claude statusLine and shell prompt HUD are both installed. Remove shell prompt output with: visa-cli config hud disable shell`),console.log(`
241
- ${e}Quick start:${s}`),i||console.log(` visa-cli config hud enable ${t}# Claude Code statusLine (recommended)${s}`),d||console.log(` visa-cli config hud enable shell ${t}# zsh/bash prompt line (opt-in)${s}`),i&&d&&console.log(` ${n}All surfaces enabled.${s}`),(i||d)&&console.log(` visa-cli config hud disable [shell] ${t}# remove a surface${s}`),console.log(` visa-cli config hud doctor ${t}# diagnose connectivity${s}`),console.log()});Tn.command("enable").description("Enable the Visa HUD \u2014 claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{Jl(Bs(e,{homeDir:K.homedir(),installVisaStatusLine:Nn,installShellHud:_r}))});Tn.command("disable").description("Disable the Visa HUD from a surface: claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{let t=e??"claude";if(t==="shell"||t==="prompt"){let o=vr();o.removed||(console.error(o.message),process.exit(1)),console.log(o.message);return}let n=wr(t);n||(console.error(`Unknown HUD surface: ${t}`),console.error("Supported: claude (default), shell, all"),process.exit(1));let r=!1,s=!1;if(n==="claude"||n==="claude-code"||n==="all"){let o=Et.join(K.homedir(),".claude","settings.json"),i=js(o);console.log(i.message),i.removed&&(s=!0),!i.removed&&n!=="all"&&(r=!0)}if(n==="all"){let o=vr();console.log(o.message),o.removed&&(s=!0),!o.removed&&n!=="all"&&(r=!0)}n==="all"&&!s&&(r=!0),r&&process.exit(1)});Tn.command("doctor").description("Diagnose HUD installation and connectivity across all surfaces").action(async()=>{let e=!0,t=(c,u,d)=>{console.log(` ${u?"\u2713":"\u2717"} ${c}: ${d}`),u||(e=!1)};console.log(`Visa HUD Doctor
242
- `);let n=Et.join(K.homedir(),".claude","settings.json"),r=!1;try{if($e.existsSync(n)){let c=JSON.parse($e.readFileSync(n,"utf-8")),u=typeof c.statusLine=="object"?c.statusLine.command:"";r=Rt(u)}}catch{}t("Claude Code statusLine",r,r?"registered":"not registered \u2014 run: visa-cli config hud enable");let s=Mn(K.homedir()),o=cn();if(t("Shell detected",!!o,o??"none (zsh, bash, or PowerShell required)"),o){let c=Pn(o),u=$e.existsSync(c);if(t("RC file exists",u,c.replace(K.homedir(),"~")),u){let f=$e.readFileSync(c,"utf-8").includes("visa-cli shell hud v2");console.log(` ${f?"\u2713":"\u2013"} Shell HUD block: ${f?"installed":"not installed (opt-in \u2014 run: visa-cli config hud enable shell)"}`)}}s.length>0&&console.log(` \u2713 Shell HUD rc scan: installed in ${s.map(c=>c.replace(K.homedir(),"~")).join(", ")}`),r&&s.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");let i=dt(),a=$e.existsSync(i);if(t("HUD cache file",a,a?i.replace(K.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),a)try{let c=JSON.parse($e.readFileSync(i,"utf-8")),u=Date.now()-(c.renderedAt??0),d=Math.round(u/1e3),f=d<=30;console.log(` ${f?"\u2713":"\u26A0"} Cache freshness: ${d}s old${f?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{t("Cache readable",!1,"corrupt JSON")}let l=!1;try{l=!!await U.getSessionToken()}catch{}if(t("Auth token",l,l?"found in keychain":"missing \u2014 run: visa-cli setup"),l)try{await se().getStatus(),t("API connectivity",!0,"GET /v1/status OK")}catch(c){let u=c instanceof Error?c.message:"unknown error";t("API connectivity",!1,u)}console.log(e?`
240
+ `);let o=At.join(K.homedir(),".claude","settings.json"),i=!1,a=!1;try{if($e.existsSync(o)){let w=JSON.parse($e.readFileSync(o,"utf-8")),y=typeof w.statusLine=="object"?w.statusLine.command:"";i=It(y),a=!!w.statusLine&&!i}}catch{}let l=i?`${n}\u2713${s}`:`${t}\u2717${s}`,c=i?"registered in ~/.claude/settings.json":a?`${r}another HUD is configured${s} \u2014 edit settings.json to switch`:"not enabled";console.log(` ${l} ${e}Claude Code${s} (statusLine) ${c}`);let u=On(K.homedir()),d=u.length>0||br(),f=d?`${n}\u2713${s}`:`${t}\u2717${s}`,g=d?`installed in shell rc file${u.length>0?` (${u.map(w=>w.replace(K.homedir(),"~")).join(", ")})`:""}`:"not installed (opt-in)";console.log(` ${f} ${e}Shell prompt${s} ${g}`),i&&d&&console.log(` ${r}!${s} ${e}Overlap${s} Claude statusLine and shell prompt HUD are both installed. Remove shell prompt output with: visa-cli config hud disable shell`),console.log(`
241
+ ${e}Quick start:${s}`),i||console.log(` visa-cli config hud enable ${t}# Claude Code statusLine (recommended)${s}`),d||console.log(` visa-cli config hud enable shell ${t}# zsh/bash prompt line (opt-in)${s}`),i&&d&&console.log(` ${n}All surfaces enabled.${s}`),(i||d)&&console.log(` visa-cli config hud disable [shell] ${t}# remove a surface${s}`),console.log(` visa-cli config hud doctor ${t}# diagnose connectivity${s}`),console.log()});En.command("enable").description("Enable the Visa HUD \u2014 claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{Xl(Ks(e,{homeDir:K.homedir(),installVisaStatusLine:Ln,installShellHud:Sr}))});En.command("disable").description("Disable the Visa HUD from a surface: claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{let t=e??"claude";if(t==="shell"||t==="prompt"){let o=wr();o.removed||(console.error(o.message),process.exit(1)),console.log(o.message);return}let n=kr(t);n||(console.error(`Unknown HUD surface: ${t}`),console.error("Supported: claude (default), shell, all"),process.exit(1));let r=!1,s=!1;if(n==="claude"||n==="claude-code"||n==="all"){let o=At.join(K.homedir(),".claude","settings.json"),i=qs(o);console.log(i.message),i.removed&&(s=!0),!i.removed&&n!=="all"&&(r=!0)}if(n==="all"){let o=wr();console.log(o.message),o.removed&&(s=!0),!o.removed&&n!=="all"&&(r=!0)}n==="all"&&!s&&(r=!0),r&&process.exit(1)});En.command("doctor").description("Diagnose HUD installation and connectivity across all surfaces").action(async()=>{let e=!0,t=(c,u,d)=>{console.log(` ${u?"\u2713":"\u2717"} ${c}: ${d}`),u||(e=!1)};console.log(`Visa HUD Doctor
242
+ `);let n=At.join(K.homedir(),".claude","settings.json"),r=!1;try{if($e.existsSync(n)){let c=JSON.parse($e.readFileSync(n,"utf-8")),u=typeof c.statusLine=="object"?c.statusLine.command:"";r=It(u)}}catch{}t("Claude Code statusLine",r,r?"registered":"not registered \u2014 run: visa-cli config hud enable");let s=On(K.homedir()),o=ln();if(t("Shell detected",!!o,o??"none (zsh, bash, or PowerShell required)"),o){let c=Mn(o),u=$e.existsSync(c);if(t("RC file exists",u,c.replace(K.homedir(),"~")),u){let f=$e.readFileSync(c,"utf-8").includes("visa-cli shell hud v2");console.log(` ${f?"\u2713":"\u2013"} Shell HUD block: ${f?"installed":"not installed (opt-in \u2014 run: visa-cli config hud enable shell)"}`)}}s.length>0&&console.log(` \u2713 Shell HUD rc scan: installed in ${s.map(c=>c.replace(K.homedir(),"~")).join(", ")}`),r&&s.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");let i=mt(),a=$e.existsSync(i);if(t("HUD cache file",a,a?i.replace(K.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),a)try{let c=JSON.parse($e.readFileSync(i,"utf-8")),u=Date.now()-(c.renderedAt??0),d=Math.round(u/1e3),f=d<=30;console.log(` ${f?"\u2713":"\u26A0"} Cache freshness: ${d}s old${f?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{t("Cache readable",!1,"corrupt JSON")}let l=!1;try{l=!!await U.getSessionToken()}catch{}if(t("Auth token",l,l?"found in keychain":"missing \u2014 run: visa-cli setup"),l)try{await ne().getStatus(),t("API connectivity",!0,"GET /v1/status OK")}catch(c){let u=c instanceof Error?c.message:"unknown error";t("API connectivity",!1,u)}console.log(e?`
243
243
  All checks passed.`:`
244
- Some checks failed \u2014 see above.`),e||process.exit(1)});Tn.command("enable-claude").description("Alias for: hud enable claude").action(()=>{let e=Et.join(K.homedir(),".claude","settings.json"),t=Nn(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});Tn.command("disable-claude").description("Alias for: hud disable claude").action(()=>{let e=Et.join(K.homedir(),".claude","settings.json"),t=js(e);console.log(t.message),t.removed||process.exit(1)});var En=G.command("merchants").description("List discoverable platform merchants and refresh JIT tools").addHelpCommand(!1);En.description("Discover and run paid merchant tools");En.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 ye(()=>U.getSessionToken()),n=await t.listPublicMerchants();if(n.length===0){e.json?console.log(JSON.stringify({merchants:[]},null,2)):console.log(`
244
+ Some checks failed \u2014 see above.`),e||process.exit(1)});En.command("enable-claude").description("Alias for: hud enable claude").action(()=>{let e=At.join(K.homedir(),".claude","settings.json"),t=Ln(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});En.command("disable-claude").description("Alias for: hud disable claude").action(()=>{let e=At.join(K.homedir(),".claude","settings.json"),t=qs(e);console.log(t.message),t.removed||process.exit(1)});var An=G.command("merchants").description("List discoverable platform merchants and refresh JIT tools").addHelpCommand(!1).action(Pe);An.description("Discover and run paid merchant tools");An.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 ye(()=>U.getSessionToken()),n=await t.listPublicMerchants();if(n.length===0){e.json?console.log(JSON.stringify({merchants:[]},null,2)):console.log(`
245
245
  No live platform merchants on this auth server.
246
246
  `);return}let r=await Promise.all(n.map(async a=>{let l=await t.getPublicMerchantDiscover(a.slug);return{slug:a.slug,display_name:a.display_name,provider:l?.title??a.display_name,merchant_of_record:l?.merchant_of_record??a.display_name,upstream:l?.upstream,tools:(l?.routes??[]).filter(c=>c.tool_id).map(c=>({tool_id:c.tool_id,mcp_name:c.tool_id.replace(/-/g,"_"),method:c.method,path:c.path,price_cents:c.price_cents,category:c.category??null,description:c.description??null}))}}));if(e.json){console.log(JSON.stringify({merchants:r},null,2));return}let s="\x1B[1m",o="\x1B[2m",i="\x1B[0m";console.log();for(let a of r){let l=a.merchant_of_record!==a.provider?` ${o}(MoR: ${a.merchant_of_record})${i}`:"";if(console.log(` ${s}${a.provider}${i}${l} ${o}\u2014 slug: ${a.slug}${i}`),a.upstream&&console.log(` ${o}upstream: ${a.upstream}${i}`),a.tools.length===0)console.log(` ${o}(no routes with tool_id \u2014 agents can't see this merchant yet)${i}`);else for(let c of a.tools){let u=c.category?` ${o}[${c.category}]${i}`:"",d=`$${(c.price_cents/100).toFixed(2)}`;console.log(` ${c.tool_id}${u} ${o}\u2192 Claude: ${c.mcp_name}${i} ${d} ${o}${c.method} ${c.path}${i}`),c.description&&console.log(` ${o}${c.description}${i}`)}console.log()}console.log(` ${o}To enable JIT tools in your MCP server, set: visa-cli config set merchants.discover all (or =<slug,...>)${i}
247
- `)}catch(t){console.error("Error:",t.message),process.exit(1)}});En.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 ${Fl}, max ${Bl})`,Al).option("--offset <n>","Pagination offset (default 0)",Al).action(async e=>{try{let t=se(),{limit:n,offset:r}=ph(e),s=await mh(t,{query:e.query,category:e.category,limit:n,offset:r});if(e.json){console.log(JSON.stringify({tools:s},null,2));return}if(s.length===0){console.log("No merchant tools found. Try: visa-cli merchants tools --category image");return}e.verbose?ah(s):ih(s)}catch(t){console.error("Error:",t.message),process.exit(1)}});En.command("describe <tool>").description("Show tool schema, price, and examples").action(async e=>{try{let n=await se().catalogTool(e,"discover_tools");n||(console.error(`Tool not found: ${e}`),console.error('Search with: visa-cli merchants tools --query "what you want to do"'),process.exit(1)),console.log(`
247
+ `)}catch(t){console.error("Error:",t.message),process.exit(1)}});An.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 ${Kl}, max ${Gl})`,$l).option("--offset <n>","Pagination offset (default 0)",$l).action(async e=>{try{let t=ne(),{limit:n,offset:r}=hh(e),s=await gh(t,{query:e.query,category:e.category,limit:n,offset:r});if(e.json){console.log(JSON.stringify({tools:s},null,2));return}if(s.length===0){console.log("No merchant tools found. Try: visa-cli merchants tools --category image");return}e.verbose?uh(s):lh(s)}catch(t){console.error("Error:",t.message),process.exit(1)}});An.command("describe <tool>").description("Show tool schema, price, and examples").action(async e=>{try{let n=await ne().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(`
248
248
  ${n.id}
249
249
  `),console.log(n.description),console.log(`
250
- Price`),console.log(` ${Xo(n.priceCents,n.priceDisplay)}`),console.log(`
250
+ Price`),console.log(` ${ei(n.priceCents,n.priceDisplay)}`),console.log(`
251
251
  Provider`),console.log(` ${n.provider} \xB7 ${n.category}`),console.log(`
252
- Inputs`);let r=n.inputSchema?.properties;if(r&&typeof r=="object"&&!Array.isArray(r)){let o=Array.isArray(n.inputSchema.required)?new Set(n.inputSchema.required):new Set;for(let[i,a]of Object.entries(r)){let l=o.has(i)?"required":"optional",c=a?.description?` - ${a.description}`:"";console.log(` ${i.padEnd(12)} ${l}${c}`)}}else console.log(" No published schema. Use --json with the request body.");console.log(`
253
- Examples`);let s=ml(n);console.log(` visa-cli merchants run ${n.id} --json '${JSON.stringify(s)}'`),n.category==="image"&&console.log(' visa-cli generate image "a lobster on a marble counter"'),console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});function Ah(e){return["fal-flux-pro-ultra","fal-flux-pro","fal-flux-schnell","fal-recraft-v3","fal-ideogram-v2","fal-minimax-video","fal-wan-video","fal-kling-video","fal-ace-step-music","check_fal_status_card","query_onchain_prices"].includes(e)}async function Ql(e,t,n){return Ah(e)?je.shortcut(e,t,n):je.executeTool({tool_id:e,params:t},n,"execute_tool")}En.command("run <tool>").description("Run any merchant tool by id").option("--json <json>","Tool parameters as a JSON object").option("--prompt <prompt>","Prompt parameter for prompt-shaped tools").action(async(e,t)=>{try{let n=sh(t.json,"--json");t.prompt&&(n.prompt=t.prompt),console.log(`Running ${e}`);let r=await Ql(e,n,`visa-cli merchants run ${e}`);jl(r),Vl(r)}catch(n){console.error("Error:",n.message),process.exit(1)}});En.command("refresh").description("Hint: restart the MCP server (Claude/Cursor) to refresh discovered tools \u2014 discovery is in-process").action(()=>{console.log(`
252
+ Inputs`);let r=n.inputSchema?.properties;if(r&&typeof r=="object"&&!Array.isArray(r)){let o=Array.isArray(n.inputSchema.required)?new Set(n.inputSchema.required):new Set,i=Object.entries(r),a=Math.max(12,...i.map(([l])=>l.length));for(let[l,c]of i){let u=o.has(l)?"required":"optional",d=ma(c),f=d?` ${d.padEnd(8)}`:" ",g=c?.description?` - ${c.description}`:"";console.log(` ${l.padEnd(a)} ${u}${f}${g}`)}}else console.log(" No published schema. Use --json with the request body.");console.log(`
253
+ Examples`);let s=gl(n);console.log(` visa-cli merchants run ${n.id} --json '${JSON.stringify(s)}'`),n.category==="image"&&console.log(' visa-cli generate image "a lobster on a marble counter"'),console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});function $h(e){return["fal-flux-pro-ultra","fal-flux-pro","fal-flux-schnell","fal-recraft-v3","fal-ideogram-v2","fal-minimax-video","fal-wan-video","fal-kling-video","fal-ace-step-music","check_fal_status_card","query_onchain_prices"].includes(e)}async function nu(e,t,n){return $h(e)?Ve.shortcut(e,t,n):Ve.executeTool({tool_id:e,params:t},n,"execute_tool")}An.command("run <tool>").description("Run any merchant tool by id").option("--json <json>","Tool parameters as a JSON object").option("--prompt <prompt>","Prompt parameter for prompt-shaped tools").action(async(e,t)=>{try{let n=ah(t.json,"--json");t.prompt&&(n.prompt=t.prompt),console.log(`Running ${e}`);let r=await nu(e,n,`visa-cli merchants run ${e}`);Fl(r),Hl(r)}catch(n){console.error("Error:",n.message),process.exit(1)}});An.command("refresh").description("Hint: restart the MCP server (Claude/Cursor) to refresh discovered tools \u2014 discovery is in-process").action(()=>{console.log(`
254
254
  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.
255
- `)});var or=G.command("generate").description("Generate media with merchant tools").addHelpCommand(!1);async function ir(e){console.log(`
255
+ `)});var ar=G.command("generate").description("Generate media with merchant tools").addHelpCommand(!1).action(Pe);async function cr(e){console.log(`
256
256
  ${e.kind}
257
257
  `),console.log(`Using: ${e.toolId}`),console.log(`Prompt: ${e.prompt}
258
- `);let t=await Ql(e.toolId,e.params,`visa-cli generate ${e.kind.toLowerCase()}: ${e.prompt}`);jl(t),Vl(t)}var Rh=(e,t)=>n=>(t.includes(n)||G.error(`error: option '${e}' accepts ${t.map(r=>`'${r}'`).join(", ")} (got '${n}')`,{exitCode:2}),n);or.command("image <prompt>").description("Generate an image from a prompt").option("--quality <quality>","Image quality: standard or high",Rh("--quality",["standard","high"]),"standard").option("--fast","Use the fast image tool").option("--tool <tool>","Exact tool id override").action(async(e,t)=>{try{let n=t.tool??(t.fast||t.quality!=="high"?"fal-flux-pro":"fal-flux-pro-ultra");await ir({kind:"Image generation",toolId:n,params:{prompt:e},prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});or.command("video <prompt>").description("Generate a video from a prompt").option("--tool <tool>","Exact tool id override").option("--aspect-ratio <ratio>","Aspect ratio, when supported by the selected tool").option("--duration <seconds>","Duration in seconds, when supported by the selected tool").action(async(e,t)=>{try{let n={prompt:e};t.aspectRatio&&(n.aspect_ratio=t.aspectRatio),t.duration&&(n.duration=Number(t.duration)),await ir({kind:"Video generation",toolId:t.tool??"fal-minimax-video",params:n,prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});or.command("music <prompt>").description("Generate music from a prompt").option("--tool <tool>","Exact tool id override").option("--instrumental","Generate instrumental music").option("--duration <seconds>","Duration in seconds, when supported by the selected tool").action(async(e,t)=>{try{let n={prompt:e};t.instrumental&&(n.instrumental=!0),t.duration&&(n.duration=Number(t.duration)),await ir({kind:"Music generation",toolId:t.tool??"fal-ace-step-music",params:n,prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});or.command("speech <text>").description("Generate speech from text using a voice sample").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").action(async(e,t)=>{try{let n=t.audioUrl??t.refAudioUrl;n||G.error("error: option '--audio-url <url>' is required for visa-cli generate speech",{exitCode:2});let r={text:e,audio_url:n};await ir({kind:"Speech generation",toolId:t.tool??"fal-metavoice",params:r,prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});or.command("3d <image-url>").alias("model").description("Generate a 3D model from an image URL").option("--tool <tool>","Exact tool id override").action(async(e,t)=>{try{let n={image_url:e};await ir({kind:"3D generation",toolId:t.tool??"fal-trellis-3d",params:n,prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});G.command("uninstall [client]").description("Remove MCP server from an AI client").option("--all","Remove from all clients").option("--scope <scope>","Uninstall scope: global or project","global").action(async(e,t)=>{try{let n=t.scope==="project"?"project":"global";if(t.all){let o=[];for(let i of Ie)Ko(i,n).removed&&o.push(i.displayName);o.length>0?console.log(`Removed visa-cli from: ${o.join(", ")}.`):console.log("visa-cli was not installed in any client.");return}e||(console.error("Usage: visa-cli uninstall <client>"),console.error(" visa-cli uninstall --all"),console.error(`
259
- Supported clients: ${Ie.map(o=>o.id).join(", ")}`),process.exit(1));let r=Vo(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${Ie.map(o=>o.id).join(", ")}`),process.exit(1));let s=Ko(r,n);s.removed?console.log(`Removed visa-cli from ${s.configPath}`):console.log(`visa-cli was not installed for ${r.displayName}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});G.hook("postAction",()=>{if(rr){rr=!1;return}ds&&dl(ds.lastSignals)});bh(["setup","install","status","cards","tokens","balance","merchants","generate","config","feedback","update","uninstall"]);Hl(G);G.parseAsync().catch(async e=>{console.error("Error:",e instanceof Error?e.message:String(e));let{reportFatal:t}=await Promise.resolve().then(()=>(us(),ls));await t(e)});process.on("uncaughtException",async e=>{console.error("Uncaught exception:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(us(),ls));await t(e)});process.on("unhandledRejection",async e=>{console.error("Unhandled rejection:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(us(),ls));await t(e)});
258
+ `);let t=await nu(e.toolId,e.params,`visa-cli generate ${e.kind.toLowerCase()}: ${e.prompt}`);Fl(t),Hl(t)}var Ph=(e,t)=>n=>(t.includes(n)||G.error(`error: option '${e}' accepts ${t.map(r=>`'${r}'`).join(", ")} (got '${n}')`,{exitCode:2}),n);ar.command("image <prompt>").description("Generate an image from a prompt").option("--quality <quality>","Image quality: standard or high",Ph("--quality",["standard","high"]),"standard").option("--fast","Use the fast image tool").option("--tool <tool>","Exact tool id override").action(async(e,t)=>{try{let n=t.tool??(t.fast||t.quality!=="high"?"fal-flux-pro":"fal-flux-pro-ultra");await cr({kind:"Image generation",toolId:n,params:{prompt:e},prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});ar.command("video <prompt>").description("Generate a video from a prompt").option("--tool <tool>","Exact tool id override").option("--aspect-ratio <ratio>","Aspect ratio, when supported by the selected tool").option("--duration <seconds>","Duration in seconds, when supported by the selected tool").action(async(e,t)=>{try{let n={prompt:e};t.aspectRatio&&(n.aspect_ratio=t.aspectRatio),t.duration&&(n.duration=Number(t.duration)),await cr({kind:"Video generation",toolId:t.tool??"fal-minimax-video",params:n,prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});ar.command("music <prompt>").description("Generate music from a prompt").option("--tool <tool>","Exact tool id override").option("--instrumental","Generate instrumental music").option("--duration <seconds>","Duration in seconds, when supported by the selected tool").action(async(e,t)=>{try{let n={prompt:e};t.instrumental&&(n.instrumental=!0),t.duration&&(n.duration=Number(t.duration)),await cr({kind:"Music generation",toolId:t.tool??"fal-ace-step-music",params:n,prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});ar.command("speech <text>").description("Generate speech from text using a voice sample").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").action(async(e,t)=>{try{let n=t.audioUrl??t.refAudioUrl;n||G.error("error: option '--audio-url <url>' is required for visa-cli generate speech",{exitCode:2});let r={text:e,audio_url:n};await cr({kind:"Speech generation",toolId:t.tool??"fal-metavoice",params:r,prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});ar.command("3d <image-url>").alias("model").description("Generate a 3D model from an image URL").option("--tool <tool>","Exact tool id override").action(async(e,t)=>{try{let n={image_url:e};await cr({kind:"3D generation",toolId:t.tool??"fal-trellis-3d",params:n,prompt:e})}catch(n){console.error("Error:",n.message),process.exit(1)}});G.command("uninstall [client]").description("Remove MCP server from an AI client").option("--all","Remove from all clients").option("--scope <scope>","Uninstall scope: global or project","global").action(async(e,t)=>{try{let n=t.scope==="project"?"project":"global";if(t.all){let o=[];for(let i of Ie)zo(i,n).removed&&o.push(i.displayName);o.length>0?console.log(`Removed visa-cli from: ${o.join(", ")}.`):console.log("visa-cli was not installed in any client.");return}e||(console.error("Usage: visa-cli uninstall <client>"),console.error(" visa-cli uninstall --all"),console.error(`
259
+ Supported clients: ${Ie.map(o=>o.id).join(", ")}`),process.exit(1));let r=Bo(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${Ie.map(o=>o.id).join(", ")}`),process.exit(1));let s=zo(r,n);s.removed?console.log(`Removed visa-cli from ${s.configPath}`):console.log(`visa-cli was not installed for ${r.displayName}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});G.hook("postAction",()=>{if(or){or=!1;return}ps&&fl(ps.lastSignals)});xh(["setup","install","status","cards","tokens","balance","merchants","generate","config","feedback","update","uninstall"]);zl(G);G.parseAsync().catch(async e=>{console.error("Error:",e instanceof Error?e.message:String(e));let{reportFatal:t}=await Promise.resolve().then(()=>(ms(),ds));await t(e)});process.on("uncaughtException",async e=>{console.error("Uncaught exception:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(ms(),ds));await t(e)});process.on("unhandledRejection",async e=>{console.error("Unhandled rejection:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(ms(),ds));await t(e)});0&&(module.exports={printGroupHelpAndExit});