@visa/cli 2.6.0-rc.7 → 2.6.0-rc.8

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 yd=Object.create;var $r=Object.defineProperty;var _d=Object.getOwnPropertyDescriptor;var vd=Object.getOwnPropertyNames;var bd=Object.getPrototypeOf,Sd=Object.prototype.hasOwnProperty;var wd=(e,t)=>()=>(e&&(t=e(e=0)),t);var Zi=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Zo=(e,t)=>{for(var n in t)$r(e,n,{get:t[n],enumerable:!0})},Qi=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of vd(t))!Sd.call(e,o)&&o!==n&&$r(e,o,{get:()=>t[o],enumerable:!(r=_d(t,o))||r.enumerable});return e};var E=(e,t,n)=>(n=e!=null?yd(bd(e)):{},Qi(t||!e||!e.__esModule?$r(n,"default",{value:e,enumerable:!0}):n,e)),xd=e=>Qi($r({},"__esModule",{value:!0}),e);var Kn=Zi((L_,Ld)=>{Ld.exports={name:"@visa/cli",version:"2.6.0-rc.7",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{"sync:server-json":"node scripts/sync-server-json.mjs","check:server-json":"node scripts/sync-server-json.mjs --check",prebuild:"node scripts/sync-server-json.mjs && pnpm --filter @visa/money build && pnpm --filter @visa-cli/tools build",build:"tsc --noEmit && node esbuild.config.js",prepack:"node scripts/sync-server-json.mjs --check",dev:"tsc --watch",pretest:"pnpm build",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0",commander:"^12.1.0",zod:"^3.23.0"},devDependencies:{"@visa/money":"workspace:*","@visa/observability":"workspace:*","@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.31.0","@types/jest":"^30.0.0","@types/node":"^25.9.1","@typescript-eslint/eslint-plugin":"^8.60.0","@typescript-eslint/parser":"^8.60.0","@types/express":"^5.0.0",esbuild:"^0.27.4",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.3","ts-jest":"^29.4.11",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","server.json","README.md","LICENSE"]}});var yr=Zi(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.micros=Sg;oe.fromCents=wg;oe.fromUsdc=xg;oe.fromUsd=kg;oe.toCents=Cg;oe.toCentsForAcquirer=Tg;oe.toUsdc=Eg;oe.toWire=Ag;oe.fromWire=Rg;oe.toDisplay=Ig;oe.toUsdRounded2dp=$g;oe.add=Pg;oe.sub=Mg;oe.clampNonNegative=Og;oe.isNonNegative=Ng;oe.max=Lg;oe.min=Ug;var dt=10000n,Nl=1000000n;function Sg(e){return e}function wg(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*dt}function xg(e){return e}function kg(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function Cg(e){if(e>=0n)return Number(e/dt);let t=e/dt,n=e%dt;return Number(n===0n?t:t-1n)}function Tg(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/dt)}function Eg(e){return e}function Ag(e){return e.toString()}function Rg(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 Ig(e,t={}){let n=t.decimals??2,r=t.symbol??"$",o=e<0n,s=o?-e:e,i=s/Nl,a=s%Nl,l=o?"-":"";if(n===0)return`${l}${r}${i.toString()}`;let c=a.toString().padStart(6,"0").slice(0,n);return`${l}${r}${i.toString()}.${c}`}function $g(e){let t=e<0n,n=t?-e:e,r=n/dt,s=n%dt*2n,i;s<dt?i=r:s>dt?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function Pg(e,t){return e+t}function Mg(e,t){return e-t}function Og(e){return e<0n?0n:e}function Ng(e){return e>=0n}function Lg(e,t){return e>t?e:t}function Ug(e,t){return e<t?e:t}});var Ko={};Zo(Ko,{initSentry:()=>zy,isSentryConfigured:()=>Gy,reportFatal:()=>Wy});function Gy(){return!1}async function zy(){return null}async function Wy(e,t){process.exit(t?.exitCode??1)}var Go=wd(()=>{});var R_={};Zo(R_,{printGroupHelpAndExit:()=>De});module.exports=xd(R_);var Gu=require("commander"),Wo=E(require("crypto")),J=E(require("fs")),z=E(require("os")),Ie=E(require("path")),zu=require("child_process"),Wu=require("node:readline/promises"),Ju=require("util");var Or=require("child_process"),la=require("util"),yt=E(require("fs")),Nr=E(require("os")),os=E(require("path"));var ra=E(require("crypto"));var et="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";var oa="VISA_ALLOW_INSECURE_MOCKS",ea,ta,na;function Qo(e){return`${e}-${ra.randomBytes(24).toString("base64url")}`}function sa(e=process.env){return e.NODE_ENV==="test"||e[oa]==="true"}function gt(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&sa(e)}function _n(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&sa(e)}function es(){return`Set ${oa}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function ia(){return ea??=Qo("mock-session"),ea}function aa(e=process.env){return e.NODE_ENV==="test"?et:(ta??=Qo("mock-rc"),ta)}function ca(){return na??=Qo("mock-signature"),na}var je=(0,la.promisify)(Or.execFile),ss=os.join(Nr.homedir(),".visa-mcp"),Bn=os.join(ss,"session-token"),Te="visa-cli",ht="session-token",Pr="rc-access",kd=5e3,Mr=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function Cd(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
2
- `)}function ua(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=Cd(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function Td(){try{let{stdout:e}=await je("security",["find-generic-password","-s",Te,"-a",ht,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(ua(e))throw new Mr("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 Ed(e){try{try{await je("security",["delete-generic-password","-s",Te,"-a",ht],{timeout:5e3})}catch{}return await je("security",["add-generic-password","-s",Te,"-a",ht,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function Ad(){try{await je("security",["delete-generic-password","-s",Te,"-a",ht],{timeout:5e3})}catch{}}async function Rd(){if(!is())return null;try{let{stdout:e}=await je("secret-tool",["lookup","service",Te,"account",ht],{timeout:5e3});return e.trim()||null}catch{return null}}async function Id(e){if(!is())return!1;try{let t=(0,Or.execFile)("secret-tool",["store","--label",`${Te} ${ht}`,"service",Te,"account",ht]);return t.stdin?(t.stdin.write(e),t.stdin.end(),await Promise.race([new Promise((n,r)=>{t.on("exit",o=>o===0?n():r(new Error(`secret-tool exited ${o}`))),t.on("error",r)}),new Promise((n,r)=>setTimeout(()=>{t.kill(),r(new Error("secret-tool timed out"))},kd))]),!0):!1}catch{return!1}}async function $d(){if(is())try{await je("secret-tool",["clear","service",Te,"account",ht],{timeout:5e3})}catch{}}function is(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function Pd(){try{let{stdout:e}=await je("security",["find-generic-password","-s",Te,"-a",Pr,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Md(e){try{try{await je("security",["delete-generic-password","-s",Te,"-a",Pr],{timeout:5e3})}catch{}await je("security",["add-generic-password","-s",Te,"-a",Pr,"-w",e],{timeout:5e3})}catch{}}async function Od(){try{await je("security",["delete-generic-password","-s",Te,"-a",Pr],{timeout:5e3})}catch{}}function ns(){try{return yt.readFileSync(Bn,"utf-8").trim()||null}catch(e){if(ua(e))throw new Mr(`Unable to read Visa CLI credentials from ${Bn}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function da(e){yt.mkdirSync(ss,{recursive:!0,mode:448}),yt.writeFileSync(Bn,e,{mode:384}),process.platform==="win32"&&Nd(Bn)}function rs(){try{yt.unlinkSync(Bn)}catch{}}function Nd(e){try{let t=Nr.userInfo().username;(0,Or.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 ts(){switch(process.platform){case"darwin":return{get:Td,store:Ed,delete:Ad};case"linux":return{get:Rd,store:Id,delete:$d};default:return{get:async()=>ns(),store:async e=>{try{return da(e),!0}catch{return!1}},delete:async()=>rs(),storesInSessionFile:!0}}}var F=class{static async getSessionToken(){if(gt())return Promise.resolve(ia());let t=ts(),n=await t.get();if(n)return n;let r=ns();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(gt())return;let n=ts();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||rs();return}await n.delete()}if(da(t),ns()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${ss} is writable.`))}static async getRcAccessToken(){return gt()?aa():Pd()}static async saveRcAccessToken(t){gt()||await Md(t)}static async deleteSessionToken(){if(gt())return;await ts().delete(),rs()}static async clearAll(){await this.deleteSessionToken(),await Od()}};var Lr=E(require("crypto")),Ur=E(require("tty")),Dr=E(require("fs"));function Ud(e){return/-rc\.|-beta\./.test(e)}function as(e){return Lr.createHash("sha256").update(e.trim()).digest("hex")}function ma(e){return et==="SKIP"?!0:Lr.timingSafeEqual(Buffer.from(as(e)),Buffer.from(et))}function Dd(){try{let e=Dr.openSync("/dev/tty","r+"),t=new Ur.ReadStream(e),n=new Ur.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{Dr.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 jd(e){return new Promise((t,n)=>{let r;try{r=Dd()}catch(u){n(u);return}let{input:o,output:s,cleanupStreams:i}=r,a=()=>{o.off("data",c);try{o.setRawMode?.(!1)}catch{}i()};s.write(e),o.setRawMode?.(!0),o.resume(),o.setEncoding("utf8");let l="",c=u=>{u==="\r"||u===`
1
+ "use strict";var Ad=Object.create;var Lr=Object.defineProperty;var Rd=Object.getOwnPropertyDescriptor;var Id=Object.getOwnPropertyNames;var $d=Object.getPrototypeOf,Pd=Object.prototype.hasOwnProperty;var Od=(e,t)=>()=>(e&&(t=e(e=0)),t);var ia=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),is=(e,t)=>{for(var n in t)Lr(e,n,{get:t[n],enumerable:!0})},aa=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Id(t))!Pd.call(e,o)&&o!==n&&Lr(e,o,{get:()=>t[o],enumerable:!(r=Rd(t,o))||r.enumerable});return e};var E=(e,t,n)=>(n=e!=null?Ad($d(e)):{},aa(t||!e||!e.__esModule?Lr(n,"default",{value:e,enumerable:!0}):n,e)),Md=e=>aa(Lr({},"__esModule",{value:!0}),e);var Jn=ia((Q_,zd)=>{zd.exports={name:"@visa/cli",version:"2.6.0-rc.8",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{"sync:server-json":"node scripts/sync-server-json.mjs","check:server-json":"node scripts/sync-server-json.mjs --check",prebuild:"node scripts/sync-server-json.mjs && pnpm --filter @visa/money build && pnpm --filter @visa-cli/tools build",build:"tsc --noEmit && node esbuild.config.js",prepack:"node scripts/sync-server-json.mjs --check",dev:"tsc --watch",pretest:"pnpm build",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0",commander:"^12.1.0",zod:"^3.23.0"},devDependencies:{"@visa/money":"workspace:*","@visa/observability":"workspace:*","@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.31.0","@types/jest":"^30.0.0","@types/node":"^25.9.1","@typescript-eslint/eslint-plugin":"^8.60.0","@typescript-eslint/parser":"^8.60.0","@types/express":"^5.0.0",esbuild:"^0.27.4",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.3","ts-jest":"^29.4.11",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","server.json","README.md","LICENSE"]}});var wr=ia(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.micros=Dg;oe.fromCents=jg;oe.fromUsdc=Fg;oe.fromUsd=qg;oe.toCents=Vg;oe.toCentsForAcquirer=Hg;oe.toUsdc=Bg;oe.toWire=Kg;oe.fromWire=Gg;oe.toDisplay=zg;oe.toUsdRounded2dp=Wg;oe.add=Jg;oe.sub=Yg;oe.clampNonNegative=Xg;oe.isNonNegative=Zg;oe.max=Qg;oe.min=eh;var mt=10000n,Gl=1000000n;function Dg(e){return e}function jg(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*mt}function Fg(e){return e}function qg(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function Vg(e){if(e>=0n)return Number(e/mt);let t=e/mt,n=e%mt;return Number(n===0n?t:t-1n)}function Hg(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/mt)}function Bg(e){return e}function Kg(e){return e.toString()}function Gg(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 zg(e,t={}){let n=t.decimals??2,r=t.symbol??"$",o=e<0n,s=o?-e:e,i=s/Gl,a=s%Gl,l=o?"-":"";if(n===0)return`${l}${r}${i.toString()}`;let c=a.toString().padStart(6,"0").slice(0,n);return`${l}${r}${i.toString()}.${c}`}function Wg(e){let t=e<0n,n=t?-e:e,r=n/mt,s=n%mt*2n,i;s<mt?i=r:s>mt?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function Jg(e,t){return e+t}function Yg(e,t){return e-t}function Xg(e){return e<0n?0n:e}function Zg(e){return e>=0n}function Qg(e,t){return e>t?e:t}function eh(e,t){return e<t?e:t}});var Qo={};is(Qo,{initSentry:()=>u_,isSentryConfigured:()=>l_,reportFatal:()=>d_});function l_(){return!1}async function u_(){return null}async function d_(e,t){process.exit(t?.exitCode??1)}var es=Od(()=>{});var G_={};is(G_,{printGroupHelpAndExit:()=>je});module.exports=Md(G_);var rd=require("commander"),ns=E(require("crypto")),J=E(require("fs")),z=E(require("os")),$e=E(require("path")),od=require("child_process"),sd=require("node:readline/promises"),id=require("util");var jr=require("child_process"),ya=require("util"),_t=E(require("fs")),Fr=E(require("os")),ms=E(require("path"));var da=E(require("crypto"));var tt="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";var ma="VISA_ALLOW_INSECURE_MOCKS",ca,la,ua;function as(e){return`${e}-${da.randomBytes(24).toString("base64url")}`}function pa(e=process.env){return e.NODE_ENV==="test"||e[ma]==="true"}function ht(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&pa(e)}function bn(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&pa(e)}function cs(){return`Set ${ma}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function fa(){return ca??=as("mock-session"),ca}function ga(e=process.env){return e.NODE_ENV==="test"?tt:(la??=as("mock-rc"),la)}function ha(){return ua??=as("mock-signature"),ua}var Fe=(0,ya.promisify)(jr.execFile),ps=ms.join(Fr.homedir(),".visa-mcp"),Wn=ms.join(ps,"session-token"),Ee="visa-cli",yt="session-token",Ur="rc-access",Nd=5e3,Dr=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function Ld(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
2
+ `)}function _a(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=Ld(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function Ud(){try{let{stdout:e}=await Fe("security",["find-generic-password","-s",Ee,"-a",yt,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(_a(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 Dd(e){try{try{await Fe("security",["delete-generic-password","-s",Ee,"-a",yt],{timeout:5e3})}catch{}return await Fe("security",["add-generic-password","-s",Ee,"-a",yt,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function jd(){try{await Fe("security",["delete-generic-password","-s",Ee,"-a",yt],{timeout:5e3})}catch{}}async function Fd(){if(!fs())return null;try{let{stdout:e}=await Fe("secret-tool",["lookup","service",Ee,"account",yt],{timeout:5e3});return e.trim()||null}catch{return null}}async function qd(e){if(!fs())return!1;try{let t=(0,jr.execFile)("secret-tool",["store","--label",`${Ee} ${yt}`,"service",Ee,"account",yt]);return t.stdin?(t.stdin.write(e),t.stdin.end(),await Promise.race([new Promise((n,r)=>{t.on("exit",o=>o===0?n():r(new Error(`secret-tool exited ${o}`))),t.on("error",r)}),new Promise((n,r)=>setTimeout(()=>{t.kill(),r(new Error("secret-tool timed out"))},Nd))]),!0):!1}catch{return!1}}async function Vd(){if(fs())try{await Fe("secret-tool",["clear","service",Ee,"account",yt],{timeout:5e3})}catch{}}function fs(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function Hd(){try{let{stdout:e}=await Fe("security",["find-generic-password","-s",Ee,"-a",Ur,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Bd(e){try{try{await Fe("security",["delete-generic-password","-s",Ee,"-a",Ur],{timeout:5e3})}catch{}await Fe("security",["add-generic-password","-s",Ee,"-a",Ur,"-w",e],{timeout:5e3})}catch{}}async function Kd(){try{await Fe("security",["delete-generic-password","-s",Ee,"-a",Ur],{timeout:5e3})}catch{}}function us(){try{return _t.readFileSync(Wn,"utf-8").trim()||null}catch(e){if(_a(e))throw new Dr(`Unable to read Visa CLI credentials from ${Wn}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function va(e){_t.mkdirSync(ps,{recursive:!0,mode:448}),_t.writeFileSync(Wn,e,{mode:384}),process.platform==="win32"&&Gd(Wn)}function ds(){try{_t.unlinkSync(Wn)}catch{}}function Gd(e){try{let t=Fr.userInfo().username;(0,jr.execFile)("icacls",[e,"/inheritance:r","/grant:r",`${t}:F`],{timeout:5e3},n=>{n&&console.error(`[visa-cli] icacls ACL restriction failed: ${n.message}`)})}catch(t){console.error(`[visa-cli] Failed to invoke icacls: ${t instanceof Error?t.message:String(t)}`)}}function ls(){switch(process.platform){case"darwin":return{get:Ud,store:Dd,delete:jd};case"linux":return{get:Fd,store:qd,delete:Vd};default:return{get:async()=>us(),store:async e=>{try{return va(e),!0}catch{return!1}},delete:async()=>ds(),storesInSessionFile:!0}}}var F=class{static async getSessionToken(){if(ht())return Promise.resolve(fa());let t=ls(),n=await t.get();if(n)return n;let r=us();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(ht())return;let n=ls();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||ds();return}await n.delete()}if(va(t),us()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${ps} is writable.`))}static async getRcAccessToken(){return ht()?ga():Hd()}static async saveRcAccessToken(t){ht()||await Bd(t)}static async deleteSessionToken(){if(ht())return;await ls().delete(),ds()}static async clearAll(){await this.deleteSessionToken(),await Kd()}};var qr=E(require("crypto")),Vr=E(require("tty")),Hr=E(require("fs"));function Wd(e){return/-rc\.|-beta\./.test(e)}function gs(e){return qr.createHash("sha256").update(e.trim()).digest("hex")}function ba(e){return tt==="SKIP"?!0:qr.timingSafeEqual(Buffer.from(gs(e)),Buffer.from(tt))}function Jd(){try{let e=Hr.openSync("/dev/tty","r+"),t=new Vr.ReadStream(e),n=new Vr.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{Hr.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 Yd(e){return new Promise((t,n)=>{let r;try{r=Jd()}catch(u){n(u);return}let{input:o,output:s,cleanupStreams:i}=r,a=()=>{o.off("data",c);try{o.setRawMode?.(!1)}catch{}i()};s.write(e),o.setRawMode?.(!0),o.resume(),o.setEncoding("utf8");let l="",c=u=>{u==="\r"||u===`
3
3
  `?(s.write(`
4
4
  `),a(),t(l)):u===""?(s.write(`
5
- `),a(),n(new Error("Cancelled"))):u==="\x7F"||u==="\b"?l.length>0&&(l=l.slice(0,-1),s.write("\b \b")):(l+=u,s.write("\u2022"))};o.on("data",c)})}var Fd=`
5
+ `),a(),n(new Error("Cancelled"))):u==="\x7F"||u==="\b"?l.length>0&&(l=l.slice(0,-1),s.write("\b \b")):(l+=u,s.write("\u2022"))};o.on("data",c)})}var Xd=`
6
6
  \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
7
7
  \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557
8
8
  \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551
@@ -11,25 +11,25 @@
11
11
  \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D
12
12
 
13
13
  This is a Release Candidate build. Access is restricted to Visa employees.
14
- `;async function pa(e={}){let t=e.version??Kn().version;if(!Ud(t))return;let n=process.env.VISA_RC_CODE;if(n&&ma(n)){await F.saveRcAccessToken(as(n));return}if(e.isMcp??!1){let i=await F.getRcAccessToken();if(i&&(et==="SKIP"||i===et))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
15
- `),process.exit(1)}let o=await F.getRcAccessToken();if(o&&(et==="SKIP"||o===et))return;console.log(Fd);let s=3;for(let i=1;i<=s;i++){let a;try{a=await jd(" Enter RC access code: ")}catch{process.exit(1)}if(ma(a)){await F.saveRcAccessToken(as(a)),console.log(`
14
+ `;async function Sa(e={}){let t=e.version??Jn().version;if(!Wd(t))return;let n=process.env.VISA_RC_CODE;if(n&&ba(n)){await F.saveRcAccessToken(gs(n));return}if(e.isMcp??!1){let i=await F.getRcAccessToken();if(i&&(tt==="SKIP"||i===tt))return;process.stderr.write(`[visa-cli] RC build requires access. Run: visa-cli setup
15
+ `),process.exit(1)}let o=await F.getRcAccessToken();if(o&&(tt==="SKIP"||o===tt))return;console.log(Xd);let s=3;for(let i=1;i<=s;i++){let a;try{a=await Yd(" Enter RC access code: ")}catch{process.exit(1)}if(ba(a)){await F.saveRcAccessToken(gs(a)),console.log(`
16
16
  Access granted. Welcome.
17
17
  `);return}i<s&&console.log(`
18
18
  Invalid code. ${s-i} attempt(s) remaining.
19
19
  `)}console.log(`
20
20
  Invalid code. Contact your team lead.
21
- `),process.exit(1)}var jr=E(require("fs")),fa=E(require("os")),cs=E(require("path")),qd=[{prefix:"iVBORw0KGgo",sig:{mime:"image/png",ext:"png"}},{prefix:"/9j/",sig:{mime:"image/jpeg",ext:"jpg"}},{prefix:"R0lGOD",sig:{mime:"image/gif",ext:"gif"}},{prefix:"UklGR",sig:{mime:"image/webp",ext:"webp"}}],Vd=/^data:(image\/(png|jpeg|jpg|gif|webp));base64,([A-Za-z0-9+/=]+)$/;function vn(e){if(typeof e!="string"||e.length===0)return null;let t=e.trim(),n=Vd.exec(t);if(n){let o=n[2]==="jpg"?"jpeg":n[2],s=o==="png"?{mime:"image/png",ext:"png"}:o==="jpeg"?{mime:"image/jpeg",ext:"jpg"}:o==="gif"?{mime:"image/gif",ext:"gif"}:{mime:"image/webp",ext:"webp"};return{base64:n[3],sig:s}}if(!/^[A-Za-z0-9+/=\s]+$/.test(t)||t.length<64)return null;let r=t.replace(/\s+/g,"");for(let{prefix:o,sig:s}of qd)if(r.startsWith(o))return{base64:r,sig:s};return null}function Gn(e,t={}){let n=t.outputDir??cs.join(fa.tmpdir(),"visa-cli");jr.mkdirSync(n,{recursive:!0});let r=(t.tag??"media").toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"media",o=new Date().toISOString().replace(/[:.]/g,"-"),s=cs.join(n,`${r}-${o}.${e.sig.ext}`),i=Buffer.from(e.base64,"base64");return jr.writeFileSync(s,i,{mode:384}),{filePath:s,bytes:i.length,mime:e.sig.mime}}function Hd(e,t={}){let n={success:!0,command:e,ts:new Date().toISOString()};for(let[r,o]of Object.entries(t))o!==void 0&&(n[r]=o);return n}function zn(e,t,n={}){let r={success:!1,command:e,ts:new Date().toISOString(),error:t};for(let[o,s]of Object.entries(n))s!==void 0&&(r[o]=s);return r}function ls(e,t){if(!t||typeof t!="object")return zn(e,"No result payload from tool");let n=t;if(n.success===!1)return zn(e,typeof n.error=="string"?n.error:"Tool execution failed",{error_code:typeof n.error_code=="string"?n.error_code:typeof n.code=="string"?n.code:void 0,transactionId:typeof n.transactionId=="string"?n.transactionId:null});let r=Array.isArray(n.urls)?n.urls.filter(u=>typeof u=="string"):Array.isArray(n.receipt?.urls)?n.receipt.urls.filter(u=>typeof u=="string"):void 0,o=n.data&&typeof n.data=="object"?n.data:void 0,s=n.result&&typeof n.result=="object"?n.result:void 0,i=s&&Array.isArray(s.choices)?s.choices:void 0,a=i&&i[0]&&typeof i[0]=="object"?i[0]:void 0,l=a&&a.message&&typeof a.message=="object"?a.message:void 0,c;if(o&&typeof o.content=="string")c=o.content;else if(o&&typeof o.text=="string")c=o.text;else if(typeof n.content=="string")c=n.content;else if(typeof n.text=="string")c=n.text;else if(l&&typeof l.content=="string")c=l.content;else if(a&&typeof a.text=="string")c=a.text;else if(Array.isArray(n.content)&&n.content[0]&&typeof n.content[0]=="object"){let u=n.content[0].text;typeof u=="string"&&(c=u)}return Hd(e,{transactionId:typeof n.transactionId=="string"?n.transactionId:void 0,amount:typeof n.amount=="number"?n.amount:void 0,currency:typeof n.currency=="string"?n.currency:void 0,merchantName:typeof n.merchantName=="string"?n.merchantName:void 0,toolId:typeof n.toolId=="string"?n.toolId:typeof n.tool_id=="string"?n.tool_id:void 0,urls:r,text:c})}var us=require("process");async function ds(){let e="";us.stdin.setEncoding("utf8");for await(let t of us.stdin)e+=t;return e.endsWith(`
22
- `)?e.slice(0,-1):e}async function jt(e,t){if(e==="-"||t.stdin===!0&&!e){let o=(await ds()).trim();if(!o)throw new Error("stdin was empty \u2014 pipe a prompt or pass it as the positional argument");return o}if(e&&e.length>0)return e;throw new Error("prompt required (positional arg, `-`, or --stdin)")}function Fr(e,t){if(!(t?.isTty??!!process.stdout.isTTY)&&!e.yes)throw new Error("Non-TTY shell detected on a paid command. Pass --yes to confirm you intend to charge the card from a pipe/script.")}var _a=E(require("fs")),qr=E(require("path"));var _t=class extends Error{constructor(t){super(t),this.name="FromStdinFieldError"}},ga=new Set;function Bd(e){ga.add(e)}function ha(e){return ga.has(e)}function ya(e,t){if(!t.startsWith("."))throw new _t(`--from-stdin path must start with "." (got: "${t}")`);let n=Kd(t),r=e;for(let s of n){if(r==null)throw new _t(`--from-stdin path "${t}" failed: hit ${r===null?"null":"undefined"} at segment "${s}"`);if(typeof r!="object")throw new _t(`--from-stdin path "${t}" failed: cannot descend into primitive at segment "${s}"`);if(typeof s=="number"){if(!Array.isArray(r))throw new _t(`--from-stdin path "${t}" failed: expected array at segment [${s}], got object`);r=r[s]}else r=r[s]}if(r==null)throw new _t(`--from-stdin path "${t}" resolved to ${r===null?"null":"undefined"}`);if(typeof r=="object")throw new _t(`--from-stdin path "${t}" resolved to ${Array.isArray(r)?"an array":"an object"} \u2014 refusing to coerce non-primitive to flag value`);let o=String(r);return Bd(o),o}function Kd(e){let t=e.slice(1),n=[];for(let r of t.split(".")){if(!r)continue;let o=/^([^[\]]+)|\[(\d+)\]/g,s;for(;(s=o.exec(r))!==null;)s[1]!==void 0?/^\d+$/.test(s[1])?n.push(Number(s[1])):n.push(s[1]):s[2]!==void 0&&n.push(Number(s[2]))}return n}var ms=class extends Error{constructor(t){super(t),this.name="FileShorthandStdinSourceError"}};async function va(e){if(e===void 0)return;if(!e.startsWith("@"))return e;if(ha(e))throw new ms("Refusing to expand @file from a --from-stdin-sourced value: upstream JSON cannot be allowed to read arbitrary local files. If the file path is legitimate, pass it as an argv flag instead of routing it through --from-stdin.");let t=e.slice(1),n=t.startsWith("~")?qr.join(process.env.HOME??"",t.slice(1)):qr.resolve(process.cwd(),t),r=await _a.promises.readFile(n,"utf8");return r.endsWith(`
23
- `)?r.slice(0,-1):r}var Wn=require("process"),vt=["json","yaml","tsv","table"];function Vr(e){return vt.includes(e)}function Jn(e,t){switch(t){case"json":Wn.stdout.write(JSON.stringify(e)+`
24
- `);return;case"yaml":Wn.stdout.write(Gd(e)+`
25
- `);return;case"tsv":Wn.stdout.write(zd(e)+`
26
- `);return;case"table":Wn.stdout.write(Wd(e)+`
27
- `);return}}function Gd(e){let t=[];for(let[n,r]of Object.entries(e))if(r!==void 0)if(Array.isArray(r)){t.push(`${n}:`);for(let o of r)t.push(` - ${ba(o)}`)}else r!==null&&typeof r=="object"?t.push(`${n}: ${JSON.stringify(r)}`):t.push(`${n}: ${ba(r)}`);return t.join(`
28
- `)}function ba(e){if(e===null)return"null";if(typeof e=="boolean"||typeof e=="number")return String(e);let t=String(e);return t===""?'""':/^[-?:,\[\]{}#&*!|>'"%@`]/.test(t)||/:\s|\s#/.test(t)||/^\s|\s$/.test(t)?JSON.stringify(t):t}function zd(e){let t=[];for(let[n,r]of Object.entries(e)){if(r===void 0)continue;let o=Array.isArray(r)||r!==null&&typeof r=="object"?JSON.stringify(r):String(r);t.push(`${n} ${o}`)}return t.join(`
29
- `)}function Wd(e){let t=[];for(let[r,o]of Object.entries(e)){if(o===void 0)continue;let s=Array.isArray(o)||o!==null&&typeof o=="object"?JSON.stringify(o):String(o);t.push([r,s])}let n=Math.max(...t.map(([r])=>r.length),1);return t.map(([r,o])=>`${r.padEnd(n)} ${o}`).join(`
30
- `)}var wa=require("child_process");function ps(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 Jd(e){let n=e.length+4;return[`\u250C${"\u2500".repeat(n)}\u2510`,`\u2502${" ".repeat(2)}${e}${" ".repeat(2)}\u2502`,`\u2514${"\u2500".repeat(n)}\u2518`].join(`
31
- `)}function Yn(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 xa(e,t){let n=Yn(e);if(!n)return null;let r,o;try{r=new URL(n),o=new URL(t)}catch{return null}return r.origin===o.origin?n:null}function ka(e,t){return t==="darwin"?{cmd:"open",args:[e]}:t==="win32"?{cmd:"rundll32.exe",args:["url.dll,FileProtocolHandler",e]}:t==="linux"?{cmd:"xdg-open",args:[e]}:null}function Ca(e,t=process.platform){let n=Yn(e);return n?ka(n,t):null}function Sa(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function fs(e,t={}){let n=t.log??(c=>console.log(c)),r=t.env??process.env,o=t.platform??process.platform,s=Yn(e),i=t.spawn??((c,u,d)=>{(0,wa.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 Jd(s??e).split(`
32
- `))n(` ${c}`);if(n(""),!s){n(" (Auth URL is not a valid absolute http(s) URL \u2014 skipping browser auto-open.)"),n(" Open the URL above manually to continue."),n("");return}let a=ps(r,o);if(a.headless){n(` (${a.reason} \u2014 skipping browser auto-open.)`),n(" Open the URL above on any device with a browser. The CLI will"),n(" continue waiting for you to complete sign-in."),n("");return}let l=ka(s,o);if(!l){n(` No known browser-open command for platform "${o}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(c=>{let u=d=>{d?Sa(n,d):(n(" Opened browser. Waiting for you to sign in..."),n("")),c()};try{i(l.cmd,l.args,u)}catch(d){Sa(n,d instanceof Error?d:new Error(String(d))),c()}})}function Yd(e){return new Promise(t=>setTimeout(t,e))}function Ta(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 Ea(e){return!Number.isFinite(e)||e===null||e<=0?1e3:Math.min(Math.max(Math.ceil(e),1e3),3e4)}async function Xd(e,t=Math.random()*250){let n=o=>Math.min(o+Math.max(0,Math.ceil(t)),3e4);if(!e||e.status!==429)return n(1e3);let r=Ta(e.headers?.get("Retry-After"));if(r!==null)return n(Ea(r));if(typeof e.json=="function")try{let o=await e.json();return n(Ea(Ta(o?.retryAfter)))}catch{return n(1e3)}return n(1e3)}async function bt(e,t){let n=await Xd(e);return t?.(n),await Yd(n),n}var Ha=E(require("crypto")),Ba=require("child_process"),se=E(require("fs")),Ka=E(require("os")),pe=E(require("path"));var q=E(require("fs")),qt=E(require("os")),V=E(require("path")),Ia=require("child_process"),$a=require("crypto"),Zd=2,Hr="# >>> visa-cli shell hud v2 >>>",Br="# <<< visa-cli shell hud v2 <<<",Qd="# >>> visa-cli shell hud >>>",em="# <<< visa-cli shell hud <<<",Pa=3e4,tm=6e4,nm="VISA | HUD not ready \u2014 run: visa-cli config hud doctor",rm={currentVersion:"0.0.0"},om=15e3;function ys(){try{return V.join(bs(),".visa-cli")}catch{return V.join(qt.tmpdir(),".visa-cli")}}function St(){return V.join(ys(),"shell-hud.json")}function Xn(){return V.join(ys(),"shell-hud.line")}function Ma(){return V.join(ys(),"shell-hud.lock")}function wn(e){let t=e??process.env.SHELL;if(!t)return null;let n=V.basename(t.replace(/\\/g,"/")).toLowerCase();return n==="zsh"?"zsh":n==="bash"?"bash":n==="pwsh"||n==="pwsh.exe"||n==="powershell"||n==="powershell.exe"?"powershell":null}function Zn(e){let t=bs();if(e==="zsh")return V.join(t,".zshrc");if(e==="bash")return V.join(t,".bashrc");let n=(process.platform==="win32","PowerShell");return V.join(t,"Documents",n,"Microsoft.PowerShell_profile.ps1")}function Oa(e,t){let n=t??bs(),r=[{shell:"zsh",rcPath:V.join(n,".zshrc")},{shell:"bash",rcPath:V.join(n,".bashrc")},{shell:"bash",rcPath:V.join(n,".bash_profile")},{shell:"powershell",rcPath:V.join(n,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:V.join(n,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:V.join(n,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:V.join(n,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:V.join(n,".config","powershell","Microsoft.PowerShell_profile.ps1")}];if(!e)return r;let o=r.filter(i=>i.shell===e),s=r.filter(i=>i.shell!==e);return[...o,...s]}function sm(e){let t="$HOME/.visa-cli/shell-hud.line",n=wm(e),r=xm(e);if(e==="zsh")return`${Hr}
21
+ `),process.exit(1)}var Br=E(require("fs")),wa=E(require("os")),hs=E(require("path")),Zd=[{prefix:"iVBORw0KGgo",sig:{mime:"image/png",ext:"png"}},{prefix:"/9j/",sig:{mime:"image/jpeg",ext:"jpg"}},{prefix:"R0lGOD",sig:{mime:"image/gif",ext:"gif"}},{prefix:"UklGR",sig:{mime:"image/webp",ext:"webp"}}],Qd=/^data:(image\/(png|jpeg|jpg|gif|webp));base64,([A-Za-z0-9+/=]+)$/;function Sn(e){if(typeof e!="string"||e.length===0)return null;let t=e.trim(),n=Qd.exec(t);if(n){let o=n[2]==="jpg"?"jpeg":n[2],s=o==="png"?{mime:"image/png",ext:"png"}:o==="jpeg"?{mime:"image/jpeg",ext:"jpg"}:o==="gif"?{mime:"image/gif",ext:"gif"}:{mime:"image/webp",ext:"webp"};return{base64:n[3],sig:s}}if(!/^[A-Za-z0-9+/=\s]+$/.test(t)||t.length<64)return null;let r=t.replace(/\s+/g,"");for(let{prefix:o,sig:s}of Zd)if(r.startsWith(o))return{base64:r,sig:s};return null}function Yn(e,t={}){let n=t.outputDir??hs.join(wa.tmpdir(),"visa-cli");Br.mkdirSync(n,{recursive:!0});let r=(t.tag??"media").toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"media",o=new Date().toISOString().replace(/[:.]/g,"-"),s=hs.join(n,`${r}-${o}.${e.sig.ext}`),i=Buffer.from(e.base64,"base64");return Br.writeFileSync(s,i,{mode:384}),{filePath:s,bytes:i.length,mime:e.sig.mime}}function em(e,t={}){let n={success:!0,command:e,ts:new Date().toISOString()};for(let[r,o]of Object.entries(t))o!==void 0&&(n[r]=o);return n}function Xn(e,t,n={}){let r={success:!1,command:e,ts:new Date().toISOString(),error:t};for(let[o,s]of Object.entries(n))s!==void 0&&(r[o]=s);return r}function ys(e,t){if(!t||typeof t!="object")return Xn(e,"No result payload from tool");let n=t;if(n.success===!1)return Xn(e,typeof n.error=="string"?n.error:"Tool execution failed",{error_code:typeof n.error_code=="string"?n.error_code:typeof n.code=="string"?n.code:void 0,transactionId:typeof n.transactionId=="string"?n.transactionId:null});let r=Array.isArray(n.urls)?n.urls.filter(u=>typeof u=="string"):Array.isArray(n.receipt?.urls)?n.receipt.urls.filter(u=>typeof u=="string"):void 0,o=n.data&&typeof n.data=="object"?n.data:void 0,s=n.result&&typeof n.result=="object"?n.result:void 0,i=s&&Array.isArray(s.choices)?s.choices:void 0,a=i&&i[0]&&typeof i[0]=="object"?i[0]:void 0,l=a&&a.message&&typeof a.message=="object"?a.message:void 0,c;if(o&&typeof o.content=="string")c=o.content;else if(o&&typeof o.text=="string")c=o.text;else if(typeof n.content=="string")c=n.content;else if(typeof n.text=="string")c=n.text;else if(l&&typeof l.content=="string")c=l.content;else if(a&&typeof a.text=="string")c=a.text;else if(Array.isArray(n.content)&&n.content[0]&&typeof n.content[0]=="object"){let u=n.content[0].text;typeof u=="string"&&(c=u)}return em(e,{transactionId:typeof n.transactionId=="string"?n.transactionId:void 0,amount:typeof n.amount=="number"?n.amount:void 0,currency:typeof n.currency=="string"?n.currency:void 0,merchantName:typeof n.merchantName=="string"?n.merchantName:void 0,toolId:typeof n.toolId=="string"?n.toolId:typeof n.tool_id=="string"?n.tool_id:void 0,urls:r,text:c})}var _s=require("process");async function vs(){let e="";_s.stdin.setEncoding("utf8");for await(let t of _s.stdin)e+=t;return e.endsWith(`
22
+ `)?e.slice(0,-1):e}async function Ft(e,t){if(e==="-"||t.stdin===!0&&!e){let o=(await vs()).trim();if(!o)throw new Error("stdin was empty \u2014 pipe a prompt or pass it as the positional argument");return o}if(e&&e.length>0)return e;throw new Error("prompt required (positional arg, `-`, or --stdin)")}function Kr(e,t){if(!(t?.isTty??!!process.stdout.isTTY)&&!e.yes)throw new Error("Non-TTY shell detected on a paid command. Pass --yes to confirm you intend to charge the card from a pipe/script.")}var Ta=E(require("fs")),Gr=E(require("path"));var vt=class extends Error{constructor(t){super(t),this.name="FromStdinFieldError"}},xa=new Set;function tm(e){xa.add(e)}function ka(e){return xa.has(e)}function Ca(e,t){if(!t.startsWith("."))throw new vt(`--from-stdin path must start with "." (got: "${t}")`);let n=nm(t),r=e;for(let s of n){if(r==null)throw new vt(`--from-stdin path "${t}" failed: hit ${r===null?"null":"undefined"} at segment "${s}"`);if(typeof r!="object")throw new vt(`--from-stdin path "${t}" failed: cannot descend into primitive at segment "${s}"`);if(typeof s=="number"){if(!Array.isArray(r))throw new vt(`--from-stdin path "${t}" failed: expected array at segment [${s}], got object`);r=r[s]}else r=r[s]}if(r==null)throw new vt(`--from-stdin path "${t}" resolved to ${r===null?"null":"undefined"}`);if(typeof r=="object")throw new vt(`--from-stdin path "${t}" resolved to ${Array.isArray(r)?"an array":"an object"} \u2014 refusing to coerce non-primitive to flag value`);let o=String(r);return tm(o),o}function nm(e){let t=e.slice(1),n=[];for(let r of t.split(".")){if(!r)continue;let o=/^([^[\]]+)|\[(\d+)\]/g,s;for(;(s=o.exec(r))!==null;)s[1]!==void 0?/^\d+$/.test(s[1])?n.push(Number(s[1])):n.push(s[1]):s[2]!==void 0&&n.push(Number(s[2]))}return n}var bs=class extends Error{constructor(t){super(t),this.name="FileShorthandStdinSourceError"}};async function Ea(e){if(e===void 0)return;if(!e.startsWith("@"))return e;if(ka(e))throw new bs("Refusing to expand @file from a --from-stdin-sourced value: upstream JSON cannot be allowed to read arbitrary local files. If the file path is legitimate, pass it as an argv flag instead of routing it through --from-stdin.");let t=e.slice(1),n=t.startsWith("~")?Gr.join(process.env.HOME??"",t.slice(1)):Gr.resolve(process.cwd(),t),r=await Ta.promises.readFile(n,"utf8");return r.endsWith(`
23
+ `)?r.slice(0,-1):r}var Zn=require("process"),bt=["json","yaml","tsv","table"];function zr(e){return bt.includes(e)}function Qn(e,t){switch(t){case"json":Zn.stdout.write(JSON.stringify(e)+`
24
+ `);return;case"yaml":Zn.stdout.write(rm(e)+`
25
+ `);return;case"tsv":Zn.stdout.write(om(e)+`
26
+ `);return;case"table":Zn.stdout.write(sm(e)+`
27
+ `);return}}function rm(e){let t=[];for(let[n,r]of Object.entries(e))if(r!==void 0)if(Array.isArray(r)){t.push(`${n}:`);for(let o of r)t.push(` - ${Aa(o)}`)}else r!==null&&typeof r=="object"?t.push(`${n}: ${JSON.stringify(r)}`):t.push(`${n}: ${Aa(r)}`);return t.join(`
28
+ `)}function Aa(e){if(e===null)return"null";if(typeof e=="boolean"||typeof e=="number")return String(e);let t=String(e);return t===""?'""':/^[-?:,\[\]{}#&*!|>'"%@`]/.test(t)||/:\s|\s#/.test(t)||/^\s|\s$/.test(t)?JSON.stringify(t):t}function om(e){let t=[];for(let[n,r]of Object.entries(e)){if(r===void 0)continue;let o=Array.isArray(r)||r!==null&&typeof r=="object"?JSON.stringify(r):String(r);t.push(`${n} ${o}`)}return t.join(`
29
+ `)}function sm(e){let t=[];for(let[r,o]of Object.entries(e)){if(o===void 0)continue;let s=Array.isArray(o)||o!==null&&typeof o=="object"?JSON.stringify(o):String(o);t.push([r,s])}let n=Math.max(...t.map(([r])=>r.length),1);return t.map(([r,o])=>`${r.padEnd(n)} ${o}`).join(`
30
+ `)}var Ia=require("child_process");function Ss(e=process.env,t=process.platform){return e.VISA_CLI_NO_BROWSER==="1"||e.VISA_CLI_NO_BROWSER==="true"?{headless:!0,reason:"VISA_CLI_NO_BROWSER is set"}:e.CI==="true"||e.CI==="1"?{headless:!0,reason:"CI environment detected"}:e.SSH_CONNECTION||e.SSH_TTY?{headless:!0,reason:"SSH session detected"}:t==="linux"&&!e.DISPLAY&&!e.WAYLAND_DISPLAY?{headless:!0,reason:"Linux with no $DISPLAY or $WAYLAND_DISPLAY"}:{headless:!1}}function im(e){let n=e.length+4;return[`\u250C${"\u2500".repeat(n)}\u2510`,`\u2502${" ".repeat(2)}${e}${" ".repeat(2)}\u2502`,`\u2514${"\u2500".repeat(n)}\u2518`].join(`
31
+ `)}function er(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 $a(e,t){let n=er(e);if(!n)return null;let r,o;try{r=new URL(n),o=new URL(t)}catch{return null}return r.origin===o.origin?n:null}function Pa(e,t){return t==="darwin"?{cmd:"open",args:[e]}:t==="win32"?{cmd:"rundll32.exe",args:["url.dll,FileProtocolHandler",e]}:t==="linux"?{cmd:"xdg-open",args:[e]}:null}function Oa(e,t=process.platform){let n=er(e);return n?Pa(n,t):null}function Ra(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function ws(e,t={}){let n=t.log??(c=>console.log(c)),r=t.env??process.env,o=t.platform??process.platform,s=er(e),i=t.spawn??((c,u,d)=>{(0,Ia.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 im(s??e).split(`
32
+ `))n(` ${c}`);if(n(""),!s){n(" (Auth URL is not a valid absolute http(s) URL \u2014 skipping browser auto-open.)"),n(" Open the URL above manually to continue."),n("");return}let a=Ss(r,o);if(a.headless){n(` (${a.reason} \u2014 skipping browser auto-open.)`),n(" Open the URL above on any device with a browser. The CLI will"),n(" continue waiting for you to complete sign-in."),n("");return}let l=Pa(s,o);if(!l){n(` No known browser-open command for platform "${o}".`),n(" Open the URL above manually to continue."),n("");return}await new Promise(c=>{let u=d=>{d?Ra(n,d):(n(" Opened browser. Waiting for you to sign in..."),n("")),c()};try{i(l.cmd,l.args,u)}catch(d){Ra(n,d instanceof Error?d:new Error(String(d))),c()}})}function am(e){return new Promise(t=>setTimeout(t,e))}function Ma(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 Na(e){return!Number.isFinite(e)||e===null||e<=0?1e3:Math.min(Math.max(Math.ceil(e),1e3),3e4)}async function cm(e,t=Math.random()*250){let n=o=>Math.min(o+Math.max(0,Math.ceil(t)),3e4);if(!e||e.status!==429)return n(1e3);let r=Ma(e.headers?.get("Retry-After"));if(r!==null)return n(Na(r));if(typeof e.json=="function")try{let o=await e.json();return n(Na(Ma(o?.retryAfter)))}catch{return n(1e3)}return n(1e3)}async function St(e,t){let n=await cm(e);return t?.(n),await am(n),n}var ec=E(require("crypto")),tc=require("child_process"),se=E(require("fs")),nc=E(require("os")),fe=E(require("path"));var q=E(require("fs")),Ht=E(require("os")),H=E(require("path")),Va=require("child_process"),Cs=require("crypto");var xn=E(require("fs")),Wr=E(require("tty"));function Ua(e=process.env){let t=(e.COLORTERM??"").toLowerCase();if(t==="truecolor"||t==="24bit")return!0;let n=(e.TERM??"").toLowerCase();return n.includes("truecolor")||n.includes("24bit")}function Da(e,t){let n=(o,s,i)=>`\x1B[38;2;${o};${s};${i}m`,r=o=>`\x1B[38;5;${o}m`;return e==="light"?{reset:"\x1B[0m",visaBlue:t?n(20,52,203):r(26),visaBlueSoft:t?n(11,78,162):r(25),visaGold:t?n(122,82,0):r(94),green:t?n(15,107,47):r(22),muted:t?n(92,100,112):r(241),chrome:t?n(138,138,138):r(245)}:{reset:"\x1B[0m",visaBlue:t?n(168,184,255):r(153),visaBlueSoft:t?n(127,149,242):r(111),visaGold:t?n(255,210,74):r(221),green:t?n(86,211,100):r(77),muted:t?n(199,205,215):r(251),chrome:t?n(110,118,129):r(243)}}function ja(e){if(!e)return null;let t=e.split(";");if(t.length<2)return null;let n=t[t.length-1].trim();if(n==="0")return"dark";if(n==="7"||n==="15")return"light";let r=Number(n);return Number.isInteger(r)&&r>=0&&r<=255?r<=6||r>=232&&r<=243?"dark":"light":null}function La(e){let t=/rgb:([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})/.exec(e);if(!t)return null;let n=i=>{let a=parseInt(i,16),l=(1<<i.length*4)-1;return l>0?a/l:0},r=n(t[1]),o=n(t[2]),s=n(t[3]);return[r,o,s].some(i=>!Number.isFinite(i))?null:.299*r+.587*o+.114*s}var lm=80,um="/dev/tty";function dm(e=um){if(process.platform==="win32")return null;let t,n;try{t=xn.openSync(e,"r"),n=xn.openSync(e,"w");let r=new Wr.ReadStream(t),o=new Wr.WriteStream(n);return{stdin:r,stdout:o,close:()=>{try{r.destroy?.()}catch{}try{o.destroy?.()}catch{}}}}catch{try{t!==void 0&&xn.closeSync(t)}catch{}try{n!==void 0&&xn.closeSync(n)}catch{}return null}}function mm(e){let t={stdin:e.stdin??process.stdin,stdout:e.stdout??process.stdout};if(t.stdout.isTTY&&t.stdin.isTTY&&typeof t.stdin.setRawMode=="function")return t;let n=e.stdin!==void 0||e.stdout!==void 0;if(!(e.allowControllingTerminal??!n))return null;let s=(e.openControllingTerminal??dm)(e.ttyPath);return s?.stdout.isTTY&&s.stdin.isTTY&&typeof s.stdin.setRawMode=="function"?s:(s?.close?.(),null)}async function pm(e={}){let t=mm(e);if(!t)return null;let{stdin:n,stdout:r}=t,o=e.timeoutMs??lm,s=e.setTimeoutFn??((a,l)=>setTimeout(a,l)),i=e.clearTimeoutFn??(a=>clearTimeout(a));return new Promise(a=>{let l=!1,c="",u=n.isRaw===!0,d=S=>{c+=typeof S=="string"?S:S.toString("utf-8");let $=La(c),V=c.includes("\x07")||c.includes("\x1B\\");$!==null&&V&&m($>.5?"light":"dark")},f=()=>{try{n.removeListener("data",d)}catch{}try{i(_)}catch{}try{!u&&typeof n.setRawMode=="function"&&n.setRawMode(!1)}catch{}try{n.pause?.()}catch{}try{n.unref?.()}catch{}try{t.close?.()}catch{}},m=S=>{l||(l=!0,f(),a(S))},_=s(()=>{let S=La(c);m(S!==null?S>.5?"light":"dark":null)},o);try{u||n.setRawMode?.(!0),n.resume?.(),n.on("data",d),r.write("\x1B]11;?\x1B\\")}catch{m(null)}})}var qt,tr;function fm(e){if((e.NO_COLOR??"")!=="")return"no-color";let t=(e.VISA_CLI_HUD_THEME??"").toLowerCase().trim();if(t==="light")return"light";if(t==="dark")return"dark";let n=ja(e.COLORFGBG);return n||"dark"}function Jr(e=process.env){return qt!==void 0||(qt=fm(e)),qt}function le(e=process.env){if(tr!==void 0)return tr;let t=Jr(e),n=Ua(e);return tr=Da(t==="light"?"light":"dark",n),tr}function Yr(e=process.env){return Jr(e)==="no-color"}async function xs(e={}){if(qt!==void 0)return qt;let t=e.env??process.env;if((t.NO_COLOR??"")!=="")return wn("no-color",t);let n=(t.VISA_CLI_HUD_THEME??"").toLowerCase().trim();if(n==="light")return wn("light",t);if(n==="dark")return wn("dark",t);let r=ja(t.COLORFGBG);if(r)return wn(r,t);let o=await pm(e);return wn(o||"dark",t)}function wn(e,t){qt=e;let n=Ua(t);return tr=Da(e==="light"?"light":"dark",n),e}var gm=2,Xr="# >>> visa-cli shell hud v2 >>>",Zr="# <<< visa-cli shell hud v2 <<<",hm="# >>> visa-cli shell hud >>>",ym="# <<< visa-cli shell hud <<<",Ha=3e4,_m=6e4,vm="VISA | HUD not ready \u2014 run: visa-cli config hud doctor",bm={currentVersion:"0.0.0"},Sm=15e3;function Ts(){try{return H.join(Rs(),".visa-cli")}catch{return H.join(Ht.tmpdir(),".visa-cli")}}function wt(){return H.join(Ts(),"shell-hud.json")}function nr(){return H.join(Ts(),"shell-hud.line")}function Ba(){return H.join(Ts(),"shell-hud.lock")}function Tn(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 rr(e){let t=Rs();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 Ka(e,t){let n=t??Rs(),r=[{shell:"zsh",rcPath:H.join(n,".zshrc")},{shell:"bash",rcPath:H.join(n,".bashrc")},{shell:"bash",rcPath:H.join(n,".bash_profile")},{shell:"powershell",rcPath:H.join(n,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:H.join(n,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:H.join(n,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:H.join(n,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1")},{shell:"powershell",rcPath:H.join(n,".config","powershell","Microsoft.PowerShell_profile.ps1")}];if(!e)return r;let o=r.filter(i=>i.shell===e),s=r.filter(i=>i.shell!==e);return[...o,...s]}function wm(e){let t="$HOME/.visa-cli/shell-hud.line",n=Fm(e),r=qm(e);if(e==="zsh")return`${Xr}
33
33
  _visa_cli_shell_hud_precmd() {
34
34
  setopt localoptions no_bg_nice
35
35
  if [[ -f "${t}" ]]; then
@@ -46,7 +46,7 @@ autoload -Uz add-zsh-hook
46
46
  if [[ -z "\${precmd_functions[(r)_visa_cli_shell_hud_precmd]}" ]]; then
47
47
  add-zsh-hook precmd _visa_cli_shell_hud_precmd
48
48
  fi
49
- ${Br}`;if(e==="powershell"){let o="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${Hr}
49
+ ${Zr}`;if(e==="powershell"){let o="(Join-Path $HOME '.visa-cli/shell-hud.line')";return`${Xr}
50
50
  if (-not (Test-Path Function:\\global:__visa_cli_original_prompt)) {
51
51
  $function:global:__visa_cli_original_prompt = if (Test-Path Function:\\prompt) { $function:prompt } else { { '' } }
52
52
  }
@@ -65,7 +65,7 @@ function global:prompt {
65
65
  }
66
66
  & $function:global:__visa_cli_original_prompt
67
67
  }
68
- ${Br}`}return`${Hr}
68
+ ${Zr}`}return`${Xr}
69
69
  __visa_cli_shell_hud_precmd() {
70
70
  if [ -f "${t}" ]; then
71
71
  cat "${t}"
@@ -82,104 +82,104 @@ case ";$PROMPT_COMMAND;" in
82
82
  *";__visa_cli_shell_hud_precmd;"*) ;;
83
83
  *) PROMPT_COMMAND="__visa_cli_shell_hud_precmd\${PROMPT_COMMAND:+;$PROMPT_COMMAND}" ;;
84
84
  esac
85
- ${Br}`}function im(e){return e.includes("_visa_cli_shell_hud_precmd")||e.includes("visa-cli config shell-hud refresh")||e.includes("shell-hud.line")||e.includes("__visa_cli_original_prompt")||e.includes("function global:prompt")}function am(e,t,n){let r=new RegExp(`(^|\\n)([ \\t]*${Ra(t)}[ \\t]*\\r?\\n)([\\s\\S]*?)(\\r?\\n[ \\t]*${Ra(n)}[ \\t]*)(?=\\r?\\n|$)(\\r?\\n)?`,"g");return e.replace(r,(o,s,i,a,l,c,u)=>{if(!im(a))return o;let d=u>0?e[u-1]:"";return s===`
85
+ ${Zr}`}function xm(e){return e.includes("_visa_cli_shell_hud_precmd")||e.includes("visa-cli config shell-hud refresh")||e.includes("shell-hud.line")||e.includes("__visa_cli_original_prompt")||e.includes("function global:prompt")}function km(e,t,n){let r=new RegExp(`(^|\\n)([ \\t]*${qa(t)}[ \\t]*\\r?\\n)([\\s\\S]*?)(\\r?\\n[ \\t]*${qa(n)}[ \\t]*)(?=\\r?\\n|$)(\\r?\\n)?`,"g");return e.replace(r,(o,s,i,a,l,c,u)=>{if(!xm(a))return o;let d=u>0?e[u-1]:"";return s===`
86
86
  `&&d!==`
87
87
  `?`
88
- `:""})}function Qn(e){let t=e;for(let[n,r]of[[Hr,Br],[Qd,em]])t=am(t,n,r);return t.trimEnd()}function Na(e){return Qn(e)!==e.trimEnd()}function cm(e,t){let n=Qn(e).trimEnd(),r=sm(t);return n.length>0?`${n}
88
+ `:""})}function or(e){let t=e;for(let[n,r]of[[Xr,Zr],[hm,ym]])t=km(t,n,r);return t.trimEnd()}function Ga(e){return or(e)!==e.trimEnd()}function Cm(e,t){let n=or(e).trimEnd(),r=wm(t);return n.length>0?`${n}
89
89
 
90
90
  ${r}
91
91
  `:`${r}
92
- `}function Kr(e=wn()){if(!e)return!1;try{let t=Zn(e),n=q.readFileSync(t,"utf-8");return Na(n)}catch{return!1}}function Vt(e=qt.homedir()){let t=[],n=lm(e);for(let r of n)try{if(!q.existsSync(r))continue;let o=q.readFileSync(r,"utf-8");Na(o)&&t.push(r)}catch{}return t}function lm(e){return Oa(null,e).map(t=>t.rcPath)}function Gr(e=wn()){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=Zn(e);let n=q.existsSync(t)?q.readFileSync(t,"utf-8"):"",r=cm(n,e),o=r!==n;return o&&Sn(t,r),{installed:!0,changed:o,shell:e,rcPath:t,message:o?`Persistent shell HUD installed in ${t}. Open a new terminal to start seeing it. Disable it any time with: visa-cli config shell-hud disable`:`Persistent shell HUD already installed in ${t}. Disable it any time with: visa-cli config shell-hud disable`}}catch(n){return{installed:!1,changed:!1,shell:e,rcPath:t,message:`Failed to install persistent shell HUD in ${t}: ${hs(n)}`}}}function tt(e=wn(),t){let n=[],r=[],o=[];try{for(let s of Oa(e,t))if(r.push(s.rcPath),!!q.existsSync(s.rcPath))try{let i=q.readFileSync(s.rcPath,"utf-8"),a=Qn(i);if(a===i.trimEnd())continue;Sn(s.rcPath,a.length>0?`${a}
93
- `:""),n.push(s.rcPath)}catch(i){o.push(`${s.rcPath}: ${hs(i)}`)}return n.length>0?{removed:!0,shell:e,rcPath:n[0],rcPaths:n,message:o.length>0?`Removed persistent shell HUD from ${n.join(", ")}. Some rc files could not be updated: ${o.join("; ")}.`:`Removed persistent shell HUD from ${n.join(", ")}.`}:o.length>0?{removed:!1,shell:e,rcPath:r[0],rcPaths:r,message:`Failed to remove persistent shell HUD: ${o.join("; ")}`}:{removed:!0,shell:e,rcPath:r[0],rcPaths:r,message:"Persistent shell HUD was not installed in any supported shell rc file."}}catch(s){return{removed:!1,shell:e,message:`Failed to remove persistent shell HUD: ${hs(s)}`}}}function _s(e,t){let n=t??rm,r=n.currentVersion==="0.0.0"&&e.version?e.version:n.currentVersion,o=wt(r),s=` ${G("\u2502",K.dim)} `,i=La(n),a=fm(n,i),l=n.updateCheckDisabled?"":i,c=pm(o,l);if(!e.enrolled)return[c,G("setup needed",K.visaGold),a].filter(Boolean).join(s);let u=bm(e),d=mm(e),f=wt(qt.hostname().split(".")[0]),p=[c,f?G(f,K.dim):"",G(u,K.visaGold),a].filter(Boolean).join(s),_=[d,um(e)].filter(Boolean),T=_.length>0?_.join(s):"";return T?`${p}
94
- ${T}`:p}function um(e){let t=` ${G("\u2502",K.dim)} `,n=[],r=e.dailyCardFundedTopupSpent??e.dailySpent;if(typeof r=="number"&&Number.isFinite(r)){let o=Math.max(0,r);n.push(G(`top-ups today ${bn(o)}`,K.dim))}if(typeof e.apiKeyCount=="number"&&Number.isFinite(e.apiKeyCount)){let o=Math.max(0,Math.floor(e.apiKeyCount)),s=o===1?"api key":"api keys";n.push(G(`${o} ${s}`,K.dim))}if(e.lastService&&typeof e.lastService.toolName=="string"&&e.lastService.toolName.length>0){let o=vm(wt(e.lastService.toolName)),s=dm(e.lastService.createdAt),i=G(s?`last ${o} ${s}`:`last ${o}`,K.dim);n.push(i)}return n.join(t)}function dm(e){if(!e)return"";let t=Date.parse(e);if(!Number.isFinite(t))return"";let n=Date.now()-t;if(n<0)return"";let r=Math.floor(n/1e3);if(r<60)return`${r}s`;let o=Math.floor(r/60);if(o<60)return`${o}m`;let s=Math.floor(o/60);return s<24?`${s}h`:`${Math.floor(s/24)}d`}function mm(e){let t=typeof e.balanceCents=="number"?e.balanceCents:typeof e.prepaidBalance?.cents=="number"?e.prepaidBalance.cents:null,n=e.activeSession;if(t===null)return G("balance unknown",K.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`${_m(c)} ${G(`${bn(a/100)} in session`,K.green)} ${G(`(${bn(l/100)}/${bn(i/100)} cap)`,K.dim)} ${G("\xB7",K.dim)} ${G(`${bn(r)} balance`,K.dim)}`}let o=10,s=`balance ${bn(r)}`;return t>=o?G(s,K.green):G(`${s} \u2014 top up via buy_credits`,K.visaGold)}function pm(e,t){let n=e,r=`${G("VISA CLI",K.visaBlue)} ${G(`v${n}`,K.visaBlueSoft)}`;if(!t)return r;let o=t;return`${r} ${G("\u2B06 update",K.visaGold)} ${G(`v${o}`,K.visaGold)}`}function fm(e,t){return t&&!e.updateCheckDisabled?G("run: visa-cli update",K.visaGold):t?null:gm(e)}function La(e){return e.latestVersion?wt(e.latestVersion):""}function gm(e){let t=La(e);return t?G(`update ready v${t}`,K.visaGold):null}function Ua(){let e=er();return!(!e||Date.now()-e.renderedAt>Pa||e.cwd&&e.cwd!==process.cwd())}function zr(){let e=er(),t=Date.now();if(e&&t-e.renderedAt<=Pa||(ym(),e?.line))return Aa(e.line,e,t);try{let n=Xn();if(q.existsSync(n)){let r=q.readFileSync(n,"utf-8").trimEnd();if(r&&!Wr(r))return r}}catch{}return nm}function Aa(e,t,n){let r=n-t.renderedAt,o=typeof t.refreshFailedAt=="number"&&t.refreshFailedAt>t.renderedAt,s=[];if(r>=tm&&s.push(`stale ${hm(r)}`),o&&s.push("\u26A0 refresh failed"),s.length===0)return e;let i=` ${G("\xB7",K.dim)} ${G(s.join(" \xB7 "),K.visaGold)}`,a=e.split(`
92
+ `}function Qr(e=Tn()){if(!e)return!1;try{let t=rr(e),n=q.readFileSync(t,"utf-8");return Ga(n)}catch{return!1}}function Bt(e=Ht.homedir()){let t=[],n=Tm(e);for(let r of n)try{if(!q.existsSync(r))continue;let o=q.readFileSync(r,"utf-8");Ga(o)&&t.push(r)}catch{}return t}function Tm(e){return Ka(null,e).map(t=>t.rcPath)}function eo(e=Tn()){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=rr(e);let n=q.existsSync(t)?q.readFileSync(t,"utf-8"):"",r=Cm(n,e),o=r!==n;return o&&Cn(t,r),{installed:!0,changed:o,shell:e,rcPath:t,message:o?`Persistent shell HUD installed in ${t}. Open a new terminal to start seeing it. Disable it any time with: visa-cli config shell-hud disable`:`Persistent shell HUD already installed in ${t}. Disable it any time with: visa-cli config shell-hud disable`}}catch(n){return{installed:!1,changed:!1,shell:e,rcPath:t,message:`Failed to install persistent shell HUD in ${t}: ${ks(n)}`}}}function nt(e=Tn(),t){let n=[],r=[],o=[];try{for(let s of Ka(e,t))if(r.push(s.rcPath),!!q.existsSync(s.rcPath))try{let i=q.readFileSync(s.rcPath,"utf-8"),a=or(i);if(a===i.trimEnd())continue;Cn(s.rcPath,a.length>0?`${a}
93
+ `:""),n.push(s.rcPath)}catch(i){o.push(`${s.rcPath}: ${ks(i)}`)}return n.length>0?{removed:!0,shell:e,rcPath:n[0],rcPaths:n,message:o.length>0?`Removed persistent shell HUD from ${n.join(", ")}. Some rc files could not be updated: ${o.join("; ")}.`:`Removed persistent shell HUD from ${n.join(", ")}.`}:o.length>0?{removed:!1,shell:e,rcPath:r[0],rcPaths:r,message:`Failed to remove persistent shell HUD: ${o.join("; ")}`}:{removed:!0,shell:e,rcPath:r[0],rcPaths:r,message:"Persistent shell HUD was not installed in any supported shell rc file."}}catch(s){return{removed:!1,shell:e,message:`Failed to remove persistent shell HUD: ${ks(s)}`}}}function Es(e,t){let n=t??bm,r=n.currentVersion==="0.0.0"&&e.version?e.version:n.currentVersion,o=xt(r),s=` ${G("\u2502",K.chrome)} `,i=za(n),a=$m(n,i),l=n.updateCheckDisabled?"":i,c=Im(o,l);if(!e.enrolled)return[c,G("setup needed",K.visaGold),a].filter(Boolean).join(s);let u=jm(e),d=Rm(e),f=xt(Ht.hostname().split(".")[0]),m=[c,f?G(f,K.muted):"",G(u,K.visaGold),a].filter(Boolean).join(s),_=[d,Em(e)].filter(Boolean),S=_.length>0?_.join(s):"";return S?`${m}
94
+ ${S}`:m}function Em(e){let t=` ${G("\u2502",K.chrome)} `,n=[],r=e.dailyCardFundedTopupSpent??e.dailySpent;if(typeof r=="number"&&Number.isFinite(r)){let o=Math.max(0,r);n.push(G(`top-ups today ${kn(o)}`,K.muted))}if(typeof e.apiKeyCount=="number"&&Number.isFinite(e.apiKeyCount)){let o=Math.max(0,Math.floor(e.apiKeyCount)),s=o===1?"api key":"api keys";n.push(G(`${o} ${s}`,K.muted))}if(e.lastService&&typeof e.lastService.toolName=="string"&&e.lastService.toolName.length>0){let o=Dm(xt(e.lastService.toolName)),s=Am(e.lastService.createdAt),i=G(s?`last ${o} ${s}`:`last ${o}`,K.muted);n.push(i)}return n.join(t)}function Am(e){if(!e)return"";let t=Date.parse(e);if(!Number.isFinite(t))return"";let n=Date.now()-t;if(n<0)return"";let r=Math.floor(n/1e3);if(r<60)return`${r}s`;let o=Math.floor(r/60);if(o<60)return`${o}m`;let s=Math.floor(o/60);return s<24?`${s}h`:`${Math.floor(s/24)}d`}function Rm(e){let t=typeof e.balanceCents=="number"?e.balanceCents:typeof e.prepaidBalance?.cents=="number"?e.prepaidBalance.cents:null,n=e.activeSession;if(t===null)return G("balance unknown",K.muted);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`${Um(c)} ${G(`${kn(a/100)} in session`,K.green)} ${G(`(${kn(l/100)}/${kn(i/100)} cap)`,K.muted)} ${G("\xB7",K.chrome)} ${G(`${kn(r)} balance`,K.muted)}`}let o=10,s=`balance ${kn(r)}`;return t>=o?G(s,K.green):G(`${s} \u2014 top up via buy_credits`,K.visaGold)}function Im(e,t){let n=e,r=`${G("VISA CLI",K.visaBlue)} ${G(`v${n}`,K.visaBlueSoft)}`;if(!t)return r;let o=t;return`${r} ${G("\u2B06 update",K.visaGold)} ${G(`v${o}`,K.visaGold)}`}function $m(e,t){return t&&!e.updateCheckDisabled?G("run: visa-cli update",K.visaGold):t?null:Pm(e)}function za(e){return e.latestVersion?xt(e.latestVersion):""}function Pm(e){let t=za(e);return t?G(`update ready v${t}`,K.visaGold):null}function Wa(){let e=sr();return!(!e||Date.now()-e.renderedAt>Ha||e.cwd&&e.cwd!==process.cwd())}function to(){let e=sr(),t=Date.now();if(e&&t-e.renderedAt<=Ha||(Mm(),e?.line))return Fa(e.line,e,t);try{let n=nr();if(q.existsSync(n)){let r=q.readFileSync(n,"utf-8").trimEnd();if(r&&!no(r))return r}}catch{}return vm}function Fa(e,t,n){let r=n-t.renderedAt,o=typeof t.refreshFailedAt=="number"&&t.refreshFailedAt>t.renderedAt,s=[];if(r>=_m&&s.push(`stale ${Om(r)}`),o&&s.push("\u26A0 refresh failed"),s.length===0)return e;let i=` ${G("\xB7",K.chrome)} ${G(s.join(" \xB7 "),K.visaGold)}`,a=e.split(`
95
95
  `);for(let l=a.length-1;l>=0;l--)if(a[l].length>0)return a[l]=`${a[l]}${i}`,a.join(`
96
- `);return`${e}${i}`}function hm(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 vs(e,t){try{let n=V.dirname(St());q.mkdirSync(n,{recursive:!0});let r=e.split(`
97
- `).map(s=>wt(s)).filter(s=>s.length>0).join(`
98
- `),o={hudVersion:Zd,renderedAt:Date.now(),line:r,cwd:process.cwd(),status:t};Sn(St(),JSON.stringify(o)+`
99
- `),Sn(Xn(),r+`
100
- `)}catch{}}function Da(e){try{let t=er();if(!t)return;let n=Math.max(Date.now(),t.renderedAt+1),r={...t,refreshFailedAt:n,refreshErrorReason:wt(e).slice(0,200)};Sn(St(),JSON.stringify(r)+`
101
- `)}catch{}}function ja(){try{let e=er();if(!e)return;let t={...e,renderedAt:0};Sn(St(),JSON.stringify(t)+`
102
- `)}catch{}}function Ft(){try{q.unlinkSync(Ma())}catch{}}function er(){let e=St();if(!q.existsSync(e))return null;try{let t=JSON.parse(q.readFileSync(e,"utf-8"));return typeof t?.line=="string"&&Wr(t.line)?null:t}catch{return null}}function Wr(e){for(let t of e.split(`
103
- `)){let n=t.trim();if(n.length===0)continue;let r=n.replace(/\[[0-?]*[ -/]*[@-~]/g,"").trim();if(/^VISA\s*\|\s*loading\b/i.test(r)||/^VISA\s*\|\s*HUD\s+not\s+(ready|initialized)\b/i.test(r))return!0}return!1}function Fa(){return er()?.status??null}function ym(){if(process.env.JEST_WORKER_ID)return;let e=Ma();try{if(q.mkdirSync(V.dirname(e),{recursive:!0}),!km(e))return;let t=process.argv[1]?V.resolve(process.argv[1]):"";if(!t){Ft();return}let n=(0,Ia.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});n.once("error",Ft),n.unref()}catch{Ft()}}function wt(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 _m(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),o="\u2591".repeat(10-n);return`${G(r||"",K.green)}${G(o||"",K.dim)}`}function bn(e){return`$${e.toFixed(2)}`}function vm(e){let t=e;if(t.startsWith("/")&&(t=t.replace(/^\/(?:api\/)?v\d+\/fal\//,""),t=t.replace(/^\/(?:api\/)?v\d+\/(?:shortcuts|openrouter)\//,""),t.startsWith("/"))){let o=t.split("/").filter(Boolean);t=o[o.length-1]||t}return t=t.replace(/^fal-ai\//,""),t=t.replace(/^fal-/,""),t=t.replace(/^or-/,""),t=t.split("/").filter(Boolean).map(o=>o.replace(/^v\d+(?:\.\d+)?-?/,"")||null).filter(o=>o!==null&&o.length>0).join(" "),t=t.replace(/_card$/,""),t.length>28&&(t=t.slice(0,28).trimEnd()),t||e}function bm(e){let t=e.cards?.find(a=>a.isDefault)??e.cards?.[0];if(!t)return"card none";let n=typeof t.brand=="string"?t.brand:"card",r=typeof t.last4=="string"?t.last4:"????",o=wt(n.toUpperCase()),s=wt(r);return`${t.isDefault?"default":"active"} ${o} ****${s}`}function Sm(){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 gs=Sm(),K={reset:"\x1B[0m",visaBlue:gs?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:gs?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:gs?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function G(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${K.reset}`}function Ra(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bs(){let e=qt.homedir();if(!e||!V.isAbsolute(e))throw new Error("unable to determine a valid home directory");return V.resolve(e)}function wm(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function xm(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function km(e){for(let t=0;t<2;t+=1){let n;try{return n=q.openSync(e,"wx"),q.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let o=q.statSync(e);if(Date.now()-o.mtimeMs<=om)return!1;q.unlinkSync(e)}catch{}}finally{n!==void 0&&q.closeSync(n)}}return!1}function hs(e){return e instanceof Error?e.message:"unknown file system error"}function Sn(e,t){q.mkdirSync(V.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${(0,$a.randomBytes)(8).toString("hex")}.tmp`;try{q.writeFileSync(n,t),q.renameSync(n,e)}catch(r){try{q.unlinkSync(n)}catch{}throw r}}var Cm=1440*60*1e3;function Yr(e,t){se.mkdirSync(pe.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Ha.randomBytes(8).toString("hex")}.tmp`;try{se.writeFileSync(n,JSON.stringify(t,null,2)+`
104
- `),se.renameSync(n,e)}catch(r){try{se.unlinkSync(n)}catch{}throw r}}function qa(e){return`'${e.replace(/'/g,"'\\''")}'`}var ws="# visa-cli-hud-v1";function Xr(e,t){if(!e&&!t&&Tm())return`visa-cli config statusline ${ws}`;let n=e??process.execPath,r=t??process.argv[1]??"",o=r?pe.resolve(r):"";return`${o?`${qa(n)} ${qa(o)} config statusline`:"visa-cli config statusline"} ${ws}`}function Tm(){try{return(0,Ba.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function xt(e){return typeof e!="string"?!1:e.includes(ws)?!0:e.includes("visa-cli")&&e.includes("statusline")}function Em(){return"2.6.0-rc.7"}function Zr(e){let t=pe.dirname(pe.resolve(e));return pe.basename(t)===".claude"?pe.dirname(t):Ka.homedir()}function Jr(e,t){let n=pe.relative(t,e);return!n.startsWith("..")&&!pe.isAbsolute(n)?`~/${n}`:e}function Am(e){return pe.join(Zr(e),".visa-cli","hud-self-heal.json")}function Rm(e,t,n,r){try{if(!se.existsSync(e))return!1;let o=JSON.parse(se.readFileSync(e,"utf-8"));return o.version===t&&typeof o.checkedAt=="number"&&n-o.checkedAt<r}catch{return!1}}function Ss(e,t,n){try{Yr(e,{version:t,checkedAt:n})}catch{}}function Im(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function xs(e,t={}){let n=t.now??Date.now(),r=t.version??Em(),o=t.stampPath??Am(e),s=t.minIntervalMs??Cm,i=[],a=!1,l=!1;if(!t.force&&Rm(o,r,n,s))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:i,skippedReason:"recently checked"};try{if(!se.existsSync(e))return Ss(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:l,messages:i};let c=JSON.parse(se.readFileSync(e,"utf-8")),u=c.statusLine,d=u&&typeof u=="object"&&!Array.isArray(u)?u.command:"";if(!xt(d))return Ss(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:l,messages:i};let f=(t.getCommand??Xr)();if(d!==f&&(c.statusLine=Im(u,f),Yr(e,c),a=!0,i.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!Qr()){let p=Zr(e);if(Vt(p).length>0){let T=tt(null,p);if(T.removed&&T.rcPaths&&T.rcPaths.length>0){let P=T.rcPaths.map(H=>Jr(H,p)).join(", ");l=!0,i.push(`Cleaned legacy shell-prompt HUD block from ${P}.`)}}}return Ss(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:l,messages:i}}catch(c){if(t.force){let u=c instanceof Error?c.message:"unknown error";try{process.stderr.write(`visa-cli: HUD self-heal skipped \u2014 ${u}. Run: visa-cli config hud doctor
105
- `)}catch{}}return{checked:!0,statusLineRepaired:a,shellHudRemoved:l,messages:i}}}function $m(e,t){let n=Zr(t),r=Vt(n);if(r.length===0)return e;let o=r.map(s=>Jr(s,n)).join(", ");return`${e}
106
- Note: a shell-prompt HUD block was detected in ${o}. If it is unintended, remove it with: visa-cli config hud disable shell`}function Qr(e=process.env.VISA_HUD_KEEP_SHELL){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function Va(e,t){let n=Zr(t),r=Vt(n);if(r.length===0)return e;let o=r.map(i=>Jr(i,n)).join(", ");if(Qr())return`${e}
107
- Note: a legacy shell-prompt HUD block was detected in ${o}. VISA_HUD_KEEP_SHELL set \u2014 leaving it in place. Remove it any time with: visa-cli config hud disable shell`;let s=tt(null,n);if(s.removed&&s.rcPaths&&s.rcPaths.length>0){let i=s.rcPaths.map(a=>Jr(a,n)).join(", ");return`${e}
96
+ `);return`${e}${i}`}function Om(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 As(e,t){try{let n=H.dirname(wt());q.mkdirSync(n,{recursive:!0});let r=e.split(`
97
+ `).map(s=>Lm(s)).filter(s=>s.length>0).join(`
98
+ `),o={hudVersion:gm,renderedAt:Date.now(),line:r,cwd:process.cwd(),status:t};Cn(wt(),JSON.stringify(o)+`
99
+ `),Cn(nr(),r+`
100
+ `)}catch{}}function Ja(e){try{let t=sr();if(!t)return;let n=Math.max(Date.now(),t.renderedAt+1),r={...t,refreshFailedAt:n,refreshErrorReason:xt(e).slice(0,200)};Cn(wt(),JSON.stringify(r)+`
101
+ `)}catch{}}function Ya(){try{let e=sr();if(!e)return;let t={...e,renderedAt:0};Cn(wt(),JSON.stringify(t)+`
102
+ `)}catch{}}function Vt(){try{q.unlinkSync(Ba())}catch{}}function sr(){let e=wt();if(!q.existsSync(e))return null;try{let t=JSON.parse(q.readFileSync(e,"utf-8"));return typeof t?.line=="string"&&no(t.line)?null:t}catch{return null}}function no(e){for(let t of e.split(`
103
+ `)){let n=t.trim();if(n.length===0)continue;let r=n.replace(/\[[0-?]*[ -/]*[@-~]/g,"").trim();if(/^VISA\s*\|\s*loading\b/i.test(r)||/^VISA\s*\|\s*HUD\s+not\s+(ready|initialized)\b/i.test(r))return!0}return!1}function Xa(){return sr()?.status??null}function Mm(){if(process.env.JEST_WORKER_ID)return;let e=Ba();try{if(q.mkdirSync(H.dirname(e),{recursive:!0}),!Vm(e))return;let t=process.argv[1]?H.resolve(process.argv[1]):"";if(!t){Vt();return}let n=Jr(),r=(process.env.VISA_CLI_HUD_THEME??"").toLowerCase().trim(),o=n==="no-color"||r==="light"||r==="dark"?{}:{VISA_CLI_HUD_THEME:n},s=(0,Va.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,...o,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});s.once("error",Vt),s.unref()}catch{Vt()}}function xt(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim()}var Nm=/^\u001B\[(?:0|38;2;\d{1,3};\d{1,3};\d{1,3}|38;5;\d{1,3})m$/;function Lm(e){let t=[],n=`__VISA_CLI_HUD_SGR_${(0,Cs.randomBytes)(8).toString("hex")}_`,r=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,s=>{if(!Nm.test(s))return"";let i=`${n}${t.length}__`;return t.push(s),i}),o=new RegExp(`${n}(\\d+)__`,"g");return xt(r).replace(o,(s,i)=>t[Number(i)]??"")}function Um(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),o="\u2591".repeat(10-n);return`${G(r||"",K.green)}${G(o||"",K.chrome)}`}function kn(e){return`$${e.toFixed(2)}`}function Dm(e){let t=e;if(t.startsWith("/")&&(t=t.replace(/^\/(?:api\/)?v\d+\/fal\//,""),t=t.replace(/^\/(?:api\/)?v\d+\/(?:shortcuts|openrouter)\//,""),t.startsWith("/"))){let o=t.split("/").filter(Boolean);t=o[o.length-1]||t}return t=t.replace(/^fal-ai\//,""),t=t.replace(/^fal-/,""),t=t.replace(/^or-/,""),t=t.split("/").filter(Boolean).map(o=>o.replace(/^v\d+(?:\.\d+)?-?/,"")||null).filter(o=>o!==null&&o.length>0).join(" "),t=t.replace(/_card$/,""),t.length>28&&(t=t.slice(0,28).trimEnd()),t||e}function jm(e){let t=e.cards?.find(a=>a.isDefault)??e.cards?.[0];if(!t)return"card none";let n=typeof t.brand=="string"?t.brand:"card",r=typeof t.last4=="string"?t.last4:"????",o=xt(n.toUpperCase()),s=xt(r);return`${t.isDefault?"default":"active"} ${o} ****${s}`}var K={get reset(){return le().reset},get visaBlue(){return le().visaBlue},get visaBlueSoft(){return le().visaBlueSoft},get visaGold(){return le().visaGold},get green(){return le().green},get muted(){return le().muted},get chrome(){return le().chrome}};function G(e,t){return e.length===0||process.env.NO_COLOR||Yr()?e:`${t}${e}${K.reset}`}function qa(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Rs(){let e=Ht.homedir();if(!e||!H.isAbsolute(e))throw new Error("unable to determine a valid home directory");return H.resolve(e)}function Fm(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function qm(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function Vm(e){for(let t=0;t<2;t+=1){let n;try{return n=q.openSync(e,"wx"),q.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let o=q.statSync(e);if(Date.now()-o.mtimeMs<=Sm)return!1;q.unlinkSync(e)}catch{}}finally{n!==void 0&&q.closeSync(n)}}return!1}function ks(e){return e instanceof Error?e.message:"unknown file system error"}function Cn(e,t){q.mkdirSync(H.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${(0,Cs.randomBytes)(8).toString("hex")}.tmp`;try{q.writeFileSync(n,t),q.renameSync(n,e)}catch(r){try{q.unlinkSync(n)}catch{}throw r}}var Hm=1440*60*1e3;function oo(e,t){se.mkdirSync(fe.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${ec.randomBytes(8).toString("hex")}.tmp`;try{se.writeFileSync(n,JSON.stringify(t,null,2)+`
104
+ `),se.renameSync(n,e)}catch(r){try{se.unlinkSync(n)}catch{}throw r}}function Za(e){return`'${e.replace(/'/g,"'\\''")}'`}var $s="# visa-cli-hud-v1";function so(e,t){if(!e&&!t&&Bm())return`visa-cli config statusline ${$s}`;let n=e??process.execPath,r=t??process.argv[1]??"",o=r?fe.resolve(r):"";return`${o?`${Za(n)} ${Za(o)} config statusline`:"visa-cli config statusline"} ${$s}`}function Bm(){try{return(0,tc.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function kt(e){return typeof e!="string"?!1:e.includes($s)?!0:e.includes("visa-cli")&&e.includes("statusline")}function Km(){return"2.6.0-rc.8"}function io(e){let t=fe.dirname(fe.resolve(e));return fe.basename(t)===".claude"?fe.dirname(t):nc.homedir()}function ro(e,t){let n=fe.relative(t,e);return!n.startsWith("..")&&!fe.isAbsolute(n)?`~/${n}`:e}function Gm(e){return fe.join(io(e),".visa-cli","hud-self-heal.json")}function zm(e,t,n,r){try{if(!se.existsSync(e))return!1;let o=JSON.parse(se.readFileSync(e,"utf-8"));return o.version===t&&typeof o.checkedAt=="number"&&n-o.checkedAt<r}catch{return!1}}function Is(e,t,n){try{oo(e,{version:t,checkedAt:n})}catch{}}function Wm(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function Ps(e,t={}){let n=t.now??Date.now(),r=t.version??Km(),o=t.stampPath??Gm(e),s=t.minIntervalMs??Hm,i=[],a=!1,l=!1;if(!t.force&&zm(o,r,n,s))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:i,skippedReason:"recently checked"};try{if(!se.existsSync(e))return Is(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:l,messages:i};let c=JSON.parse(se.readFileSync(e,"utf-8")),u=c.statusLine,d=u&&typeof u=="object"&&!Array.isArray(u)?u.command:"";if(!kt(d))return Is(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:l,messages:i};let f=(t.getCommand??so)();if(d!==f&&(c.statusLine=Wm(u,f),oo(e,c),a=!0,i.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!ao()){let m=io(e);if(Bt(m).length>0){let S=nt(null,m);if(S.removed&&S.rcPaths&&S.rcPaths.length>0){let $=S.rcPaths.map(V=>ro(V,m)).join(", ");l=!0,i.push(`Cleaned legacy shell-prompt HUD block from ${$}.`)}}}return Is(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:l,messages:i}}catch(c){if(t.force){let u=c instanceof Error?c.message:"unknown error";try{process.stderr.write(`visa-cli: HUD self-heal skipped \u2014 ${u}. Run: visa-cli config hud doctor
105
+ `)}catch{}}return{checked:!0,statusLineRepaired:a,shellHudRemoved:l,messages:i}}}function Jm(e,t){let n=io(t),r=Bt(n);if(r.length===0)return e;let o=r.map(s=>ro(s,n)).join(", ");return`${e}
106
+ Note: a shell-prompt HUD block was detected in ${o}. If it is unintended, remove it with: visa-cli config hud disable shell`}function ao(e=process.env.VISA_HUD_KEEP_SHELL){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function Qa(e,t){let n=io(t),r=Bt(n);if(r.length===0)return e;let o=r.map(i=>ro(i,n)).join(", ");if(ao())return`${e}
107
+ Note: a legacy shell-prompt HUD block was detected in ${o}. VISA_HUD_KEEP_SHELL set \u2014 leaving it in place. Remove it any time with: visa-cli config hud disable shell`;let s=nt(null,n);if(s.removed&&s.rcPaths&&s.rcPaths.length>0){let i=s.rcPaths.map(a=>ro(a,n)).join(", ");return`${e}
108
108
  Cleaned legacy shell-prompt HUD block from ${i} (was leaking output above every shell prompt). Set VISA_HUD_KEEP_SHELL=true to keep both surfaces (also accepts 1, yes, on).`}return`${e}
109
- Note: a legacy shell-prompt HUD block was detected in ${o} but could not be auto-removed (${s.message}). Remove it manually with: visa-cli config hud disable shell`}function tr(e,t=Xr){let n={},r=!1;if(se.existsSync(e)){r=!0;try{n=JSON.parse(se.readFileSync(e,"utf-8"))}catch(o){return{installed:"malformed-json",message:`~/.claude/settings.json is not valid JSON (${o.message}). Fix the file manually, then run: visa-cli config hud enable claude`}}}if(n.statusLine){let o=typeof n.statusLine=="object"?n.statusLine.command:"";return xt(o)?{installed:"already-visa",message:Va("Visa HUD already registered in ~/.claude/settings.json.",e)}:{installed:"other-hud-present",message:$m("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()},Yr(e,n),{installed:"new",message:Va(`Visa HUD registered in ~/.claude/settings.json${r?"":" (new file)"}. Restart Claude Code to see it pinned below the input.`,e)}}catch(o){return{installed:"error",message:`Failed to write settings: ${o.message}. Enable manually later with: visa-cli config hud enable claude`}}}function ks(e){if(!se.existsSync(e))return{removed:!1,status:"missing-settings",message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(se.readFileSync(e,"utf-8"))}catch(r){return{removed:!1,status:"malformed-json",message:`~/.claude/settings.json is not valid JSON: ${r.message}`}}if(!t.statusLine)return{removed:!1,status:"missing-statusline",message:"No statusLine configured."};let n=typeof t.statusLine=="object"?t.statusLine.command:"";if(!xt(n))return{removed:!1,status:"foreign-statusline",message:"statusLine is owned by another tool \u2014 leaving it alone."};delete t.statusLine;try{Yr(e,t)}catch(r){return{removed:!1,status:"error",message:`Failed to write ~/.claude/settings.json: ${r.message}`}}return{removed:!0,status:"removed",message:"Visa HUD removed from ~/.claude/settings.json. Restart Claude Code to take effect."}}var Ga=E(require("os")),za=E(require("path"));function nt(e=Ga.homedir()){return za.join(e,".claude","settings.json")}var rt=E(require("fs")),Fe=E(require("path")),Pm=1,Ht={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},Mm=["terminal","claude","claude-code","all"];function to(e){let t=e.toLowerCase();return Mm.includes(t)?t:null}var Om=50,Nm=64*1024,Wa=10,Cs=80;function Lm(){let e=(process.env.COLORTERM??"").toLowerCase();if(e==="truecolor"||e==="24bit")return!0;let t=(process.env.TERM??"").toLowerCase();return t.includes("truecolor")||t.includes("24bit")}var Ts=Lm(),C={reset:"\x1B[0m",visaBlue:Ts?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:Ts?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:Ts?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function A(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${C.reset}`}function Ja(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function Qa(e=process.stdin){return e.isTTY?null:new Promise(t=>{let n=[],r=!1,o=()=>{e.removeListener("data",i),e.removeListener("end",a),e.removeListener("error",l),clearTimeout(c)},s=u=>{r||(r=!0,o(),t(u))},i=u=>{n.push(typeof u=="string"?Buffer.from(u):u)},a=()=>{let u=Buffer.concat(n).toString("utf-8").trim();if(!u)return s(null);try{let d=JSON.parse(u);s(d&&typeof d=="object"?d:null)}catch{s(null)}},l=()=>s(null),c=setTimeout(()=>{n.length>0?a():s(null)},Om);e.on("data",i),e.on("end",a),e.on("error",l)})}function nr(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),o="\u2591".repeat(10-n);return`${A(r||"",C.visaBlueSoft)}${A(o||"",C.dim)}`}function rr(e){return!Number.isFinite(e)||e<0?"0":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:String(Math.round(e))}function Um(e){if(lc(e))return jm(e);let t=` ${A("\u2502",C.dim)} `,n=eo(e)||"claude",r=e.cwd?ee(Fe.basename(e.cwd)):"",o=no(e.workspace),s=r||o,i=o&&o!==s?` ${A(`@${o}`,C.visaBlueSoft)}`:"",a=[A(`[${n}]`,C.visaBlueSoft)];s&&a.push(`${A(s,C.visaGold)}${i}`);let l=ee(e.git_branch??e.branch??"");l&&a.push(`${A("git:(",C.dim)}${A(l,C.visaBlueSoft)}${A(")",C.dim)}`);let c=a.join(t),u=Number(e.context_window?.context_window_size??0),d=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,f=e.context_window?.current_usage,p=[f?.input_tokens,f?.output_tokens,f?.cache_creation_input_tokens,f?.cache_read_input_tokens].filter(k=>typeof k=="number"&&Number.isFinite(k)),_=p.length>0?p.reduce((k,L)=>k+L,0):null,T=Number(e.context_window?.total_input_tokens??_??f?.input_tokens??0),P=d!==null?Math.max(0,Math.min(1,d/100)):u>0?Math.max(0,Math.min(1,T/u)):0,H=d!==null&&u>0?Math.round(P*u):T,D;if(u>0||d!==null){let k=`${String(Math.round(P*100)).padStart(2," ")}%`,L=u>0?` ${A(`(${rr(H)}/${rr(u)})`,C.dim)}`:"";D=`${A("Context",C.dim)} ${nr(P)} ${A(k,C.green)}${L}`}else D=`${A("Context",C.dim)} ${A("-",C.dim)}`;let S=ec(e.rate_limits),w=[D];S&&w.push(S);let y=w.join(t);return`${c}
110
- ${y}`}function Dm(e){if(lc(e))return null;let t=` ${A("\u2502",C.dim)} `,n=eo(e)||"claude",r=e.cwd?ee(Fe.basename(e.cwd)):"",o=no(e.workspace),s=r||o,i=o&&o!==s?` ${A(`@${o}`,C.visaBlueSoft)}`:"",a=[A(`[${n}]`,C.visaBlueSoft)];s&&a.push(`${A(s,C.visaGold)}${i}`);let l=ee(e.git_branch??e.branch??"");l&&a.push(`${A("git:(",C.dim)}${A(l,C.visaBlueSoft)}${A(")",C.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(w=>typeof w=="number"&&Number.isFinite(w)),p=f.length>0?f.reduce((w,y)=>w+y,0):null,_=Number(e.context_window?.total_input_tokens??p??d?.input_tokens??0),T=u!==null?Math.max(0,Math.min(1,u/100)):c>0?Math.max(0,Math.min(1,_/c)):0,P=u!==null&&c>0?Math.round(T*c):_,H;if(c>0||u!==null){let w=`${String(Math.round(T*100)).padStart(2," ")}%`,y=c>0?` ${A(`(${rr(P)}/${rr(c)})`,C.dim)}`:"";H=`${A("Context",C.dim)} ${nr(T)} ${A(w,C.green)}${y}`}else H=`${A("Context",C.dim)} ${A("-",C.dim)}`;let D=ec(e.rate_limits),S=[H];return D&&S.push(D),{identity:a.join(t),metrics:S.join(t)}}function jm(e){let t=` ${A("\u2502",C.dim)} `,n=uc(e),r=n.model||"codex",o=[A(`[${r}]`,C.visaBlueSoft)];n.project&&o.push(A(n.project,C.visaGold)),n.gitBranch&&o.push(`${A("git",C.dim)} ${A(n.gitBranch,C.visaGold)}`);let s=o.join(t),i=[];if(typeof n.contextUsedPercent=="number"){let l=Math.max(0,Math.min(1,n.contextUsedPercent/100));i.push(`${A("Context",C.dim)} ${nr(l)} ${A(`${Math.round(n.contextUsedPercent)}%`,C.green)}`)}else if(typeof n.contextRemainingPercent=="number"){let l=100-n.contextRemainingPercent,c=Math.max(0,Math.min(1,l/100));i.push(`${A("Context",C.dim)} ${nr(c)} ${A(`${Math.round(l)}%`,C.green)}`)}typeof n.usedTokens=="number"&&i.push(`${A("Tokens",C.dim)} ${rr(n.usedTokens)}`),n.status&&i.push(`${A("Status",C.dim)} ${A(n.status,C.visaBlueSoft)}`),n.threadTitle&&i.push(`${A("Thread",C.dim)} ${A(n.threadTitle,C.visaBlueSoft)}`);let a=i.length>0?i.join(t):`${A("Context",C.dim)} ${A("-",C.dim)}`;return`${s}
111
- ${a}`}function Fm(e){if(typeof e!="number"||e<=0)return"";let n=(e>1e12?e:e*1e3)-Date.now();if(n<=0||n>=10080*60*1e3)return"";let r=Math.floor(n/6e4),o=Math.floor(r/60),s=r%60;return o>0?`${o}h ${s}m`:`${s}m`}function Ya(e,t){if(!e||typeof e.used_percentage!="number")return null;let n=Math.max(0,Math.min(100,e.used_percentage)),r=n/100,o=nr(r),s=n>=90?"\x1B[38;5;196m":n>=70?C.visaGold:C.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=Fm(e.resets_at),l=a?` ${A(`(${a} / ${t})`,C.dim)}`:` ${A(`(${t})`,C.dim)}`;return`${o} ${A(i,s)}${l}`}function ec(e){if(!e)return null;let t=Ya(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?Ya(e.seven_day,"7d"):null;if(!t&&!r)return null;let o=` ${A("\u2502",C.dim)} `,s=[t,r].filter(Boolean);return`${A("Usage",C.dim)} ${s.join(o)}`}function tc(e){let t;try{let n=rt.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let o=Math.min(r,Nm),s=r-o;t=rt.openSync(e,"r");let i=Buffer.alloc(o);rt.readSync(t,i,0,o,s);let a=i.toString("utf-8");if(s>0){let l=Buffer.alloc(1);if(rt.readSync(t,l,0,1,s-1),l[0]!==10){let c=a.indexOf(`
112
- `);c>=0&&(a=a.slice(c+1))}}return a}catch{return null}finally{if(t!==void 0)try{rt.closeSync(t)}catch{}}}function qm(e){if(!e||typeof e!="object")return;let t=e,n=["file_path","path","notebook_path","pattern","command","url"];for(let r of n){let o=t[r];if(typeof o=="string"&&o.length>0){if(r.endsWith("_path")||r==="path"){let s=Fe.basename(Fe.dirname(o)),i=Fe.basename(o);return s&&s!=="."&&s!=="/"?`${s}/${i}`:i}return o}}}function Vm(e){let t=e.split(`
113
- `),n=[],r=new Set;for(let o=t.length-1;o>=0&&n.length<Wa*3;o-=1){let s=t[o].trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{continue}if(!i||typeof i!="object")continue;let l=i.message;if(!l||typeof l!="object")continue;let c=l.content;if(Array.isArray(c))for(let u of c){if(!u||typeof u!="object")continue;let d=u;if(d.type==="tool_result"&&typeof d.tool_use_id=="string")r.add(d.tool_use_id);else if(d.type==="tool_use"&&typeof d.name=="string"){let f=typeof d.id=="string"?d.id:"",p=f.length>0?!r.has(f):!1;n.push({name:d.name,target:qm(d.input),running:p})}}}return n.reverse(),n.slice(Math.max(0,n.length-Wa))}function Hm(e){let t=[];for(let n of e){let r=t[t.length-1];r&&!r.running&&!n.running&&r.name===n.name&&r.target===void 0&&n.target===void 0?r.count+=1:t.push({...n,count:1})}return t}function Bm(e){let t=e.running?A("\u25D0",C.visaGold):A("\u2713",C.green),n=e.running?C.visaGold:C.visaBlueSoft,r=A(ee(e.name),n),o=e.target?ee(e.target):"",s=o?`${A(":",C.dim)} ${A(o,C.dim)}`:"",i=e.count>1?` ${A(`\xD7${e.count}`,C.dim)}`:"";return s?`${t} ${r}${s}${i}`:`${t} ${r}${i}`}function Km(e){let t=` ${A("\u2502",C.dim)} `,n=Ja(t),r=e.slice();for(;r.length>0;){let l=r.join(t);if(Ja(l)<=Cs)return l;r=r.slice(1)}if(e.length===0)return"";let o="\u2026",i=e[e.length-1].replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,""),a=i.length>Cs-n-1?i.slice(0,Cs-n-1)+o:i;return`${A(o,C.dim)}${t}${a}`}async function Xa(e){if(!e||typeof e!="string")return null;let t=tc(e);if(!t)return null;let n;try{n=Vm(t)}catch{return null}if(n.length===0)return null;let o=Hm(n).map(Bm);return Km(o)||null}async function nc(e,t,n){return(await oc(e,t,n)).join(`
114
- `)}function rc(e,t,n){let r=!!t?.activeSession||e.includes("in session"),o=n?zm(n):!1;return{isActive:r||o,hasSession:r,hasToolActivity:o}}async function oc(e,t,n){let{isActive:r}=rc(e,n,t?.transcript_path),o=e.split(`
115
- `).filter(a=>a.length>0),i=t&&!r?o.map(a=>A(Es(a),C.dim)):[...o];if(t){let a=Dm(t);if(a){if(i.push(a.identity),t.transcript_path){let l=await Xa(t.transcript_path);l&&i.push(...l.split(`
116
- `))}i.push(a.metrics)}else{let l=Um(t);if(l&&i.push(...l.split(`
117
- `)),t.transcript_path){let c=await Xa(t.transcript_path);c&&i.push(...c.split(`
118
- `))}}}return i}var Gm=["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 zm(e){let t=tc(e);if(!t)return!1;let n=t.slice(-16384).toLowerCase();return Gm.some(r=>n.includes(`"${r}"`))}async function sc(e,t,n){let r=await oc(e,t,n),o=r.join(`
119
- `),{isActive:s}=rc(e,n,t?.transcript_path);return{schemaVersion:Pm,client:t?cc(t):Ht.UNKNOWN,rendered:o,lines:r.map(Es),visa:{spendLine:Es(e),balanceCents:n?.balanceCents,balanceUsd:n?.amountUsd,sessionMode:n?.sessionMode,activeSession:n?.activeSession,isVisaActive:s},context:t?uc(t):{}}}function ee(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 no(e){if(typeof e=="string")return ee(Fe.basename(e));if(!e||typeof e!="object")return"";let t=typeof e.current_dir=="string"?e.current_dir:typeof e.path=="string"?e.path:"";return ee(t?Fe.basename(t):e.name)}function ic(e){return ee(e.app_name??e.appName??e.app??e.client)}function eo(e){return ee(e.model?.display_name??e.model?.id??e.model_name??e.modelName)}function ac(e){return ee(e.cwd??e.current_dir??e.project_root)}function Za(e){let t=ee(e.project);if(t)return t;let n=ac(e);if(n)return ee(Fe.basename(n));let r=no(e.workspace);return r||""}function Pe(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function cc(e){let t=ic(e).toLowerCase();return t.includes("codex")?Ht.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?Ht.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||Pe(e.context_used)!==void 0?Ht.CODEX:Ht.UNKNOWN}function lc(e){return cc(e)===Ht.CODEX}function uc(e){let t=ic(e),n=ac(e),r=no(e.workspace),o=Pe(e.context_used)??Pe(e.context_window?.used_percentage??void 0),s=Pe(e.context_remaining)??Pe(e.context_window?.remaining_percentage??void 0);return{...t?{app:t}:{},...eo(e)?{model:eo(e)}:{},...Za(e)?{project:Za(e)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...ee(e.git_branch??e.branch)?{gitBranch:ee(e.git_branch??e.branch)}:{},...ee(e.status??e.run_state??e.runState)?{status:ee(e.status??e.run_state??e.runState)}:{},...ee(e.thread_title??e.threadTitle)?{threadTitle:ee(e.thread_title??e.threadTitle)}:{},...o!==void 0?{contextUsedPercent:o}:{},...s!==void 0?{contextRemainingPercent:s}:{},...Pe(e.used_tokens)!==void 0?{usedTokens:Pe(e.used_tokens)}:{},...Pe(e.total_input_tokens)!==void 0?{totalInputTokens:Pe(e.total_input_tokens)}:{},...Pe(e.total_output_tokens)!==void 0?{totalOutputTokens:Pe(e.total_output_tokens)}:{}}}function Es(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}var mc=E(require("path"));function dc(e){return e instanceof Error?e.message:String(e)}function As(e,t){let n=[],r=[],o=e??"claude",s=to(o);if(o==="shell"||o==="prompt")try{let a=t.installShellHud();return a.installed?{ok:!0,messages:[a.message],errors:r}:{ok:!1,messages:n,errors:[a.message]}}catch(a){return{ok:!1,messages:n,errors:[`Failed to install shell HUD: ${dc(a)}`]}}if(!s)return{ok:!1,messages:n,errors:[`Unknown HUD surface: ${o}`,"Supported: claude (default), shell, all"]};let i=!0;if(s==="claude"||s==="claude-code"||s==="all"){let a=mc.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: ${dc(l)}`)}}return{ok:i,messages:n,errors:r}}function pc(e){if(!e||typeof e!="object")return"";let t=e;return Array.isArray(t.enum)&&t.enum.length>0?"enum":typeof t.type=="string"?t.type:Array.isArray(t.type)?t.type.filter(n=>typeof n=="string").join("|"):""}var fc=E(require("os")),gc=require("node:readline/promises"),or={card:"default VISA ****7242",balance:"balance $6.38",spentToday:"spent today $0.62",lastActivity:"last Visa tool 38m",model:"Opus 4.6"};async function hc(e,t=!1){if(!process.stdin.isTTY)return t;let n=t?"[Y/n]":"[y/N]",r,o;try{r=(0,gc.createInterface)({input:process.stdin,output:process.stdout});let s=new AbortController;o=()=>s.abort(),r.once("close",o);let i=(await r.question(`${e} ${n} `,{signal:s.signal})).trim();return i?/^y(es)?$/i.test(i):t}catch{return t}finally{r&&o&&r.off("close",o),r?.close()}}function Wm(e,t){return e.replace(/[\x00-\x1F\x7F\u202A-\u202E\u2066-\u2069]/g,"").trim()||t}function yc(e=fc.hostname()){let t=Kn().version,n=Wm(e,"this-machine");return[" Preview if installed (sample):",` VISA CLI v${t} | ${n} | ${or.card}`,` ${or.balance} | ${or.spentToday} | ${or.lastActivity}`,` [${or.model}] | you`," Activity live"].join(`
120
- `)}async function Bt(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,o=setTimeout(()=>r.abort(),n);try{let{timeoutMs:s,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(o)}}var Kt=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},xn=class extends Error{code;budgetId;status;constructor(t,n,r={}){super(t),this.name="SessionInvalidError",this.code=n,this.budgetId=r.budgetId,this.status=r.status}},Gt=class extends Error{code="SESSION_LOCK_CONTENDED";retryAfterSecs;status;constructor(t,n=1,r){super(t),this.name="SessionLockContendedError",this.retryAfterSecs=n,this.status=r}},le=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(t,n,r,o,s,i,a,l){super(t),this.name="CardDeclinedError",this.retryable=n,this.code=r,this.reason=o,this.paymentErrorClass=s,this.correlationId=i,this.transactionId=a,this.retryAfter=l}},ot=class extends Error{code;transactionId;retryable;reconciliationRequired;constructor(t,n,r={}){super(t),this.name="TopupAmbiguousError",this.code=n,this.transactionId=r.transactionId,this.retryable=r.retryable??!1,this.reconciliationRequired=r.reconciliationRequired??!0}};var _c={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 Rs(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&&_c[n]?_c[n]:`Network error contacting the Visa CLI server (${n?`${n}: ${typeof t.message=="string"?t.message:"unknown"}`:typeof t.message=="string"&&t.message.length>0?t.message:"unknown error"}). Check https://visacli.sh for status.`}var he=E(require("fs")),Ps=E(require("path")),vc=E(require("os")),$s=Ps.join(vc.homedir(),".visa-mcp"),sr=Ps.join($s,"mcp-server.log"),Jm=5*1024*1024,Is=null;function Ym(){he.existsSync($s)||he.mkdirSync($s,{recursive:!0,mode:448})}function Xm(){if(!Is){if(Ym(),he.existsSync(sr)&&he.statSync(sr).size>Jm){let t=sr+".1";he.existsSync(t)&&he.unlinkSync(t),he.renameSync(sr,t)}Is=he.createWriteStream(sr,{flags:"a"})}return Is}function Zm(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function ro(e,...t){let n=new Date().toISOString(),r=t.map(s=>typeof s=="string"?s:JSON.stringify(s,null,2)).join(" "),o=`[${n}] [${e}] ${r}
121
- `;Zm(e)&&process.stderr.write(o),Xm().write(o)}var m={debug:(...e)=>ro("DEBUG",...e),info:(...e)=>ro("INFO",...e),warn:(...e)=>ro("WARN",...e),error:(...e)=>ro("ERROR",...e)};var Qm=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Sc(e,t){let n=bc(e),r=bc(t);if(!n||!r)return!1;for(let o=0;o<3;o++)if(n.main[o]!==r.main[o])return n.main[o]>r.main[o];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:ep(n.pre,r.pre)>0}function bc(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(Qm);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function ep(e,t){let n=e.split("."),r=t.split("."),o=Math.max(n.length,r.length);for(let s=0;s<o;s++){if(s>=n.length)return-1;if(s>=r.length)return 1;let i=n[s],a=r[s],l=/^\d+$/.test(i),c=/^\d+$/.test(a);if(l&&c){let u=Number(i)-Number(a);if(u!==0)return u}else{if(l)return-1;if(c)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function qe(){return!!(wc(process.env.VISA_CLI_NO_UPDATE_CHECK)||wc(process.env.CI)||process.env.NODE_ENV==="test")}function wc(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var Ct=E(require("fs")),Ls=require("node:net"),Tc=E(require("os")),Ec=E(require("path"));var oo=E(require("fs")),xc=E(require("path")),kc=E(require("os"));var Ms=xc.join(kc.homedir(),".visa-mcp"),ir=class{static ensureConfigDir(){oo.existsSync(Ms)||oo.mkdirSync(Ms,{recursive:!0,mode:448})}static getConfigDir(){return Ms}static TOOL_STATES={login:!0,get_status:!0,get_cards:!0,add_card:!0,pay:!1,transaction_history:!0,update_spending_controls:!0,enroll_device:!1,verify_otp:!1,reset:!0,batch:!0,generate_x402_image:!1,browser_launch:!1,browser_navigate:!1,browser_snapshot:!1,browser_click:!1,browser_type:!1,browser_scroll:!1,generate_music_card:!1,generate_image_card:!1,query_onchain_prices_card:!1,generate_music_tempo_card:!1,check_music_status_tempo_card:!1,generate_image_fast_card:!1,generate_video_tempo_card:!1};static loadToolStates(){return{...this.TOOL_STATES}}static getDisabledTools(){let t=new Set;for(let[n,r]of Object.entries(this.TOOL_STATES))r||t.add(n);return t}static isToolDisabled(t){return this.TOOL_STATES[t]===!1}};function Cc(e){let t=Tc.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}var tp="settings.json",np="must use https unless it points at localhost/loopback for local development";function ar(){return Ec.join(ir.getConfigDir(),tp)}function Ac(e){if((0,Ls.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function rp(e){let t=e.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!t)return!1;let n=Number.parseInt(t[1],16),r=Number.parseInt(t[2],16);if(!Number.isFinite(n)||!Number.isFinite(r))return!1;let o=[n>>8&255,n&255,r>>8&255,r&255].join(".");return Ac(o)}function op(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,Ls.isIP)(t);return n===4?Ac(t):n===6?t==="::1"||rp(t):!1}function Os(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:"&&op(n.hostname)))throw new Error(`${t} ${np}`)}var Tt={"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");Os(e)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."},"ui.suppressFeed":{type:"boolean",description:"When true, generated images/music are not auto-submitted to the public Made-with-Visa feed."},"tools.meta":{type:"boolean",description:"Show category meta-tools (generate_image, generate_video, generate_music, run_llm, ...). Restart required.",requiresRestart:!0},"tools.discover":{type:"boolean",description:"Show the dynamic-catalog tools (discover_tools, execute_tool). Restart required.",requiresRestart:!0},"merchants.discover":{type:"string",description:'Platform-merchant JIT tool discovery: "all" = every live merchant, "off" = none, comma-separated slugs = exactly those. Equivalent to VISA_MERCHANT_DISCOVER / VISA_MERCHANT_SLUGS env. Restart required.',requiresRestart:!0,validate:e=>{if(typeof e!="string")throw new Error("merchants.discover must be a string");let t=e.trim().toLowerCase();if(t===""||t==="all"||t==="off"||t==="*")return;let n=/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/,r=e.split(",").map(o=>o.trim()).filter(Boolean);for(let o of r)if(!n.test(o))throw new Error(`merchants.discover: "${o}" is not a valid merchant slug`)}},"credit.sessionCapCents":{type:"number",description:"Default cap (in cents) for start_session and pay-as-you-go one-shot approvals. Server clamps to [10, 10000] = $0.10\u2013$100. Default 500 ($5).",validate:e=>{if(typeof e!="number"||!Number.isFinite(e))throw new Error("credit.sessionCapCents must be a number");if(!Number.isInteger(e))throw new Error("credit.sessionCapCents must be a whole number of cents (no fractional cents)");if(e<10||e>1e4)throw new Error("credit.sessionCapCents must be between 10 ($0.10) and 10000 ($100)")}}},Us=500,so={"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 zt(){let e=ar();if(!Ct.existsSync(e))return{};try{let t=Ct.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?(m.warn("settings:corrupt",{path:Cc(e),reason:"not_object"}),{}):n}catch(t){return m.warn("settings:corrupt",{path:Cc(e),error:t?.message||String(t)}),{}}}function Ns(e){ir.ensureConfigDir();let t=ar(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
122
- `;Ct.writeFileSync(n,r,{mode:384}),Ct.renameSync(n,t)}function Ds(e){let t=zt()[e];return typeof t=="string"?t:void 0}function io(e){let t=zt()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function js(e){let t=zt()[e];if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim().length>0){let n=Number(t);if(Number.isFinite(n))return n}}var st=class extends Error{constructor(t){let n=Object.keys(Tt).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"}},it=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"}},kt=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+so[t]),this.name="RetiredSettingKeyError"}},Rc=["biometric.","spending.","account.","cards.","biometric"];function ao(e,t){if(Rc.some(s=>e.startsWith(s)))throw new it(e);if(e in so)throw new kt(e);let n=Tt[e];if(!n)throw new st(e);let r;if(n.type==="boolean")if(typeof t=="boolean")r=t;else if(typeof t=="string"){let s=t.toLowerCase();if(s==="true")r=!0;else if(s==="false")r=!1;else throw new Error(`${e} expects true or false (got: ${JSON.stringify(t)})`)}else throw new Error(`${e} expects a boolean (got: ${typeof t})`);else if(n.type==="number")if(typeof t=="number")r=t;else if(typeof t=="string"&&t.trim().length>0){let s=Number(t);if(!Number.isFinite(s))throw new Error(`${e} expects a number (got: ${JSON.stringify(t)})`);r=s}else throw new Error(`${e} expects a number (got: ${typeof t})`);else{if(typeof t!="string"||t.length===0)throw new Error(`${e} expects a non-empty string`);r=t}n.validate&&n.validate(r);let o=zt();return o[e]=r,Ns(o),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:ar()}}function co(e){if(Rc.some(s=>e.startsWith(s)))throw new it(e);let t=Tt[e];if(e in so){let s=zt(),i=e in s;return i&&(delete s[e],Ns(s)),{key:e,removed:i,requiresRestart:!1,path:ar()}}if(!t)throw new st(e);let r=zt(),o=e in r;return o&&(delete r[e],Ns(r)),{key:e,removed:o,requiresRestart:o&&!!t.requiresRestart,path:ar()}}function Ic(){let e=zt();return Object.entries(so).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}var sp="https://auth.visacli.sh",ip="https://auth-visa-code-preview.up.railway.app";function ap(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function cp(){try{let e=Kn();return ap(e.version)}catch{return!1}}function lp(e){return e.envVar!==void 0&&e.envVar!==""?(Os(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(Os(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?ip:sp}function ye(){return lp({envVar:process.env.VISA_AUTH_URL,settingValue:Ds("auth.serverUrl"),isPrerelease:cp()})}function $c(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":io("ui.suppressBrowser")??!1}function Pc(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":io("ui.suppressFeed")??!1}function Mc(){let e=process.env.VISA_CREDIT_SESSION_CAP_CENTS;if(e!==void 0){let n=Number(e);if(Number.isFinite(n)&&n>=10&&n<=1e4)return Math.floor(n)}let t=js("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):Us}var up="CARD_REENROLLMENT_REQUIRED",dp="https://auth.visacli.sh/enroll-card";function mp(){try{return new URL("/enroll-card",ye()).toString()}catch{return dp}}function pp(e){let t=mp();if(typeof e!="string")return t;try{let n=new URL(e),r=new URL(t);if(n.origin===r.origin&&n.pathname==="/enroll-card")return n.toString()}catch{}return m.warn("card-reenroll:reenroll_url_rejected_fallback",{reason:"untrusted_or_malformed_reenroll_url",fallbackPath:"/enroll-card"}),t}var cr="2.6.0-rc.7",fp=/^vk_[A-Za-z0-9_-]{32,}$/;function gp(e){if(typeof e!="string")return null;switch(e){case"BUDGET_CLOSED":case"BUDGET_NOT_FOUND":case"BUDGET_EXPIRED":return e;default:return null}}function Oc(e){return e==="TOPUP_CHARGE_AMBIGUOUS"||e==="TOPUP_RECONCILIATION_REQUIRED"?e:null}var hp="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function kn(e){return typeof e=="string"?e.trim():""}function Nc(e){let t=e&&typeof e=="object"?e:{},n=kn(t.error)||kn(t.message);if(!n)return hp;let r=kn(t.error_code),o=[["surface",kn(t.disabled_surface)],["flag",kn(t.flag)],["correlation_id",kn(t.correlation_id)]].filter(([,i])=>i).map(([i,a])=>`${i}=${a}`),s=o.length?` (${o.join(" ")})`:"";return r?`503 [${r}] ${n}${s}`:`503 ${n}${s}`}function Lc(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?fp.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(`
123
- `)}var we=class{constructor(t){this.getSessionToken=t;this.baseUrl=ye()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!qe()){let r=t.headers.get("X-Latest-Version");r&&Sc(r,cr)&&(this.lastSignals.updateAvailable={currentVersion:cr,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return cr}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new Kt(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(Nc(n))}async request(t,n,r,o,s,i){let a=await this.getSessionToken();if(!a)throw new Error(Lc());let l={Authorization:`Bearer ${a}`};s&&(t==="GET"?l["X-User-Context"]=encodeURIComponent(s.replace(/[\r\n\0]/g," ").slice(0,1e3)):r={...r||{},user_context:s}),i&&(l["X-Visa-Meta-Tool"]=i),r&&(l["Content-Type"]="application/json");let c;try{c=await Bt(`${this.baseUrl}${n}`,{method:t,headers:{...l,"X-Visa-CLI-Version":cr,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:o})}catch(d){throw new Error(Rs(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===up){let f=typeof u?.last4=="string"?u.last4:"",p=typeof u?.brand=="string"?u.brand:"card",_=pp(u?.reenroll_url),T=f?`${p} ending in ${f}`:"your card";throw new Error(`Please re-add ${T} to keep payments running. Open: ${_}`)}let d=Oc(u?.error_code);if(d)throw new ot(u?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",d,{transactionId:typeof u?.transactionId=="string"?u.transactionId:void 0,retryable:!!u?.retryable,reconciliationRequired:u?.reconciliation_required!==!1});if(u?.declined){let f=Number(u.retryAfter??c.headers.get("Retry-After"));throw new le(u.error||"Your card was declined.",!!u.retryable,u.code,u.reason,u.payment_error_class,u.correlation_id,u.transactionId,Number.isFinite(f)&&f>0?f:void 0)}if(c.status===402){let f=u?.error||"Gateway returned 402",p=typeof u?.error_code=="string"?u.error_code:"";throw p==="SPENDING_LIMIT_EXCEEDED"||p==="DAILY_LIMIT_EXCEEDED"||p==="PER_TXN_LIMIT_EXCEEDED"?new Error(`${f}. Check your limits with get_status or run: visa-cli update-spending-controls`):new Error(f)}throw new Error(u?.error||`Request failed (${c.status}). Try again.`)}return u}async shortcut(t,n,r,o,s){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,o,s)}async shortcutWithSession(t,n,r,o,s,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,l=await this.getSessionToken();if(!l)throw new Error(Lc());let c={Authorization:`Bearer ${l}`,"X-Visa-CLI-Version":cr,"X-Source":"cli","Content-Type":"application/json"};i&&(c["X-Visa-Meta-Tool"]=i);let u={...n,...r};s&&(u.user_context=s.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await Bt(`${this.baseUrl}${a}`,{method:"POST",headers:c,body:JSON.stringify(u),timeoutMs:o})}catch(_){throw new Error(Rs(_))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let _=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${_}s. Tip: use the batch tool to combine multiple requests into one.`)}let f=d.headers.get("X-Voucher-Receipt"),p;try{p=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(p),d.status===503){if(p?.error_code==="SESSION_LOCK_CONTENDED"){let P=Number(d.headers.get("Retry-After"))||1;throw new Gt(p?.message||p?.error||"Session budget is being modified by another request. Retry shortly.",P,d.status)}throw new Error(Nc(p))}let _=gp(p?.error_code);if(_||d.status===410){let P=_??"BUDGET_CLOSED";throw new xn(p?.message||p?.error||"Your session was invalidated by the server.",P,{budgetId:n.session_budget_id,status:d.status})}if(p?.declined){let P=Number(p.retryAfter??d.headers.get("Retry-After"));throw new le(p.error||"Your card was declined.",!!p.retryable,p.code,p.reason,p.payment_error_class,p.correlation_id,p.transactionId,Number.isFinite(P)&&P>0?P:void 0)}let T=Oc(p?.error_code);throw T?new ot(p?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",T,{transactionId:typeof p?.transactionId=="string"?p.transactionId:void 0,retryable:!!p?.retryable,reconciliationRequired:p?.reconciliation_required!==!1}):new Error(p?.error||`Request failed (${d.status}). Try again.`)}return{data:p,voucherReceiptHeader:f}}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async catalogSearch(t,n,r,o){let s=r??"discover_tools",i=new URLSearchParams;t&&i.set("q",t),n&&i.set("category",n),o?.limit!=null&&i.set("limit",String(o.limit)),o?.offset!=null&&i.set("offset",String(o.offset));let a=i.toString();return this.request("GET",`/v1/catalog${a?`?${a}`:""}`,void 0,void 0,void 0,s)}async catalogTool(t,n){let r=n??"discover_tools";try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(t)}`,void 0,void 0,void 0,r)}catch{return null}}async discoverMerchantRoutes(t){try{return await this.request("GET",`/v1/platform/discover/${encodeURIComponent(t)}`)}catch{return null}}async listPublicMerchants(){try{let t=await Bt(`${this.baseUrl}/v1/platform/merchants/public`,{method:"GET",timeoutMs:8e3});if(!t.ok)return[];let n=await t.json();return Array.isArray(n.merchants)?n.merchants:[]}catch{return[]}}async getPublicMerchantDiscover(t){try{let n=await Bt(`${this.baseUrl}/v1/platform/discover/${encodeURIComponent(t)}`,{method:"GET",timeoutMs:8e3});return n.ok?await n.json():null}catch{return null}}async paymentPreview(t,n){return this.request("POST","/v1/payment-preview",t,void 0,n)}async getBalance(){return this.request("GET","/v1/balance")}async topupBalance(t){return this.request("POST","/v1/balance/topup",t)}async createEnrollCode(){return this.request("POST","/v1/enroll-code")}async getAutoTopup(){let t=await this.getBalance();return{success:t.success,targetCents:t.autoTopupCents??null,thresholdCents:t.autoTopupThresholdCents??0}}async disableAutoTopup(){return this.request("PATCH","/v1/balance/auto-topup",{auto_topup_cents:null})}async createSessionBudget(t){return this.request("POST","/v1/session-budget/create",{...t,mode:"prepaid"})}async closeSession(t){return this.request("POST","/v1/session/close",{session_budget_id:t})}async getSessionBudget(t){return this.request("GET",`/v1/session-budget/${encodeURIComponent(t)}`)}async getSessionLedger(t){return this.request("GET",`/v1/session/${encodeURIComponent(t)}/ledger`)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getVisaSmi(t,n){return this.request("POST","/v1/visa/smi",t,6e4,n)}async getTransactions(t,n){let r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.offset!=null&&r.set("offset",String(t.offset));let o=r.toString(),s=o?`/v1/transactions?${o}`:"/v1/transactions";return this.request("GET",s,void 0,void 0,n)}async updateSpendingControls(t,n){return this.request("POST","/v1/spending-controls",t,void 0,n)}async removeCard(t,n,r){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(t))}`,n,void 0,r)}async setDefaultCard(t,n,r){return this.request("POST",`/v1/cards/${encodeURIComponent(String(t))}/default`,n,void 0,r)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t,n){return this.request("POST","/v1/attestation-key",{publicKey:t,...n?{attestation:n}:{}})}async startAttestationRecovery(t,n){return this.request("POST","/v1/attestation-key/recovery/start",{state:t},void 0,n)}async setBiometricPreference(t,n){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,n)}async logout(t,n){return this.request("POST","/v1/logout",t,void 0,n)}async feedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async createAppApiKey(t){return this.request("POST","/v1/api/keys",t)}async listAppApiKeys(){return this.request("GET","/v1/api/keys")}async revokeAppApiKey(t){return this.request("DELETE",`/v1/api/keys/${encodeURIComponent(String(t))}`)}async feedSubmit(t){return this.request("POST","/v1/feed",t)}async feedList(t){let n=new URLSearchParams;t?.tab&&n.set("tab",t.tab),t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset));let r=n.toString();return this.request("GET",`/v1/feed${r?"?"+r:""}`)}async feedVote(t,n){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/vote`,{direction:n})}async feedApprove(t){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/approve`)}async feedDelete(t){return this.request("DELETE",`/v1/feed/${encodeURIComponent(t)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async getFeedback(t,n){let r=new URLSearchParams;t&&r.set("limit",String(t));let o=r.toString();return this.request("GET",`/v1/feedback${o?"?"+o:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}};var g={};Zo(g,{BRAND:()=>Vp,DIRTY:()=>Wt,EMPTY_PATH:()=>bp,INVALID:()=>R,NEVER:()=>Ef,OK:()=>ue,ParseStatus:()=>ce,Schema:()=>N,ZodAny:()=>Rt,ZodArray:()=>ut,ZodBigInt:()=>Yt,ZodBoolean:()=>Xt,ZodBranded:()=>ur,ZodCatch:()=>ln,ZodDate:()=>Zt,ZodDefault:()=>cn,ZodDiscriminatedUnion:()=>mo,ZodEffects:()=>Re,ZodEnum:()=>sn,ZodError:()=>_e,ZodFirstPartyTypeKind:()=>I,ZodFunction:()=>fo,ZodIntersection:()=>nn,ZodIssueCode:()=>h,ZodLazy:()=>rn,ZodLiteral:()=>on,ZodMap:()=>In,ZodNaN:()=>Pn,ZodNativeEnum:()=>an,ZodNever:()=>Me,ZodNull:()=>en,ZodNullable:()=>Be,ZodNumber:()=>Jt,ZodObject:()=>ve,ZodOptional:()=>Ee,ZodParsedType:()=>b,ZodPipeline:()=>dr,ZodPromise:()=>It,ZodReadonly:()=>un,ZodRecord:()=>po,ZodSchema:()=>N,ZodSet:()=>$n,ZodString:()=>At,ZodSymbol:()=>An,ZodTransformer:()=>Re,ZodTuple:()=>He,ZodType:()=>N,ZodUndefined:()=>Qt,ZodUnion:()=>tn,ZodUnknown:()=>lt,ZodVoid:()=>Rn,addIssueToContext:()=>v,any:()=>Xp,array:()=>tf,bigint:()=>Gp,boolean:()=>zc,coerce:()=>Tf,custom:()=>Bc,date:()=>zp,datetimeRegex:()=>Vc,defaultErrorMap:()=>at,discriminatedUnion:()=>sf,effect:()=>_f,enum:()=>gf,function:()=>mf,getErrorMap:()=>Cn,getParsedType:()=>Ve,instanceof:()=>Bp,intersection:()=>af,isAborted:()=>lo,isAsync:()=>Tn,isDirty:()=>uo,isValid:()=>Et,late:()=>Hp,lazy:()=>pf,literal:()=>ff,makeIssue:()=>lr,map:()=>uf,nan:()=>Kp,nativeEnum:()=>hf,never:()=>Qp,null:()=>Yp,nullable:()=>bf,number:()=>Gc,object:()=>nf,objectUtil:()=>Fs,oboolean:()=>Cf,onumber:()=>kf,optional:()=>vf,ostring:()=>xf,pipeline:()=>wf,preprocess:()=>Sf,promise:()=>yf,quotelessJson:()=>yp,record:()=>lf,set:()=>df,setErrorMap:()=>vp,strictObject:()=>rf,string:()=>Kc,symbol:()=>Wp,transformer:()=>_f,tuple:()=>cf,undefined:()=>Jp,union:()=>of,unknown:()=>Zp,util:()=>U,void:()=>ef});var U;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},e.getValidEnumValues=o=>{let s=e.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return e.objectValues(i)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},e.find=(o,s)=>{for(let i of o)if(s(i))return i},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(U||(U={}));var Fs;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Fs||(Fs={}));var b=U.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ve=e=>{switch(typeof e){case"undefined":return b.undefined;case"string":return b.string;case"number":return Number.isNaN(e)?b.nan:b.number;case"boolean":return b.boolean;case"function":return b.function;case"bigint":return b.bigint;case"symbol":return b.symbol;case"object":return Array.isArray(e)?b.array:e===null?b.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?b.promise:typeof Map<"u"&&e instanceof Map?b.map:typeof Set<"u"&&e instanceof Set?b.set:typeof Date<"u"&&e instanceof Date?b.date:b.object;default:return b.unknown}};var h=U.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"]),yp=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),_e=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,l=0;for(;l<i.path.length;){let c=i.path[l];l===i.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(i))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return o(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,U.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];n[s]=n[s]||[],n[s].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};_e.create=e=>new _e(e);var _p=(e,t)=>{let n;switch(e.code){case h.invalid_type:e.received===b.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case h.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,U.jsonStringifyReplacer)}`;break;case h.unrecognized_keys:n=`Unrecognized key(s) in object: ${U.joinValues(e.keys,", ")}`;break;case h.invalid_union:n="Invalid input";break;case h.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${U.joinValues(e.options)}`;break;case h.invalid_enum_value:n=`Invalid enum value. Expected ${U.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}"`:U.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,U.assertNever(e)}return{message:n}},at=_p;var Uc=at;function vp(e){Uc=e}function Cn(){return Uc}var lr=e=>{let{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)a=c(i,{data:t,defaultError:a}).message;return{...o,path:s,message:a}},bp=[];function v(e,t){let n=Cn(),r=lr({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===at?void 0:at].filter(o=>!!o)});e.common.issues.push(r)}var ce=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let o of n){if(o.status==="aborted")return R;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let o of n){let s=await o.key,i=await o.value;r.push({key:s,value:i})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let o of n){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return R;s.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:t.value,value:r}}},R=Object.freeze({status:"aborted"}),Wt=e=>({status:"dirty",value:e}),ue=e=>({status:"valid",value:e}),lo=e=>e.status==="aborted",uo=e=>e.status==="dirty",Et=e=>e.status==="valid",Tn=e=>typeof Promise<"u"&&e instanceof Promise;var x;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(x||(x={}));var Ae=class{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Dc=(e,t)=>{if(Et(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new _e(e.common.issues);return this._error=n,this._error}}};function M(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(i,a)=>{let{message:l}=e;return i.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:o}}var N=class{get description(){return this._def.description}_getType(t){return Ve(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Ve(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ce,ctx:{common:t.parent.common,data:t.data,parsedType:Ve(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Tn(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:Ve(t)},o=this._parseSync({data:t,path:r.path,parent:r});return Dc(r,o)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Ve(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return Et(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=>Et(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:Ve(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(Tn(o)?o:Promise.resolve(o));return Dc(r,s)}refine(t,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{let i=t(o),a=()=>s.addIssue({code:h.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Re({schema:this,typeName:I.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Ee.create(this,this._def)}nullable(){return Be.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ut.create(this)}promise(){return It.create(this,this._def)}or(t){return tn.create([this,t],this._def)}and(t){return nn.create(this,t,this._def)}transform(t){return new Re({...M(this._def),schema:this,typeName:I.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new cn({...M(this._def),innerType:this,defaultValue:n,typeName:I.ZodDefault})}brand(){return new ur({typeName:I.ZodBranded,type:this,...M(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new ln({...M(this._def),innerType:this,catchValue:n,typeName:I.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return dr.create(this,t)}readonly(){return un.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Sp=/^c[^\s-]{8,}$/i,wp=/^[0-9a-z]+$/,xp=/^[0-9A-HJKMNP-TV-Z]{26}$/i,kp=/^[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,Cp=/^[a-z0-9_-]{21}$/i,Tp=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ep=/^[-+]?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)?)??$/,Ap=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Rp="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",qs,Ip=/^(?:(?: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])$/,$p=/^(?:(?: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])$/,Pp=/^(([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]))$/,Mp=/^(([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])$/,Op=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Np=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Fc="((\\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])))",Lp=new RegExp(`^${Fc}$`);function qc(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 Up(e){return new RegExp(`^${qc(e)}$`)}function Vc(e){let t=`${Fc}T${qc(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 Dp(e,t){return!!((t==="v4"||!t)&&Ip.test(e)||(t==="v6"||!t)&&Pp.test(e))}function jp(e,t){if(!Tp.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function Fp(e,t){return!!((t==="v4"||!t)&&$p.test(e)||(t==="v6"||!t)&&Mp.test(e))}var At=class e extends N{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==b.string){let s=this._getOrReturnCtx(t);return v(s,{code:h.invalid_type,expected:b.string,received:s.parsedType}),R}let r=new ce,o;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),v(o,{code:h.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),v(o,{code:h.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let i=t.data.length>s.value,a=t.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(t,o),i?v(o,{code:h.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&v(o,{code:h.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")Ap.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"email",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")qs||(qs=new RegExp(Rp,"u")),qs.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"emoji",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")kp.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"uuid",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")Cp.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"nanoid",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")Sp.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"cuid",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")wp.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"cuid2",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")xp.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"ulid",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),v(o,{validation:"url",code:h.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"regex",code:h.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),v(o,{code:h.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),v(o,{code:h.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),v(o,{code:h.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?Vc(s).test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{code:h.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?Lp.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{code:h.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?Up(s).test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{code:h.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?Ep.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"duration",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?Dp(t.data,s.version)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"ip",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?jp(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"jwt",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?Fp(t.data,s.version)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"cidr",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?Op.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"base64",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?Np.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"base64url",code:h.invalid_string,message:s.message}),r.dirty()):U.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:h.invalid_string,...x.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...x.errToObj(t)})}url(t){return this._addCheck({kind:"url",...x.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...x.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...x.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...x.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...x.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...x.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...x.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...x.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...x.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...x.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...x.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...x.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,...x.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,...x.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...x.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...x.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...x.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...x.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...x.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...x.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...x.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...x.errToObj(n)})}nonempty(t){return this.min(1,x.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};At.create=e=>new At({checks:[],typeName:I.ZodString,coerce:e?.coerce??!1,...M(e)});function qp(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/10**o}var Jt=class e extends N{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==b.number){let s=this._getOrReturnCtx(t);return v(s,{code:h.invalid_type,expected:b.number,received:s.parsedType}),R}let r,o=new ce;for(let s of this._def.checks)s.kind==="int"?U.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),v(r,{code:h.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),v(r,{code:h.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),v(r,{code:h.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?qp(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),v(r,{code:h.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),v(r,{code:h.not_finite,message:s.message}),o.dirty()):U.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,x.toString(n))}gt(t,n){return this.setLimit("min",t,!1,x.toString(n))}lte(t,n){return this.setLimit("max",t,!0,x.toString(n))}lt(t,n){return this.setLimit("max",t,!1,x.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:x.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:x.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:x.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:x.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:x.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:x.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:x.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:x.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:x.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:x.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"&&U.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)}};Jt.create=e=>new Jt({checks:[],typeName:I.ZodNumber,coerce:e?.coerce||!1,...M(e)});var Yt=class e extends N{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==b.bigint)return this._getInvalidInput(t);let r,o=new ce;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),v(r,{code:h.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),v(r,{code:h.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),v(r,{code:h.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):U.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return v(n,{code:h.invalid_type,expected:b.bigint,received:n.parsedType}),R}gte(t,n){return this.setLimit("min",t,!0,x.toString(n))}gt(t,n){return this.setLimit("min",t,!1,x.toString(n))}lte(t,n){return this.setLimit("max",t,!0,x.toString(n))}lt(t,n){return this.setLimit("max",t,!1,x.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:x.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:x.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:x.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:x.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:x.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:x.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}};Yt.create=e=>new Yt({checks:[],typeName:I.ZodBigInt,coerce:e?.coerce??!1,...M(e)});var Xt=class extends N{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==b.boolean){let r=this._getOrReturnCtx(t);return v(r,{code:h.invalid_type,expected:b.boolean,received:r.parsedType}),R}return ue(t.data)}};Xt.create=e=>new Xt({typeName:I.ZodBoolean,coerce:e?.coerce||!1,...M(e)});var Zt=class e extends N{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==b.date){let s=this._getOrReturnCtx(t);return v(s,{code:h.invalid_type,expected:b.date,received:s.parsedType}),R}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return v(s,{code:h.invalid_date}),R}let r=new ce,o;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),v(o,{code:h.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),v(o,{code:h.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):U.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:x.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:x.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};Zt.create=e=>new Zt({checks:[],coerce:e?.coerce||!1,typeName:I.ZodDate,...M(e)});var An=class extends N{_parse(t){if(this._getType(t)!==b.symbol){let r=this._getOrReturnCtx(t);return v(r,{code:h.invalid_type,expected:b.symbol,received:r.parsedType}),R}return ue(t.data)}};An.create=e=>new An({typeName:I.ZodSymbol,...M(e)});var Qt=class extends N{_parse(t){if(this._getType(t)!==b.undefined){let r=this._getOrReturnCtx(t);return v(r,{code:h.invalid_type,expected:b.undefined,received:r.parsedType}),R}return ue(t.data)}};Qt.create=e=>new Qt({typeName:I.ZodUndefined,...M(e)});var en=class extends N{_parse(t){if(this._getType(t)!==b.null){let r=this._getOrReturnCtx(t);return v(r,{code:h.invalid_type,expected:b.null,received:r.parsedType}),R}return ue(t.data)}};en.create=e=>new en({typeName:I.ZodNull,...M(e)});var Rt=class extends N{constructor(){super(...arguments),this._any=!0}_parse(t){return ue(t.data)}};Rt.create=e=>new Rt({typeName:I.ZodAny,...M(e)});var lt=class extends N{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ue(t.data)}};lt.create=e=>new lt({typeName:I.ZodUnknown,...M(e)});var Me=class extends N{_parse(t){let n=this._getOrReturnCtx(t);return v(n,{code:h.invalid_type,expected:b.never,received:n.parsedType}),R}};Me.create=e=>new Me({typeName:I.ZodNever,...M(e)});var Rn=class extends N{_parse(t){if(this._getType(t)!==b.undefined){let r=this._getOrReturnCtx(t);return v(r,{code:h.invalid_type,expected:b.void,received:r.parsedType}),R}return ue(t.data)}};Rn.create=e=>new Rn({typeName:I.ZodVoid,...M(e)});var ut=class e extends N{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==b.array)return v(n,{code:h.invalid_type,expected:b.array,received:n.parsedType}),R;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(v(n,{code:i?h.too_big:h.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(v(n,{code:h.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(v(n,{code:h.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>o.type._parseAsync(new Ae(n,i,n.path,a)))).then(i=>ce.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new Ae(n,i,n.path,a)));return ce.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:x.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:x.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:x.toString(n)}})}nonempty(t){return this.min(1,t)}};ut.create=(e,t)=>new ut({type:e,minLength:null,maxLength:null,exactLength:null,typeName:I.ZodArray,...M(t)});function En(e){if(e instanceof ve){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Ee.create(En(r))}return new ve({...e._def,shape:()=>t})}else return e instanceof ut?new ut({...e._def,type:En(e.element)}):e instanceof Ee?Ee.create(En(e.unwrap())):e instanceof Be?Be.create(En(e.unwrap())):e instanceof He?He.create(e.items.map(t=>En(t))):e}var ve=class e extends N{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=U.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==b.object){let c=this._getOrReturnCtx(t);return v(c,{code:h.invalid_type,expected:b.object,received:c.parsedType}),R}let{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Me&&this._def.unknownKeys==="strip"))for(let c in o.data)i.includes(c)||a.push(c);let l=[];for(let c of i){let u=s[c],d=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Ae(o,d,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Me){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")a.length>0&&(v(o,{code: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=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Ae(o,d,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of l){let d=await u.key,f=await u.value;c.push({key:d,value:f,alwaysSet:u.alwaysSet})}return c}).then(c=>ce.mergeObjectSync(r,c)):ce.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return x.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:x.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:I.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of U.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 U.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return En(this)}partial(t){let n={};for(let r of U.objectKeys(this.shape)){let o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let r of U.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Ee;)s=s._def.innerType;n[r]=s}return new e({...this._def,shape:()=>n})}keyof(){return Hc(U.objectKeys(this.shape))}};ve.create=(e,t)=>new ve({shape:()=>e,unknownKeys:"strip",catchall:Me.create(),typeName:I.ZodObject,...M(t)});ve.strictCreate=(e,t)=>new ve({shape:()=>e,unknownKeys:"strict",catchall:Me.create(),typeName:I.ZodObject,...M(t)});ve.lazycreate=(e,t)=>new ve({shape:e,unknownKeys:"strip",catchall:Me.create(),typeName:I.ZodObject,...M(t)});var tn=class extends N{_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new _e(a.ctx.common.issues));return v(n,{code:h.invalid_union,unionErrors:i}),R}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let l of r){let c={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(l=>new _e(l));return v(n,{code:h.invalid_union,unionErrors:a}),R}}get options(){return this._def.options}};tn.create=(e,t)=>new tn({options:e,typeName:I.ZodUnion,...M(t)});var ct=e=>e instanceof rn?ct(e.schema):e instanceof Re?ct(e.innerType()):e instanceof on?[e.value]:e instanceof sn?e.options:e instanceof an?U.objectValues(e.enum):e instanceof cn?ct(e._def.innerType):e instanceof Qt?[void 0]:e instanceof en?[null]:e instanceof Ee?[void 0,...ct(e.unwrap())]:e instanceof Be?[null,...ct(e.unwrap())]:e instanceof ur||e instanceof un?ct(e.unwrap()):e instanceof ln?ct(e._def.innerType):[],mo=class e extends N{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.object)return v(n,{code:h.invalid_type,expected:b.object,received:n.parsedType}),R;let r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(v(n,{code:h.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),R)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let o=new Map;for(let s of n){let i=ct(s.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);o.set(a,s)}}return new e({typeName:I.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...M(r)})}};function Vs(e,t){let n=Ve(e),r=Ve(t);if(e===t)return{valid:!0,data:e};if(n===b.object&&r===b.object){let o=U.objectKeys(t),s=U.objectKeys(e).filter(a=>o.indexOf(a)!==-1),i={...e,...t};for(let a of s){let l=Vs(e[a],t[a]);if(!l.valid)return{valid:!1};i[a]=l.data}return{valid:!0,data:i}}else if(n===b.array&&r===b.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let s=0;s<e.length;s++){let i=e[s],a=t[s],l=Vs(i,a);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===b.date&&r===b.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var nn=class extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=(s,i)=>{if(lo(s)||lo(i))return R;let a=Vs(s.value,i.value);return a.valid?((uo(s)||uo(i))&&n.dirty(),{status:n.value,value:a.data}):(v(r,{code:h.invalid_intersection_types}),R)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};nn.create=(e,t,n)=>new nn({left:e,right:t,typeName:I.ZodIntersection,...M(n)});var He=class e extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.array)return v(r,{code:h.invalid_type,expected:b.array,received:r.parsedType}),R;if(r.data.length<this._def.items.length)return v(r,{code:h.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),R;!this._def.rest&&r.data.length>this._def.items.length&&(v(r,{code:h.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Ae(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>ce.mergeArray(n,i)):ce.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};He.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new He({items:e,typeName:I.ZodTuple,rest:null,...M(t)})};var po=class e extends N{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.object)return v(r,{code:h.invalid_type,expected:b.object,received:r.parsedType}),R;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new Ae(r,a,r.path,a)),value:i._parse(new Ae(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?ce.mergeObjectAsync(n,o):ce.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof N?new e({keyType:t,valueType:n,typeName:I.ZodRecord,...M(r)}):new e({keyType:At.create(),valueType:t,typeName:I.ZodRecord,...M(n)})}},In=class extends N{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.map)return v(r,{code:h.invalid_type,expected:b.map,received:r.parsedType}),R;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,l],c)=>({key:o._parse(new Ae(r,a,r.path,[c,"key"])),value:s._parse(new Ae(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 R;(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 R;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}}}};In.create=(e,t,n)=>new In({valueType:t,keyType:e,typeName:I.ZodMap,...M(n)});var $n=class e extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.set)return v(r,{code:h.invalid_type,expected:b.set,received:r.parsedType}),R;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(v(r,{code:h.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(v(r,{code:h.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(l){let c=new Set;for(let u of l){if(u.status==="aborted")return R;u.status==="dirty"&&n.dirty(),c.add(u.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((l,c)=>s._parse(new Ae(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:x.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:x.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:I.ZodSet,...M(t)});var fo=class e extends N{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.function)return v(n,{code:h.invalid_type,expected:b.function,received:n.parsedType}),R;function r(a,l){return lr({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Cn(),at].filter(c=>!!c),issueData:{code:h.invalid_arguments,argumentsError:l}})}function o(a,l){return lr({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Cn(),at].filter(c=>!!c),issueData:{code:h.invalid_return_type,returnTypeError:l}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof It){let a=this;return ue(async function(...l){let c=new _e([]),u=await a._def.args.parseAsync(l,s).catch(p=>{throw c.addIssue(r(l,p)),c}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,s).catch(p=>{throw c.addIssue(o(d,p)),c})})}else{let a=this;return ue(function(...l){let c=a._def.args.safeParse(l,s);if(!c.success)throw new _e([r(l,c.error)]);let u=Reflect.apply(i,this,c.data),d=a._def.returns.safeParse(u,s);if(!d.success)throw new _e([o(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:He.create(t).rest(lt.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||He.create([]).rest(lt.create()),returns:n||lt.create(),typeName:I.ZodFunction,...M(r)})}},rn=class extends N{get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};rn.create=(e,t)=>new rn({getter:e,typeName:I.ZodLazy,...M(t)});var on=class extends N{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return v(n,{received:n.data,code:h.invalid_literal,expected:this._def.value}),R}return{status:"valid",value:t.data}}get value(){return this._def.value}};on.create=(e,t)=>new on({value:e,typeName:I.ZodLiteral,...M(t)});function Hc(e,t){return new sn({values:e,typeName:I.ZodEnum,...M(t)})}var sn=class e extends N{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return v(n,{expected:U.joinValues(r),received:n.parsedType,code:h.invalid_type}),R}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return v(n,{received:n.data,code:h.invalid_enum_value,options:r}),R}return ue(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};sn.create=Hc;var an=class extends N{_parse(t){let n=U.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==b.string&&r.parsedType!==b.number){let o=U.objectValues(n);return v(r,{expected:U.joinValues(o),received:r.parsedType,code:h.invalid_type}),R}if(this._cache||(this._cache=new Set(U.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let o=U.objectValues(n);return v(r,{received:r.data,code:h.invalid_enum_value,options:o}),R}return ue(t.data)}get enum(){return this._def.values}};an.create=(e,t)=>new an({values:e,typeName:I.ZodNativeEnum,...M(t)});var It=class extends N{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.promise&&n.common.async===!1)return v(n,{code:h.invalid_type,expected:b.promise,received:n.parsedType}),R;let r=n.parsedType===b.promise?n.data:Promise.resolve(n.data);return ue(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};It.create=(e,t)=>new It({type:e,typeName:I.ZodPromise,...M(t)});var Re=class extends N{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===I.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:i=>{v(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return R;let l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?R:l.status==="dirty"?Wt(l.value):n.value==="dirty"?Wt(l.value):l});{if(n.value==="aborted")return R;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?R:a.status==="dirty"?Wt(a.value):n.value==="dirty"?Wt(a.value):a}}if(o.type==="refinement"){let i=a=>{let l=o.refinement(a,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?R:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?R:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Et(i))return R;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>Et(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):R);U.assertNever(o)}};Re.create=(e,t,n)=>new Re({schema:e,typeName:I.ZodEffects,effect:t,...M(n)});Re.createWithPreprocess=(e,t,n)=>new Re({schema:t,effect:{type:"preprocess",transform:e},typeName:I.ZodEffects,...M(n)});var Ee=class extends N{_parse(t){return this._getType(t)===b.undefined?ue(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ee.create=(e,t)=>new Ee({innerType:e,typeName:I.ZodOptional,...M(t)});var Be=class extends N{_parse(t){return this._getType(t)===b.null?ue(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Be.create=(e,t)=>new Be({innerType:e,typeName:I.ZodNullable,...M(t)});var cn=class extends N{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===b.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};cn.create=(e,t)=>new cn({innerType:e,typeName:I.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...M(t)});var ln=class extends N{_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Tn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new _e(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new _e(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};ln.create=(e,t)=>new ln({innerType:e,typeName:I.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...M(t)});var Pn=class extends N{_parse(t){if(this._getType(t)!==b.nan){let r=this._getOrReturnCtx(t);return v(r,{code:h.invalid_type,expected:b.nan,received:r.parsedType}),R}return{status:"valid",value:t.data}}};Pn.create=e=>new Pn({typeName:I.ZodNaN,...M(e)});var Vp=Symbol("zod_brand"),ur=class extends N{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},dr=class e extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?R:s.status==="dirty"?(n.dirty(),Wt(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?R:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:I.ZodPipeline})}},un=class extends N{_parse(t){let n=this._def.innerType._parse(t),r=o=>(Et(o)&&(o.value=Object.freeze(o.value)),o);return Tn(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};un.create=(e,t)=>new un({innerType:e,typeName:I.ZodReadonly,...M(t)});function jc(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Bc(e,t={},n){return e?Rt.create().superRefine((r,o)=>{let s=e(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=jc(t,r),l=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:l})}});if(!s){let i=jc(t,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Rt.create()}var Hp={object:ve.lazycreate},I;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(I||(I={}));var Bp=(e,t={message:`Input not instance of ${e.name}`})=>Bc(n=>n instanceof e,t),Kc=At.create,Gc=Jt.create,Kp=Pn.create,Gp=Yt.create,zc=Xt.create,zp=Zt.create,Wp=An.create,Jp=Qt.create,Yp=en.create,Xp=Rt.create,Zp=lt.create,Qp=Me.create,ef=Rn.create,tf=ut.create,nf=ve.create,rf=ve.strictCreate,of=tn.create,sf=mo.create,af=nn.create,cf=He.create,lf=po.create,uf=In.create,df=$n.create,mf=fo.create,pf=rn.create,ff=on.create,gf=sn.create,hf=an.create,yf=It.create,_f=Re.create,vf=Ee.create,bf=Be.create,Sf=Re.createWithPreprocess,wf=dr.create,xf=()=>Kc().optional(),kf=()=>Gc().optional(),Cf=()=>zc().optional(),Tf={string:(e=>At.create({...e,coerce:!0})),number:(e=>Jt.create({...e,coerce:!0})),boolean:(e=>Xt.create({...e,coerce:!0})),bigint:(e=>Yt.create({...e,coerce:!0})),date:(e=>Zt.create({...e,coerce:!0}))};var Ef=R;var Af=/^[A-Za-z0-9._-]+$/,Rf=/^[A-Za-z0-9._-]+(\|[A-Za-z0-9._-]+)*$/,Wc=new Set([".",".."]),fe=class extends Error{pattern;constructor(t,n){super(`Invalid freeReadPathPattern ${JSON.stringify(n)}: ${t}`),this.pattern=n,this.name="FreePathPatternError"}};function If(e,t){if(e==="*")return{raw:e,kind:"single"};if(e==="**")return{raw:e,kind:"multi"};if(e.startsWith("(")){let n=e.endsWith(")?"),r=e.endsWith(")");if(!n&&!r)throw new fe(`malformed alternation segment ${JSON.stringify(e)}`,t);let o=n?e.slice(1,-2):e.slice(1,-1);if(!Rf.test(o))throw new fe(`malformed alternation segment ${JSON.stringify(e)}`,t);let s=o.split("|");if(s.some(i=>Wc.has(i)))throw new fe(`alternation segment ${JSON.stringify(e)} may not contain '.' or '..'`,t);return{raw:e,kind:n?"alt-optional":"alt",alternatives:s}}if(Af.test(e)){if(Wc.has(e))throw new fe(`literal segment ${JSON.stringify(e)} is not permitted`,t);return{raw:e,kind:"literal"}}throw new fe(`segment ${JSON.stringify(e)} must be '*', '**', a [A-Za-z0-9._-]+ literal, or (a|b) alternation`,t)}function $f(e){if(typeof e!="string"||e.length===0)throw new fe("must be a non-empty string",String(e));if(!e.startsWith("/"))throw new fe("must start with '/'",e);if(e.slice(1).includes("//"))throw new fe("empty segments ('//') are not permitted",e);if(e.length>1&&e.endsWith("/"))throw new fe("must not end with '/'",e);let n=e.slice(1).split("/").map(s=>If(s,e));if(n.filter(s=>s.kind==="multi").length>1)throw new fe("at most one '**' is permitted per pattern",e);if(n[0]?.kind==="multi")throw new fe("'**' may not be the first segment (a literal prefix anchor is required)",e);let o=n.findIndex(s=>s.kind==="alt-optional");if(o!==-1&&o!==n.length-1)throw new fe("optional alternation '(...)?' is only allowed as the final segment",e);return n}function Hs(e){$f(e)}var Jc=["tempo","mpp_self","merchant_self"],Yc=["catalog_static","fal_direct","fal_queue","openrouter_chat","openrouter_image","platform_proxy","tempo_gateway","x402_gateway"],Xc=["image","audio","queued_audio","video","queued_video","model_3d","llm","transcription","utility"],Zc=["images[0].url","image.url","audio.url","audio_file.url","audio_url","video.url","model_mesh.url","text","choices[0].message.content","choices[0].message.images[0].image_url.url","request_id"];var Ks=g.object({inputPerMillion:g.number().positive(),outputPerMillion:g.number().positive(),contextWindow:g.number().int().positive().optional(),maxOutput:g.number().int().positive().optional(),perRequestFeeCents:g.number().nonnegative().optional()}),Pf=g.object({strategy:g.enum(["flat","token","band"]).optional(),pricingModel:g.enum(["per-call","per-token","band"]).optional(),priceCents:g.number().nonnegative().optional(),currency:g.string().optional(),display:g.string().optional(),estimate:g.boolean().optional(),source:g.string().optional(),priceBand:g.record(g.unknown()).optional(),tokenPricing:Ks.optional()}).passthrough(),Gs=g.discriminatedUnion("type",[g.object({type:g.literal("shortcut"),routedPath:g.string().min(1).startsWith("/")}),g.object({type:g.literal("custom"),merchantSlug:g.string().min(1),subPath:g.string().optional()}),g.object({type:g.literal("local"),fn:g.string().min(1)}),g.object({type:g.literal("read")})]),zs=g.object({amount:g.number().nonnegative(),currency:g.string().length(3).optional(),display:g.string().optional(),free:g.boolean().optional(),batchDiscount:g.number().min(0).max(100).optional()}),Qc=g.object({attestation:g.boolean().optional(),rateLimitMs:g.number().positive().optional()}),el=g.object({displayName:g.string().optional(),feedbackEligible:g.boolean().optional(),suggestionEligible:g.boolean().optional(),batchable:g.boolean().optional()}),tl=g.object({enabled:g.boolean().optional(),gatewayPath:g.string().min(1).startsWith("/").optional(),method:g.enum(["GET","POST","PUT","PATCH","DELETE"]).optional(),timeoutMs:g.number().int().positive().max(12e4).optional()}).strict(),Mf=g.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),Of=120,Nf=120,Lf=1200,Uf=/^[^\u0000-\u001F\u007F]+$/;function Bs(e,t){return g.string().min(1).max(e).regex(Uf,`${t} must not contain control characters`)}var Ws={id:g.string().min(1),name:Bs(Of,"name"),description:Bs(Lf,"description"),provider:g.string().min(1),model:g.string().min(1),category:Mf,priceCents:g.number().nonnegative(),inputSchema:g.record(g.unknown()),gatewayUrl:g.string().min(1),merchantName:Bs(Nf,"merchantName"),isAsync:g.boolean().optional(),pollUrl:g.string().optional(),pollInterval:g.number().positive().optional(),pollTimeout:g.number().positive().optional(),tags:g.array(g.string()).optional(),tokenPricing:Ks.optional(),priceDisplay:g.string().optional(),pricingModel:g.enum(["per-call","per-token","band"]).optional(),pricingInfo:Pf.optional(),status:g.enum(["available","unavailable"]).optional(),handler:Gs.optional(),pricing:zs.optional(),security:Qc.optional(),engagement:el.optional(),gatewayConfig:tl.optional(),freeReadPathPattern:g.string().optional().superRefine((e,t)=>{if(e!==void 0)try{Hs(e)}catch(n){t.addIssue({code:g.ZodIssueCode.custom,message:n instanceof Error?n.message:String(n)})}}),enabled:g.boolean().optional(),beta:g.boolean().optional(),deprecated:g.boolean().optional(),internal:g.boolean().optional(),replacementTool:g.string().optional(),minCliVersion:g.string().optional(),sunsetAt:g.string().optional(),rail:g.enum(Jc).optional(),executionKind:g.enum(Yc).optional(),resultKind:g.enum(Xc).optional(),extractionMode:g.enum(Zc).optional(),pricingStrategy:g.enum(["flat","token","band"]).optional()},nl=g.object({...Ws,dispatch:g.literal("routed"),routedPath:g.string().min(1).startsWith("/")}).strict(),rl=g.object({...Ws,dispatch:g.literal("enveloped")}).strict(),ol=g.object({...Ws,handler:Gs,pricing:zs}).strict(),sl=g.union([g.discriminatedUnion("dispatch",[nl,rl]),ol]);var Js=/^[a-z0-9][a-z0-9_-]*$/;var Ff="https://fal.run",ll="https://openrouter.mpp.tempo.xyz",Xs=1024,ho=8192,qf=4096,Vf=10;function Hf(e){return e>=Vf?qf:ho}function ul(e,t){let n=typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):Xs;return Math.min(n,t)}function Bf(e){let{attestation:t,tool_id:n,...r}=e;return r}var il={"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 go(e){let{attestation:t,tool_id:n,aspect_ratio:r,image_size:o,...s}=e,i={...s};return typeof o=="string"&&o.length>0?(i.image_size=o,i):(typeof r=="string"&&il[r]&&(i.image_size=il[r]),i)}function Kf(e){let{attestation:t,tool_id:n,...r}=e;return r}function al(e){let t={chain:e.chain,token_address:e.token_address};if(e.start_timestamp){let n=e.end_timestamp||new Date().toISOString(),r=e.time_granularity;if(!r){let o=new Date(e.start_timestamp).getTime();(new Date(n).getTime()-o)/(1e3*60*60*24)<=2?r="1h":r="1d"}return{addresses:[t],start_timestamp:e.start_timestamp,end_timestamp:n,time_granularity:r}}return[t]}function Gf(e,t,n,r,o,s,i,a,l){return{id:e,name:t,description:n,provider:r,model:o.replace(/^\//,""),category:s,gatewayUrl:`https://${r}${o}`,merchantName:t,inputSchema:a,handler:{type:"custom",merchantSlug:r,subPath:o},pricing:{amount:i,currency:"USD",display:`$${(i/100).toFixed(2)}`},priceCents:i,tags:[],...l}}function zf(e,t,n,r,o,s,i,a){return Gf(e,t,n,"suno-ai",r,o,s,i,{merchantName:"Suno AI",...a})}function te(e,t,n,r,o,s,i,a){return{dispatch:"routed",id:e,name:t,description:n,provider:"fal",model:r,category:o,priceCents:s,inputSchema:i,routedPath:`/api/v1/fal/${r}`,gatewayUrl:`${Ff}/${r}`,merchantName:"fal.ai",buildBody:Bf,tags:[],...a}}function Wf(e,t=ho){return n=>{let{attestation:r,tool_id:o,prompt:s,system_prompt:i,max_tokens:a,max_completion_tokens:l,temperature:c,...u}=n;return{model:e,messages:[...i?[{role:"system",content:i}]:[],{role:"user",content:s}],temperature:c??.7,...u,max_tokens:ul(a??l,t)}}}function Jf(e,t=ho){return n=>{let{attestation:r,tool_id:o,prompt:s,image_url:i,aspect_ratio:a,max_tokens:l,max_completion_tokens:c,temperature:u,...d}=n,f=[{type:"text",text:s}];return typeof i=="string"&&i.length>0&&f.push({type:"image_url",image_url:{url:i}}),{model:e,messages:[{role:"user",content:f}],temperature:u??.7,...typeof a=="string"&&a.length>0?{image_config:{aspect_ratio:a}}:{},...d,max_tokens:ul(l??c,t)}}}function X(e,t,n,r,o,s,i){let a=i?.maxOutputTokens??Hf(s),l=i?.perRequestFeeCents??0,c=500/1e6*o*100,u=500/1e6*s*100,d=Math.max(1,Math.ceil(c+u+l)),{perRequestFeeCents:f,maxOutputTokens:p,..._}=i??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"llm",priceCents:d,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The prompt or question to send to the model"},system_prompt:{type:"string",description:"Optional system prompt to set model behavior"},max_tokens:{type:"integer",description:`Maximum tokens in response (default: ${Xs}); values above ${a} are clamped to ${a}`,minimum:1,maximum:a},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${ll}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:Wf(r,a),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:o,outputPerMillion:s,...l>0?{perRequestFeeCents:l}:{}},..._}}function Ys(e,t,n,r,o,s){let i=s?.maxOutputTokens??ho,{maxOutputTokens:a,...l}=s??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"image",pricingStrategy:"band",priceCents:o,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate or edit"},image_url:{type:"string",description:"Optional source image URL for edits"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"1:1"},max_tokens:{type:"integer",description:`Maximum text tokens in response metadata (default: ${Xs}); values above ${i} are clamped to ${i}`,minimum:1,maximum:i},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${ll}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:Jf(r,i),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...l}}var Zs=[te("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"]}),te("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:go}),te("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:go}),te("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:go}),te("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"]}),Ys("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),Ys("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}}),Ys("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}}),te("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"]}),te("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"]}),te("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"]}),te("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"]}),te("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"]}),te("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"]}),te("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"]}),te("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"]}),te("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"]}),zf("suno-music","Suno Music","AI music generation. Create full songs with vocals or instrumentals.","/suno/generate-music","audio",10,{type:"object",properties:{prompt:{type:"string",description:"Description of the song (genre, mood, instruments)"},instrumental:{type:"boolean",description:"Instrumental only, no vocals",default:!1}},required:["prompt"]},{isAsync:!0,pollUrl:"https://api.sunoapi.org/suno/get-music-status",deprecated:!0,tags:["music","song","vocals","instrumental"],buildBody:e=>{let{attestation:t,tool_id:n,prompt:r,instrumental:o,...s}=e;return{prompt:r,customMode:!1,instrumental:typeof o=="boolean"?o:!1,model:"V4",...s}}}),te("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"]}),te("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"]}),te("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"]}),te("fal-whisper","Whisper Transcription","Transcribe audio to text. Supports multiple languages.","fal-ai/whisper","transcription",2,{type:"object",properties:{audio_url:{type:"string",description:"URL of the audio to transcribe"},language:{type:"string",description:"Language code (e.g. en, es, fr)"}},required:["audio_url"]},{tags:["transcription","speech-to-text","whisper"]}),X("or-gpt-4o","GPT-4o","OpenAI's flagship multimodal model. Best for complex reasoning and analysis.","openai/gpt-4o",2.5,10,{tags:["llm","gpt","openai","multimodal","reasoning"]}),X("or-gpt-55","GPT-5.5","OpenAI frontier model for complex professional reasoning, coding, and long-context analysis.","openai/gpt-5.5",5,30,{tags:["llm","gpt","openai","frontier","reasoning","coding","long-context"]}),X("or-gpt-55-pro","GPT-5.5 Pro","OpenAI high-capability frontier model optimized for deep reasoning and high-stakes workloads.","openai/gpt-5.5-pro",30,180,{tags:["llm","gpt","openai","frontier","pro","deep-reasoning","coding","long-context"]}),X("or-gpt-4o-mini","GPT-4o Mini","Fast, affordable GPT-4o. Great for everyday tasks, chat, and simple analysis.","openai/gpt-4o-mini",.15,.6,{tags:["llm","gpt","openai","fast","cheap"]}),X("or-claude-opus","Claude Opus 4.7","Anthropic's most capable model. 1M context, reasoning, best for complex tasks.","anthropic/claude-opus-4.7",15,75,{tags:["llm","claude","anthropic","reasoning","coding"]}),X("or-claude-sonnet","Claude Sonnet 4.6","Anthropic's best balance of intelligence and speed. Excellent for coding and analysis.","anthropic/claude-sonnet-4.6",3,15,{tags:["llm","claude","anthropic","coding","analysis"]}),X("or-claude-opus-fast","Claude Opus 4.6 Fast","Fast Opus variant with lower latency.","anthropic/claude-opus-4.6-fast",15,75,{tags:["llm","claude","anthropic","fast"]}),X("or-claude-haiku","Claude 3.5 Haiku","Anthropic's fastest model. Great for quick tasks, chat, and simple reasoning.","anthropic/claude-3.5-haiku",.8,4,{tags:["llm","claude","anthropic","fast"]}),X("or-gemini-pro","Gemini 2.0 Flash","Google's fast multimodal model. Good for general tasks with long context.","google/gemini-2.0-flash-001",.1,.4,{tags:["llm","gemini","google","multimodal","fast","cheap"]}),X("or-gemini-3-flash","Gemini 3 Flash","Google's high-speed thinking model for agentic workflows, coding, and multimodal tasks.","google/gemini-3-flash-preview",.5,3,{tags:["llm","gemini","google","agentic","coding","fast"]}),X("or-gemini-3-pro","Gemini 3 Pro","Google's flagship frontier model for deep reasoning, multimodal analysis, and agentic coding.","google/gemini-3-pro-preview",2,12,{tags:["llm","gemini","google","reasoning","coding","multimodal"]}),X("or-gemini-35-flash","Gemini 3.5 Flash","Google frontier Flash model for multimodal reasoning, coding, and parallel agentic workflows.","google/gemini-3.5-flash",1.5,9,{tags:["llm","gemini","google","frontier","multimodal","reasoning","coding","fast"]}),X("or-gemini-3-lite","Gemini 3.1 Flash Lite","Google's efficient multimodal model optimized for low-latency, high-volume agent workloads.","google/gemini-3.1-flash-lite",.25,1.5,{tags:["llm","gemini","google","fast","cheap","multimodal"]}),X("or-llama-70b","Llama 3.3 70B","Meta's best open model. Strong reasoning, fully open-source.","meta-llama/llama-3.3-70b-instruct",.3,.4,{tags:["llm","llama","meta","open-source","reasoning"]}),X("or-llama-8b","Llama 3.1 8B","Fast, lightweight open model. Great for simple tasks at minimal cost.","meta-llama/llama-3.1-8b-instruct",.05,.08,{tags:["llm","llama","meta","open-source","fast","cheap"]}),X("or-mistral-large","Mistral Large","Mistral's flagship model. Strong at multilingual and European languages.","mistralai/mistral-large-2411",2,6,{tags:["llm","mistral","multilingual","european"]}),X("or-mistral-small","Mistral Small","Fast, efficient Mistral model. Good for everyday tasks.","mistralai/mistral-small-3.1-24b-instruct",.1,.3,{tags:["llm","mistral","fast","cheap"]}),X("or-deepseek-chat","DeepSeek Chat V3","Strong reasoning model at very low cost. Excellent for coding and math.","deepseek/deepseek-chat-v3-0324",.3,.88,{tags:["llm","deepseek","coding","math","cheap","reasoning"]}),X("or-deepseek-r1","DeepSeek R1","Advanced reasoning model with chain-of-thought. Best for complex problems.","deepseek/deepseek-r1",.55,2.19,{tags:["llm","deepseek","reasoning","chain-of-thought","math"]}),X("or-qwen-72b","Qwen 2.5 72B","Alibaba's large model. Strong at coding, math, and multilingual tasks.","qwen/qwen-2.5-72b-instruct",.3,.4,{tags:["llm","qwen","alibaba","coding","multilingual"]}),X("or-phi-4","Phi-4","Microsoft's compact reasoning model. Punches above its weight for size.","microsoft/phi-4",.07,.14,{tags:["llm","phi","microsoft","compact","cheap","reasoning"]}),X("or-perplexity-sonar","Perplexity Sonar","Search-augmented LLM. Answers with real-time web sources and citations.","perplexity/sonar",1,1,{perRequestFeeCents:.5,tags:["llm","perplexity","search","web","citations","real-time"]}),{dispatch:"enveloped",id:"query_onchain_prices",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly and daily granularity.",provider:"allium",model:"allium-prices",category:"onchain",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly) or '1d' (daily). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",internal:!0,executionKind:"x402_gateway",resultKind:"utility",gatewayConfig:{enabled:!1,gatewayPath:"/gateway",method:"POST",timeoutMs:3e4},buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:al,tags:["onchain","prices","allium","crypto"]},{dispatch:"enveloped",id:"parallel-search-tempo",name:"Parallel Search (Tempo)",description:"Internal Tempo gateway route for Parallel's paid search endpoint.",provider:"parallel",model:"search",category:"utility",priceCents:1,inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query. Mapped by Parallel to objective when provided."},objective:{type:"string",description:"Search objective. Use with search_queries for advanced requests."},search_queries:{type:"array",items:{type:"string"},description:"Optional explicit search query list."},mode:{type:"string",enum:["one-shot","fast"],description:"Parallel search mode.",default:"one-shot"}},anyOf:[{required:["query"]},{required:["objective"]}]},gatewayUrl:"https://parallelmpp.dev/api/search",merchantName:"Parallel",internal:!0,rail:"tempo",executionKind:"tempo_gateway",resultKind:"utility",gatewayConfig:{enabled:!1,gatewayPath:"/gateway",method:"POST",timeoutMs:3e4},buildBody:Kf,tags:["search","parallel","tempo","internal"]},{dispatch:"enveloped",id:"generate_image_card",name:"Generate Image (Ultra)",description:"Generate a high-quality AI image (FLUX Pro Ultra, 2K, ~$0.06).",provider:"fal",model:"fal-ai/flux-pro/v1.1-ultra",category:"image",priceCents:6,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1-ultra",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro-ultra",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),t},tags:["image","flux","ultra","legacy"]},{dispatch:"enveloped",id:"generate_image_fast_card",name:"Generate Image (Fast)",description:"Generate an AI image (FLUX Pro v1.1, 1K, ~$0.04).",provider:"fal",model:"fal-ai/flux-pro/v1.1",category:"image",priceCents:4,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro",buildBody:e=>go({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"]},te("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"}),te("edit_image_seed_card","Edit Image (SeedEdit)","Inpaint/edit an image with a prompt using SeedEdit.","fal-ai/bytedance/seededit","image",5,{type:"object",properties:{image_url:{type:"string"},prompt:{type:"string"},seed:{type:"number"}},required:["image_url","prompt"]},{buildBody:e=>{let t={image_url:e.image_url,prompt:e.prompt};return e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","edit","inpaint","seededit"],deprecated:!0,replacementTool:"or-gemini-nano-banana"}),{dispatch:"enveloped",id:"generate_video_tempo_card",name:"Generate Video (Grok)",description:"Generate a video from a text prompt using Grok Imagine Video.",provider:"fal",model:"xai/grok-imagine-video/text-to-video",category:"video",priceCents:30,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/xai/grok-imagine-video/text-to-video",merchantName:"Grok Video via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),t},tags:["video","grok","legacy"]},{dispatch:"enveloped",id:"generate_video_kling_card",name:"Generate Video (Kling)",description:"Generate a video using Kling v1.6 (async, ~$0.40).",provider:"fal",model:"fal-ai/kling-video/v1.6/standard/text-to-video",category:"video",priceCents:40,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/kling-video/v1.6/standard/text-to-video",merchantName:"Kling via fal.ai",deprecated:!0,replacementTool:"fal-kling-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","kling","legacy"]},{dispatch:"enveloped",id:"generate_video_wan_card",name:"Generate Video (Wan)",description:"Generate a video using Wan T2V (async, ~$0.25).",provider:"fal",model:"fal-ai/wan/t2v-1.3b",category:"video",priceCents:25,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/wan/t2v-1.3b",merchantName:"Wan T2V via fal.ai",deprecated:!0,replacementTool:"fal-wan-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","wan","legacy"]},{dispatch:"enveloped",id:"generate_video_minimax_card",name:"Generate Video (MiniMax)",description:"Generate a video using MiniMax (async, ~$0.35).",provider:"fal",model:"fal-ai/minimax/video-01",category:"video",priceCents:35,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/minimax/video-01",merchantName:"MiniMax via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","minimax","legacy"]},{id:"check_fal_status",name:"Check fal Async Job Status",description:"Poll an async fal.ai queue job for completion. Free.",provider:"fal",model:"queue-status",category:"image",priceCents:0,inputSchema:{type:"object",properties:{model_path:{type:"string",description:"Model path (e.g. fal-ai/kling-video/v1.6/standard/text-to-video)"},request_id:{type:"string"}},required:["model_path","request_id"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue",merchantName:"fal.ai",handler:{type:"local",fn:"check_fal_status"},pricing:{amount:0,currency:"USD",display:"$0.00",free:!0},freeReadPathPattern:"/api/v1/fal/**/requests/*/(status)?",tags:["status","fal","async"]},{dispatch:"enveloped",id:"generate_3d_card",name:"Generate 3D Model",description:"Generate a 3D mesh from a text prompt using Meshy (async, ~$0.50).",provider:"fal",model:"fal-ai/meshy-ai/text-to-3d",category:"3d",priceCents:50,inputSchema:{type:"object",properties:{object_prompt:{type:"string"},style_prompt:{type:"string"},negative_prompt:{type:"string"},art_style:{type:"string"},seed:{type:"number"}},required:["object_prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/meshy-ai/text-to-3d",merchantName:"Meshy via fal.ai",deprecated:!0,replacementTool:"fal-trellis-3d",buildBody:e=>{let t={object_prompt:e.object_prompt};return e.style_prompt&&(t.style_prompt=e.style_prompt),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.art_style&&(t.art_style=e.art_style),e.seed!==void 0&&(t.seed=e.seed),t},tags:["3d","mesh","meshy","legacy"]},{dispatch:"enveloped",id:"generate_speech_card",name:"Generate Speech",description:"Text-to-speech using F5-TTS with optional voice cloning.",provider:"fal",model:"fal-ai/f5-tts",category:"tts",priceCents:3,inputSchema:{type:"object",properties:{gen_text:{type:"string",description:"Text to synthesize"},ref_audio_url:{type:"string",description:"Reference audio URL (for voice cloning)"},ref_text:{type:"string",description:"Transcription of ref audio"},remove_silence:{type:"boolean"}},required:["gen_text"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/f5-tts",merchantName:"fal.ai",buildBody:e=>{let t={gen_text:e.gen_text};return e.ref_audio_url&&(t.ref_audio_url=e.ref_audio_url),e.ref_text&&(t.ref_text=e.ref_text),e.remove_silence!==void 0&&(t.remove_silence=e.remove_silence),t},deprecated:!0,replacementTool:"fal-metavoice",tags:["tts","speech","f5-tts","legacy"]},{dispatch:"enveloped",id:"generate_music_tempo_card",name:"Generate Music (Suno) \u2014 retired",description:"[Retired] Suno music generation. Use `generate_music` (ACE-Step) instead.",enabled:!1,sunsetAt:"2026-06-25",provider:"suno",model:"suno-v4",category:"audio",priceCents:50,inputSchema:{type:"object",properties:{prompt:{type:"string"},instrumental:{type:"boolean"},model:{type:"string",default:"V4"}},required:["prompt"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/generate-music",merchantName:"Suno via Tempo",buildBody:e=>({prompt:e.prompt,customMode:!1,instrumental:e.instrumental??!1,model:e.model||"V4"}),isAsync:!0,pollUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",pollInterval:15e3,pollTimeout:3e5,deprecated:!0,replacementTool:"fal-ace-step-music",tags:["music","audio","suno","async","legacy"]},{dispatch:"enveloped",id:"check_music_status_tempo_card",name:"Check Music Status (Suno) \u2014 retired",description:"[Retired] Suno status poll. No replacement; ACE-Step jobs poll via `check_fal_status`.",enabled:!1,sunsetAt:"2026-06-25",provider:"suno",model:"suno-status",category:"audio",priceCents:0,inputSchema:{type:"object",properties:{taskId:{type:"string"}},required:["taskId"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",merchantName:"Suno Status",buildBody:e=>({taskId:e.taskId}),deprecated:!0,tags:["music","status","suno","legacy"]},{dispatch:"enveloped",id:"query_onchain_prices_card",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly, daily, and weekly granularity.",provider:"allium",model:"allium-prices",category:"llm",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly), '1d' (daily), or '1w' (weekly). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",deprecated:!0,replacementTool:"query_onchain_prices",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:al,tags:["onchain","prices","allium","crypto","legacy"]}];function mr(e){return Zs.find(t=>t.id===e)}var dl=1,ml=["pick_one","fan_out"],pl=["concat","dedupe_by_url","top_k_by_score"],Zf=8,Qf=g.object({type:g.string().min(1),description:g.string().min(1),enum:g.array(g.string()).optional(),default:g.unknown().optional(),minimum:g.number().optional(),maximum:g.number().optional()}),eg=g.object({toolId:g.string().min(1),notes:g.string().min(1)}),tg=g.string().regex(/^[a-z0-9_-]{1,32}$/,"tier key must be 1-32 chars [a-z0-9_-]"),ng=g.object({providers:g.array(g.string().min(1)).min(1).max(Zf),merge:g.enum(pl),maxResults:g.number().int().positive().optional()}),fl=g.object({mode:g.enum(ml).default("pick_one"),intro:g.string().min(1),defaultTier:g.string().min(1),tiers:g.record(tg,eg).refine(e=>Object.keys(e).length>0,{message:"must have at least one tier"}),fanOut:ng.optional(),guidance:g.string().min(1),inputProperties:g.record(g.string(),Qf),required:g.array(g.string())}).refine(e=>e.tiers[e.defaultTier]!==void 0,{message:"defaultTier must exist in tiers",path:["defaultTier"]}).refine(e=>e.mode!=="fan_out"||e.fanOut!==void 0,{message:"fan_out mode requires fanOut config",path:["fanOut"]}).refine(e=>e.required.every(t=>t in e.inputProperties),{message:"required entries must exist in inputProperties",path:["required"]}),rg=g.object({version:g.literal(dl),generatedAt:g.string().datetime(),tools:g.record(g.string().regex(Js,"tool name must match MCP naming rules"),fl).refine(e=>Object.keys(e).length>0,{message:"manifest must have at least one tool"})});var vo=require("child_process"),vl=require("util"),bl=E(require("crypto")),de=E(require("fs")),Sl=E(require("os")),Ke=E(require("path"));var Mn=(0,vl.promisify)(vo.execFile),bo=Ke.join(Sl.homedir(),".visa-mcp","bin"),dn=Ke.join(bo,"Visa CLI"),ig=Ke.join(__dirname,"..","native"),gl="6",hl=Ke.join(bo,"visa-keychain.version"),yl=Ke.join(bo,"visa-keychain.sha256");function _l(e){let t=de.readFileSync(e);return bl.createHash("sha256").update(t).digest("hex")}async function ei(){try{if(de.readFileSync(hl,"utf-8").trim()===gl&&de.existsSync(dn)){let r=de.readFileSync(yl,"utf-8").trim();if(_l(dn)!==r)m.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),de.unlinkSync(dn);else return dn}}catch{}let e=Ke.join(ig,"visa-keychain.m");if(de.existsSync(e)||(e=Ke.resolve(__dirname,"..","..","native","visa-keychain.m")),de.existsSync(e)||(e=Ke.resolve(__dirname,"..","native","visa-keychain.m")),!de.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");de.mkdirSync(bo,{recursive:!0,mode:448});try{await Mn("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",dn,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=_l(dn);return de.writeFileSync(yl,t,{mode:384}),de.writeFileSync(hl,gl,{mode:384}),dn}async function wl(e){let t=await ei(),n;try{n=(await Mn(t,e,{timeout:6e4})).stdout}catch(s){n=s.stdout||"";let i=n.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(s.stderr?.trim()||s.message||"Unknown error")}let r=n.trim();if(r.startsWith("OK:"))return r.slice(3);if(r==="OK")return;let o=r.startsWith("ERROR:")?r.slice(6):"Unknown error";throw new Error(o)}var Qs=null;function ie(){return _n()?!0:process.platform!=="darwin"?!1:Qs!==null?Qs:(Qs=!0,!0)}var yo="visa-cli",_o="attestation-key";async function ag(e){try{await Mn("security",["delete-generic-password","-s",yo,"-a",_o],{timeout:5e3})}catch{}await Mn("security",["add-generic-password","-s",yo,"-a",_o,"-w",e],{timeout:5e3})}async function ti(){try{let{stdout:e}=await Mn("security",["find-generic-password","-s",yo,"-a",_o,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function So(){let e=await wl(["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 ag(n),r}async function xl(){return await ti()!==null}async function kl(){if(_n())return"mock-public-key-spki";let e=await ti();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await ei();return new Promise((n,r)=>{let o=(0,vo.execFile)(t,["public-key"],{timeout:6e4},(s,i)=>{let a=(i||"").trim();if(s){a.startsWith("ERROR:")?r(new Error(a.slice(6))):r(new Error(s.stderr?.trim()||s.message||"Unknown error"));return}a.startsWith("OK:")?n(a.slice(3)):r(new Error(a.startsWith("ERROR:")?a.slice(6):"Unknown error"))});o.stdin.write(e),o.stdin.end()})}async function On(e,t){if(_n())return Promise.resolve(ca());let n=await ti();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await ei(),o=["sign",e];return t&&o.push(t),new Promise((s,i)=>{let a=(0,vo.execFile)(r,o,{timeout:6e4},(l,c)=>{let u=(c||"").trim();if(l){u.startsWith("ERROR:")?i(new Error(u.slice(6))):i(new Error(l.stderr?.trim()||l.message||"Unknown error"));return}u.startsWith("OK:")?s(u.slice(3)):i(new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error"))});a.stdin.write(n),a.stdin.end()})}async function wo(){try{await Mn("security",["delete-generic-password","-s",yo,"-a",_o],{timeout:5e3})}catch{}try{await wl(["delete-key"])}catch{}}var cg=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],lg=[...cg.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 ri(e,t=lg){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=ni(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(ni(r.match.provider)))&&r.match.keywords.every(o=>n.includes(ni(o))))return r.targetToolId;return null}function ni(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}var pr={generate_image:{intro:'Generate an AI image from a text prompt \u2014 useful for hero shots, marketing assets, social posts, blog covers, app mockups, or any time the user asks for art, a logo, an icon, a thumbnail, or "a picture of \u2026". From $0.01 (fast) to $0.06 (pro), returns a hosted PNG/JPG URL. Default tier: balanced ($0.04, 1K, ~10s).',tiers:{balanced:{toolId:"fal-flux-pro",notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",notes:"Recraft V3 \u2014 vector/flat/illustration styles"}},guidance:"If the user didn't specify a tier, pick 'balanced' unless the prompt clearly signals otherwise (text \u2192 text_heavy, logo/icon \u2192 vector, quick test \u2192 fast, hero/print \u2192 pro).",inputProperties:{prompt:{type:"string",description:"Text description of the image to generate."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9", "1:1", "9:16".',default:"16:9"}},required:["prompt"]},generate_video:{intro:'Generate a short AI video from a text prompt \u2014 useful for product demos, social clips, mood reels, ad concepts, or any "make me a video of \u2026" request. $0.10\u2013$0.40 per ~6s clip depending on tier. Async: returns a request_id; use execute_tool with tool_id "check_fal_status" to resolve it (60\u2013180s).',tiers:{balanced:{toolId:"fal-minimax-video",notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",notes:"Kling \u2014 highest quality, cinematic"}},guidance:'Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate and are processed asynchronously. The response includes a request_id and model_path. Poll with execute_tool using tool_id "check_fal_status" and the exact request_id/model_path returned by the async response. Do not substitute the catalog model path manually. Do not poll more than once per 30 seconds.',inputProperties:{prompt:{type:"string",description:"Text description of the video scene."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9" or "9:16".',default:"16:9"}},required:["prompt"]},generate_music:{intro:'Generate an original music track from a prompt via ACE-Step. ~$0.02 for the default 60s track. Use for songs, backing tracks, jingles, vocal music, instrumental music, or any "make a song/music/track" request. Takes ~60-90s and may return a request_id to poll with check_fal_status. For SFX, chimes, ambient beds, or TTS, use generate_audio instead.',tiers:{ace_step:{toolId:"fal-ace-step-music",notes:"ACE-Step \u2014 prompt-to-music with vocals or instrumentals"}},guidance:"Use for songs and music tracks. Takes ~60-90s and may return a request_id to poll with check_fal_status. For sound effects, chimes, ambient beds, or TTS, use generate_audio instead.",inputProperties:{prompt:{type:"string",description:"Musical style, mood, instruments, subject, and lyrics direction."},instrumental:{type:"boolean",description:"True for instrumental music with no vocals; false for vocal tracks.",default:!1},duration:{type:"number",description:"Duration in seconds.",default:60}},required:["prompt"]},generate_audio:{intro:'Generate sound effects from a text prompt (sfx tier \u2014 default), or voice-cloned speech from text + a reference audio URL (tts tier). $0.03\u2013$0.04. Use for SFX, chimes, UI sounds, ambient audio (default sfx), or voice cloning when a reference audio URL is available (pass tier:"tts"). Default tier is sfx; pass tier:"tts" for voice cloning.',tiers:{sfx:{toolId:"fal-stable-audio",notes:"Stable Audio \u2014 sound effects and ambient from a prompt"},tts:{toolId:"fal-metavoice",notes:"MetaVoice \u2014 voice cloning TTS (requires a voice sample URL)"}},guidance:'Default tier is sfx: pass prompt describing the sound. For tts (voice cloning): pass tier:"tts" + text + audio_url.',inputProperties:{prompt:{type:"string",description:"Description of sound to generate (sfx tier, default)."},text:{type:"string",description:"Text to speak aloud (tts tier)."},audio_url:{type:"string",description:"URL of a voice sample to clone (tts tier, required for voice cloning)."}},required:[]},generate_3d:{intro:"Generate a 3D mesh (GLB) from an image URL via Trellis. ~$0.08, ~30\u201360s. Use when the user shares an image and asks for a 3D model, asset, AR-ready mesh, or game-ready GLB.",tiers:{trellis:{toolId:"fal-trellis-3d",notes:"Trellis \u2014 image-to-3D, returns a GLB mesh URL"}},guidance:"Pass an image URL. Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{image_url:{type:"string",description:"URL of the image to convert to a 3D model."}},required:["image_url"]},upscale_image:{intro:'Upscale an image to 4\xD7 resolution via Aura SR (preserves detail without hallucination). ~$0.03. Use whenever the user shares a low-res image and asks to "upscale", "make this higher resolution", "4x this", "enhance", or to print/export at larger size.',tiers:{aura:{toolId:"fal-aura-sr",notes:"Aura SR \u2014 default; preserves detail without hallucination"}},guidance:"Pass the existing image URL. Returns an upscaled version.",inputProperties:{image_url:{type:"string",description:"URL of the image to upscale."}},required:["image_url"]},transcribe_audio:{intro:'Transcribe speech in an audio or video file (URL) to text via OpenAI Whisper. ~$0.02 per file, multilingual, handles long files. Use whenever the user asks to "transcribe this", "what does this audio say", "make subtitles", "convert this to text", or shares an audio/video URL with no other clear intent.',tiers:{whisper:{toolId:"fal-whisper",notes:"OpenAI Whisper \u2014 fast, multilingual"}},guidance:"Pass the URL. Returns the transcript text.",inputProperties:{audio_url:{type:"string",description:"URL of the audio or video file to transcribe."}},required:["audio_url"]},run_llm:{intro:"Run a text prompt through a different LLM (GPT-4o-mini, Claude Sonnet, DeepSeek R1/V3, Perplexity Sonar with web search, or Llama 70B). Token-metered, typically ~$0.01\u2013$0.10 per call. Use for: web-grounded answers (search tier), second-opinion reasoning (reasoning tier), code generation in a different family (coding tier), deep math/logic (deep_reasoning tier), or fast cheap text cleanup (fast tier). Pair with batch for multi-model councils.",tiers:{fast:{toolId:"or-gpt-4o-mini",notes:"GPT-4o Mini. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",notes:"Claude Sonnet. Strong reasoning, long-context. Warn user it is materially pricier than `fast`."},frontier_openai:{toolId:"or-gpt-55",notes:"GPT-5.5. OpenAI frontier model for complex professional reasoning."},frontier_openai_pro:{toolId:"or-gpt-55-pro",notes:"GPT-5.5 Pro. Highest-capability OpenAI frontier tier; materially more expensive."},frontier_anthropic:{toolId:"or-claude-opus",notes:"Claude Opus 4.7. Anthropic frontier model for complex tasks."},frontier_google:{toolId:"or-gemini-35-flash",notes:"Gemini 3.5 Flash. Google frontier Flash model for multimodal reasoning and coding."},deep_reasoning:{toolId:"or-deepseek-r1",notes:"DeepSeek R1. Deep chain-of-thought reasoning, mid-range pricing."},search:{toolId:"or-perplexity-sonar",notes:"Perplexity Sonar. Search-augmented, web-grounded with citations."},open_source:{toolId:"or-llama-70b",notes:"Llama 3.3 70B. Open-source large model."},coding:{toolId:"or-deepseek-chat",notes:"DeepSeek Chat V3. Strong at code generation."}},guidance:"Pick based on the user's need: fast (most questions, cheapest), reasoning (complex analysis; warn user it is materially pricier than fast), frontier_* (top-model council / highest quality; warn user these are materially pricier), search (questions about current events), coding (code generation), deep_reasoning (hard math/logic problems).",inputProperties:{prompt:{type:"string",description:"The user query."},system_prompt:{type:"string",description:"Optional system prompt to set model behavior."},max_tokens:{type:"number",description:"Maximum output tokens.",default:1024,minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature \u2014 0 is deterministic, higher is more creative.",default:.7,minimum:0,maximum:2}},required:["prompt"]}};function $t(e,t,n){if(!Tl(e))return pg(e,n);let r=Cl[e];if(!r)return e;let o=Object.keys(r.tiers),s=t||o[0],i=fg(e,s,n);return i||gg(e,r,s,o)}function pg(e,t){return ri({requestedTool:e,intentText:t})??e}function fg(e,t,n){return ri({requestedTool:e,metaTool:e,tier:t,intentText:n})}function gg(e,t,n,r){let o=t.tiers[n];if(!o)throw new Error(`Unknown tier '${n}' for ${e}. Valid tiers: ${r.join(", ")}`);return o.toolId}var Cl=pr;function Tl(e){return e in Cl}var fr=Object.keys(pr);function oi(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function El(e=process.env){return oi(e)!==null}var uu=require("child_process"),me=E(require("crypto")),Le=E(require("fs")),vr=E(require("os")),Do=E(require("path"));function mn(e,t={}){if(!e||typeof e!="object")return e;let n=e,r=t.tag??(typeof n.merchantName=="string"?n.merchantName:"media"),o=n.content?.[0]?.text,s=typeof o=="string"?vn(o):null,i=Array.isArray(n.urls)?n.urls[0]:void 0,l=typeof i=="string"&&i.startsWith("data:")?vn(i):null;if(!s&&!l)return e;let c=s??l,u=s?"content":"urls",d;try{d=Gn(c,{tag:hg(r,n)})}catch(p){return{...n,_inline_media_warning:`Failed to persist inline media to disk: ${p instanceof Error?p.message:String(p)}`}}let f={...n,filePath:d.filePath,mime:d.mime,bytes:d.bytes};return u==="urls"?f.urls=void 0:(f.content=Array.isArray(n.content)?[...n.content]:[{}],f.content[0]={...f.content[0]??{},text:`[inline media saved to ${d.filePath}]`}),f}function hg(e,t){let n=typeof t.transactionId=="string"?t.transactionId:typeof t.transaction_id=="string"?t.transaction_id:null;return n?`${e}-${n}`:e}var Al=!1;async function gr(e,t,n){try{return await t()}catch(r){if(!(r.message==="Invalid signature"||r.code==="ATTESTATION_KEY_DRIFT"||r.error_code==="ATTESTATION_KEY_DRIFT"||r.name==="AttestationDriftError")||!ie())throw r;if(m.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(Al)throw m.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;Al=!0,m.info("attestation:starting-browser-recovery");try{let s=await n();if(!s.success)throw m.error("attestation:browser-recovery-failed",{message:s.message}),r;let i=await So();return await e.registerAttestationKey(i),await e.setBiometricPreference({required:!0}),m.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),m.info("attestation:key-reregistered-after-recovery"),await t()}catch(s){throw m.error("attestation:recovery-failure",{error:s.message}),r}}throw r}}var Rl="2.6.0-rc.7";function si(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function ko(e,t,n){let r=process.env[e];if(r!==void 0)return{value:n==="opt-in"?r==="true":r!=="false",source:{kind:"env",var:e}};let o=io(t);return o!==void 0?{value:o,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function xe(e){return e==null?"\u2014":e?"yes":"no"}function Co(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function yg(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function _g(){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=js("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:Us,source:{kind:"default"}}}async function hr(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(L){n=L?.message||"unknown error"}let r=[],o=process.env.VISA_AUTH_URL,s=Ds("auth.serverUrl"),i=ye(),a=o!==void 0&&o!==""?{kind:"env",var:"VISA_AUTH_URL"}:s!==void 0?{kind:"settings"}:{kind:"default"};r.push({key:"auth.serverUrl",value:i,formatted:i,source:a,hint:a.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),r.push({key:"account.enrolled",value:t?.enrolled??null,formatted:xe(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:xe(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:xe(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:ie(),formatted:xe(ie()),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:Co(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:Co(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:Co(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:Co(t?.dailyRemaining),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"cards.count",value:t?.cardCount??null,formatted:t?.cardCount!=null?String(t.cardCount):"\u2014",source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}});let f=t?.cards?.find(L=>L.isDefault)??t?.cards?.[0];f&&r.push({key:"cards.default",value:{brand:f.brand??null,last4:f.last4},formatted:`${f.brand||"card"} \u2022\u2022\u2022\u2022 ${f.last4}`,source:{kind:"server"}});let p=_g();r.push({key:"credit.sessionCapCents",value:p.value,formatted:yg(p.value),source:p.source});let _=Ic();_.length>0&&r.push({key:"settings.retired",value:_.map(L=>L.key),formatted:_.map(L=>L.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${_.map(L=>`visa-cli config unset ${L.key}`).join(" && ")}`});let T=ko("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:T.value,formatted:xe(T.value),source:T.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let P=ko("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:P.value,formatted:xe(P.value),source:P.source});let H=qe(),D;process.env.VISA_CLI_NO_UPDATE_CHECK?D={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?D={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?D={kind:"env",var:"NODE_ENV"}:D={kind:"default"},r.push({key:"ui.updateCheck",value:!H,formatted:xe(!H),source:D});let S=ko("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:S.value,formatted:xe(S.value),source:S.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let w=ko("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:w.value,formatted:xe(w.value),source:w.source});let y=process.env.VISA_DRY_RUN,k=El();if(r.push({key:"tools.dryRun",value:k,formatted:xe(k),source:y===void 0?{kind:"default"}:{kind:"env",var:"VISA_DRY_RUN"},hint:"VISA_DRY_RUN=true|1|mock returns deterministic paid-tool fixtures (no card, no upstream). VISA_DRY_RUN=preflight makes a real zero-cost OpenRouter call for LLM tools (image/video still mocked)."}),r.push({key:"client.version",value:Rl,formatted:Rl,source:{kind:"default"}}),e.includeDev){let L=process.env.VISA_MOCK_KEYCHAIN,$e=gt();r.push({key:"dev.mockKeychain",value:$e,formatted:xe($e),source:si("VISA_MOCK_KEYCHAIN",!!L),hint:es()});let Dt=process.env.VISA_MOCK_TOUCHID,Se=_n();r.push({key:"dev.mockTouchid",value:Se,formatted:xe(Se),source:si("VISA_MOCK_TOUCHID",!!Dt),hint:es()});let B=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!B,formatted:xe(!!B),source:si("VISA_CLI_DEBUG",!!B)})}return{entries:r,statusError:n}}function vg(e){switch(e.kind){case"default":return"default";case"env":return`env ${e.var}`;case"settings":return"settings.json";case"server":return"server";case"device":return"device";case"unset":return"unset";case"unknown":return`unknown (${e.reason})`}}function Il(e,t={}){if(e.length===0)return"";let n=Math.max(...e.map(s=>s.key.length)),r=Math.max(...e.map(s=>s.formatted.length)),o=[];for(let s of e){let i=s.key.padEnd(n+2),a=s.formatted.padEnd(r+2);o.push(`${i}${a}(${vg(s.source)})`),t.verbose&&s.hint&&o.push(` ${"\u21B3".padStart(n)} ${s.hint}`)}return o.join(`
124
- `)}function $l(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 Pl(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 Pt=require("fs"),Ol=require("os"),ii=require("path"),bg=(0,ii.join)((0,Ol.homedir)(),".visa-mcp"),Ml=(0,ii.join)(bg,"mcp-session-budget.json");function To(){try{(0,Pt.existsSync)(Ml)&&(0,Pt.unlinkSync)(Ml)}catch{}}var ci=require("crypto"),Ne=E(yr()),pn=null,ke=0,Nn=0,be=0,Mt=null,li=null,ui=null,Ao=Promise.resolve();function Dg(e){return Number((0,Ne.fromCents)(e))}function Ul(e){return(0,Ne.toCents)((0,Ne.micros)(BigInt(e)))}function Ll(e){return(0,Ne.toWire)((0,Ne.fromCents)(e))}function ai(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Eo(e){return typeof e=="string"&&/^\d+$/.test(e)}var jg=43,Fg=new RegExp(`^[A-Za-z0-9_-]{${jg}}$`);function qg(e){return typeof e=="string"&&Fg.test(e)}function Vg(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||pn&&e.session_id!==pn||typeof e.nonce!="string"||e.nonce.length===0||!qg(e.server_signature)||!ai(e.cumulative)||!ai(e.remaining)||!ai(e.delta)||e.cumulative<ke||be>0&&e.cumulative>be||be>0&&e.remaining>be||e.cumulative_micros!==void 0&&!Eo(e.cumulative_micros)||e.remaining_micros!==void 0&&!Eo(e.remaining_micros)||e.delta_micros!==void 0&&!Eo(e.delta_micros)||e.reserved_micros!==void 0&&!Eo(e.reserved_micros))}function mt(e){pn=e,ke=0,Nn=0,be=0,Mt=null,li=null,ui=null,Ao=Promise.resolve()}function _r(e){be=Math.max(0,Math.floor(e))}function di(){return pn}function mi(e){if(!pn)return null;let t=ke+Nn;return be>0&&t>be&&(t=be),{session_budget_id:pn,cumulative_micros:Dg(t),nonce:(0,ci.randomUUID)(),idempotency_key:e||(0,ci.randomUUID)()}}function pi(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 Vg(r)?(ke=Math.max(ke,r.cumulative),Nn=0,Mt=r,r):null}function Dl(){return Mt}function fi(e){let t=Ul(e.cumulative_micros);ke=Math.max(ke,t),Nn=0;let n={status:"accepted",session_id:e.session_budget_id,cumulative:ke,remaining:Math.max(0,be-ke),delta:0,cumulative_micros:Ll(ke),remaining_micros:Ll(Math.max(0,be-ke)),delta_micros:"0",nonce:e.nonce};return Mt=n,n}function gi(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,Ne.toCents)((0,Ne.micros)(n));if(!Number.isFinite(r)||r<0)return;li=t;let o=e,s=typeof o.session_id=="string"?o.session_id:pn??"";Mt?(typeof o.remaining_micros=="string"&&/^\d+$/.test(o.remaining_micros)&&(Mt.remaining_micros=o.remaining_micros),typeof o.charged_micros=="string"&&/^\d+$/.test(o.charged_micros)&&(Mt.delta_micros=o.charged_micros)):Mt={session_id:s,cumulative:r,remaining:0,delta:0,nonce:typeof o.transaction_id=="string"?o.transaction_id:"",remaining_micros:typeof o.remaining_micros=="string"&&/^\d+$/.test(o.remaining_micros)?o.remaining_micros:void 0,delta_micros:typeof o.charged_micros=="string"&&/^\d+$/.test(o.charged_micros)?o.charged_micros:void 0}}function jl(e){let t=e.receipt??null;ui={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:Ul(e.voucher.cumulative_micros),estimatedCumulativeCents:Ro(),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 Fl(){return ui}function ql(){return ke}function Vl(){return li}function Ro(){let e=ke+Nn;return be>0&&e>be&&(e=be),e}function Hl(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return Ao=Ao.then(()=>{Nn+=t}),Ao}var Hg=10,Bg=1,Z=null,Bl=Promise.resolve();function hi(e){let t=Bl.catch(()=>{}).then(e);return Bl=t.then(()=>{},()=>{}),t}var ge=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 yi(e,t,n){return hi(()=>Kl(e,t,n))}async function Kl(e,t,n){if(To(),Z&&new Date(Z.expiresAt).getTime()>Date.now())return di()!==Z.budgetId&&(mt(Z.budgetId),_r(Z.totalCents)),m.info("mcp-session:active-hit",{budgetId:Z.budgetId,tool:n.toolName,remainingEstimatedCents:Z.totalCents-Ro()}),{budgetId:Z.budgetId,isFresh:!1,totalCents:Z.totalCents,requestedCapCents:Z.totalCents,appliedCapCents:Z.totalCents,clampedReason:null};Z&&(Z=null,mt(null));let r=await e.getBalance();if(!r.success)throw new Error(`Could not read balance: ${r.error||"unknown error"}`);let o=n.sessionKind??"explicit",s=o==="one_shot"?Bg:Hg,i=Math.max(s,Math.ceil(n.minRequiredCents??s));if(r.balanceCents<i)throw new ge(r.balanceCents,i);let a=n.capCentsOverride??Mc(),l=Math.min(a,r.balanceCents),c=l<a?"balance":null,u=await t("session_create",l,"Visa CLI Session",`open credit-model session with $${(l/100).toFixed(2)} cap`,n.userContext),d=await e.createSessionBudget({total_cents:l,session_kind:o,...u?{attestation:u}:{}});if(!d.success||!d.budget){let p=d.error||"unknown error";throw new Error(`Failed to open credit session: ${p}`)}let f={budgetId:d.budget.id,expiresAt:d.budget.expiresAt,totalCents:d.budget.totalCents,createdAt:d.budget.createdAt};return Z=f,mt(f.budgetId),_r(f.totalCents),m.info("mcp-session:opened",{budgetId:f.budgetId,capCents:f.totalCents,requestedCapCents:a,clampedReason:c,sessionKind:o,expiresAt:f.expiresAt,tool:n.toolName}),{budgetId:f.budgetId,isFresh:!0,totalCents:f.totalCents,requestedCapCents:a,appliedCapCents:f.totalCents,clampedReason:c}}async function Gl(e,t,n){return hi(async()=>{let o=Ot()?await zl(e):null,s=await Kl(e,t,n);return{budgetId:s.budgetId,totalCents:s.totalCents,closedPrevious:o,requestedCapCents:s.requestedCapCents,appliedCapCents:s.appliedCapCents,clampedReason:s.clampedReason}})}async function zl(e){let n=Ot()?.budgetId??di(),r=!1,o,s;if(n)try{let i=await e.closeSession(n);r=!!i?.success,typeof i?.finalCumulativeCents=="number"&&(o=i.finalCumulativeCents),typeof i?.finalCumulativeMicros=="string"&&(s=i.finalCumulativeMicros)}catch(i){m.warn("mcp-session:close-server-failed",{budgetId:n,error:i?.message||String(i)})}return To(),Z=null,mt(null),{closedServerSide:r,budgetId:n,finalCumulativeCents:o,finalCumulativeMicros:s}}async function Io(e){return hi(()=>zl(e))}function Ot(){return To(),Z?new Date(Z.expiresAt).getTime()<=Date.now()?(Z=null,mt(null),null):{budgetId:Z.budgetId,totalCents:Z.totalCents,lastReceiptCumulative:ql(),lastReceiptCumulativeMicros:Dl()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:Vl(),estimatedCumulative:Ro(),lastToolSpend:Fl(),expiresAt:Z.expiresAt}:null}var Jl=E(yr()),Wl=10000n;function Kg(e){return e<=0n?0:Number((e+Wl-1n)/Wl)}function Yl(e){return Kg((0,Jl.fromUsd)(e))}var $o=E(yr()),Gg=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;function Po(e){if(typeof e!="string"||!Gg.test(e))return{ok:!1,error:"amount must be a USD amount with at most two decimal places"};let[t,n=""]=e.split("."),r=BigInt(t)*100n+BigInt(n.padEnd(2,"0"));if(r>BigInt(Number.MAX_SAFE_INTEGER))return{ok:!1,error:"amount is too large"};let o=Number(r);return o<=0?{ok:!1,error:"amount must be greater than $0.00"}:{ok:!0,cents:o,displayUsd:(0,$o.toDisplay)((0,$o.fromCents)(o),{symbol:""})}}var Mo="Buying credits currently requires local biometric attestation from a macOS Touch ID-capable CLI/MCP process. This device cannot create the required attestation, so no card charge was attempted. Credits are account-level, so you can top up this account from any interactive Touch ID-capable CLI, then use the balance from this remote server. For unattended workloads, scoped API keys with daily caps are also supported.",Xl="Tell the user that buying credits requires a local Touch ID-capable CLI/MCP process today. Credits are account-level: suggest topping up the same account from any interactive Touch ID-capable CLI, then continuing on this remote server. For unattended workloads, scoped API keys with daily caps are also supported. Do not retry buy_credits from this process; it cannot produce the required card-charge attestation.";var Zl=Promise.resolve(),Ql=!1;function jo(e){let t=Zl.catch(()=>{}).then(e);return Zl=t.then(()=>{},()=>{}),t}async function du(e){let t=await yi($,Ye,{toolName:e.toolId,userContext:e.userContext}),n=mi(e.idempotencyKey);if(!n)throw new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await Qg(),o,s,i=async()=>$.shortcutWithSession(e.toolId,n,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);try{try{({data:o,voucherReceiptHeader:s}=await i())}catch(u){if(u instanceof Gt){let d=Math.min(Math.max(u.retryAfterSecs,0),5)*1e3;m.warn("mcp-session:lock-contended-retrying",{tool:e.toolId,retryAfterSecs:u.retryAfterSecs}),await new Promise(f=>setTimeout(f,d)),{data:o,voucherReceiptHeader:s}=await i()}else throw u}}catch(u){if(u instanceof xn){if(m.warn("mcp-session:server-invalidated-budget",{code:u.code,budgetId:u.budgetId??t.budgetId,tool:e.toolId}),await Io($),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 Ql||(Ql=!0,console.error(`[visa-cli] Your session was closed by another process; reopened automatically as pay-as-you-go.
125
- 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}),mu(e)}throw u instanceof Gt?(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=pi(s)??(n?fi(n):null);if(gi(o?.receipt_v2),await Hl(e.estimatedAmountCents),jl({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),fu(o))return mn(o);let l=await pu();if(e.idempotencyKey&&gu(o,l,e.idempotencyKey))return mn(o);let c=l?Lo(l):null;return mn(hu(o,r,c))}function ze(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function bi(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(bi).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${bi(r)}`).join(",")}}`}function zg(e,t,n,r){let o=me.createHash("sha256").update(`${n}:${bi(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${o}`}function Wg(e,t){return`${e}:${t}`}function Jg(e){if(e==null)return;let t=String(e);if(t.length!==0)return t.startsWith("ledger_")?t:/^\d+$/.test(t)?`ledger_${t}`:t}function eu(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,o=Ge(r),s=o!==null?o.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=Jg(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),l=i!=null?String(i):a;return{batch_id:e,item_id:Wg(e,t),index:t,...l!==void 0?{transaction_id:l}:{},...a!==void 0?{ledger_id:a}:{},...s?{amountMicros:s,amount_micros:s,cost_micros:s}:{}}}async function mu(e){let t=Math.max(1,Math.ceil(e.estimatedAmountCents)),n=await $.getBalance();if(!n.success)throw new Error(`Could not read balance: ${n.error||"unknown error"}`);if(n.balanceCents<t)throw new ge(n.balanceCents,t);let r=t,o=Lo(n),s=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(r/100).toFixed(2)})`,i=await Ye("session_create",r,"Visa CLI Session",s,e.userContext),a=await $.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;mt(l),_r(a.budget.totalCents),m.info("on-demand-session:opened",{budgetId:l,capCents:a.budget.totalCents,tool:e.toolId});try{let c=mi(e.idempotencyKey);if(!c)throw new Error(`Internal: mintVoucher returned null after on-demand session-open ${l}`);let{data:u,voucherReceiptHeader:d}=await $.shortcutWithSession(e.toolId,c,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(pi(d)||fi(c),gi(u?.receipt_v2),fu(u))return mn(u);let f=await pu();if(e.idempotencyKey&&gu(u,f,e.idempotencyKey))return mn(u);let p=f?Lo(f):null;return mn(hu(u,o,p))}finally{try{await $.closeSession(l)}catch(c){m.warn("on-demand-session:close-failed",{budgetId:l,error:c?.message||String(c)})}mt(null),m.info("on-demand-session:closed",{budgetId:l,tool:e.toolId})}}async function Lt(e){return jo(async()=>Ot()?du(e):mu(e))}function Fo(){return ye()}var $=new we(()=>F.getSessionToken());function Ge(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function Lo(e){return Ge(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function Yg(e){if(e<0n&&(e=0n),e>=1000000n){let r=(e+5000n)/10000n,o=r/100n,s=r%100n;return`$${o.toString()}.${s.toString().padStart(2,"0")}`}let t=e%1000000n;return t===0n?"$0.00":`$0.${t.toString().padStart(6,"0").replace(/0+$/,"")}`}function Xg(e){let t=Ge(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=Ge(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=Ge(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function Oo(e,t="INVALID_TOOL_PARAMS"){return{success:!1,error_code:t,code:t,error:e,message:e}}function Zg(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 Qg(){try{let e=await $.getBalance();return e.success?Lo(e):null}catch{return null}}async function pu(){try{let e=await $.getBalance();return e.success?e:null}catch{return null}}function fu(e){if(!e||e.success===!1)return!1;let t=Ge(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=Ge(e.amountMicros??e.amount_micros??e.charged_micros),r=t??n;if(r===null||r<=0n)return!1;let o=r.toString();return e.amountMicros??=o,e.amount_micros??=o,e.charged_micros??=o,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),!0}function gu(e,t,n){if(!e||e.success===!1||!t||!Array.isArray(t.ledger))return!1;let r=t.ledger.find(a=>a.idempotencyKey===n);if(!r)return!1;let o=Ge(r.deltaMicros)??BigInt(r.deltaCents)*10000n,s=o<0n?-o:o;if(s<=0n)return!1;let i=s.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(s)/1e6),!0}function hu(e,t,n){if(!e||e.success===!1||t===null||n===null)return e;let r=t-n;if(r<=0n)return e;let o=r.toString();return e.amountMicros??=o,e.amount_micros??=o,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),e}var eh="2.6.0-rc.7",ew=["","","You're ready to go! Try:","","Core:",'\u2022 "Show my account status" \u2192 get_status','\u2022 "List my enrolled cards" \u2192 get_cards','\u2022 "Show my paid tool use history" \u2192 transaction_history','\u2022 "Set my daily top-up limit to $50" \u2192 update_spending_controls','\u2022 "Generate 3 variations in parallel" \u2192 batch',"","Category tools:",'\u2022 "Generate an image of a sunset over Tokyo" \u2192 generate_image','\u2022 "Make a 4-second video of a penguin juggling" \u2192 generate_video','\u2022 "Make a song about coding late at night" \u2192 generate_music','\u2022 "Create a sound effect for a checkout chime" \u2192 generate_audio','\u2022 "Create a 3D asset from this product sketch" \u2192 generate_3d','\u2022 "Upscale this product image" \u2192 upscale_image','\u2022 "Transcribe this meeting recording" \u2192 transcribe_audio','\u2022 "Run a reasoning model on this prompt" \u2192 run_llm',"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
126
- `);function We(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=Yn(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if($c())return{opened:!1,url:t,blockedReason:"suppressed"};let n=ps();if(n.headless)return m.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let r=xa(t,Fo());if(!r)return m.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let o=Ca(r);return o?((0,uu.execFile)(o.cmd,o.args,s=>{s&&m.warn(`Browser open failed: ${s.message}. URL: ${r}`)}),{opened:!0,url:r}):(m.info(`No browser command for platform "${vr.platform()}". URL: ${r}`),{opened:!1,url:r,blockedReason:"unsupported_platform"})}async function Ce(e){return gr($,e,ku)}var yu="get_cards",_u="set_default_card";function th(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 '${yu}' to see enrolled cards and '${_u}' to switch, then retry the original request.`}function nh(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 '${yu}' to see enrolled cards and '${_u}' to switch. Do not retry automatically.`}function Je(e,t){let n=e.retryable?th(e.code,e.retryAfter):nh(e.code,t.merchantName);return{success:!1,declined:!0,retryable:e.retryable,code:e.code,reason:e.reason,payment_error_class:e.paymentErrorClass,correlation_id:e.correlationId,transactionId:e.transactionId,retryAfter:e.retryAfter,merchantName:t.merchantName,amount:t.amount,message:e.message,agent_guidance:n}}function rh(e){return{success:!1,error:e.message,error_code:e.code,transactionId:e.transactionId,reconciliation_required:e.reconciliationRequired,retryable:e.retryable,agent_guidance:"The top-up charge outcome is ambiguous. Tell the user not to retry with a new idempotency key or start another top-up. They should check transaction_history in a few minutes or contact support with the transactionId."}}var Ln=null,oh=3e4;function vu(){Ln=null}var Nt=class extends Error{constructor(n){super(`${Uo()} attestation is required for this action, but it is not available in this MCP process. `+Si());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function qo(e,t){return{success:!1,error:e.code,message:e.message,action:t,agent_guidance:`Biometric attestation is required for ${t}, but this MCP process cannot create a local attestation. `+Si()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function sh(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:Mo,agent_guidance:Xl}}function Uo(){return process.platform==="darwin"?"Touch ID":"local biometric"}function Si(){return process.platform==="darwin"?"Run the action from an interactive terminal with Touch ID access, or use reset with confirm:true to clear stale server biometric state through GitHub re-authentication.":"This platform cannot create Visa CLI Touch ID attestations. Use reset with confirm:true to clear stale server biometric state through GitHub re-authentication."}function Vo(e){return typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0}async function ih(e){let t=Date.now();if(Ln&&Ln.expiresAt>t)return{required:Ln.required,hasRegisteredKey:Ln.hasRegisteredKey};try{let n=await $.getStatus(e),r=n.attestationRequired!==!1,o=Vo(n);return Ln={required:r,hasRegisteredKey:o,expiresAt:t+oh},{required:r,hasRegisteredKey:o}}catch{return{required:!0,hasRegisteredKey:!0}}}async function Ye(e,t,n,r,o,s){if(!s?.forceRequired){let i=await ih(o);if(!i.required){m.info("attestation:skipped-by-server-policy",{context:e});return}if(!i.hasRegisteredKey){m.info("attestation:skipped-no-registered-key",{context:e});return}}if(!ie())throw m.warn("attestation:unavailable",{context:e}),new Nt(e);m.info("attestation:attempt",{context:e,amount:t,merchant:n});try{let{nonce:i}=await $.getAttestationChallenge(),a=Buffer.from(JSON.stringify({nonce:i,amount:t,merchant:n,context:e})).toString("base64");m.info("touchid:prompt",{context:e,amount:t,merchant:n});let l=await On(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 tu="[dry-run] https://placeholder.visa-cli.dev/image.png",ah=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"]),ch=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 lh(e,t){return t==="run_llm"||e.startsWith("or-")?"llm":t==="generate_image"||ah.has(e)?"image":t==="generate_video"||ch.has(e)?"video":null}function uh(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function dh(e){return e==="llm"?"OpenRouter":"fal.ai"}function Un(e,t,n,r){let o={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:dh(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${uh(n)}`;return{...o,content:i,data:{content:i,model:t,dry_run:!0}}}return{...o,urls:[tu],data:{[e==="video"?"videoUrl":"imageUrl"]:tu,metadata:{dry_run:!0}}}}async function _i(e){let t=e.mode??"mock",n=t==="preflight"?"/v1/telemetry/preflight":"/v1/telemetry/dry-run",r=t==="preflight"?"preflight":null;try{await $.emitTelemetry([{id:me.randomUUID(),timestamp:new Date().toISOString(),tool_name:e.toolName,user_prompt:e.userContext??"",tool_params:JSON.stringify(e.toolParams),result_success:!0,result_error:null,result_json:JSON.stringify(e.result),payment_rail:r,payment_amount:0,payment_currency:"USD",merchant_name:e.result.merchantName,transaction_id:e.result.transactionId,tx_hash:null,protocol:null,http_status:200,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",event_kind:"mcp_tool",endpoint:n,resolved_model:e.resolvedModel,session_budget_id:null}])}catch(o){m.warn("dry_run:telemetry_failed",{tool:e.toolName,error:o?.message||String(o),mode:t})}}var mh="https://openrouter.ai/api/v1/chat/completions",ph="openrouter/free",fh=50,gh=15e3;function hh(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 yh(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:Un("llm",e,t,n),degraded:!0,resolvedModel:null};let o=hh(t),s;try{s=await Bt(mh,{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:ph,messages:[{role:"user",content:o}],max_tokens:fh}),timeoutMs:gh})}catch(u){return m.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:Un("llm",e,t,n),degraded:!0,resolvedModel:null}}if(!s.ok){let u=await s.text().catch(()=>"");return m.warn("preflight:openrouter_http_error_falling_back_to_mock",{tool:e,status:s.status,bodyExcerpt:u.slice(0,200)}),{result:Un("llm",e,t,n),degraded:!0,resolvedModel:null}}let i;try{i=await s.json()}catch(u){return m.warn("preflight:openrouter_invalid_json_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:Un("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 Ho(e,t,n,r){let o=oi();if(!o)return null;let s=lh(e,r);if(!s)return null;let i=Date.now();if(o==="mock"){let c=Un(s,e,t,r);return await _i({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:c,userContext:n,startedAt:i,mode:"mock"}),m.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:s,mode:o}),c}if(s!=="llm"){m.warn("preflight:not_supported_for_kind_falling_back_to_mock",{tool:e,kind:s});let c=Un(s,e,t,r);return await _i({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 yh(e,t,r);return await _i({toolName:r??e,resolvedModel:l??(r&&r!==e?e:null),toolParams:t,result:a,userContext:n,startedAt:i,mode:"preflight"}),m.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:s,mode:o}),a}async function pt(e,t,n){let r=await $.paymentPreview({tool:e,url:t},n);if(!r||!r.merchantName||r.amount===void 0||r.amount===null||r.amount<0)throw new Error("Could not determine payment amount and merchant. Try again.");if(!Number.isFinite(r.amount)||r.amount<0||r.amount>999999)throw new Error(`Invalid payment amount: ${r.amount}. Payment rejected for safety.`);return r}function ft(e){return Yl(e.amount)}function _h(){return Do.join(vr.homedir(),".visa-mcp","allium-results")}var tw=16*1024,nw=50*1024*1024;function vh(){let e=_h();try{if(!Le.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=Le.readdirSync(e),n=0,r=0;for(let o of t)try{let s=Le.statSync(Do.join(e,o));s.isFile()&&(n+=s.size,r++)}catch{}return{file_count:r,size_bytes:n,path:e}}catch(t){return m.warn("allium:disk_usage_error",{error:t.message}),{file_count:0,size_bytes:0,path:e}}}var nu=3600*1e3,vi=0;function bh(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function br(e){if(!Pc()&&!(Date.now()<vi))try{if(!await F.getSessionToken())return;await $.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(bh(t)){let n=vi===0;vi=Date.now()+nu,n&&m.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:nu});return}m.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function Sh(e,t){let n=(e.state||"").trim().toUpperCase(),r=(e.county||"").trim(),o=(e.start_date||"").trim(),s=(e.end_date||o).trim();if(!/^[A-Z]{2}$/.test(n))throw new Error('state must be a 2-letter US state code (e.g. "VA").');if(!r)throw new Error("county is required.");if(!/^\d{4}-\d{2}$/.test(o))throw new Error('start_date must be YYYY-MM (e.g. "2025-08").');if(s&&!/^\d{4}-\d{2}$/.test(s))throw new Error("end_date must be YYYY-MM.");let i="Visa SMI",a=.1,l=`Pay $0.10 to ${i} for SMI data (${n} / ${r})`;m.info("payment:attempt",{tool:"get_visa_smi",amount:a,merchant:i});try{return await Ce(async()=>{let c=await Ye("get_visa_smi",a,i,l),u=await $.getVisaSmi({state:n,county:r,start_date:o,end_date:s,attestation:c,idempotencyKey:me.randomUUID()},t);return u.success?m.info("payment:success",{tool:"get_visa_smi",merchant:i,charged_cents:u.charged_cents}):m.warn("payment:declined",{tool:"get_visa_smi",merchant:i,message:u.error}),u})}catch(c){if(c instanceof le)return m.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:c.code,retryable:c.retryable}),Je(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 wh(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 Ho("generate_image_card",e,t);if(n)return n;let r=await pt("generate_image_card",void 0,t),o=me.randomUUID();m.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await Ce(async()=>{let s;try{s=await Lt({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:ft(r),userContext:t,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof ge)return ze(i);throw i}return m.info("payment:success",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>We(i)),br({prompt:e.prompt,tool:"generate_image_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):m.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof le)return m.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Je(s,r);throw m.error("payment:failure",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function xh(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 Ho("generate_image_fast_card",e,t);if(n)return n;let r=await pt("generate_image_fast_card",void 0,t),o=me.randomUUID();m.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await Ce(async()=>{let s;try{s=await Lt({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:ft(r),userContext:t,timeoutMs:6e4,idempotencyKey:o})}catch(i){if(i instanceof ge)return ze(i);throw i}return m.info("payment:success",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>We(i)),br({prompt:e.prompt,tool:"generate_image_fast_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):m.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof le)return m.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Je(s,r);throw m.error("payment:failure",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function kh(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 Ho("generate_video_tempo_card",e,t);if(n)return n;let r=await pt("generate_video_tempo_card",void 0,t),o=me.randomUUID();m.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await Ce(async()=>{let s;try{s=await Lt({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:ft(r),userContext:t,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof ge)return ze(i);throw i}return m.info("payment:success",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>We(i)),br({prompt:e.prompt,tool:"generate_video_tempo_card",mediaUrl:s.urls[0],mediaType:"video",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):m.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof le)return m.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Je(s,r);throw m.error("payment:failure",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function Ch(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 pt("generate_music_tempo_card",void 0,t),r=me.randomUUID();m.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await Ce(async()=>{let o;try{o=await Lt({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:ft(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(s){if(s instanceof ge)return ze(s);throw s}return m.info("payment:success",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),o.urls?.length&&o.status!=="processing"?(o.urls.forEach(s=>We(s)),br({prompt:e.prompt,tool:"generate_music_tempo_card",mediaUrl:o.urls[0],mediaType:"audio",cost:o.amount??n.amount,transactionId:o.transactionId,userContext:t})):o.urls?.length&&o.status==="processing"?(o._preliminary_urls=o.urls,delete o.urls,m.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):m.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof le)return m.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Je(o,n);throw m.error("payment:failure",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}async function Th(e,t){let n=await pt("check_music_status_tempo_card",void 0,t),r=me.randomUUID();m.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await Ce(async()=>{let o;try{o=await Lt({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:ft(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof ge)return ze(s);throw s}return m.info("payment:success",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),o.urls?.length&&o.urls.forEach(s=>We(s)),o})}catch(o){if(o instanceof le)return m.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Je(o,n);throw m.error("payment:failure",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}async function Eh(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 pt("query_onchain_prices",void 0,t),r=me.randomUUID();m.info("payment:attempt",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName});try{return await Ce(async()=>{let o;try{o=await Lt({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:ft(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof ge)return ze(s);throw s}if(m.info("payment:success",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,mode:"session"}),Array.isArray(o?.data))o.data=o.data.map(s=>{if("mint"in s&&!("address"in s)){let{mint:i,...a}=s;return{address:i,...a}}return s});else if(o&&"mint"in o&&!("address"in o)){let{mint:s,...i}=o;return{address:s,...i}}return o})}catch(o){if(o instanceof le)return m.warn("payment:declined",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Je(o,n);throw m.error("payment:failure",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}var Ah=["generate_music_tempo_card"],ru=10,ou=5,su=new Map;function iu(e){let t=su.get(e);if(t!==void 0)return t;let r=mr(e)?.isAsync===!0||Ah.includes(e);return su.set(e,r),r}var Rh=36e4,Ih=18e4,$h=15e3,Ph=12e4,Mh=2e3;function au(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}async function Oh(e,t){let n;if(e.requests?.some(y=>y.tool||y.tool_id)&&e.requests)n=e.requests.map(y=>{let k=y.tool||y.tool_id||e.tool;if(!k)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let L=$t(k,y.tier||e.tier,y.prompt??t),{tool:$e,tool_id:Dt,tier:Se,params:B,...re}=y,Ir=B&&typeof B=="object"?{...B,...re}:re;return{resolvedTool:L,params:Ir}});else if(e.tool){let y=$t(e.tool,e.tier,e.params?.prompt??t);n=(e.requests||(e.count&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(L=>({resolvedTool:y,params:L}))}else return au("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return au("BATCH_EMPTY","Batch requires at least one item.");if(n.length>ru)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${ru} items. Please split into smaller batches.`};if([...new Set(n.map(y=>y.resolvedTool))].some(iu)&&n.length>ou)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${ou} items. Please use multiple batches for more.`};let i=[...new Set(n.map(y=>y.resolvedTool))],a=i.length===1,l={};for(let y of i)l[y]=await Cu(y);let c=new Set(i.filter(y=>l[y]&&Tu(l[y]))),u={};for(let y of i)c.has(y)||(u[y]=await pt(y,void 0,t));let d=0;for(let y of n)d+=u[y.resolvedTool]?.amount??0;let f=[...new Set([...Object.values(u).map(y=>y.merchantName),...i.filter(y=>c.has(y)).map(y=>l[y]?.name??y)])].join(", "),p=a?i[0]:"mixed";m.info("payment:attempt",{tool:"batch",batchTool:p,count:n.length,totalAmount:d,merchant:f,heterogeneous:!a});let _=n.some(y=>iu(y.resolvedTool)),T=n.some(y=>y.resolvedTool.startsWith("or-")||y.resolvedTool==="run_llm"||y.resolvedTool==="execute_tool"),P=_?Rh:T?Ih+n.length*$h:Ph+n.length*Mh,H=me.randomUUID(),D=[],S=0,w=0n;return jo(async()=>{let y=!Ot();if(y&&d>0)try{let k=Math.max(1,Math.ceil(d*100));await yi($,Ye,{toolName:"batch",userContext:t,sessionKind:"one_shot",minRequiredCents:k,capCentsOverride:k})}catch(k){return k instanceof ge?ze(k):(m.warn("payment:batch-prewarm-failed",{batchTool:p,count:n.length,error:k?.message||String(k)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:k?.message||"Failed to authenticate batch session",tool:p,count:n.length,failedCount:n.length,results:[]})}try{for(let B=0;B<n.length;B+=1){let re=n[B],Ir=u[re.resolvedTool];try{let Y=c.has(re.resolvedTool)?await $.shortcut(re.resolvedTool,re.params,P,t,"batch"):await du({toolId:re.resolvedTool,toolParams:re.params,estimatedAmountCents:ft(Ir),userContext:t,metaTool:"batch",timeoutMs:P,idempotencyKey:zg(H,B,re.resolvedTool,re.params)});if(c.has(re.resolvedTool)&&Y&&typeof Y=="object"&&!Array.isArray(Y)&&Y.merchantName==null&&(Y.merchantName=l[re.resolvedTool]?.name??re.resolvedTool),D.push({success:Y?.success!==!1,tool:re.resolvedTool,...Y,...eu(H,B,Y)}),Y?.success!==!1){let Hn=Ge(Y?.amountMicros??Y?.amount_micros),Xi=typeof Y?.amount=="number"?Y.amount:Ir?.amount??0;Hn!==null&&Hn>0n?w+=Hn:w+=BigInt(Math.round(Xi*1e6)),S+=Xi}Y?.urls&&Y.urls.forEach(Hn=>We(Hn))}catch(Y){if(Y instanceof ge&&D.length===0)return ze(Y);m.warn("payment:batch-item-failed",{tool:re.resolvedTool,index:B,error:Y?.message||String(Y)}),D.push({success:!1,tool:re.resolvedTool,...eu(H,B),error:Y?.message||String(Y)})}}let k=D.filter(B=>B?.success===!1).length,L=D.length-k,$e=D.flatMap(B=>Array.isArray(B?.urls)?B.urls:[]),Dt=w>0n?Number(w)/1e6:Math.round((S+Number.EPSILON)*100)/100,Se=L===0?"failure":k===0?"success":"partial";return m.info("payment:success",{tool:"batch",batchTool:p,count:n.length,totalAmount:d,totalCharged:Dt,merchant:f,successCount:L,failedCount:k,outcome:Se,mode:"session",batchId:H}),{success:L>0,outcome:Se,batch_id:H,tool:a?i[0]:p,count:n.length,successCount:L,failedCount:k,totalCharged:Dt,...w>0n?{totalChargedMicros:w.toString(),amountMicros:w.toString(),amount_micros:w.toString()}:{},merchantName:f,results:D,...$e.length?{urls:$e}:{}}}catch(k){if(k instanceof le)return m.warn("payment:declined",{tool:"batch",batchTool:p,count:n.length,totalAmount:d,merchant:f,code:k.code,retryable:k.retryable}),Je(k,{amount:d,merchantName:f});throw m.error("payment:failure",{tool:"batch",batchTool:p,count:n.length,totalAmount:d,merchant:f,error:k.message}),k}finally{if(y){let k=await Io($);m.info("batch-session:closed",{budgetId:k.budgetId,closedServerSide:k.closedServerSide})}}})}function Nh(){let e=!1,t;try{let r=Do.join(vr.homedir(),".claude","settings.json");if(Le.existsSync(r)){let o=JSON.parse(Le.readFileSync(r,"utf-8")),s=typeof o.statusLine=="object"?o.statusLine.command:"";e=xt(s)}}catch{}let n=Kr();return n||(t="visa-cli config hud enable"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function Lh(e){let[t,n]=await Promise.all([$.getStatus(e),$.getBalance().catch(s=>(m.warn("get_status:balance_fetch_failed",{error:s?.message||String(s)}),null))]);typeof t?.dailyRemaining=="number"&&(t.dailyRemaining=Math.round(t.dailyRemaining*100)/100);let r=vh();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=Nh(),t.version=eh,Array.isArray(t.cards)&&(t.cards=t.cards.map(s=>({...s,displayName:wi(s)})),t.cardIdGuidance="cardId values are opaque tool parameters only; refer to cards by brand and last four digits."),n&&n.success&&(t.balanceCents=n.balanceCents,t.amountUsd=n.amountUsd);let o=Ot();if(t.sessionMode=!!o,o){let s=Math.max(0,o.totalCents-o.estimatedCumulative);t.activeSession={budgetId:o.budgetId,capCents:o.totalCents,capUsd:o.totalCents/100,lastReceiptCumulativeCents:o.lastReceiptCumulative,estimatedCumulativeCents:o.estimatedCumulative,spentCents:o.estimatedCumulative,spentUsd:o.estimatedCumulative/100,estimatedRemainingCents:s,estimatedRemainingUsd:s/100,...o.lastToolSpend?{lastToolSpend:{toolName:o.lastToolSpend.toolName,resolvedToolId:o.lastToolSpend.resolvedToolId,estimatedAmountCents:o.lastToolSpend.estimatedAmountCents,estimatedAmountUsd:o.lastToolSpend.estimatedAmountCents/100,voucherCumulativeCents:o.lastToolSpend.voucherCumulativeCents,estimatedCumulativeCents:o.lastToolSpend.estimatedCumulativeCents,receiptDeltaCents:o.lastToolSpend.receiptDeltaCents,receiptCumulativeCents:o.lastToolSpend.receiptCumulativeCents,receiptRemainingCents:o.lastToolSpend.receiptRemainingCents,recordedAt:o.lastToolSpend.recordedAt}}:{},expiresAt:o.expiresAt}}return t}function wi(e){let t=typeof e.brand=="string"&&e.brand.trim().length>0?e.brand.trim():"card",n=t.charAt(0).toUpperCase()+t.slice(1).toLowerCase(),r=typeof e.last4=="string"&&e.last4.trim().length>0?e.last4.trim():"unknown",o=e.isDefault===!0?" (default)":"";return`${n} ending in ${r}${o}`}async function bu(e,t){try{let r=((await $.getStatus(t)).cards||[]).find(o=>o?.id===e);if(r)return wi(r)}catch(n){m.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function Uh(e){let n=(await $.getStatus(e)).cards||[];return n.length===0?{cards:[],message:"No cards enrolled. Use the add_card tool to add a payment card."}:n.some(o=>!Number.isInteger(o?.id)||o.id<=0)?{success:!1,cards:[],message:"Card action handles are unavailable right now, so remove_card and set_default_card are temporarily disabled."}:{cards:n.map(o=>({...o,displayName:wi(o)})),message:"Use cardId only as an opaque tool parameter. When speaking to the user, refer to cards by brand and last four digits, not by card id."}}async function Dh(e,t){return await $.getTransactions({limit:e.limit,offset:e.offset},t)}async function jh(e,t){return await $.feedback(e.message,e.transaction_id,t)}async function Fh(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return fn("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=Po(String(e.amount));if(n.ok===!1)return{success:!1,error:n.error};let r=n.cents,o=r/100,s=me.randomUUID();m.info("buy_credits:attempt",{amountCents:r});try{return await Ce(async()=>{let i=await Ye("balance-topup",o,"Visa CLI Balance",`top up balance with $${n.displayUsd}`,t,{forceRequired:!0}),a=await $.topupBalance({amount_cents:r,idempotency_key:s,attestation:i});if(a.success){m.info("buy_credits:success",{amountCents:r,balanceCents:a.balanceCents});let l=((a.balanceCents??0)/100).toFixed(2),c=(r/100).toFixed(2);return{...a,amount:r/100,amountMicros:String(r*1e4),merchantName:"Visa CLI Balance",message:`Added $${c} \u2014 balance is now $${l}`}}return m.warn("buy_credits:failed",{amountCents:r,error:a.error}),a})}catch(i){if(i instanceof Nt)return sh();if(i instanceof ot)return m.warn("buy_credits:ambiguous",{amountCents:r,code:i.code,transactionId:i.transactionId}),rh(i);throw m.error("buy_credits:failure",{amountCents:r,error:i.message}),i}}function fn(e,t){return{success:!1,error:t,code:e,message:t}}async function qh(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return fn("MISSING_CONFIRMATION","Please confirm by setting confirm: true to update spending controls.");if(e.maxTransactionAmount!==void 0&&(typeof e.maxTransactionAmount!="number"||!Number.isFinite(e.maxTransactionAmount)||e.maxTransactionAmount<.01))return fn("INVALID_VALUE","maxTransactionAmount must be at least $0.01");if(e.dailyLimit!==void 0&&(typeof e.dailyLimit!="number"||!Number.isFinite(e.dailyLimit)||e.dailyLimit<1))return fn("INVALID_VALUE","dailyLimit must be at least $1");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return fn("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");m.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await Ce(async()=>{let n=await Ye("spending-controls",0,"","update spending controls"),r=await $.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 Nt)return qo(n,"update_spending_controls");if(String(n?.message||n).includes("Attestation required"))return fn("ATTESTATION_REQUIRED","Changing spending controls requires local attestation, even when payment biometric prompts are disabled.");throw n}}async function Vh(e){let t=await hr({api:$,includeDev:!!e.includeDev});return{config:t.entries.map(n=>({key:n.key,value:n.value,source:n.source,hint:n.hint})),statusError:t.statusError}}async function Hh(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=ao(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 st?"UNKNOWN_KEY":t instanceof it?"SERVER_CONTROLLED":t instanceof kt?"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(Tt).sort()}}}async function Bh(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=co(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 st?"UNKNOWN_KEY":t instanceof it?"SERVER_CONTROLLED":t instanceof kt?"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(Tt).sort()}}}async function Kh(e){let t=await $.getStatus(e),n=t.attestationRequired!==!1,r=Vo(t),o=ie(),s=n?r?o?`${Uo()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${Uo()} is not available in this process. ${Si()}`:"Biometric attestation is enabled on the account, but no attestation key is registered. Payments on this device proceed without a biometric signature; processor declines such as INVALID_OR_MISSING_CONFIG are card/account configuration issues, not something biometric setup fixes.":"Biometric attestation is NOT required for payments. Payments will proceed without biometric confirmation.";return{required:n,hasAttestationKey:!!t.hasAttestationKey,hasTelegramAttestationKey:!!t.hasTelegramAttestationKey,hasAnyAttestationKey:r,touchIdAvailable:o,platform:process.platform,effectiveRequiredOnThisDevice:n&&r&&o,canDisableFromThisDevice:!n||!r||o,message:s}}async function Gh(e){m.info("biometric:on");let t=await $.setBiometricPreference({required:!0},e);return t.success?(vu(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:t.error||"unknown error"}}async function zh(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return fn("MISSING_CONFIRMATION","Please confirm by setting confirm: true. Disabling Touch ID is a security downgrade \u2014 the user will be prompted for one final Touch ID confirmation before the change takes effect.");m.info("biometric:off");try{return await Ce(async()=>{let n=await $.getStatus(t),r;if(Vo(n)&&(r=await Ye("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${Uo()} confirmation required to disable \u2014 not available on this device.`);let o=await $.setBiometricPreference({required:!1,attestation:r},t);if(!o.success)throw new Error(o.error||"unknown error");return vu(),{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 Nt)return qo(n,"biometric_off");throw n}}var cu=3e4,Wh=3e5;async function Su(e,t,n="login"){let r=me.randomUUID(),o=`${e}${e.includes("?")?"&":"?"}state=${r}`,s=We(o);return!s.opened&&s.blockedReason!=="non_internal_host"&&s.blockedReason!=="invalid_url"?wu(o,s,n):s.opened?{...await xu(r,t,n),browserUrl:o}:{success:!1,browserUrl:o,message:`Could not open the browser URL safely. Please check the configured auth server and try again. URL: ${o}`}}function wu(e,t,n){let r=n==="enrollment"?"card enrollment":n==="attestation-recovery"?"biometric reset":"login",o=t.blockedReason==="suppressed"?"browser auto-open is suppressed":t.blockedReason==="headless"?"this process appears to be headless":t.blockedReason==="unsupported_platform"?"this platform has no configured browser opener":"browser auto-open is unavailable";return{success:!1,requiresBrowser:!0,browserUrl:e,message:`Browser auto-open was skipped because ${o}. Open this URL to continue ${r}: ${e}`}}async function xu(e,t,n="login"){let r=Date.now()+Wh;for(;Date.now()<r;)try{let s=await fetch(`${Fo()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:cu,...t&&{user_context:t}}),signal:AbortSignal.timeout(cu+5e3)});if(!s.ok){await bt(s,a=>{m.warn("auth_status:retry_after_http_error",{status:s.status,delayMs:a})});continue}let i=await s.json();if(i.status==="pending")continue;if(i.status==="expired")return{success:!1,message:"Session expired. Please try again."};if(i.status==="error")return{success:!1,message:i.error||"Authentication failed. Please try again."};if(i.status==="complete"){if(n==="attestation-recovery"||i.attestationCleared)return m.info("auth:attestation_recovery_complete",{user:i.user||""}),{success:!0,message:"Server-side biometric state cleared. Run visa-cli setup to register a fresh key before reenabling Touch ID."};let a=i.welcomeBonusCents??0,l=Pl(a);if(n!=="enrollment"&&i.sessionToken){await F.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 bt(void 0,s=>{m.warn("auth_status:retry_after_network_error",{delayMs:s})})}return{success:!1,message:n==="enrollment"?"Card enrollment timed out. Please try again.":n==="attestation-recovery"?"Biometric reset timed out. Please try reset again.":"Login timed out. Please try again."}}async function ku(e){let t=me.randomUUID(),n;try{n=await $.startAttestationRecovery(t,e)}catch(s){return{success:!1,message:`Could not start biometric reset: ${s?.message||"unknown error"}`}}if(!n.success||!n.recoveryUrl)return{success:!1,message:n.error||"Could not start biometric reset. Please try again."};let r=We(n.recoveryUrl);return!r.opened&&r.blockedReason!=="non_internal_host"&&r.blockedReason!=="invalid_url"?wu(n.recoveryUrl,r,"attestation-recovery"):r.opened?{...await xu(t,e,"attestation-recovery"),browserUrl:n.recoveryUrl}:{success:!1,browserUrl:n.recoveryUrl,message:`Could not open the browser URL safely. Please check the configured auth server and try again. URL: ${n.recoveryUrl}`}}async function Jh(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to remove this card."};let n=e.cardId;if(!Number.isInteger(n)||n<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to get the opaque cardId for the card you want to remove."};m.info("cards:remove_attempt",{cardId:n});let r=`remove-card:${n}`,o=`remove ${await bu(n,t)}`;try{return await Ce(async()=>{let s=await Ye(r,0,"",o,t,{forceRequired:!0}),i=await $.removeCard(n,{attestation:s},t);return m.info("cards:remove_success",{cardId:n,promotedId:i?.promotedId??null}),i})}catch(s){if(m.error("cards:remove_failure",{cardId:n,error:s.message}),s instanceof Nt)return qo(s,"remove_card");throw s}}async function Yh(e,t){let n=e.cardId;if(!Number.isInteger(n)||n<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to get the opaque cardId for the card you want to make default."};m.info("cards:set_default_attempt",{cardId:n});let r=`set-default-card:${n}`,o=`set ${await bu(n,t)} as default`;try{return await Ce(async()=>{let s=await Ye(r,0,"",o,t,{forceRequired:!0}),i=await $.setDefaultCard(n,{attestation:s},t);return m.info("cards:set_default_success",{cardId:n}),i})}catch(s){if(m.error("cards:set_default_failure",{cardId:n,error:s.message}),s instanceof Nt)return qo(s,"set_default_card");throw s}}async function Xh(e){return m.info("auth:login_attempt"),Su(`${Fo()}/login`,e)}function Zh(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 Qh(e={},t){let n;try{n=Zh(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return jo(async()=>{let r=await Gl($,Ye,{toolName:"start_session",userContext:t,capCentsOverride:n});m.info("session:started",{budgetId:r.budgetId,totalCents:r.totalCents,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious});let o=(r.appliedCapCents/100).toFixed(2),s=(r.requestedCapCents/100).toFixed(2),i=`Session started with a $${o} cap. Paid calls will use this approval window until you close it, it expires, or this MCP process restarts.`,a=r.clampedReason==="balance"?`${i} Note: requested cap of $${s} was clamped to your prepaid balance of $${o}. Run buy_credits to top up if you need a larger session.`:i;return{success:!0,budgetId:r.budgetId,totalCents:r.totalCents,amountUsd:r.totalCents/100,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious,message:a}})}async function ey(){let e=Ot();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 ty(){return jo(async()=>{let e=Ot();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 Io($);m.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=Xg(e),r=Ge(t.finalCumulativeMicros),o=r??(typeof t.finalCumulativeCents=="number"?BigInt(Math.max(0,t.finalCumulativeCents))*10000n:n.micros),s=Number(o/10000n);return m.info("session:closed:final-spend",{budgetId:t.budgetId,closedServerSide:t.closedServerSide,finalSpendMicros:o.toString(),finalSpendCents:s,finalSpendSource:r!==null?"server.finalCumulativeMicros":typeof t.finalCumulativeCents=="number"?"server.finalCumulativeCents":n.source,totalCents:e.totalCents}),{success:!0,closed:!0,closedServerSide:t.closedServerSide,budgetId:t.budgetId,finalEstimatedCumulativeCents:s,finalEstimatedCumulativeMicros:o.toString(),totalCents:e.totalCents,message:t.closedServerSide?`Explicit approval window closed. Spent ${Yg(o)} of $${(e.totalCents/100).toFixed(2)} cap. Future paid calls are pay-as-you-go until you start a new explicit approval window.`:"Explicit approval window cleared locally; server-side close call did not succeed (likely already closed). Future paid calls are pay-as-you-go until you start a new explicit approval window."}})}async function ny(e){if(m.info("auth:add_card_attempt"),!await F.getSessionToken())return{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."};let{code:n}=await $.createEnrollCode();return Su(`${Fo()}/enroll-card?code=${encodeURIComponent(n)}`,e,"enrollment")}async function ry(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 $.getStatus(t);if(r&&Vo(r)){let o=await ku(t);if(!o.success)return o;n=!0}}catch(r){let o=r?.message||"unknown error";if(!/not logged in|session.*expired|no local credentials/i.test(o))return{success:!1,message:`Could not check server biometric state: ${o}`};m.warn("reset:server_attestation_status_unavailable",{error:o})}try{await $.logout(void 0,t)}catch{}if(await F.clearAll(),ie())try{await wo()}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 oy(e){let t=e.query?.trim()||void 0,n=e.category?.trim()||void 0,r=!t&&!n;m.info("catalog:discover",{query:t,category:n,browseAll:r});try{let s=(await $.catalogSearch(t,n)).tools||[];if(s.length===0)return{content:[{type:"text",text:r?"The tool catalog is currently empty.":`No tools found for "${t||n}". Try a different search term.`}]};if(r){let a={};for(let c of s){let u=c.category||"other";(a[u]??=[]).push(c)}let l=Object.keys(a).sort().map(c=>{let u=a[c].map((f,p)=>`${p+1}. **${f.name}** (${f.id})
109
+ Note: a legacy shell-prompt HUD block was detected in ${o} but could not be auto-removed (${s.message}). Remove it manually with: visa-cli config hud disable shell`}function ir(e,t=so){let n={},r=!1;if(se.existsSync(e)){r=!0;try{n=JSON.parse(se.readFileSync(e,"utf-8"))}catch(o){return{installed:"malformed-json",message:`~/.claude/settings.json is not valid JSON (${o.message}). Fix the file manually, then run: visa-cli config hud enable claude`}}}if(n.statusLine){let o=typeof n.statusLine=="object"?n.statusLine.command:"";return kt(o)?{installed:"already-visa",message:Qa("Visa HUD already registered in ~/.claude/settings.json.",e)}:{installed:"other-hud-present",message:Jm("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()},oo(e,n),{installed:"new",message:Qa(`Visa HUD registered in ~/.claude/settings.json${r?"":" (new file)"}. Restart Claude Code to see it pinned below the input.`,e)}}catch(o){return{installed:"error",message:`Failed to write settings: ${o.message}. Enable manually later with: visa-cli config hud enable claude`}}}function Os(e){if(!se.existsSync(e))return{removed:!1,status:"missing-settings",message:"No ~/.claude/settings.json found."};let t;try{t=JSON.parse(se.readFileSync(e,"utf-8"))}catch(r){return{removed:!1,status:"malformed-json",message:`~/.claude/settings.json is not valid JSON: ${r.message}`}}if(!t.statusLine)return{removed:!1,status:"missing-statusline",message:"No statusLine configured."};let n=typeof t.statusLine=="object"?t.statusLine.command:"";if(!kt(n))return{removed:!1,status:"foreign-statusline",message:"statusLine is owned by another tool \u2014 leaving it alone."};delete t.statusLine;try{oo(e,t)}catch(r){return{removed:!1,status:"error",message:`Failed to write ~/.claude/settings.json: ${r.message}`}}return{removed:!0,status:"removed",message:"Visa HUD removed from ~/.claude/settings.json. Restart Claude Code to take effect."}}var rc=E(require("os")),oc=E(require("path"));function rt(e=rc.homedir()){return oc.join(e,".claude","settings.json")}var ot=E(require("fs")),qe=E(require("path"));var Ym=1,Kt={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},Xm=["terminal","claude","claude-code","all"];function lo(e){let t=e.toLowerCase();return Xm.includes(t)?t:null}var Zm=50,Qm=64*1024,sc=10,Ms=80,T={get reset(){return le().reset},get visaBlue(){return le().visaBlue},get visaBlueSoft(){return le().visaBlueSoft},get visaGold(){return le().visaGold},get green(){return le().green},get muted(){return le().muted},get chrome(){return le().chrome}};function A(e,t){return e.length===0||process.env.NO_COLOR||Yr()?e:`${t}${e}${T.reset}`}function ic(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function uc(e=process.stdin){return e.isTTY?null:new Promise(t=>{let n=[],r=!1,o=()=>{e.removeListener("data",i),e.removeListener("end",a),e.removeListener("error",l),clearTimeout(c)},s=u=>{r||(r=!0,o(),t(u))},i=u=>{n.push(typeof u=="string"?Buffer.from(u):u)},a=()=>{let u=Buffer.concat(n).toString("utf-8").trim();if(!u)return s(null);try{let d=JSON.parse(u);s(d&&typeof d=="object"?d:null)}catch{s(null)}},l=()=>s(null),c=setTimeout(()=>{n.length>0?a():s(null)},Zm);e.on("data",i),e.on("end",a),e.on("error",l)})}function ar(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),o="\u2591".repeat(10-n);return`${A(r||"",T.visaBlueSoft)}${A(o||"",T.chrome)}`}function cr(e){return!Number.isFinite(e)||e<0?"0":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:String(Math.round(e))}function ep(e){if(bc(e))return np(e);let t=` ${A("\u2502",T.chrome)} `,n=co(e)||"claude",r=e.cwd?ee(qe.basename(e.cwd)):"",o=uo(e.workspace),s=r||o,i=o&&o!==s?` ${A(`@${o}`,T.visaBlueSoft)}`:"",a=[A(`[${n}]`,T.visaBlueSoft)];s&&a.push(`${A(s,T.visaGold)}${i}`);let l=ee(e.git_branch??e.branch??"");l&&a.push(`${A("git:(",T.muted)}${A(l,T.visaBlueSoft)}${A(")",T.muted)}`);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,m=[f?.input_tokens,f?.output_tokens,f?.cache_creation_input_tokens,f?.cache_read_input_tokens].filter(C=>typeof C=="number"&&Number.isFinite(C)),_=m.length>0?m.reduce((C,L)=>C+L,0):null,S=Number(e.context_window?.total_input_tokens??_??f?.input_tokens??0),$=d!==null?Math.max(0,Math.min(1,d/100)):u>0?Math.max(0,Math.min(1,S/u)):0,V=d!==null&&u>0?Math.round($*u):S,D;if(u>0||d!==null){let C=`${String(Math.round($*100)).padStart(2," ")}%`,L=u>0?` ${A(`(${cr(V)}/${cr(u)})`,T.muted)}`:"";D=`${A("Context",T.muted)} ${ar($)} ${A(C,T.green)}${L}`}else D=`${A("Context",T.muted)} ${A("-",T.muted)}`;let w=dc(e.rate_limits),x=[D];w&&x.push(w);let y=x.join(t);return`${c}
110
+ ${y}`}function tp(e){if(bc(e))return null;let t=` ${A("\u2502",T.chrome)} `,n=co(e)||"claude",r=e.cwd?ee(qe.basename(e.cwd)):"",o=uo(e.workspace),s=r||o,i=o&&o!==s?` ${A(`@${o}`,T.visaBlueSoft)}`:"",a=[A(`[${n}]`,T.visaBlueSoft)];s&&a.push(`${A(s,T.visaGold)}${i}`);let l=ee(e.git_branch??e.branch??"");l&&a.push(`${A("git:(",T.muted)}${A(l,T.visaBlueSoft)}${A(")",T.muted)}`);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(x=>typeof x=="number"&&Number.isFinite(x)),m=f.length>0?f.reduce((x,y)=>x+y,0):null,_=Number(e.context_window?.total_input_tokens??m??d?.input_tokens??0),S=u!==null?Math.max(0,Math.min(1,u/100)):c>0?Math.max(0,Math.min(1,_/c)):0,$=u!==null&&c>0?Math.round(S*c):_,V;if(c>0||u!==null){let x=`${String(Math.round(S*100)).padStart(2," ")}%`,y=c>0?` ${A(`(${cr($)}/${cr(c)})`,T.muted)}`:"";V=`${A("Context",T.muted)} ${ar(S)} ${A(x,T.green)}${y}`}else V=`${A("Context",T.muted)} ${A("-",T.muted)}`;let D=dc(e.rate_limits),w=[V];return D&&w.push(D),{identity:a.join(t),metrics:w.join(t)}}function np(e){let t=` ${A("\u2502",T.chrome)} `,n=Sc(e),r=n.model||"codex",o=[A(`[${r}]`,T.visaBlueSoft)];n.project&&o.push(A(n.project,T.visaGold)),n.gitBranch&&o.push(`${A("git",T.muted)} ${A(n.gitBranch,T.visaGold)}`);let s=o.join(t),i=[];if(typeof n.contextUsedPercent=="number"){let l=Math.max(0,Math.min(1,n.contextUsedPercent/100));i.push(`${A("Context",T.muted)} ${ar(l)} ${A(`${Math.round(n.contextUsedPercent)}%`,T.green)}`)}else if(typeof n.contextRemainingPercent=="number"){let l=100-n.contextRemainingPercent,c=Math.max(0,Math.min(1,l/100));i.push(`${A("Context",T.muted)} ${ar(c)} ${A(`${Math.round(l)}%`,T.green)}`)}typeof n.usedTokens=="number"&&i.push(`${A("Tokens",T.muted)} ${cr(n.usedTokens)}`),n.status&&i.push(`${A("Status",T.muted)} ${A(n.status,T.visaBlueSoft)}`),n.threadTitle&&i.push(`${A("Thread",T.muted)} ${A(n.threadTitle,T.visaBlueSoft)}`);let a=i.length>0?i.join(t):`${A("Context",T.muted)} ${A("-",T.muted)}`;return`${s}
111
+ ${a}`}function rp(e){if(typeof e!="number"||e<=0)return"";let n=(e>1e12?e:e*1e3)-Date.now();if(n<=0||n>=10080*60*1e3)return"";let r=Math.floor(n/6e4),o=Math.floor(r/60),s=r%60;return o>0?`${o}h ${s}m`:`${s}m`}function ac(e,t){if(!e||typeof e.used_percentage!="number")return null;let n=Math.max(0,Math.min(100,e.used_percentage)),r=n/100,o=ar(r),s=n>=90?"\x1B[38;5;196m":n>=70?T.visaGold:T.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=rp(e.resets_at),l=a?` ${A(`(${a} / ${t})`,T.muted)}`:` ${A(`(${t})`,T.muted)}`;return`${o} ${A(i,s)}${l}`}function dc(e){if(!e)return null;let t=ac(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?ac(e.seven_day,"7d"):null;if(!t&&!r)return null;let o=` ${A("\u2502",T.chrome)} `,s=[t,r].filter(Boolean);return`${A("Usage",T.muted)} ${s.join(o)}`}function mc(e){let t;try{let n=ot.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let o=Math.min(r,Qm),s=r-o;t=ot.openSync(e,"r");let i=Buffer.alloc(o);ot.readSync(t,i,0,o,s);let a=i.toString("utf-8");if(s>0){let l=Buffer.alloc(1);if(ot.readSync(t,l,0,1,s-1),l[0]!==10){let c=a.indexOf(`
112
+ `);c>=0&&(a=a.slice(c+1))}}return a}catch{return null}finally{if(t!==void 0)try{ot.closeSync(t)}catch{}}}function op(e){if(!e||typeof e!="object")return;let t=e,n=["file_path","path","notebook_path","pattern","command","url"];for(let r of n){let o=t[r];if(typeof o=="string"&&o.length>0){if(r.endsWith("_path")||r==="path"){let s=qe.basename(qe.dirname(o)),i=qe.basename(o);return s&&s!=="."&&s!=="/"?`${s}/${i}`:i}return o}}}function sp(e){let t=e.split(`
113
+ `),n=[],r=new Set;for(let o=t.length-1;o>=0&&n.length<sc*3;o-=1){let s=t[o].trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{continue}if(!i||typeof i!="object")continue;let l=i.message;if(!l||typeof l!="object")continue;let c=l.content;if(Array.isArray(c))for(let u of c){if(!u||typeof u!="object")continue;let d=u;if(d.type==="tool_result"&&typeof d.tool_use_id=="string")r.add(d.tool_use_id);else if(d.type==="tool_use"&&typeof d.name=="string"){let f=typeof d.id=="string"?d.id:"",m=f.length>0?!r.has(f):!1;n.push({name:d.name,target:op(d.input),running:m})}}}return n.reverse(),n.slice(Math.max(0,n.length-sc))}function ip(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 ap(e){let t=e.running?A("\u25D0",T.visaGold):A("\u2713",T.green),n=e.running?T.visaGold:T.visaBlueSoft,r=A(ee(e.name),n),o=e.target?ee(e.target):"",s=o?`${A(":",T.chrome)} ${A(o,T.muted)}`:"",i=e.count>1?` ${A(`\xD7${e.count}`,T.muted)}`:"";return s?`${t} ${r}${s}${i}`:`${t} ${r}${i}`}function cp(e){let t=` ${A("\u2502",T.chrome)} `,n=ic(t),r=e.slice();for(;r.length>0;){let l=r.join(t);if(ic(l)<=Ms)return l;r=r.slice(1)}if(e.length===0)return"";let o="\u2026",i=e[e.length-1].replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,""),a=i.length>Ms-n-1?i.slice(0,Ms-n-1)+o:i;return`${A(o,T.muted)}${t}${a}`}async function cc(e){if(!e||typeof e!="string")return null;let t=mc(e);if(!t)return null;let n;try{n=sp(t)}catch{return null}if(n.length===0)return null;let o=ip(n).map(ap);return cp(o)||null}async function pc(e,t,n){return(await gc(e,t,n)).join(`
114
+ `)}function fc(e,t,n){let r=!!t?.activeSession||e.includes("in session"),o=n?up(n):!1;return{isActive:r||o,hasSession:r,hasToolActivity:o}}async function gc(e,t,n){let{isActive:r}=fc(e,n,t?.transcript_path),o=e.split(`
115
+ `).filter(a=>a.length>0),i=t&&!r?o.map(a=>A(Ns(a),T.muted)):[...o];if(t){let a=tp(t);if(a){if(i.push(a.identity),t.transcript_path){let l=await cc(t.transcript_path);l&&i.push(...l.split(`
116
+ `))}i.push(a.metrics)}else{let l=ep(t);if(l&&i.push(...l.split(`
117
+ `)),t.transcript_path){let c=await cc(t.transcript_path);c&&i.push(...c.split(`
118
+ `))}}}return i}var lp=["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 up(e){let t=mc(e);if(!t)return!1;let n=t.slice(-16384).toLowerCase();return lp.some(r=>n.includes(`"${r}"`))}async function hc(e,t,n){let r=await gc(e,t,n),o=r.join(`
119
+ `),{isActive:s}=fc(e,n,t?.transcript_path);return{schemaVersion:Ym,client:t?vc(t):Kt.UNKNOWN,rendered:o,lines:r.map(Ns),visa:{spendLine:Ns(e),balanceCents:n?.balanceCents,balanceUsd:n?.amountUsd,sessionMode:n?.sessionMode,activeSession:n?.activeSession,isVisaActive:s},context:t?Sc(t):{}}}function ee(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 uo(e){if(typeof e=="string")return ee(qe.basename(e));if(!e||typeof e!="object")return"";let t=typeof e.current_dir=="string"?e.current_dir:typeof e.path=="string"?e.path:"";return ee(t?qe.basename(t):e.name)}function yc(e){return ee(e.app_name??e.appName??e.app??e.client)}function co(e){return ee(e.model?.display_name??e.model?.id??e.model_name??e.modelName)}function _c(e){return ee(e.cwd??e.current_dir??e.project_root)}function lc(e){let t=ee(e.project);if(t)return t;let n=_c(e);if(n)return ee(qe.basename(n));let r=uo(e.workspace);return r||""}function Oe(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function vc(e){let t=yc(e).toLowerCase();return t.includes("codex")?Kt.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?Kt.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||Oe(e.context_used)!==void 0?Kt.CODEX:Kt.UNKNOWN}function bc(e){return vc(e)===Kt.CODEX}function Sc(e){let t=yc(e),n=_c(e),r=uo(e.workspace),o=Oe(e.context_used)??Oe(e.context_window?.used_percentage??void 0),s=Oe(e.context_remaining)??Oe(e.context_window?.remaining_percentage??void 0);return{...t?{app:t}:{},...co(e)?{model:co(e)}:{},...lc(e)?{project:lc(e)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...ee(e.git_branch??e.branch)?{gitBranch:ee(e.git_branch??e.branch)}:{},...ee(e.status??e.run_state??e.runState)?{status:ee(e.status??e.run_state??e.runState)}:{},...ee(e.thread_title??e.threadTitle)?{threadTitle:ee(e.thread_title??e.threadTitle)}:{},...o!==void 0?{contextUsedPercent:o}:{},...s!==void 0?{contextRemainingPercent:s}:{},...Oe(e.used_tokens)!==void 0?{usedTokens:Oe(e.used_tokens)}:{},...Oe(e.total_input_tokens)!==void 0?{totalInputTokens:Oe(e.total_input_tokens)}:{},...Oe(e.total_output_tokens)!==void 0?{totalOutputTokens:Oe(e.total_output_tokens)}:{}}}function Ns(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}var xc=E(require("path"));function wc(e){return e instanceof Error?e.message:String(e)}function Ls(e,t){let n=[],r=[],o=e??"claude",s=lo(o);if(o==="shell"||o==="prompt")try{let a=t.installShellHud();return a.installed?{ok:!0,messages:[a.message],errors:r}:{ok:!1,messages:n,errors:[a.message]}}catch(a){return{ok:!1,messages:n,errors:[`Failed to install shell HUD: ${wc(a)}`]}}if(!s)return{ok:!1,messages:n,errors:[`Unknown HUD surface: ${o}`,"Supported: claude (default), shell, all"]};let i=!0;if(s==="claude"||s==="claude-code"||s==="all"){let a=xc.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: ${wc(l)}`)}}return{ok:i,messages:n,errors:r}}function kc(e){if(!e||typeof e!="object")return"";let t=e;return Array.isArray(t.enum)&&t.enum.length>0?"enum":typeof t.type=="string"?t.type:Array.isArray(t.type)?t.type.filter(n=>typeof n=="string").join("|"):""}var Cc=E(require("os")),Tc=require("node:readline/promises"),lr={card:"default VISA ****7242",balance:"balance $6.38",spentToday:"spent today $0.62",lastActivity:"last Visa tool 38m",model:"Opus 4.6"};async function Ec(e,t=!1){if(!process.stdin.isTTY)return t;let n=t?"[Y/n]":"[y/N]",r,o;try{r=(0,Tc.createInterface)({input:process.stdin,output:process.stdout});let s=new AbortController;o=()=>s.abort(),r.once("close",o);let i=(await r.question(`${e} ${n} `,{signal:s.signal})).trim();return i?/^y(es)?$/i.test(i):t}catch{return t}finally{r&&o&&r.off("close",o),r?.close()}}function dp(e,t){return e.replace(/[\x00-\x1F\x7F\u202A-\u202E\u2066-\u2069]/g,"").trim()||t}function Ac(e=Cc.hostname()){let t=Jn().version,n=dp(e,"this-machine");return[" Preview if installed (sample):",` VISA CLI v${t} | ${n} | ${lr.card}`,` ${lr.balance} | ${lr.spentToday} | ${lr.lastActivity}`,` [${lr.model}] | you`," Activity live"].join(`
120
+ `)}async function Gt(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,o=setTimeout(()=>r.abort(),n);try{let{timeoutMs:s,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(o)}}var zt=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},En=class extends Error{code;budgetId;status;constructor(t,n,r={}){super(t),this.name="SessionInvalidError",this.code=n,this.budgetId=r.budgetId,this.status=r.status}},Wt=class extends Error{code="SESSION_LOCK_CONTENDED";retryAfterSecs;status;constructor(t,n=1,r){super(t),this.name="SessionLockContendedError",this.retryAfterSecs=n,this.status=r}},ue=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(t,n,r,o,s,i,a,l){super(t),this.name="CardDeclinedError",this.retryable=n,this.code=r,this.reason=o,this.paymentErrorClass=s,this.correlationId=i,this.transactionId=a,this.retryAfter=l}},st=class extends Error{code;transactionId;retryable;reconciliationRequired;constructor(t,n,r={}){super(t),this.name="TopupAmbiguousError",this.code=n,this.transactionId=r.transactionId,this.retryable=r.retryable??!1,this.reconciliationRequired=r.reconciliationRequired??!0}};var Rc={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 Us(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&&Rc[n]?Rc[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 ye=E(require("fs")),Fs=E(require("path")),Ic=E(require("os")),js=Fs.join(Ic.homedir(),".visa-mcp"),ur=Fs.join(js,"mcp-server.log"),mp=5*1024*1024,Ds=null;function pp(){ye.existsSync(js)||ye.mkdirSync(js,{recursive:!0,mode:448})}function fp(){if(!Ds){if(pp(),ye.existsSync(ur)&&ye.statSync(ur).size>mp){let t=ur+".1";ye.existsSync(t)&&ye.unlinkSync(t),ye.renameSync(ur,t)}Ds=ye.createWriteStream(ur,{flags:"a"})}return Ds}function gp(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function mo(e,...t){let n=new Date().toISOString(),r=t.map(s=>typeof s=="string"?s:JSON.stringify(s,null,2)).join(" "),o=`[${n}] [${e}] ${r}
121
+ `;gp(e)&&process.stderr.write(o),fp().write(o)}var p={debug:(...e)=>mo("DEBUG",...e),info:(...e)=>mo("INFO",...e),warn:(...e)=>mo("WARN",...e),error:(...e)=>mo("ERROR",...e)};var hp=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function Pc(e,t){let n=$c(e),r=$c(t);if(!n||!r)return!1;for(let o=0;o<3;o++)if(n.main[o]!==r.main[o])return n.main[o]>r.main[o];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:yp(n.pre,r.pre)>0}function $c(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(hp);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function yp(e,t){let n=e.split("."),r=t.split("."),o=Math.max(n.length,r.length);for(let s=0;s<o;s++){if(s>=n.length)return-1;if(s>=r.length)return 1;let i=n[s],a=r[s],l=/^\d+$/.test(i),c=/^\d+$/.test(a);if(l&&c){let u=Number(i)-Number(a);if(u!==0)return u}else{if(l)return-1;if(c)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function Ve(){return!!(Oc(process.env.VISA_CLI_NO_UPDATE_CHECK)||Oc(process.env.CI)||process.env.NODE_ENV==="test")}function Oc(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var Tt=E(require("fs")),Bs=require("node:net"),Uc=E(require("os")),Dc=E(require("path"));var po=E(require("fs")),Mc=E(require("path")),Nc=E(require("os"));var qs=Mc.join(Nc.homedir(),".visa-mcp"),dr=class{static ensureConfigDir(){po.existsSync(qs)||po.mkdirSync(qs,{recursive:!0,mode:448})}static getConfigDir(){return qs}static TOOL_STATES={login:!0,get_status:!0,get_cards:!0,add_card:!0,pay:!1,transaction_history:!0,update_spending_controls:!0,enroll_device:!1,verify_otp:!1,reset:!0,batch:!0,generate_x402_image:!1,browser_launch:!1,browser_navigate:!1,browser_snapshot:!1,browser_click:!1,browser_type:!1,browser_scroll:!1,generate_music_card:!1,generate_image_card:!1,query_onchain_prices_card:!1,generate_music_tempo_card:!1,check_music_status_tempo_card:!1,generate_image_fast_card:!1,generate_video_tempo_card:!1};static loadToolStates(){return{...this.TOOL_STATES}}static getDisabledTools(){let t=new Set;for(let[n,r]of Object.entries(this.TOOL_STATES))r||t.add(n);return t}static isToolDisabled(t){return this.TOOL_STATES[t]===!1}};function Lc(e){let t=Uc.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}var _p="settings.json",vp="must use https unless it points at localhost/loopback for local development";function mr(){return Dc.join(dr.getConfigDir(),_p)}function jc(e){if((0,Bs.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function bp(e){let t=e.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!t)return!1;let n=Number.parseInt(t[1],16),r=Number.parseInt(t[2],16);if(!Number.isFinite(n)||!Number.isFinite(r))return!1;let o=[n>>8&255,n&255,r>>8&255,r&255].join(".");return jc(o)}function Sp(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,Bs.isIP)(t);return n===4?jc(t):n===6?t==="::1"||bp(t):!1}function Vs(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:"&&Sp(n.hostname)))throw new Error(`${t} ${vp}`)}var Et={"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");Vs(e)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."},"ui.suppressFeed":{type:"boolean",description:"When true, generated images/music are not auto-submitted to the public Made-with-Visa feed."},"tools.meta":{type:"boolean",description:"Show category meta-tools (generate_image, generate_video, generate_music, run_llm, ...). Restart required.",requiresRestart:!0},"tools.discover":{type:"boolean",description:"Show the dynamic-catalog tools (discover_tools, execute_tool). Restart required.",requiresRestart:!0},"merchants.discover":{type:"string",description:'Platform-merchant JIT tool discovery: "all" = every live merchant, "off" = none, comma-separated slugs = exactly those. Equivalent to VISA_MERCHANT_DISCOVER / VISA_MERCHANT_SLUGS env. Restart required.',requiresRestart:!0,validate:e=>{if(typeof e!="string")throw new Error("merchants.discover must be a string");let t=e.trim().toLowerCase();if(t===""||t==="all"||t==="off"||t==="*")return;let n=/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/,r=e.split(",").map(o=>o.trim()).filter(Boolean);for(let o of r)if(!n.test(o))throw new Error(`merchants.discover: "${o}" is not a valid merchant slug`)}},"credit.sessionCapCents":{type:"number",description:"Default cap (in cents) for start_session and pay-as-you-go one-shot approvals. Server clamps to [10, 10000] = $0.10\u2013$100. Default 500 ($5).",validate:e=>{if(typeof e!="number"||!Number.isFinite(e))throw new Error("credit.sessionCapCents must be a number");if(!Number.isInteger(e))throw new Error("credit.sessionCapCents must be a whole number of cents (no fractional cents)");if(e<10||e>1e4)throw new Error("credit.sessionCapCents must be between 10 ($0.10) and 10000 ($100)")}}},Ks=500,fo={"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 Jt(){let e=mr();if(!Tt.existsSync(e))return{};try{let t=Tt.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?(p.warn("settings:corrupt",{path:Lc(e),reason:"not_object"}),{}):n}catch(t){return p.warn("settings:corrupt",{path:Lc(e),error:t?.message||String(t)}),{}}}function Hs(e){dr.ensureConfigDir();let t=mr(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
122
+ `;Tt.writeFileSync(n,r,{mode:384}),Tt.renameSync(n,t)}function Gs(e){let t=Jt()[e];return typeof t=="string"?t:void 0}function go(e){let t=Jt()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function zs(e){let t=Jt()[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 it=class extends Error{constructor(t){let n=Object.keys(Et).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"}},at=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"}},Ct=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+fo[t]),this.name="RetiredSettingKeyError"}},Fc=["biometric.","spending.","account.","cards.","biometric"];function ho(e,t){if(Fc.some(s=>e.startsWith(s)))throw new at(e);if(e in fo)throw new Ct(e);let n=Et[e];if(!n)throw new it(e);let r;if(n.type==="boolean")if(typeof t=="boolean")r=t;else if(typeof t=="string"){let s=t.toLowerCase();if(s==="true")r=!0;else if(s==="false")r=!1;else throw new Error(`${e} expects true or false (got: ${JSON.stringify(t)})`)}else throw new Error(`${e} expects a boolean (got: ${typeof t})`);else if(n.type==="number")if(typeof t=="number")r=t;else if(typeof t=="string"&&t.trim().length>0){let s=Number(t);if(!Number.isFinite(s))throw new Error(`${e} expects a number (got: ${JSON.stringify(t)})`);r=s}else throw new Error(`${e} expects a number (got: ${typeof t})`);else{if(typeof t!="string"||t.length===0)throw new Error(`${e} expects a non-empty string`);r=t}n.validate&&n.validate(r);let o=Jt();return o[e]=r,Hs(o),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:mr()}}function yo(e){if(Fc.some(s=>e.startsWith(s)))throw new at(e);let t=Et[e];if(e in fo){let s=Jt(),i=e in s;return i&&(delete s[e],Hs(s)),{key:e,removed:i,requiresRestart:!1,path:mr()}}if(!t)throw new it(e);let r=Jt(),o=e in r;return o&&(delete r[e],Hs(r)),{key:e,removed:o,requiresRestart:o&&!!t.requiresRestart,path:mr()}}function qc(){let e=Jt();return Object.entries(fo).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}var wp="https://auth.visacli.sh",xp="https://auth-visa-code-preview.up.railway.app";function kp(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function Cp(){try{let e=Jn();return kp(e.version)}catch{return!1}}function Tp(e){return e.envVar!==void 0&&e.envVar!==""?(Vs(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(Vs(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?xp:wp}function _e(){return Tp({envVar:process.env.VISA_AUTH_URL,settingValue:Gs("auth.serverUrl"),isPrerelease:Cp()})}function Vc(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":go("ui.suppressBrowser")??!1}function Hc(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":go("ui.suppressFeed")??!1}function Bc(){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=zs("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):Ks}var Ep="CARD_REENROLLMENT_REQUIRED",Ap="https://auth.visacli.sh/enroll-card";function Rp(){try{return new URL("/enroll-card",_e()).toString()}catch{return Ap}}function Ip(e){let t=Rp();if(typeof e!="string")return t;try{let n=new URL(e),r=new URL(t);if(n.origin===r.origin&&n.pathname==="/enroll-card")return n.toString()}catch{}return p.warn("card-reenroll:reenroll_url_rejected_fallback",{reason:"untrusted_or_malformed_reenroll_url",fallbackPath:"/enroll-card"}),t}var pr="2.6.0-rc.8",$p=/^vk_[A-Za-z0-9_-]{32,}$/;function Pp(e){if(typeof e!="string")return null;switch(e){case"BUDGET_CLOSED":case"BUDGET_NOT_FOUND":case"BUDGET_EXPIRED":return e;default:return null}}function Kc(e){return e==="TOPUP_CHARGE_AMBIGUOUS"||e==="TOPUP_RECONCILIATION_REQUIRED"?e:null}var Op="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function An(e){return typeof e=="string"?e.trim():""}function Gc(e){let t=e&&typeof e=="object"?e:{},n=An(t.error)||An(t.message);if(!n)return Op;let r=An(t.error_code),o=[["surface",An(t.disabled_surface)],["flag",An(t.flag)],["correlation_id",An(t.correlation_id)]].filter(([,i])=>i).map(([i,a])=>`${i}=${a}`),s=o.length?` (${o.join(" ")})`:"";return r?`503 [${r}] ${n}${s}`:`503 ${n}${s}`}function zc(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?$p.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(`
123
+ `)}var xe=class{constructor(t){this.getSessionToken=t;this.baseUrl=_e()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!Ve()){let r=t.headers.get("X-Latest-Version");r&&Pc(r,pr)&&(this.lastSignals.updateAvailable={currentVersion:pr,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return pr}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new zt(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(Gc(n))}async request(t,n,r,o,s,i){let a=await this.getSessionToken();if(!a)throw new Error(zc());let l={Authorization:`Bearer ${a}`};s&&(t==="GET"?l["X-User-Context"]=encodeURIComponent(s.replace(/[\r\n\0]/g," ").slice(0,1e3)):r={...r||{},user_context:s}),i&&(l["X-Visa-Meta-Tool"]=i),r&&(l["Content-Type"]="application/json");let c;try{c=await Gt(`${this.baseUrl}${n}`,{method:t,headers:{...l,"X-Visa-CLI-Version":pr,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:o})}catch(d){throw new Error(Us(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===Ep){let f=typeof u?.last4=="string"?u.last4:"",m=typeof u?.brand=="string"?u.brand:"card",_=Ip(u?.reenroll_url),S=f?`${m} ending in ${f}`:"your card";throw new Error(`Please re-add ${S} to keep payments running. Open: ${_}`)}let d=Kc(u?.error_code);if(d)throw new st(u?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",d,{transactionId:typeof u?.transactionId=="string"?u.transactionId:void 0,retryable:!!u?.retryable,reconciliationRequired:u?.reconciliation_required!==!1});if(u?.declined){let f=Number(u.retryAfter??c.headers.get("Retry-After"));throw new ue(u.error||"Your card was declined.",!!u.retryable,u.code,u.reason,u.payment_error_class,u.correlation_id,u.transactionId,Number.isFinite(f)&&f>0?f:void 0)}if(c.status===402){let f=u?.error||"Gateway returned 402",m=typeof u?.error_code=="string"?u.error_code:"";throw m==="SPENDING_LIMIT_EXCEEDED"||m==="DAILY_LIMIT_EXCEEDED"||m==="PER_TXN_LIMIT_EXCEEDED"?new Error(`${f}. Check your limits with get_status or run: visa-cli update-spending-controls`):new Error(f)}throw new Error(u?.error||`Request failed (${c.status}). Try again.`)}return u}async shortcut(t,n,r,o,s){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,o,s)}async shortcutWithSession(t,n,r,o,s,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,l=await this.getSessionToken();if(!l)throw new Error(zc());let c={Authorization:`Bearer ${l}`,"X-Visa-CLI-Version":pr,"X-Source":"cli","Content-Type":"application/json"};i&&(c["X-Visa-Meta-Tool"]=i);let u={...n,...r};s&&(u.user_context=s.replace(/[\r\n\0]/g," ").slice(0,1e3));let d;try{d=await Gt(`${this.baseUrl}${a}`,{method:"POST",headers:c,body:JSON.stringify(u),timeoutMs:o})}catch(_){throw new Error(Us(_))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let _=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${_}s. Tip: use the batch tool to combine multiple requests into one.`)}let f=d.headers.get("X-Voucher-Receipt"),m;try{m=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(m),d.status===503){if(m?.error_code==="SESSION_LOCK_CONTENDED"){let $=Number(d.headers.get("Retry-After"))||1;throw new Wt(m?.message||m?.error||"Session budget is being modified by another request. Retry shortly.",$,d.status)}throw new Error(Gc(m))}let _=Pp(m?.error_code);if(_||d.status===410){let $=_??"BUDGET_CLOSED";throw new En(m?.message||m?.error||"Your session was invalidated by the server.",$,{budgetId:n.session_budget_id,status:d.status})}if(m?.declined){let $=Number(m.retryAfter??d.headers.get("Retry-After"));throw new ue(m.error||"Your card was declined.",!!m.retryable,m.code,m.reason,m.payment_error_class,m.correlation_id,m.transactionId,Number.isFinite($)&&$>0?$:void 0)}let S=Kc(m?.error_code);throw S?new st(m?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",S,{transactionId:typeof m?.transactionId=="string"?m.transactionId:void 0,retryable:!!m?.retryable,reconciliationRequired:m?.reconciliation_required!==!1}):new Error(m?.error||`Request failed (${d.status}). Try again.`)}return{data:m,voucherReceiptHeader:f}}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async catalogSearch(t,n,r,o){let s=r??"discover_tools",i=new URLSearchParams;t&&i.set("q",t),n&&i.set("category",n),o?.limit!=null&&i.set("limit",String(o.limit)),o?.offset!=null&&i.set("offset",String(o.offset));let a=i.toString();return this.request("GET",`/v1/catalog${a?`?${a}`:""}`,void 0,void 0,void 0,s)}async catalogTool(t,n){let r=n??"discover_tools";try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(t)}`,void 0,void 0,void 0,r)}catch{return null}}async discoverMerchantRoutes(t){try{return await this.request("GET",`/v1/platform/discover/${encodeURIComponent(t)}`)}catch{return null}}async listPublicMerchants(){try{let t=await Gt(`${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 Gt(`${this.baseUrl}/v1/platform/discover/${encodeURIComponent(t)}`,{method:"GET",timeoutMs:8e3});return n.ok?await n.json():null}catch{return null}}async paymentPreview(t,n){return this.request("POST","/v1/payment-preview",t,void 0,n)}async getBalance(){return this.request("GET","/v1/balance")}async topupBalance(t){return this.request("POST","/v1/balance/topup",t)}async createEnrollCode(){return this.request("POST","/v1/enroll-code")}async getAutoTopup(){let t=await this.getBalance();return{success:t.success,targetCents:t.autoTopupCents??null,thresholdCents:t.autoTopupThresholdCents??0}}async disableAutoTopup(){return this.request("PATCH","/v1/balance/auto-topup",{auto_topup_cents:null})}async createSessionBudget(t){return this.request("POST","/v1/session-budget/create",{...t,mode:"prepaid"})}async closeSession(t){return this.request("POST","/v1/session/close",{session_budget_id:t})}async getSessionBudget(t){return this.request("GET",`/v1/session-budget/${encodeURIComponent(t)}`)}async getSessionLedger(t){return this.request("GET",`/v1/session/${encodeURIComponent(t)}/ledger`)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getVisaSmi(t,n){return this.request("POST","/v1/visa/smi",t,6e4,n)}async getTransactions(t,n){let r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.offset!=null&&r.set("offset",String(t.offset));let o=r.toString(),s=o?`/v1/transactions?${o}`:"/v1/transactions";return this.request("GET",s,void 0,void 0,n)}async updateSpendingControls(t,n){return this.request("POST","/v1/spending-controls",t,void 0,n)}async removeCard(t,n,r){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(t))}`,n,void 0,r)}async setDefaultCard(t,n,r){return this.request("POST",`/v1/cards/${encodeURIComponent(String(t))}/default`,n,void 0,r)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t,n){return this.request("POST","/v1/attestation-key",{publicKey:t,...n?{attestation:n}:{}})}async startAttestationRecovery(t,n){return this.request("POST","/v1/attestation-key/recovery/start",{state:t},void 0,n)}async setBiometricPreference(t,n){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,n)}async logout(t,n){return this.request("POST","/v1/logout",t,void 0,n)}async feedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async createAppApiKey(t){return this.request("POST","/v1/api/keys",t)}async listAppApiKeys(){return this.request("GET","/v1/api/keys")}async revokeAppApiKey(t){return this.request("DELETE",`/v1/api/keys/${encodeURIComponent(String(t))}`)}async feedSubmit(t){return this.request("POST","/v1/feed",t)}async feedList(t){let n=new URLSearchParams;t?.tab&&n.set("tab",t.tab),t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset));let r=n.toString();return this.request("GET",`/v1/feed${r?"?"+r:""}`)}async feedVote(t,n){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/vote`,{direction:n})}async feedApprove(t){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/approve`)}async feedDelete(t){return this.request("DELETE",`/v1/feed/${encodeURIComponent(t)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async getFeedback(t,n){let r=new URLSearchParams;t&&r.set("limit",String(t));let o=r.toString();return this.request("GET",`/v1/feedback${o?"?"+o:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}};var g={};is(g,{BRAND:()=>sf,DIRTY:()=>Yt,EMPTY_PATH:()=>Up,INVALID:()=>R,NEVER:()=>Bf,OK:()=>de,ParseStatus:()=>ce,Schema:()=>N,ZodAny:()=>It,ZodArray:()=>dt,ZodBigInt:()=>Zt,ZodBoolean:()=>Qt,ZodBranded:()=>gr,ZodCatch:()=>dn,ZodDate:()=>en,ZodDefault:()=>un,ZodDiscriminatedUnion:()=>bo,ZodEffects:()=>Ie,ZodEnum:()=>cn,ZodError:()=>ve,ZodFirstPartyTypeKind:()=>I,ZodFunction:()=>wo,ZodIntersection:()=>on,ZodIssueCode:()=>h,ZodLazy:()=>sn,ZodLiteral:()=>an,ZodMap:()=>Mn,ZodNaN:()=>Ln,ZodNativeEnum:()=>ln,ZodNever:()=>Me,ZodNull:()=>nn,ZodNullable:()=>Ke,ZodNumber:()=>Xt,ZodObject:()=>be,ZodOptional:()=>Ae,ZodParsedType:()=>b,ZodPipeline:()=>hr,ZodPromise:()=>$t,ZodReadonly:()=>mn,ZodRecord:()=>So,ZodSchema:()=>N,ZodSet:()=>Nn,ZodString:()=>Rt,ZodSymbol:()=>Pn,ZodTransformer:()=>Ie,ZodTuple:()=>Be,ZodType:()=>N,ZodUndefined:()=>tn,ZodUnion:()=>rn,ZodUnknown:()=>ut,ZodVoid:()=>On,addIssueToContext:()=>v,any:()=>gf,array:()=>vf,bigint:()=>uf,boolean:()=>ol,coerce:()=>Hf,custom:()=>tl,date:()=>df,datetimeRegex:()=>Qc,defaultErrorMap:()=>ct,discriminatedUnion:()=>xf,effect:()=>Nf,enum:()=>Pf,function:()=>Rf,getErrorMap:()=>Rn,getParsedType:()=>He,instanceof:()=>cf,intersection:()=>kf,isAborted:()=>_o,isAsync:()=>In,isDirty:()=>vo,isValid:()=>At,late:()=>af,lazy:()=>If,literal:()=>$f,makeIssue:()=>fr,map:()=>Ef,nan:()=>lf,nativeEnum:()=>Of,never:()=>yf,null:()=>ff,nullable:()=>Uf,number:()=>rl,object:()=>bf,objectUtil:()=>Ws,oboolean:()=>Vf,onumber:()=>qf,optional:()=>Lf,ostring:()=>Ff,pipeline:()=>jf,preprocess:()=>Df,promise:()=>Mf,quotelessJson:()=>Mp,record:()=>Tf,set:()=>Af,setErrorMap:()=>Lp,strictObject:()=>Sf,string:()=>nl,symbol:()=>mf,transformer:()=>Nf,tuple:()=>Cf,undefined:()=>pf,union:()=>wf,unknown:()=>hf,util:()=>U,void:()=>_f});var U;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},e.getValidEnumValues=o=>{let s=e.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return e.objectValues(i)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},e.find=(o,s)=>{for(let i of o)if(s(i))return i},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(U||(U={}));var Ws;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Ws||(Ws={}));var b=U.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),He=e=>{switch(typeof e){case"undefined":return b.undefined;case"string":return b.string;case"number":return Number.isNaN(e)?b.nan:b.number;case"boolean":return b.boolean;case"function":return b.function;case"bigint":return b.bigint;case"symbol":return b.symbol;case"object":return Array.isArray(e)?b.array:e===null?b.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?b.promise:typeof Map<"u"&&e instanceof Map?b.map:typeof Set<"u"&&e instanceof Set?b.set:typeof Date<"u"&&e instanceof Date?b.date:b.object;default:return b.unknown}};var h=U.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"]),Mp=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ve=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,l=0;for(;l<i.path.length;){let c=i.path[l];l===i.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(i))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return o(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,U.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];n[s]=n[s]||[],n[s].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};ve.create=e=>new ve(e);var Np=(e,t)=>{let n;switch(e.code){case h.invalid_type:e.received===b.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case h.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,U.jsonStringifyReplacer)}`;break;case h.unrecognized_keys:n=`Unrecognized key(s) in object: ${U.joinValues(e.keys,", ")}`;break;case h.invalid_union:n="Invalid input";break;case h.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${U.joinValues(e.options)}`;break;case h.invalid_enum_value:n=`Invalid enum value. Expected ${U.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}"`:U.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,U.assertNever(e)}return{message:n}},ct=Np;var Wc=ct;function Lp(e){Wc=e}function Rn(){return Wc}var fr=e=>{let{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)a=c(i,{data:t,defaultError:a}).message;return{...o,path:s,message:a}},Up=[];function v(e,t){let n=Rn(),r=fr({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===ct?void 0:ct].filter(o=>!!o)});e.common.issues.push(r)}var ce=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let o of n){if(o.status==="aborted")return R;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let o of n){let s=await o.key,i=await o.value;r.push({key:s,value:i})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let o of n){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return R;s.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:t.value,value:r}}},R=Object.freeze({status:"aborted"}),Yt=e=>({status:"dirty",value:e}),de=e=>({status:"valid",value:e}),_o=e=>e.status==="aborted",vo=e=>e.status==="dirty",At=e=>e.status==="valid",In=e=>typeof Promise<"u"&&e instanceof Promise;var k;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(k||(k={}));var Re=class{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Jc=(e,t)=>{if(At(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new ve(e.common.issues);return this._error=n,this._error}}};function O(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(i,a)=>{let{message:l}=e;return i.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:o}}var N=class{get description(){return this._def.description}_getType(t){return He(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:He(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ce,ctx:{common:t.parent.common,data:t.data,parsedType:He(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(In(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:He(t)},o=this._parseSync({data:t,path:r.path,parent:r});return Jc(r,o)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:He(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return At(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=>At(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:He(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(In(o)?o:Promise.resolve(o));return Jc(r,s)}refine(t,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{let i=t(o),a=()=>s.addIssue({code:h.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Ie({schema:this,typeName:I.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Ae.create(this,this._def)}nullable(){return Ke.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return dt.create(this)}promise(){return $t.create(this,this._def)}or(t){return rn.create([this,t],this._def)}and(t){return on.create(this,t,this._def)}transform(t){return new Ie({...O(this._def),schema:this,typeName:I.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new un({...O(this._def),innerType:this,defaultValue:n,typeName:I.ZodDefault})}brand(){return new gr({typeName:I.ZodBranded,type:this,...O(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new dn({...O(this._def),innerType:this,catchValue:n,typeName:I.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return hr.create(this,t)}readonly(){return mn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Dp=/^c[^\s-]{8,}$/i,jp=/^[0-9a-z]+$/,Fp=/^[0-9A-HJKMNP-TV-Z]{26}$/i,qp=/^[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,Vp=/^[a-z0-9_-]{21}$/i,Hp=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Bp=/^[-+]?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)?)??$/,Kp=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Gp="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Js,zp=/^(?:(?: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])$/,Wp=/^(?:(?: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])$/,Jp=/^(([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]))$/,Yp=/^(([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])$/,Xp=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Zp=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Xc="((\\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])))",Qp=new RegExp(`^${Xc}$`);function Zc(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 ef(e){return new RegExp(`^${Zc(e)}$`)}function Qc(e){let t=`${Xc}T${Zc(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 tf(e,t){return!!((t==="v4"||!t)&&zp.test(e)||(t==="v6"||!t)&&Jp.test(e))}function nf(e,t){if(!Hp.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function rf(e,t){return!!((t==="v4"||!t)&&Wp.test(e)||(t==="v6"||!t)&&Yp.test(e))}var Rt=class e extends N{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==b.string){let s=this._getOrReturnCtx(t);return v(s,{code:h.invalid_type,expected:b.string,received:s.parsedType}),R}let r=new ce,o;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),v(o,{code:h.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),v(o,{code:h.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let i=t.data.length>s.value,a=t.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(t,o),i?v(o,{code:h.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&v(o,{code:h.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")Kp.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"email",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Js||(Js=new RegExp(Gp,"u")),Js.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"emoji",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")qp.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"uuid",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")Vp.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"nanoid",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")Dp.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"cuid",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")jp.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"cuid2",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")Fp.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"ulid",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),v(o,{validation:"url",code:h.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"regex",code:h.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),v(o,{code:h.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),v(o,{code:h.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),v(o,{code:h.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?Qc(s).test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{code:h.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?Qp.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{code:h.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?ef(s).test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{code:h.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?Bp.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"duration",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?tf(t.data,s.version)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"ip",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?nf(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"jwt",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?rf(t.data,s.version)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"cidr",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?Xp.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"base64",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?Zp.test(t.data)||(o=this._getOrReturnCtx(t,o),v(o,{validation:"base64url",code:h.invalid_string,message:s.message}),r.dirty()):U.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:h.invalid_string,...k.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...k.errToObj(t)})}url(t){return this._addCheck({kind:"url",...k.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...k.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...k.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...k.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...k.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...k.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...k.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...k.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...k.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...k.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...k.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...k.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...k.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...k.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...k.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...k.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...k.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...k.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...k.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...k.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...k.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...k.errToObj(n)})}nonempty(t){return this.min(1,k.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};Rt.create=e=>new Rt({checks:[],typeName:I.ZodString,coerce:e?.coerce??!1,...O(e)});function of(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/10**o}var Xt=class e extends N{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==b.number){let s=this._getOrReturnCtx(t);return v(s,{code:h.invalid_type,expected:b.number,received:s.parsedType}),R}let r,o=new ce;for(let s of this._def.checks)s.kind==="int"?U.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),v(r,{code:h.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),v(r,{code:h.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),v(r,{code:h.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?of(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),v(r,{code:h.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),v(r,{code:h.not_finite,message:s.message}),o.dirty()):U.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,k.toString(n))}gt(t,n){return this.setLimit("min",t,!1,k.toString(n))}lte(t,n){return this.setLimit("max",t,!0,k.toString(n))}lt(t,n){return this.setLimit("max",t,!1,k.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:k.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:k.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:k.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:k.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:k.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:k.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:k.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:k.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:k.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:k.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&U.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};Xt.create=e=>new Xt({checks:[],typeName:I.ZodNumber,coerce:e?.coerce||!1,...O(e)});var Zt=class e extends N{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==b.bigint)return this._getInvalidInput(t);let r,o=new ce;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),v(r,{code:h.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),v(r,{code:h.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),v(r,{code:h.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):U.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return v(n,{code:h.invalid_type,expected:b.bigint,received:n.parsedType}),R}gte(t,n){return this.setLimit("min",t,!0,k.toString(n))}gt(t,n){return this.setLimit("min",t,!1,k.toString(n))}lte(t,n){return this.setLimit("max",t,!0,k.toString(n))}lt(t,n){return this.setLimit("max",t,!1,k.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:k.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:k.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:k.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:k.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:k.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:k.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};Zt.create=e=>new Zt({checks:[],typeName:I.ZodBigInt,coerce:e?.coerce??!1,...O(e)});var Qt=class extends N{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==b.boolean){let r=this._getOrReturnCtx(t);return v(r,{code:h.invalid_type,expected:b.boolean,received:r.parsedType}),R}return de(t.data)}};Qt.create=e=>new Qt({typeName:I.ZodBoolean,coerce:e?.coerce||!1,...O(e)});var en=class e extends N{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==b.date){let s=this._getOrReturnCtx(t);return v(s,{code:h.invalid_type,expected:b.date,received:s.parsedType}),R}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return v(s,{code:h.invalid_date}),R}let r=new ce,o;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),v(o,{code:h.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),v(o,{code:h.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):U.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:k.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:k.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};en.create=e=>new en({checks:[],coerce:e?.coerce||!1,typeName:I.ZodDate,...O(e)});var Pn=class extends N{_parse(t){if(this._getType(t)!==b.symbol){let r=this._getOrReturnCtx(t);return v(r,{code:h.invalid_type,expected:b.symbol,received:r.parsedType}),R}return de(t.data)}};Pn.create=e=>new Pn({typeName:I.ZodSymbol,...O(e)});var tn=class extends N{_parse(t){if(this._getType(t)!==b.undefined){let r=this._getOrReturnCtx(t);return v(r,{code:h.invalid_type,expected:b.undefined,received:r.parsedType}),R}return de(t.data)}};tn.create=e=>new tn({typeName:I.ZodUndefined,...O(e)});var nn=class extends N{_parse(t){if(this._getType(t)!==b.null){let r=this._getOrReturnCtx(t);return v(r,{code:h.invalid_type,expected:b.null,received:r.parsedType}),R}return de(t.data)}};nn.create=e=>new nn({typeName:I.ZodNull,...O(e)});var It=class extends N{constructor(){super(...arguments),this._any=!0}_parse(t){return de(t.data)}};It.create=e=>new It({typeName:I.ZodAny,...O(e)});var ut=class extends N{constructor(){super(...arguments),this._unknown=!0}_parse(t){return de(t.data)}};ut.create=e=>new ut({typeName:I.ZodUnknown,...O(e)});var Me=class extends N{_parse(t){let n=this._getOrReturnCtx(t);return v(n,{code:h.invalid_type,expected:b.never,received:n.parsedType}),R}};Me.create=e=>new Me({typeName:I.ZodNever,...O(e)});var On=class extends N{_parse(t){if(this._getType(t)!==b.undefined){let r=this._getOrReturnCtx(t);return v(r,{code:h.invalid_type,expected:b.void,received:r.parsedType}),R}return de(t.data)}};On.create=e=>new On({typeName:I.ZodVoid,...O(e)});var dt=class e extends N{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==b.array)return v(n,{code:h.invalid_type,expected:b.array,received:n.parsedType}),R;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(v(n,{code:i?h.too_big:h.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(v(n,{code:h.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(v(n,{code:h.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>o.type._parseAsync(new Re(n,i,n.path,a)))).then(i=>ce.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new Re(n,i,n.path,a)));return ce.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:k.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:k.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:k.toString(n)}})}nonempty(t){return this.min(1,t)}};dt.create=(e,t)=>new dt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:I.ZodArray,...O(t)});function $n(e){if(e instanceof be){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Ae.create($n(r))}return new be({...e._def,shape:()=>t})}else return e instanceof dt?new dt({...e._def,type:$n(e.element)}):e instanceof Ae?Ae.create($n(e.unwrap())):e instanceof Ke?Ke.create($n(e.unwrap())):e instanceof Be?Be.create(e.items.map(t=>$n(t))):e}var be=class e extends N{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=U.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==b.object){let c=this._getOrReturnCtx(t);return v(c,{code:h.invalid_type,expected:b.object,received:c.parsedType}),R}let{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Me&&this._def.unknownKeys==="strip"))for(let c in o.data)i.includes(c)||a.push(c);let l=[];for(let c of i){let u=s[c],d=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Re(o,d,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Me){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")a.length>0&&(v(o,{code: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=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Re(o,d,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of l){let d=await u.key,f=await u.value;c.push({key:d,value:f,alwaysSet:u.alwaysSet})}return c}).then(c=>ce.mergeObjectSync(r,c)):ce.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return k.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:k.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:I.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of U.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 U.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return $n(this)}partial(t){let n={};for(let r of U.objectKeys(this.shape)){let o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let r of U.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Ae;)s=s._def.innerType;n[r]=s}return new e({...this._def,shape:()=>n})}keyof(){return el(U.objectKeys(this.shape))}};be.create=(e,t)=>new be({shape:()=>e,unknownKeys:"strip",catchall:Me.create(),typeName:I.ZodObject,...O(t)});be.strictCreate=(e,t)=>new be({shape:()=>e,unknownKeys:"strict",catchall:Me.create(),typeName:I.ZodObject,...O(t)});be.lazycreate=(e,t)=>new be({shape:e,unknownKeys:"strip",catchall:Me.create(),typeName:I.ZodObject,...O(t)});var rn=class extends N{_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new ve(a.ctx.common.issues));return v(n,{code:h.invalid_union,unionErrors:i}),R}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let l of r){let c={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(l=>new ve(l));return v(n,{code:h.invalid_union,unionErrors:a}),R}}get options(){return this._def.options}};rn.create=(e,t)=>new rn({options:e,typeName:I.ZodUnion,...O(t)});var lt=e=>e instanceof sn?lt(e.schema):e instanceof Ie?lt(e.innerType()):e instanceof an?[e.value]:e instanceof cn?e.options:e instanceof ln?U.objectValues(e.enum):e instanceof un?lt(e._def.innerType):e instanceof tn?[void 0]:e instanceof nn?[null]:e instanceof Ae?[void 0,...lt(e.unwrap())]:e instanceof Ke?[null,...lt(e.unwrap())]:e instanceof gr||e instanceof mn?lt(e.unwrap()):e instanceof dn?lt(e._def.innerType):[],bo=class e extends N{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.object)return v(n,{code:h.invalid_type,expected:b.object,received:n.parsedType}),R;let r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(v(n,{code:h.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),R)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let o=new Map;for(let s of n){let i=lt(s.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);o.set(a,s)}}return new e({typeName:I.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...O(r)})}};function Ys(e,t){let n=He(e),r=He(t);if(e===t)return{valid:!0,data:e};if(n===b.object&&r===b.object){let o=U.objectKeys(t),s=U.objectKeys(e).filter(a=>o.indexOf(a)!==-1),i={...e,...t};for(let a of s){let l=Ys(e[a],t[a]);if(!l.valid)return{valid:!1};i[a]=l.data}return{valid:!0,data:i}}else if(n===b.array&&r===b.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let s=0;s<e.length;s++){let i=e[s],a=t[s],l=Ys(i,a);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===b.date&&r===b.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var on=class extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=(s,i)=>{if(_o(s)||_o(i))return R;let a=Ys(s.value,i.value);return a.valid?((vo(s)||vo(i))&&n.dirty(),{status:n.value,value:a.data}):(v(r,{code:h.invalid_intersection_types}),R)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};on.create=(e,t,n)=>new on({left:e,right:t,typeName:I.ZodIntersection,...O(n)});var Be=class e extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.array)return v(r,{code:h.invalid_type,expected:b.array,received:r.parsedType}),R;if(r.data.length<this._def.items.length)return v(r,{code:h.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),R;!this._def.rest&&r.data.length>this._def.items.length&&(v(r,{code:h.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Re(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>ce.mergeArray(n,i)):ce.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Be.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Be({items:e,typeName:I.ZodTuple,rest:null,...O(t)})};var So=class e extends N{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.object)return v(r,{code:h.invalid_type,expected:b.object,received:r.parsedType}),R;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new Re(r,a,r.path,a)),value:i._parse(new Re(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?ce.mergeObjectAsync(n,o):ce.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof N?new e({keyType:t,valueType:n,typeName:I.ZodRecord,...O(r)}):new e({keyType:Rt.create(),valueType:t,typeName:I.ZodRecord,...O(n)})}},Mn=class extends N{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.map)return v(r,{code:h.invalid_type,expected:b.map,received:r.parsedType}),R;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,l],c)=>({key:o._parse(new Re(r,a,r.path,[c,"key"])),value:s._parse(new Re(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 R;(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 R;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}}}};Mn.create=(e,t,n)=>new Mn({valueType:t,keyType:e,typeName:I.ZodMap,...O(n)});var Nn=class e extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.set)return v(r,{code:h.invalid_type,expected:b.set,received:r.parsedType}),R;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(v(r,{code:h.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(v(r,{code:h.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(l){let c=new Set;for(let u of l){if(u.status==="aborted")return R;u.status==="dirty"&&n.dirty(),c.add(u.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((l,c)=>s._parse(new Re(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:k.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:k.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};Nn.create=(e,t)=>new Nn({valueType:e,minSize:null,maxSize:null,typeName:I.ZodSet,...O(t)});var wo=class e extends N{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.function)return v(n,{code:h.invalid_type,expected:b.function,received:n.parsedType}),R;function r(a,l){return fr({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Rn(),ct].filter(c=>!!c),issueData:{code:h.invalid_arguments,argumentsError:l}})}function o(a,l){return fr({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Rn(),ct].filter(c=>!!c),issueData:{code:h.invalid_return_type,returnTypeError:l}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof $t){let a=this;return de(async function(...l){let c=new ve([]),u=await a._def.args.parseAsync(l,s).catch(m=>{throw c.addIssue(r(l,m)),c}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,s).catch(m=>{throw c.addIssue(o(d,m)),c})})}else{let a=this;return de(function(...l){let c=a._def.args.safeParse(l,s);if(!c.success)throw new ve([r(l,c.error)]);let u=Reflect.apply(i,this,c.data),d=a._def.returns.safeParse(u,s);if(!d.success)throw new ve([o(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Be.create(t).rest(ut.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||Be.create([]).rest(ut.create()),returns:n||ut.create(),typeName:I.ZodFunction,...O(r)})}},sn=class extends N{get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};sn.create=(e,t)=>new sn({getter:e,typeName:I.ZodLazy,...O(t)});var an=class extends N{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return v(n,{received:n.data,code:h.invalid_literal,expected:this._def.value}),R}return{status:"valid",value:t.data}}get value(){return this._def.value}};an.create=(e,t)=>new an({value:e,typeName:I.ZodLiteral,...O(t)});function el(e,t){return new cn({values:e,typeName:I.ZodEnum,...O(t)})}var cn=class e extends N{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return v(n,{expected:U.joinValues(r),received:n.parsedType,code:h.invalid_type}),R}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return v(n,{received:n.data,code:h.invalid_enum_value,options:r}),R}return de(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})}};cn.create=el;var ln=class extends N{_parse(t){let n=U.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==b.string&&r.parsedType!==b.number){let o=U.objectValues(n);return v(r,{expected:U.joinValues(o),received:r.parsedType,code:h.invalid_type}),R}if(this._cache||(this._cache=new Set(U.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let o=U.objectValues(n);return v(r,{received:r.data,code:h.invalid_enum_value,options:o}),R}return de(t.data)}get enum(){return this._def.values}};ln.create=(e,t)=>new ln({values:e,typeName:I.ZodNativeEnum,...O(t)});var $t=class extends N{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.promise&&n.common.async===!1)return v(n,{code:h.invalid_type,expected:b.promise,received:n.parsedType}),R;let r=n.parsedType===b.promise?n.data:Promise.resolve(n.data);return de(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};$t.create=(e,t)=>new $t({type:e,typeName:I.ZodPromise,...O(t)});var Ie=class extends N{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===I.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:i=>{v(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return R;let l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?R:l.status==="dirty"?Yt(l.value):n.value==="dirty"?Yt(l.value):l});{if(n.value==="aborted")return R;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?R:a.status==="dirty"?Yt(a.value):n.value==="dirty"?Yt(a.value):a}}if(o.type==="refinement"){let i=a=>{let l=o.refinement(a,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?R:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?R:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!At(i))return R;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>At(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):R);U.assertNever(o)}};Ie.create=(e,t,n)=>new Ie({schema:e,typeName:I.ZodEffects,effect:t,...O(n)});Ie.createWithPreprocess=(e,t,n)=>new Ie({schema:t,effect:{type:"preprocess",transform:e},typeName:I.ZodEffects,...O(n)});var Ae=class extends N{_parse(t){return this._getType(t)===b.undefined?de(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ae.create=(e,t)=>new Ae({innerType:e,typeName:I.ZodOptional,...O(t)});var Ke=class extends N{_parse(t){return this._getType(t)===b.null?de(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ke.create=(e,t)=>new Ke({innerType:e,typeName:I.ZodNullable,...O(t)});var un=class extends N{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===b.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};un.create=(e,t)=>new un({innerType:e,typeName:I.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...O(t)});var dn=class extends N{_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return In(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ve(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ve(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};dn.create=(e,t)=>new dn({innerType:e,typeName:I.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...O(t)});var Ln=class extends N{_parse(t){if(this._getType(t)!==b.nan){let r=this._getOrReturnCtx(t);return v(r,{code:h.invalid_type,expected:b.nan,received:r.parsedType}),R}return{status:"valid",value:t.data}}};Ln.create=e=>new Ln({typeName:I.ZodNaN,...O(e)});var sf=Symbol("zod_brand"),gr=class extends N{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},hr=class e extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?R:s.status==="dirty"?(n.dirty(),Yt(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?R:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:I.ZodPipeline})}},mn=class extends N{_parse(t){let n=this._def.innerType._parse(t),r=o=>(At(o)&&(o.value=Object.freeze(o.value)),o);return In(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};mn.create=(e,t)=>new mn({innerType:e,typeName:I.ZodReadonly,...O(t)});function Yc(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function tl(e,t={},n){return e?It.create().superRefine((r,o)=>{let s=e(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Yc(t,r),l=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:l})}});if(!s){let i=Yc(t,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):It.create()}var af={object:be.lazycreate},I;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(I||(I={}));var cf=(e,t={message:`Input not instance of ${e.name}`})=>tl(n=>n instanceof e,t),nl=Rt.create,rl=Xt.create,lf=Ln.create,uf=Zt.create,ol=Qt.create,df=en.create,mf=Pn.create,pf=tn.create,ff=nn.create,gf=It.create,hf=ut.create,yf=Me.create,_f=On.create,vf=dt.create,bf=be.create,Sf=be.strictCreate,wf=rn.create,xf=bo.create,kf=on.create,Cf=Be.create,Tf=So.create,Ef=Mn.create,Af=Nn.create,Rf=wo.create,If=sn.create,$f=an.create,Pf=cn.create,Of=ln.create,Mf=$t.create,Nf=Ie.create,Lf=Ae.create,Uf=Ke.create,Df=Ie.createWithPreprocess,jf=hr.create,Ff=()=>nl().optional(),qf=()=>rl().optional(),Vf=()=>ol().optional(),Hf={string:(e=>Rt.create({...e,coerce:!0})),number:(e=>Xt.create({...e,coerce:!0})),boolean:(e=>Qt.create({...e,coerce:!0})),bigint:(e=>Zt.create({...e,coerce:!0})),date:(e=>en.create({...e,coerce:!0}))};var Bf=R;var Kf=/^[A-Za-z0-9._-]+$/,Gf=/^[A-Za-z0-9._-]+(\|[A-Za-z0-9._-]+)*$/,sl=new Set([".",".."]),ge=class extends Error{pattern;constructor(t,n){super(`Invalid freeReadPathPattern ${JSON.stringify(n)}: ${t}`),this.pattern=n,this.name="FreePathPatternError"}};function zf(e,t){if(e==="*")return{raw:e,kind:"single"};if(e==="**")return{raw:e,kind:"multi"};if(e.startsWith("(")){let n=e.endsWith(")?"),r=e.endsWith(")");if(!n&&!r)throw new ge(`malformed alternation segment ${JSON.stringify(e)}`,t);let o=n?e.slice(1,-2):e.slice(1,-1);if(!Gf.test(o))throw new ge(`malformed alternation segment ${JSON.stringify(e)}`,t);let s=o.split("|");if(s.some(i=>sl.has(i)))throw new ge(`alternation segment ${JSON.stringify(e)} may not contain '.' or '..'`,t);return{raw:e,kind:n?"alt-optional":"alt",alternatives:s}}if(Kf.test(e)){if(sl.has(e))throw new ge(`literal segment ${JSON.stringify(e)} is not permitted`,t);return{raw:e,kind:"literal"}}throw new ge(`segment ${JSON.stringify(e)} must be '*', '**', a [A-Za-z0-9._-]+ literal, or (a|b) alternation`,t)}function Wf(e){if(typeof e!="string"||e.length===0)throw new ge("must be a non-empty string",String(e));if(!e.startsWith("/"))throw new ge("must start with '/'",e);if(e.slice(1).includes("//"))throw new ge("empty segments ('//') are not permitted",e);if(e.length>1&&e.endsWith("/"))throw new ge("must not end with '/'",e);let n=e.slice(1).split("/").map(s=>zf(s,e));if(n.filter(s=>s.kind==="multi").length>1)throw new ge("at most one '**' is permitted per pattern",e);if(n[0]?.kind==="multi")throw new ge("'**' may not be the first segment (a literal prefix anchor is required)",e);let o=n.findIndex(s=>s.kind==="alt-optional");if(o!==-1&&o!==n.length-1)throw new ge("optional alternation '(...)?' is only allowed as the final segment",e);return n}function Xs(e){Wf(e)}var il=["tempo","mpp_self","merchant_self"],al=["catalog_static","fal_direct","fal_queue","openrouter_chat","openrouter_image","platform_proxy","tempo_gateway","x402_gateway"],cl=["image","audio","queued_audio","video","queued_video","model_3d","llm","transcription","utility"],ll=["images[0].url","image.url","audio.url","audio_file.url","audio_url","video.url","model_mesh.url","text","choices[0].message.content","choices[0].message.images[0].image_url.url","request_id"];var Qs=g.object({inputPerMillion:g.number().positive(),outputPerMillion:g.number().positive(),contextWindow:g.number().int().positive().optional(),maxOutput:g.number().int().positive().optional(),perRequestFeeCents:g.number().nonnegative().optional()}),Jf=g.object({strategy:g.enum(["flat","token","band"]).optional(),pricingModel:g.enum(["per-call","per-token","band"]).optional(),priceCents:g.number().nonnegative().optional(),currency:g.string().optional(),display:g.string().optional(),estimate:g.boolean().optional(),source:g.string().optional(),priceBand:g.record(g.unknown()).optional(),tokenPricing:Qs.optional()}).passthrough(),ei=g.discriminatedUnion("type",[g.object({type:g.literal("shortcut"),routedPath:g.string().min(1).startsWith("/")}),g.object({type:g.literal("custom"),merchantSlug:g.string().min(1),subPath:g.string().optional()}),g.object({type:g.literal("local"),fn:g.string().min(1)}),g.object({type:g.literal("read")})]),ti=g.object({amount:g.number().nonnegative(),currency:g.string().length(3).optional(),display:g.string().optional(),free:g.boolean().optional(),batchDiscount:g.number().min(0).max(100).optional()}),ul=g.object({attestation:g.boolean().optional(),rateLimitMs:g.number().positive().optional()}),dl=g.object({displayName:g.string().optional(),feedbackEligible:g.boolean().optional(),suggestionEligible:g.boolean().optional(),batchable:g.boolean().optional()}),ml=g.object({enabled:g.boolean().optional(),gatewayPath:g.string().min(1).startsWith("/").optional(),method:g.enum(["GET","POST","PUT","PATCH","DELETE"]).optional(),timeoutMs:g.number().int().positive().max(12e4).optional()}).strict(),Yf=g.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),Xf=120,Zf=120,Qf=1200,eg=/^[^\u0000-\u001F\u007F]+$/;function Zs(e,t){return g.string().min(1).max(e).regex(eg,`${t} must not contain control characters`)}var ni={id:g.string().min(1),name:Zs(Xf,"name"),description:Zs(Qf,"description"),provider:g.string().min(1),model:g.string().min(1),category:Yf,priceCents:g.number().nonnegative(),inputSchema:g.record(g.unknown()),gatewayUrl:g.string().min(1),merchantName:Zs(Zf,"merchantName"),isAsync:g.boolean().optional(),pollUrl:g.string().optional(),pollInterval:g.number().positive().optional(),pollTimeout:g.number().positive().optional(),tags:g.array(g.string()).optional(),tokenPricing:Qs.optional(),priceDisplay:g.string().optional(),pricingModel:g.enum(["per-call","per-token","band"]).optional(),pricingInfo:Jf.optional(),status:g.enum(["available","unavailable"]).optional(),handler:ei.optional(),pricing:ti.optional(),security:ul.optional(),engagement:dl.optional(),gatewayConfig:ml.optional(),freeReadPathPattern:g.string().optional().superRefine((e,t)=>{if(e!==void 0)try{Xs(e)}catch(n){t.addIssue({code:g.ZodIssueCode.custom,message:n instanceof Error?n.message:String(n)})}}),enabled:g.boolean().optional(),beta:g.boolean().optional(),deprecated:g.boolean().optional(),internal:g.boolean().optional(),replacementTool:g.string().optional(),minCliVersion:g.string().optional(),sunsetAt:g.string().optional(),rail:g.enum(il).optional(),executionKind:g.enum(al).optional(),resultKind:g.enum(cl).optional(),extractionMode:g.enum(ll).optional(),pricingStrategy:g.enum(["flat","token","band"]).optional()},pl=g.object({...ni,dispatch:g.literal("routed"),routedPath:g.string().min(1).startsWith("/")}).strict(),fl=g.object({...ni,dispatch:g.literal("enveloped")}).strict(),gl=g.object({...ni,handler:ei,pricing:ti}).strict(),hl=g.union([g.discriminatedUnion("dispatch",[pl,fl]),gl]);var ri=/^[a-z0-9][a-z0-9_-]*$/;var rg="https://fal.run",bl="https://openrouter.mpp.tempo.xyz",si=1024,ko=8192,og=4096,sg=10;function ig(e){return e>=sg?og:ko}function Sl(e,t){let n=typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):si;return Math.min(n,t)}function ag(e){let{attestation:t,tool_id:n,...r}=e;return r}var yl={"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 xo(e){let{attestation:t,tool_id:n,aspect_ratio:r,image_size:o,...s}=e,i={...s};return typeof o=="string"&&o.length>0?(i.image_size=o,i):(typeof r=="string"&&yl[r]&&(i.image_size=yl[r]),i)}function cg(e){let{attestation:t,tool_id:n,...r}=e;return r}function _l(e){let t={chain:e.chain,token_address:e.token_address};if(e.start_timestamp){let n=e.end_timestamp||new Date().toISOString(),r=e.time_granularity;if(!r){let o=new Date(e.start_timestamp).getTime();(new Date(n).getTime()-o)/(1e3*60*60*24)<=2?r="1h":r="1d"}return{addresses:[t],start_timestamp:e.start_timestamp,end_timestamp:n,time_granularity:r}}return[t]}function lg(e,t,n,r,o,s,i,a,l){return{id:e,name:t,description:n,provider:r,model:o.replace(/^\//,""),category:s,gatewayUrl:`https://${r}${o}`,merchantName:t,inputSchema:a,handler:{type:"custom",merchantSlug:r,subPath:o},pricing:{amount:i,currency:"USD",display:`$${(i/100).toFixed(2)}`},priceCents:i,tags:[],...l}}function ug(e,t,n,r,o,s,i,a){return lg(e,t,n,"suno-ai",r,o,s,i,{merchantName:"Suno AI",...a})}function te(e,t,n,r,o,s,i,a){return{dispatch:"routed",id:e,name:t,description:n,provider:"fal",model:r,category:o,priceCents:s,inputSchema:i,routedPath:`/api/v1/fal/${r}`,gatewayUrl:`${rg}/${r}`,merchantName:"fal.ai",buildBody:ag,tags:[],...a}}function dg(e,t=ko){return n=>{let{attestation:r,tool_id:o,prompt:s,system_prompt:i,max_tokens:a,max_completion_tokens:l,temperature:c,...u}=n;return{model:e,messages:[...i?[{role:"system",content:i}]:[],{role:"user",content:s}],temperature:c??.7,...u,max_tokens:Sl(a??l,t)}}}function mg(e,t=ko){return n=>{let{attestation:r,tool_id:o,prompt:s,image_url:i,aspect_ratio:a,max_tokens:l,max_completion_tokens:c,temperature:u,...d}=n,f=[{type:"text",text:s}];return typeof i=="string"&&i.length>0&&f.push({type:"image_url",image_url:{url:i}}),{model:e,messages:[{role:"user",content:f}],temperature:u??.7,...typeof a=="string"&&a.length>0?{image_config:{aspect_ratio:a}}:{},...d,max_tokens:Sl(l??c,t)}}}function X(e,t,n,r,o,s,i){let a=i?.maxOutputTokens??ig(s),l=i?.perRequestFeeCents??0,c=500/1e6*o*100,u=500/1e6*s*100,d=Math.max(1,Math.ceil(c+u+l)),{perRequestFeeCents:f,maxOutputTokens:m,..._}=i??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"llm",priceCents:d,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The prompt or question to send to the model"},system_prompt:{type:"string",description:"Optional system prompt to set model behavior"},max_tokens:{type:"integer",description:`Maximum tokens in response (default: ${si}); values above ${a} are clamped to ${a}`,minimum:1,maximum:a},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${bl}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:dg(r,a),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:o,outputPerMillion:s,...l>0?{perRequestFeeCents:l}:{}},..._}}function oi(e,t,n,r,o,s){let i=s?.maxOutputTokens??ko,{maxOutputTokens:a,...l}=s??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"image",pricingStrategy:"band",priceCents:o,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate or edit"},image_url:{type:"string",description:"Optional source image URL for edits"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"1:1"},max_tokens:{type:"integer",description:`Maximum text tokens in response metadata (default: ${si}); values above ${i} are clamped to ${i}`,minimum:1,maximum:i},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${bl}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:mg(r,i),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...l}}var ii=[te("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"]}),te("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:xo}),te("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:xo}),te("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:xo}),te("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"]}),oi("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),oi("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}}),oi("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}}),te("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"]}),te("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"]}),te("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"]}),te("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"]}),te("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"]}),te("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"]}),te("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"]}),te("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"]}),te("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"]}),ug("suno-music","Suno Music","AI music generation. Create full songs with vocals or instrumentals.","/suno/generate-music","audio",10,{type:"object",properties:{prompt:{type:"string",description:"Description of the song (genre, mood, instruments)"},instrumental:{type:"boolean",description:"Instrumental only, no vocals",default:!1}},required:["prompt"]},{isAsync:!0,pollUrl:"https://api.sunoapi.org/suno/get-music-status",deprecated:!0,tags:["music","song","vocals","instrumental"],buildBody:e=>{let{attestation:t,tool_id:n,prompt:r,instrumental:o,...s}=e;return{prompt:r,customMode:!1,instrumental:typeof o=="boolean"?o:!1,model:"V4",...s}}}),te("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"]}),te("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"]}),te("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"]}),te("fal-whisper","Whisper Transcription","Transcribe audio to text. Supports multiple languages.","fal-ai/whisper","transcription",2,{type:"object",properties:{audio_url:{type:"string",description:"URL of the audio to transcribe"},language:{type:"string",description:"Language code (e.g. en, es, fr)"}},required:["audio_url"]},{tags:["transcription","speech-to-text","whisper"]}),X("or-gpt-4o","GPT-4o","OpenAI's flagship multimodal model. Best for complex reasoning and analysis.","openai/gpt-4o",2.5,10,{tags:["llm","gpt","openai","multimodal","reasoning"]}),X("or-gpt-55","GPT-5.5","OpenAI frontier model for complex professional reasoning, coding, and long-context analysis.","openai/gpt-5.5",5,30,{tags:["llm","gpt","openai","frontier","reasoning","coding","long-context"]}),X("or-gpt-55-pro","GPT-5.5 Pro","OpenAI high-capability frontier model optimized for deep reasoning and high-stakes workloads.","openai/gpt-5.5-pro",30,180,{tags:["llm","gpt","openai","frontier","pro","deep-reasoning","coding","long-context"]}),X("or-gpt-4o-mini","GPT-4o Mini","Fast, affordable GPT-4o. Great for everyday tasks, chat, and simple analysis.","openai/gpt-4o-mini",.15,.6,{tags:["llm","gpt","openai","fast","cheap"]}),X("or-claude-opus","Claude Opus 4.7","Anthropic's most capable model. 1M context, reasoning, best for complex tasks.","anthropic/claude-opus-4.7",15,75,{tags:["llm","claude","anthropic","reasoning","coding"]}),X("or-claude-sonnet","Claude Sonnet 4.6","Anthropic's best balance of intelligence and speed. Excellent for coding and analysis.","anthropic/claude-sonnet-4.6",3,15,{tags:["llm","claude","anthropic","coding","analysis"]}),X("or-claude-opus-fast","Claude Opus 4.6 Fast","Fast Opus variant with lower latency.","anthropic/claude-opus-4.6-fast",15,75,{tags:["llm","claude","anthropic","fast"]}),X("or-claude-haiku","Claude 3.5 Haiku","Anthropic's fastest model. Great for quick tasks, chat, and simple reasoning.","anthropic/claude-3.5-haiku",.8,4,{tags:["llm","claude","anthropic","fast"]}),X("or-gemini-pro","Gemini 2.0 Flash","Google's fast multimodal model. Good for general tasks with long context.","google/gemini-2.0-flash-001",.1,.4,{tags:["llm","gemini","google","multimodal","fast","cheap"]}),X("or-gemini-3-flash","Gemini 3 Flash","Google's high-speed thinking model for agentic workflows, coding, and multimodal tasks.","google/gemini-3-flash-preview",.5,3,{tags:["llm","gemini","google","agentic","coding","fast"]}),X("or-gemini-3-pro","Gemini 3 Pro","Google's flagship frontier model for deep reasoning, multimodal analysis, and agentic coding.","google/gemini-3-pro-preview",2,12,{tags:["llm","gemini","google","reasoning","coding","multimodal"]}),X("or-gemini-35-flash","Gemini 3.5 Flash","Google frontier Flash model for multimodal reasoning, coding, and parallel agentic workflows.","google/gemini-3.5-flash",1.5,9,{tags:["llm","gemini","google","frontier","multimodal","reasoning","coding","fast"]}),X("or-gemini-3-lite","Gemini 3.1 Flash Lite","Google's efficient multimodal model optimized for low-latency, high-volume agent workloads.","google/gemini-3.1-flash-lite",.25,1.5,{tags:["llm","gemini","google","fast","cheap","multimodal"]}),X("or-llama-70b","Llama 3.3 70B","Meta's best open model. Strong reasoning, fully open-source.","meta-llama/llama-3.3-70b-instruct",.3,.4,{tags:["llm","llama","meta","open-source","reasoning"]}),X("or-llama-8b","Llama 3.1 8B","Fast, lightweight open model. Great for simple tasks at minimal cost.","meta-llama/llama-3.1-8b-instruct",.05,.08,{tags:["llm","llama","meta","open-source","fast","cheap"]}),X("or-mistral-large","Mistral Large","Mistral's flagship model. Strong at multilingual and European languages.","mistralai/mistral-large-2411",2,6,{tags:["llm","mistral","multilingual","european"]}),X("or-mistral-small","Mistral Small","Fast, efficient Mistral model. Good for everyday tasks.","mistralai/mistral-small-3.1-24b-instruct",.1,.3,{tags:["llm","mistral","fast","cheap"]}),X("or-deepseek-chat","DeepSeek Chat V3","Strong reasoning model at very low cost. Excellent for coding and math.","deepseek/deepseek-chat-v3-0324",.3,.88,{tags:["llm","deepseek","coding","math","cheap","reasoning"]}),X("or-deepseek-r1","DeepSeek R1","Advanced reasoning model with chain-of-thought. Best for complex problems.","deepseek/deepseek-r1",.55,2.19,{tags:["llm","deepseek","reasoning","chain-of-thought","math"]}),X("or-qwen-72b","Qwen 2.5 72B","Alibaba's large model. Strong at coding, math, and multilingual tasks.","qwen/qwen-2.5-72b-instruct",.3,.4,{tags:["llm","qwen","alibaba","coding","multilingual"]}),X("or-phi-4","Phi-4","Microsoft's compact reasoning model. Punches above its weight for size.","microsoft/phi-4",.07,.14,{tags:["llm","phi","microsoft","compact","cheap","reasoning"]}),X("or-perplexity-sonar","Perplexity Sonar","Search-augmented LLM. Answers with real-time web sources and citations.","perplexity/sonar",1,1,{perRequestFeeCents:.5,tags:["llm","perplexity","search","web","citations","real-time"]}),{dispatch:"enveloped",id:"query_onchain_prices",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly and daily granularity.",provider:"allium",model:"allium-prices",category:"onchain",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly) or '1d' (daily). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",internal:!0,executionKind:"x402_gateway",resultKind:"utility",gatewayConfig:{enabled:!1,gatewayPath:"/gateway",method:"POST",timeoutMs:3e4},buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:_l,tags:["onchain","prices","allium","crypto"]},{dispatch:"enveloped",id:"parallel-search-tempo",name:"Parallel Search (Tempo)",description:"Internal Tempo gateway route for Parallel's paid search endpoint.",provider:"parallel",model:"search",category:"utility",priceCents:1,inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query. Mapped by Parallel to objective when provided."},objective:{type:"string",description:"Search objective. Use with search_queries for advanced requests."},search_queries:{type:"array",items:{type:"string"},description:"Optional explicit search query list."},mode:{type:"string",enum:["one-shot","fast"],description:"Parallel search mode.",default:"one-shot"}},anyOf:[{required:["query"]},{required:["objective"]}]},gatewayUrl:"https://parallelmpp.dev/api/search",merchantName:"Parallel",internal:!0,rail:"tempo",executionKind:"tempo_gateway",resultKind:"utility",gatewayConfig:{enabled:!1,gatewayPath:"/gateway",method:"POST",timeoutMs:3e4},buildBody:cg,tags:["search","parallel","tempo","internal"]},{dispatch:"enveloped",id:"generate_image_card",name:"Generate Image (Ultra)",description:"Generate a high-quality AI image (FLUX Pro Ultra, 2K, ~$0.06).",provider:"fal",model:"fal-ai/flux-pro/v1.1-ultra",category:"image",priceCents:6,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1-ultra",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro-ultra",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),t},tags:["image","flux","ultra","legacy"]},{dispatch:"enveloped",id:"generate_image_fast_card",name:"Generate Image (Fast)",description:"Generate an AI image (FLUX Pro v1.1, 1K, ~$0.04).",provider:"fal",model:"fal-ai/flux-pro/v1.1",category:"image",priceCents:4,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro",buildBody:e=>xo({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"]},te("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"}),te("edit_image_seed_card","Edit Image (SeedEdit)","Inpaint/edit an image with a prompt using SeedEdit.","fal-ai/bytedance/seededit","image",5,{type:"object",properties:{image_url:{type:"string"},prompt:{type:"string"},seed:{type:"number"}},required:["image_url","prompt"]},{buildBody:e=>{let t={image_url:e.image_url,prompt:e.prompt};return e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","edit","inpaint","seededit"],deprecated:!0,replacementTool:"or-gemini-nano-banana"}),{dispatch:"enveloped",id:"generate_video_tempo_card",name:"Generate Video (Grok)",description:"Generate a video from a text prompt using Grok Imagine Video.",provider:"fal",model:"xai/grok-imagine-video/text-to-video",category:"video",priceCents:30,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/xai/grok-imagine-video/text-to-video",merchantName:"Grok Video via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),t},tags:["video","grok","legacy"]},{dispatch:"enveloped",id:"generate_video_kling_card",name:"Generate Video (Kling)",description:"Generate a video using Kling v1.6 (async, ~$0.40).",provider:"fal",model:"fal-ai/kling-video/v1.6/standard/text-to-video",category:"video",priceCents:40,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/kling-video/v1.6/standard/text-to-video",merchantName:"Kling via fal.ai",deprecated:!0,replacementTool:"fal-kling-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","kling","legacy"]},{dispatch:"enveloped",id:"generate_video_wan_card",name:"Generate Video (Wan)",description:"Generate a video using Wan T2V (async, ~$0.25).",provider:"fal",model:"fal-ai/wan/t2v-1.3b",category:"video",priceCents:25,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/wan/t2v-1.3b",merchantName:"Wan T2V via fal.ai",deprecated:!0,replacementTool:"fal-wan-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","wan","legacy"]},{dispatch:"enveloped",id:"generate_video_minimax_card",name:"Generate Video (MiniMax)",description:"Generate a video using MiniMax (async, ~$0.35).",provider:"fal",model:"fal-ai/minimax/video-01",category:"video",priceCents:35,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/minimax/video-01",merchantName:"MiniMax via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","minimax","legacy"]},{id:"check_fal_status",name:"Check fal Async Job Status",description:"Poll an async fal.ai queue job for completion. Free.",provider:"fal",model:"queue-status",category:"image",priceCents:0,inputSchema:{type:"object",properties:{model_path:{type:"string",description:"Model path (e.g. fal-ai/kling-video/v1.6/standard/text-to-video)"},request_id:{type:"string"}},required:["model_path","request_id"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue",merchantName:"fal.ai",handler:{type:"local",fn:"check_fal_status"},pricing:{amount:0,currency:"USD",display:"$0.00",free:!0},freeReadPathPattern:"/api/v1/fal/**/requests/*/(status)?",tags:["status","fal","async"]},{dispatch:"enveloped",id:"generate_3d_card",name:"Generate 3D Model",description:"Generate a 3D mesh from a text prompt using Meshy (async, ~$0.50).",provider:"fal",model:"fal-ai/meshy-ai/text-to-3d",category:"3d",priceCents:50,inputSchema:{type:"object",properties:{object_prompt:{type:"string"},style_prompt:{type:"string"},negative_prompt:{type:"string"},art_style:{type:"string"},seed:{type:"number"}},required:["object_prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/meshy-ai/text-to-3d",merchantName:"Meshy via fal.ai",deprecated:!0,replacementTool:"fal-trellis-3d",buildBody:e=>{let t={object_prompt:e.object_prompt};return e.style_prompt&&(t.style_prompt=e.style_prompt),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.art_style&&(t.art_style=e.art_style),e.seed!==void 0&&(t.seed=e.seed),t},tags:["3d","mesh","meshy","legacy"]},{dispatch:"enveloped",id:"generate_speech_card",name:"Generate Speech",description:"Text-to-speech using F5-TTS with optional voice cloning.",provider:"fal",model:"fal-ai/f5-tts",category:"tts",priceCents:3,inputSchema:{type:"object",properties:{gen_text:{type:"string",description:"Text to synthesize"},ref_audio_url:{type:"string",description:"Reference audio URL (for voice cloning)"},ref_text:{type:"string",description:"Transcription of ref audio"},remove_silence:{type:"boolean"}},required:["gen_text"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/f5-tts",merchantName:"fal.ai",buildBody:e=>{let t={gen_text:e.gen_text};return e.ref_audio_url&&(t.ref_audio_url=e.ref_audio_url),e.ref_text&&(t.ref_text=e.ref_text),e.remove_silence!==void 0&&(t.remove_silence=e.remove_silence),t},deprecated:!0,replacementTool:"fal-metavoice",tags:["tts","speech","f5-tts","legacy"]},{dispatch:"enveloped",id:"generate_music_tempo_card",name:"Generate Music (Suno) \u2014 retired",description:"[Retired] Suno music generation. Use `generate_music` (ACE-Step) instead.",enabled:!1,sunsetAt:"2026-06-25",provider:"suno",model:"suno-v4",category:"audio",priceCents:50,inputSchema:{type:"object",properties:{prompt:{type:"string"},instrumental:{type:"boolean"},model:{type:"string",default:"V4"}},required:["prompt"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/generate-music",merchantName:"Suno via Tempo",buildBody:e=>({prompt:e.prompt,customMode:!1,instrumental:e.instrumental??!1,model:e.model||"V4"}),isAsync:!0,pollUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",pollInterval:15e3,pollTimeout:3e5,deprecated:!0,replacementTool:"fal-ace-step-music",tags:["music","audio","suno","async","legacy"]},{dispatch:"enveloped",id:"check_music_status_tempo_card",name:"Check Music Status (Suno) \u2014 retired",description:"[Retired] Suno status poll. No replacement; ACE-Step jobs poll via `check_fal_status`.",enabled:!1,sunsetAt:"2026-06-25",provider:"suno",model:"suno-status",category:"audio",priceCents:0,inputSchema:{type:"object",properties:{taskId:{type:"string"}},required:["taskId"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",merchantName:"Suno Status",buildBody:e=>({taskId:e.taskId}),deprecated:!0,tags:["music","status","suno","legacy"]},{dispatch:"enveloped",id:"query_onchain_prices_card",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly, daily, and weekly granularity.",provider:"allium",model:"allium-prices",category:"llm",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly), '1d' (daily), or '1w' (weekly). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",deprecated:!0,replacementTool:"query_onchain_prices",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:_l,tags:["onchain","prices","allium","crypto","legacy"]}];function yr(e){return ii.find(t=>t.id===e)}var wl=1,xl=["pick_one","fan_out"],kl=["concat","dedupe_by_url","top_k_by_score"],gg=8,hg=g.object({type:g.string().min(1),description:g.string().min(1),enum:g.array(g.string()).optional(),default:g.unknown().optional(),minimum:g.number().optional(),maximum:g.number().optional()}),yg=g.object({toolId:g.string().min(1),notes:g.string().min(1)}),_g=g.string().regex(/^[a-z0-9_-]{1,32}$/,"tier key must be 1-32 chars [a-z0-9_-]"),vg=g.object({providers:g.array(g.string().min(1)).min(1).max(gg),merge:g.enum(kl),maxResults:g.number().int().positive().optional()}),Cl=g.object({mode:g.enum(xl).default("pick_one"),intro:g.string().min(1),defaultTier:g.string().min(1),tiers:g.record(_g,yg).refine(e=>Object.keys(e).length>0,{message:"must have at least one tier"}),fanOut:vg.optional(),guidance:g.string().min(1),inputProperties:g.record(g.string(),hg),required:g.array(g.string())}).refine(e=>e.tiers[e.defaultTier]!==void 0,{message:"defaultTier must exist in tiers",path:["defaultTier"]}).refine(e=>e.mode!=="fan_out"||e.fanOut!==void 0,{message:"fan_out mode requires fanOut config",path:["fanOut"]}).refine(e=>e.required.every(t=>t in e.inputProperties),{message:"required entries must exist in inputProperties",path:["required"]}),bg=g.object({version:g.literal(wl),generatedAt:g.string().datetime(),tools:g.record(g.string().regex(ri,"tool name must match MCP naming rules"),Cl).refine(e=>Object.keys(e).length>0,{message:"manifest must have at least one tool"})});var Eo=require("child_process"),Il=require("util"),$l=E(require("crypto")),me=E(require("fs")),Pl=E(require("os")),Ge=E(require("path"));var Un=(0,Il.promisify)(Eo.execFile),Ao=Ge.join(Pl.homedir(),".visa-mcp","bin"),pn=Ge.join(Ao,"Visa CLI"),xg=Ge.join(__dirname,"..","native"),Tl="6",El=Ge.join(Ao,"visa-keychain.version"),Al=Ge.join(Ao,"visa-keychain.sha256");function Rl(e){let t=me.readFileSync(e);return $l.createHash("sha256").update(t).digest("hex")}async function ci(){try{if(me.readFileSync(El,"utf-8").trim()===Tl&&me.existsSync(pn)){let r=me.readFileSync(Al,"utf-8").trim();if(Rl(pn)!==r)p.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),me.unlinkSync(pn);else return pn}}catch{}let e=Ge.join(xg,"visa-keychain.m");if(me.existsSync(e)||(e=Ge.resolve(__dirname,"..","..","native","visa-keychain.m")),me.existsSync(e)||(e=Ge.resolve(__dirname,"..","native","visa-keychain.m")),!me.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");me.mkdirSync(Ao,{recursive:!0,mode:448});try{await Un("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",pn,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=Rl(pn);return me.writeFileSync(Al,t,{mode:384}),me.writeFileSync(El,Tl,{mode:384}),pn}async function Ol(e){let t=await ci(),n;try{n=(await Un(t,e,{timeout:6e4})).stdout}catch(s){n=s.stdout||"";let i=n.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(s.stderr?.trim()||s.message||"Unknown error")}let r=n.trim();if(r.startsWith("OK:"))return r.slice(3);if(r==="OK")return;let o=r.startsWith("ERROR:")?r.slice(6):"Unknown error";throw new Error(o)}var ai=null;function ie(){return bn()?!0:process.platform!=="darwin"?!1:ai!==null?ai:(ai=!0,!0)}var Co="visa-cli",To="attestation-key";async function kg(e){try{await Un("security",["delete-generic-password","-s",Co,"-a",To],{timeout:5e3})}catch{}await Un("security",["add-generic-password","-s",Co,"-a",To,"-w",e],{timeout:5e3})}async function li(){try{let{stdout:e}=await Un("security",["find-generic-password","-s",Co,"-a",To,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Ro(){let e=await Ol(["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 kg(n),r}async function Ml(){return await li()!==null}async function Nl(){if(bn())return"mock-public-key-spki";let e=await li();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await ci();return new Promise((n,r)=>{let o=(0,Eo.execFile)(t,["public-key"],{timeout:6e4},(s,i)=>{let a=(i||"").trim();if(s){a.startsWith("ERROR:")?r(new Error(a.slice(6))):r(new Error(s.stderr?.trim()||s.message||"Unknown error"));return}a.startsWith("OK:")?n(a.slice(3)):r(new Error(a.startsWith("ERROR:")?a.slice(6):"Unknown error"))});o.stdin.write(e),o.stdin.end()})}async function Dn(e,t){if(bn())return Promise.resolve(ha());let n=await li();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await ci(),o=["sign",e];return t&&o.push(t),new Promise((s,i)=>{let a=(0,Eo.execFile)(r,o,{timeout:6e4},(l,c)=>{let u=(c||"").trim();if(l){u.startsWith("ERROR:")?i(new Error(u.slice(6))):i(new Error(l.stderr?.trim()||l.message||"Unknown error"));return}u.startsWith("OK:")?s(u.slice(3)):i(new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error"))});a.stdin.write(n),a.stdin.end()})}async function Io(){try{await Un("security",["delete-generic-password","-s",Co,"-a",To],{timeout:5e3})}catch{}try{await Ol(["delete-key"])}catch{}}var Cg=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],Tg=[...Cg.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 di(e,t=Tg){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=ui(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(ui(r.match.provider)))&&r.match.keywords.every(o=>n.includes(ui(o))))return r.targetToolId;return null}function ui(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}var _r={generate_image:{intro:'Generate an AI image from a text prompt \u2014 useful for hero shots, marketing assets, social posts, blog covers, app mockups, or any time the user asks for art, a logo, an icon, a thumbnail, or "a picture of \u2026". From $0.01 (fast) to $0.06 (pro), returns a hosted PNG/JPG URL. Default tier: balanced ($0.04, 1K, ~10s).',tiers:{balanced:{toolId:"fal-flux-pro",notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",notes:"Recraft V3 \u2014 vector/flat/illustration styles"}},guidance:"If the user didn't specify a tier, pick 'balanced' unless the prompt clearly signals otherwise (text \u2192 text_heavy, logo/icon \u2192 vector, quick test \u2192 fast, hero/print \u2192 pro).",inputProperties:{prompt:{type:"string",description:"Text description of the image to generate."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9", "1:1", "9:16".',default:"16:9"}},required:["prompt"]},generate_video:{intro:'Generate a short AI video from a text prompt \u2014 useful for product demos, social clips, mood reels, ad concepts, or any "make me a video of \u2026" request. $0.10\u2013$0.40 per ~6s clip depending on tier. Async: returns a request_id; use execute_tool with tool_id "check_fal_status" to resolve it (60\u2013180s).',tiers:{balanced:{toolId:"fal-minimax-video",notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",notes:"Kling \u2014 highest quality, cinematic"}},guidance:'Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate and are processed asynchronously. The response includes a request_id and model_path. Poll with execute_tool using tool_id "check_fal_status" and the exact request_id/model_path returned by the async response. Do not substitute the catalog model path manually. Do not poll more than once per 30 seconds.',inputProperties:{prompt:{type:"string",description:"Text description of the video scene."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9" or "9:16".',default:"16:9"}},required:["prompt"]},generate_music:{intro:'Generate an original music track from a prompt via ACE-Step. ~$0.02 for the default 60s track. Use for songs, backing tracks, jingles, vocal music, instrumental music, or any "make a song/music/track" request. Takes ~60-90s and may return a request_id to poll with check_fal_status. For SFX, chimes, ambient beds, or TTS, use generate_audio instead.',tiers:{ace_step:{toolId:"fal-ace-step-music",notes:"ACE-Step \u2014 prompt-to-music with vocals or instrumentals"}},guidance:"Use for songs and music tracks. Takes ~60-90s and may return a request_id to poll with check_fal_status. For sound effects, chimes, ambient beds, or TTS, use generate_audio instead.",inputProperties:{prompt:{type:"string",description:"Musical style, mood, instruments, subject, and lyrics direction."},instrumental:{type:"boolean",description:"True for instrumental music with no vocals; false for vocal tracks.",default:!1},duration:{type:"number",description:"Duration in seconds.",default:60}},required:["prompt"]},generate_audio:{intro:'Generate sound effects from a text prompt (sfx tier \u2014 default), or voice-cloned speech from text + a reference audio URL (tts tier). $0.03\u2013$0.04. Use for SFX, chimes, UI sounds, ambient audio (default sfx), or voice cloning when a reference audio URL is available (pass tier:"tts"). Default tier is sfx; pass tier:"tts" for voice cloning.',tiers:{sfx:{toolId:"fal-stable-audio",notes:"Stable Audio \u2014 sound effects and ambient from a prompt"},tts:{toolId:"fal-metavoice",notes:"MetaVoice \u2014 voice cloning TTS (requires a voice sample URL)"}},guidance:'Default tier is sfx: pass prompt describing the sound. For tts (voice cloning): pass tier:"tts" + text + audio_url.',inputProperties:{prompt:{type:"string",description:"Description of sound to generate (sfx tier, default)."},text:{type:"string",description:"Text to speak aloud (tts tier)."},audio_url:{type:"string",description:"URL of a voice sample to clone (tts tier, required for voice cloning)."}},required:[]},generate_3d:{intro:"Generate a 3D mesh (GLB) from an image URL via Trellis. ~$0.08, ~30\u201360s. Use when the user shares an image and asks for a 3D model, asset, AR-ready mesh, or game-ready GLB.",tiers:{trellis:{toolId:"fal-trellis-3d",notes:"Trellis \u2014 image-to-3D, returns a GLB mesh URL"}},guidance:"Pass an image URL. Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{image_url:{type:"string",description:"URL of the image to convert to a 3D model."}},required:["image_url"]},upscale_image:{intro:'Upscale an image to 4\xD7 resolution via Aura SR (preserves detail without hallucination). ~$0.03. Use whenever the user shares a low-res image and asks to "upscale", "make this higher resolution", "4x this", "enhance", or to print/export at larger size.',tiers:{aura:{toolId:"fal-aura-sr",notes:"Aura SR \u2014 default; preserves detail without hallucination"}},guidance:"Pass the existing image URL. Returns an upscaled version.",inputProperties:{image_url:{type:"string",description:"URL of the image to upscale."}},required:["image_url"]},transcribe_audio:{intro:'Transcribe speech in an audio or video file (URL) to text via OpenAI Whisper. ~$0.02 per file, multilingual, handles long files. Use whenever the user asks to "transcribe this", "what does this audio say", "make subtitles", "convert this to text", or shares an audio/video URL with no other clear intent.',tiers:{whisper:{toolId:"fal-whisper",notes:"OpenAI Whisper \u2014 fast, multilingual"}},guidance:"Pass the URL. Returns the transcript text.",inputProperties:{audio_url:{type:"string",description:"URL of the audio or video file to transcribe."}},required:["audio_url"]},run_llm:{intro:"Run a text prompt through a different LLM (GPT-4o-mini, Claude Sonnet, DeepSeek R1/V3, Perplexity Sonar with web search, or Llama 70B). Token-metered, typically ~$0.01\u2013$0.10 per call. Use for: web-grounded answers (search tier), second-opinion reasoning (reasoning tier), code generation in a different family (coding tier), deep math/logic (deep_reasoning tier), or fast cheap text cleanup (fast tier). Pair with batch for multi-model councils.",tiers:{fast:{toolId:"or-gpt-4o-mini",notes:"GPT-4o Mini. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",notes:"Claude Sonnet. Strong reasoning, long-context. Warn user it is materially pricier than `fast`."},frontier_openai:{toolId:"or-gpt-55",notes:"GPT-5.5. OpenAI frontier model for complex professional reasoning."},frontier_openai_pro:{toolId:"or-gpt-55-pro",notes:"GPT-5.5 Pro. Highest-capability OpenAI frontier tier; materially more expensive."},frontier_anthropic:{toolId:"or-claude-opus",notes:"Claude Opus 4.7. Anthropic frontier model for complex tasks."},frontier_google:{toolId:"or-gemini-35-flash",notes:"Gemini 3.5 Flash. Google frontier Flash model for multimodal reasoning and coding."},deep_reasoning:{toolId:"or-deepseek-r1",notes:"DeepSeek R1. Deep chain-of-thought reasoning, mid-range pricing."},search:{toolId:"or-perplexity-sonar",notes:"Perplexity Sonar. Search-augmented, web-grounded with citations."},open_source:{toolId:"or-llama-70b",notes:"Llama 3.3 70B. Open-source large model."},coding:{toolId:"or-deepseek-chat",notes:"DeepSeek Chat V3. Strong at code generation."}},guidance:"Pick based on the user's need: fast (most questions, cheapest), reasoning (complex analysis; warn user it is materially pricier than fast), frontier_* (top-model council / highest quality; warn user these are materially pricier), search (questions about current events), coding (code generation), deep_reasoning (hard math/logic problems).",inputProperties:{prompt:{type:"string",description:"The user query."},system_prompt:{type:"string",description:"Optional system prompt to set model behavior."},max_tokens:{type:"number",description:"Maximum output tokens.",default:1024,minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature \u2014 0 is deterministic, higher is more creative.",default:.7,minimum:0,maximum:2}},required:["prompt"]}};function Pt(e,t,n){if(!Ul(e))return Ig(e,n);let r=Ll[e];if(!r)return e;let o=Object.keys(r.tiers),s=t||o[0],i=$g(e,s,n);return i||Pg(e,r,s,o)}function Ig(e,t){return di({requestedTool:e,intentText:t})??e}function $g(e,t,n){return di({requestedTool:e,metaTool:e,tier:t,intentText:n})}function Pg(e,t,n,r){let o=t.tiers[n];if(!o)throw new Error(`Unknown tier '${n}' for ${e}. Valid tiers: ${r.join(", ")}`);return o.toolId}var Ll=_r;function Ul(e){return e in Ll}var vr=Object.keys(_r);function mi(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function Dl(e=process.env){return mi(e)!==null}var Su=require("child_process"),pe=E(require("crypto")),Ue=E(require("fs")),kr=E(require("os")),Go=E(require("path"));function fn(e,t={}){if(!e||typeof e!="object")return e;let n=e,r=t.tag??(typeof n.merchantName=="string"?n.merchantName:"media"),o=n.content?.[0]?.text,s=typeof o=="string"?Sn(o):null,i=Array.isArray(n.urls)?n.urls[0]:void 0,l=typeof i=="string"&&i.startsWith("data:")?Sn(i):null;if(!s&&!l)return e;let c=s??l,u=s?"content":"urls",d;try{d=Yn(c,{tag:Og(r,n)})}catch(m){return{...n,_inline_media_warning:`Failed to persist inline media to disk: ${m instanceof Error?m.message:String(m)}`}}let f={...n,filePath:d.filePath,mime:d.mime,bytes:d.bytes};return u==="urls"?f.urls=void 0:(f.content=Array.isArray(n.content)?[...n.content]:[{}],f.content[0]={...f.content[0]??{},text:`[inline media saved to ${d.filePath}]`}),f}function Og(e,t){let n=typeof t.transactionId=="string"?t.transactionId:typeof t.transaction_id=="string"?t.transaction_id:null;return n?`${e}-${n}`:e}var jl=!1;async function br(e,t,n){try{return await t()}catch(r){if(!(r.message==="Invalid signature"||r.code==="ATTESTATION_KEY_DRIFT"||r.error_code==="ATTESTATION_KEY_DRIFT"||r.name==="AttestationDriftError")||!ie())throw r;if(p.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(jl)throw p.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;jl=!0,p.info("attestation:starting-browser-recovery");try{let s=await n();if(!s.success)throw p.error("attestation:browser-recovery-failed",{message:s.message}),r;let i=await Ro();return await e.registerAttestationKey(i),await e.setBiometricPreference({required:!0}),p.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),p.info("attestation:key-reregistered-after-recovery"),await t()}catch(s){throw p.error("attestation:recovery-failure",{error:s.message}),r}}throw r}}var Fl="2.6.0-rc.8";function pi(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function Po(e,t,n){let r=process.env[e];if(r!==void 0)return{value:n==="opt-in"?r==="true":r!=="false",source:{kind:"env",var:e}};let o=go(t);return o!==void 0?{value:o,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function ke(e){return e==null?"\u2014":e?"yes":"no"}function Oo(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function Mg(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function Ng(){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=zs("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:Ks,source:{kind:"default"}}}async function Sr(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(L){n=L?.message||"unknown error"}let r=[],o=process.env.VISA_AUTH_URL,s=Gs("auth.serverUrl"),i=_e(),a=o!==void 0&&o!==""?{kind:"env",var:"VISA_AUTH_URL"}:s!==void 0?{kind:"settings"}:{kind:"default"};r.push({key:"auth.serverUrl",value:i,formatted:i,source:a,hint:a.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),r.push({key:"account.enrolled",value:t?.enrolled??null,formatted:ke(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:ke(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:ke(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:ie(),formatted:ke(ie()),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:Oo(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:Oo(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:Oo(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:Oo(t?.dailyRemaining),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"cards.count",value:t?.cardCount??null,formatted:t?.cardCount!=null?String(t.cardCount):"\u2014",source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}});let f=t?.cards?.find(L=>L.isDefault)??t?.cards?.[0];f&&r.push({key:"cards.default",value:{brand:f.brand??null,last4:f.last4},formatted:`${f.brand||"card"} \u2022\u2022\u2022\u2022 ${f.last4}`,source:{kind:"server"}});let m=Ng();r.push({key:"credit.sessionCapCents",value:m.value,formatted:Mg(m.value),source:m.source});let _=qc();_.length>0&&r.push({key:"settings.retired",value:_.map(L=>L.key),formatted:_.map(L=>L.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${_.map(L=>`visa-cli config unset ${L.key}`).join(" && ")}`});let S=Po("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:S.value,formatted:ke(S.value),source:S.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let $=Po("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:$.value,formatted:ke($.value),source:$.source});let V=Ve(),D;process.env.VISA_CLI_NO_UPDATE_CHECK?D={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?D={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?D={kind:"env",var:"NODE_ENV"}:D={kind:"default"},r.push({key:"ui.updateCheck",value:!V,formatted:ke(!V),source:D});let w=Po("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:w.value,formatted:ke(w.value),source:w.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let x=Po("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:x.value,formatted:ke(x.value),source:x.source});let y=process.env.VISA_DRY_RUN,C=Dl();if(r.push({key:"tools.dryRun",value:C,formatted:ke(C),source:y===void 0?{kind:"default"}:{kind:"env",var:"VISA_DRY_RUN"},hint:"VISA_DRY_RUN=true|1|mock returns deterministic paid-tool fixtures (no card, no upstream). VISA_DRY_RUN=preflight makes a real zero-cost OpenRouter call for LLM tools (image/video still mocked)."}),r.push({key:"client.version",value:Fl,formatted:Fl,source:{kind:"default"}}),e.includeDev){let L=process.env.VISA_MOCK_KEYCHAIN,Pe=ht();r.push({key:"dev.mockKeychain",value:Pe,formatted:ke(Pe),source:pi("VISA_MOCK_KEYCHAIN",!!L),hint:cs()});let jt=process.env.VISA_MOCK_TOUCHID,we=bn();r.push({key:"dev.mockTouchid",value:we,formatted:ke(we),source:pi("VISA_MOCK_TOUCHID",!!jt),hint:cs()});let B=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!B,formatted:ke(!!B),source:pi("VISA_CLI_DEBUG",!!B)})}return{entries:r,statusError:n}}function Lg(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 ql(e,t={}){if(e.length===0)return"";let n=Math.max(...e.map(s=>s.key.length)),r=Math.max(...e.map(s=>s.formatted.length)),o=[];for(let s of e){let i=s.key.padEnd(n+2),a=s.formatted.padEnd(r+2);o.push(`${i}${a}(${Lg(s.source)})`),t.verbose&&s.hint&&o.push(` ${"\u21B3".padStart(n)} ${s.hint}`)}return o.join(`
124
+ `)}function Vl(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 Hl(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 Ot=require("fs"),Kl=require("os"),fi=require("path"),Ug=(0,fi.join)((0,Kl.homedir)(),".visa-mcp"),Bl=(0,fi.join)(Ug,"mcp-session-budget.json");function Mo(){try{(0,Ot.existsSync)(Bl)&&(0,Ot.unlinkSync)(Bl)}catch{}}var hi=require("crypto"),Le=E(wr()),gn=null,Ce=0,jn=0,Se=0,Mt=null,yi=null,_i=null,Lo=Promise.resolve();function th(e){return Number((0,Le.fromCents)(e))}function Wl(e){return(0,Le.toCents)((0,Le.micros)(BigInt(e)))}function zl(e){return(0,Le.toWire)((0,Le.fromCents)(e))}function gi(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function No(e){return typeof e=="string"&&/^\d+$/.test(e)}var nh=43,rh=new RegExp(`^[A-Za-z0-9_-]{${nh}}$`);function oh(e){return typeof e=="string"&&rh.test(e)}function sh(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||gn&&e.session_id!==gn||typeof e.nonce!="string"||e.nonce.length===0||!oh(e.server_signature)||!gi(e.cumulative)||!gi(e.remaining)||!gi(e.delta)||e.cumulative<Ce||Se>0&&e.cumulative>Se||Se>0&&e.remaining>Se||e.cumulative_micros!==void 0&&!No(e.cumulative_micros)||e.remaining_micros!==void 0&&!No(e.remaining_micros)||e.delta_micros!==void 0&&!No(e.delta_micros)||e.reserved_micros!==void 0&&!No(e.reserved_micros))}function pt(e){gn=e,Ce=0,jn=0,Se=0,Mt=null,yi=null,_i=null,Lo=Promise.resolve()}function xr(e){Se=Math.max(0,Math.floor(e))}function vi(){return gn}function bi(e){if(!gn)return null;let t=Ce+jn;return Se>0&&t>Se&&(t=Se),{session_budget_id:gn,cumulative_micros:th(t),nonce:(0,hi.randomUUID)(),idempotency_key:e||(0,hi.randomUUID)()}}function Si(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 sh(r)?(Ce=Math.max(Ce,r.cumulative),jn=0,Mt=r,r):null}function Jl(){return Mt}function wi(e){let t=Wl(e.cumulative_micros);Ce=Math.max(Ce,t),jn=0;let n={status:"accepted",session_id:e.session_budget_id,cumulative:Ce,remaining:Math.max(0,Se-Ce),delta:0,cumulative_micros:zl(Ce),remaining_micros:zl(Math.max(0,Se-Ce)),delta_micros:"0",nonce:e.nonce};return Mt=n,n}function xi(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,Le.toCents)((0,Le.micros)(n));if(!Number.isFinite(r)||r<0)return;yi=t;let o=e,s=typeof o.session_id=="string"?o.session_id:gn??"";Mt?(typeof o.remaining_micros=="string"&&/^\d+$/.test(o.remaining_micros)&&(Mt.remaining_micros=o.remaining_micros),typeof o.charged_micros=="string"&&/^\d+$/.test(o.charged_micros)&&(Mt.delta_micros=o.charged_micros)):Mt={session_id:s,cumulative:r,remaining:0,delta:0,nonce:typeof o.transaction_id=="string"?o.transaction_id:"",remaining_micros:typeof o.remaining_micros=="string"&&/^\d+$/.test(o.remaining_micros)?o.remaining_micros:void 0,delta_micros:typeof o.charged_micros=="string"&&/^\d+$/.test(o.charged_micros)?o.charged_micros:void 0}}function Yl(e){let t=e.receipt??null;_i={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:Wl(e.voucher.cumulative_micros),estimatedCumulativeCents:Uo(),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 Xl(){return _i}function Zl(){return Ce}function Ql(){return yi}function Uo(){let e=Ce+jn;return Se>0&&e>Se&&(e=Se),e}function eu(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return Lo=Lo.then(()=>{jn+=t}),Lo}var ih=10,ah=1,Z=null,tu=Promise.resolve();function ki(e){let t=tu.catch(()=>{}).then(e);return tu=t.then(()=>{},()=>{}),t}var he=class extends Error{balanceCents;minRequiredCents;constructor(t,n){super(`Prepaid balance is $${(t/100).toFixed(2)}; at least $${(n/100).toFixed(2)} required to open a credit session. Top up via the buy_credits tool first.`),this.name="InsufficientBalanceError"}};async function Ci(e,t,n){return ki(()=>nu(e,t,n))}async function nu(e,t,n){if(Mo(),Z&&new Date(Z.expiresAt).getTime()>Date.now())return vi()!==Z.budgetId&&(pt(Z.budgetId),xr(Z.totalCents)),p.info("mcp-session:active-hit",{budgetId:Z.budgetId,tool:n.toolName,remainingEstimatedCents:Z.totalCents-Uo()}),{budgetId:Z.budgetId,isFresh:!1,totalCents:Z.totalCents,requestedCapCents:Z.totalCents,appliedCapCents:Z.totalCents,clampedReason:null};Z&&(Z=null,pt(null));let r=await e.getBalance();if(!r.success)throw new Error(`Could not read balance: ${r.error||"unknown error"}`);let o=n.sessionKind??"explicit",s=o==="one_shot"?ah:ih,i=Math.max(s,Math.ceil(n.minRequiredCents??s));if(r.balanceCents<i)throw new he(r.balanceCents,i);let a=n.capCentsOverride??Bc(),l=Math.min(a,r.balanceCents),c=l<a?"balance":null,u=await t("session_create",l,"Visa CLI Session",`open credit-model session with $${(l/100).toFixed(2)} cap`,n.userContext),d=await e.createSessionBudget({total_cents:l,session_kind:o,...u?{attestation:u}:{}});if(!d.success||!d.budget){let m=d.error||"unknown error";throw new Error(`Failed to open credit session: ${m}`)}let f={budgetId:d.budget.id,expiresAt:d.budget.expiresAt,totalCents:d.budget.totalCents,createdAt:d.budget.createdAt};return Z=f,pt(f.budgetId),xr(f.totalCents),p.info("mcp-session:opened",{budgetId:f.budgetId,capCents:f.totalCents,requestedCapCents:a,clampedReason:c,sessionKind:o,expiresAt:f.expiresAt,tool:n.toolName}),{budgetId:f.budgetId,isFresh:!0,totalCents:f.totalCents,requestedCapCents:a,appliedCapCents:f.totalCents,clampedReason:c}}async function ru(e,t,n){return ki(async()=>{let o=Nt()?await ou(e):null,s=await nu(e,t,n);return{budgetId:s.budgetId,totalCents:s.totalCents,closedPrevious:o,requestedCapCents:s.requestedCapCents,appliedCapCents:s.appliedCapCents,clampedReason:s.clampedReason}})}async function ou(e){let n=Nt()?.budgetId??vi(),r=!1,o,s;if(n)try{let i=await e.closeSession(n);r=!!i?.success,typeof i?.finalCumulativeCents=="number"&&(o=i.finalCumulativeCents),typeof i?.finalCumulativeMicros=="string"&&(s=i.finalCumulativeMicros)}catch(i){p.warn("mcp-session:close-server-failed",{budgetId:n,error:i?.message||String(i)})}return Mo(),Z=null,pt(null),{closedServerSide:r,budgetId:n,finalCumulativeCents:o,finalCumulativeMicros:s}}async function Do(e){return ki(()=>ou(e))}function Nt(){return Mo(),Z?new Date(Z.expiresAt).getTime()<=Date.now()?(Z=null,pt(null),null):{budgetId:Z.budgetId,totalCents:Z.totalCents,lastReceiptCumulative:Zl(),lastReceiptCumulativeMicros:Jl()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:Ql(),estimatedCumulative:Uo(),lastToolSpend:Xl(),expiresAt:Z.expiresAt}:null}var iu=E(wr()),su=10000n;function ch(e){return e<=0n?0:Number((e+su-1n)/su)}function au(e){return ch((0,iu.fromUsd)(e))}var jo=E(wr()),lh=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;function Fo(e){if(typeof e!="string"||!lh.test(e))return{ok:!1,error:"amount must be a USD amount with at most two decimal places"};let[t,n=""]=e.split("."),r=BigInt(t)*100n+BigInt(n.padEnd(2,"0"));if(r>BigInt(Number.MAX_SAFE_INTEGER))return{ok:!1,error:"amount is too large"};let o=Number(r);return o<=0?{ok:!1,error:"amount must be greater than $0.00"}:{ok:!0,cents:o,displayUsd:(0,jo.toDisplay)((0,jo.fromCents)(o),{symbol:""})}}var qo="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.",cu="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 lu=Promise.resolve(),uu=!1;function zo(e){let t=lu.catch(()=>{}).then(e);return lu=t.then(()=>{},()=>{}),t}async function wu(e){let t=await Ci(P,Xe,{toolName:e.toolId,userContext:e.userContext}),n=bi(e.idempotencyKey);if(!n)throw new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await hh(),o,s,i=async()=>P.shortcutWithSession(e.toolId,n,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);try{try{({data:o,voucherReceiptHeader:s}=await i())}catch(u){if(u instanceof Wt){let d=Math.min(Math.max(u.retryAfterSecs,0),5)*1e3;p.warn("mcp-session:lock-contended-retrying",{tool:e.toolId,retryAfterSecs:u.retryAfterSecs}),await new Promise(f=>setTimeout(f,d)),{data:o,voucherReceiptHeader:s}=await i()}else throw u}}catch(u){if(u instanceof En){if(p.warn("mcp-session:server-invalidated-budget",{code:u.code,budgetId:u.budgetId??t.budgetId,tool:e.toolId}),await Do(P),process.env.VISA_REQUIRE_EXPLICIT_SESSION==="true")throw new Error(`Your session was closed by another process (${u.code}). Restart MCP or run start_session again.`);return uu||(uu=!0,console.error(`[visa-cli] Your session was closed by another process; reopened automatically as pay-as-you-go.
125
+ To require an explicit session approval instead, set VISA_REQUIRE_EXPLICIT_SESSION=true.`)),p.info("mcp-session:falling-back-to-payg",{code:u.code,tool:e.toolId}),xu(e)}throw u instanceof Wt?(p.warn("mcp-session:lock-contended-give-up",{tool:e.toolId}),new Error("Another paid call is currently in progress on this session. Wait a moment and try again.")):u}let a=Si(s)??(n?wi(n):null);if(xi(o?.receipt_v2),await eu(e.estimatedAmountCents),Yl({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),Cu(o))return fn(o);let l=await ku();if(e.idempotencyKey&&Tu(o,l,e.idempotencyKey))return fn(o);let c=l?Bo(l):null;return fn(Eu(o,r,c))}function We(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function Ai(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(Ai).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${Ai(r)}`).join(",")}}`}function uh(e,t,n,r){let o=pe.createHash("sha256").update(`${n}:${Ai(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${o}`}function dh(e,t){return`${e}:${t}`}function mh(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 du(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,o=ze(r),s=o!==null?o.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=mh(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),l=i!=null?String(i):a;return{batch_id:e,item_id:dh(e,t),index:t,...l!==void 0?{transaction_id:l}:{},...a!==void 0?{ledger_id:a}:{},...s?{amountMicros:s,amount_micros:s,cost_micros:s}:{}}}async function xu(e){let t=Math.max(1,Math.ceil(e.estimatedAmountCents)),n=await P.getBalance();if(!n.success)throw new Error(`Could not read balance: ${n.error||"unknown error"}`);if(n.balanceCents<t)throw new he(n.balanceCents,t);let r=t,o=Bo(n),s=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(r/100).toFixed(2)})`,i=await Xe("session_create",r,"Visa CLI Session",s,e.userContext),a=await P.createSessionBudget({total_cents:r,session_kind:"one_shot",...i?{attestation:i}:{}});if(!a.success||!a.budget)throw new Error(`Failed to open on-demand session: ${a.error||"unknown error"}`);let l=a.budget.id;pt(l),xr(a.budget.totalCents),p.info("on-demand-session:opened",{budgetId:l,capCents:a.budget.totalCents,tool:e.toolId});try{let c=bi(e.idempotencyKey);if(!c)throw new Error(`Internal: mintVoucher returned null after on-demand session-open ${l}`);let{data:u,voucherReceiptHeader:d}=await P.shortcutWithSession(e.toolId,c,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(Si(d)||wi(c),xi(u?.receipt_v2),Cu(u))return fn(u);let f=await ku();if(e.idempotencyKey&&Tu(u,f,e.idempotencyKey))return fn(u);let m=f?Bo(f):null;return fn(Eu(u,o,m))}finally{try{await P.closeSession(l)}catch(c){p.warn("on-demand-session:close-failed",{budgetId:l,error:c?.message||String(c)})}pt(null),p.info("on-demand-session:closed",{budgetId:l,tool:e.toolId})}}async function Ut(e){return zo(async()=>Nt()?wu(e):xu(e))}function Wo(){return _e()}var P=new xe(()=>F.getSessionToken());function ze(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function Bo(e){return ze(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function ph(e){if(e<0n&&(e=0n),e>=1000000n){let r=(e+5000n)/10000n,o=r/100n,s=r%100n;return`$${o.toString()}.${s.toString().padStart(2,"0")}`}let t=e%1000000n;return t===0n?"$0.00":`$0.${t.toString().padStart(6,"0").replace(/0+$/,"")}`}function fh(e){let t=ze(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=ze(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=ze(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function Vo(e,t="INVALID_TOOL_PARAMS"){return{success:!1,error_code:t,code:t,error:e,message:e}}function gh(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 hh(){try{let e=await P.getBalance();return e.success?Bo(e):null}catch{return null}}async function ku(){try{let e=await P.getBalance();return e.success?e:null}catch{return null}}function Cu(e){if(!e||e.success===!1)return!1;let t=ze(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=ze(e.amountMicros??e.amount_micros??e.charged_micros),r=t??n;if(r===null||r<=0n)return!1;let o=r.toString();return e.amountMicros??=o,e.amount_micros??=o,e.charged_micros??=o,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),!0}function Tu(e,t,n){if(!e||e.success===!1||!t||!Array.isArray(t.ledger))return!1;let r=t.ledger.find(a=>a.idempotencyKey===n);if(!r)return!1;let o=ze(r.deltaMicros)??BigInt(r.deltaCents)*10000n,s=o<0n?-o:o;if(s<=0n)return!1;let i=s.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(s)/1e6),!0}function Eu(e,t,n){if(!e||e.success===!1||t===null||n===null)return e;let r=t-n;if(r<=0n)return e;let o=r.toString();return e.amountMicros??=o,e.amount_micros??=o,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(r)/1e6),e}var yh="2.6.0-rc.8",bw=["","","You're ready to go! Try:","","Core:",'\u2022 "Show my account status" \u2192 get_status','\u2022 "List my enrolled cards" \u2192 get_cards','\u2022 "Show my paid tool use history" \u2192 transaction_history','\u2022 "Set my daily top-up limit to $50" \u2192 update_spending_controls','\u2022 "Generate 3 variations in parallel" \u2192 batch',"","Category tools:",'\u2022 "Generate an image of a sunset over Tokyo" \u2192 generate_image','\u2022 "Make a 4-second video of a penguin juggling" \u2192 generate_video','\u2022 "Make a song about coding late at night" \u2192 generate_music','\u2022 "Create a sound effect for a checkout chime" \u2192 generate_audio','\u2022 "Create a 3D asset from this product sketch" \u2192 generate_3d','\u2022 "Upscale this product image" \u2192 upscale_image','\u2022 "Transcribe this meeting recording" \u2192 transcribe_audio','\u2022 "Run a reasoning model on this prompt" \u2192 run_llm',"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
126
+ `);function Je(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=er(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(Vc())return{opened:!1,url:t,blockedReason:"suppressed"};let n=Ss();if(n.headless)return p.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let r=$a(t,Wo());if(!r)return p.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let o=Oa(r);return o?((0,Su.execFile)(o.cmd,o.args,s=>{s&&p.warn(`Browser open failed: ${s.message}. URL: ${r}`)}),{opened:!0,url:r}):(p.info(`No browser command for platform "${kr.platform()}". URL: ${r}`),{opened:!1,url:r,blockedReason:"unsupported_platform"})}async function Te(e){return br(P,e,Nu)}var Au="get_cards",Ru="set_default_card";function _h(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 '${Au}' to see enrolled cards and '${Ru}' to switch, then retry the original request.`}function vh(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 '${Au}' to see enrolled cards and '${Ru}' to switch. Do not retry automatically.`}function Ye(e,t){let n=e.retryable?_h(e.code,e.retryAfter):vh(e.code,t.merchantName);return{success:!1,declined:!0,retryable:e.retryable,code:e.code,reason:e.reason,payment_error_class:e.paymentErrorClass,correlation_id:e.correlationId,transactionId:e.transactionId,retryAfter:e.retryAfter,merchantName:t.merchantName,amount:t.amount,message:e.message,agent_guidance:n}}function bh(e){return{success:!1,error:e.message,error_code:e.code,transactionId:e.transactionId,reconciliation_required:e.reconciliationRequired,retryable:e.retryable,agent_guidance:"The top-up charge outcome is ambiguous. Tell the user not to retry with a new idempotency key or start another top-up. They should check transaction_history in a few minutes or contact support with the transactionId."}}var Fn=null,Sh=3e4;function Iu(){Fn=null}var Lt=class extends Error{constructor(n){super(`${Ko()} attestation is required for this action, but it is not available in this MCP process. `+Ri());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function Jo(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. `+Ri()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function wh(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:qo,agent_guidance:cu}}function Ko(){return process.platform==="darwin"?"Touch ID":"local biometric"}function Ri(){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 Yo(e){return typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0}async function xh(e){let t=Date.now();if(Fn&&Fn.expiresAt>t)return{required:Fn.required,hasRegisteredKey:Fn.hasRegisteredKey};try{let n=await P.getStatus(e),r=n.attestationRequired!==!1,o=Yo(n);return Fn={required:r,hasRegisteredKey:o,expiresAt:t+Sh},{required:r,hasRegisteredKey:o}}catch{return{required:!0,hasRegisteredKey:!0}}}async function Xe(e,t,n,r,o,s){if(!s?.forceRequired){let i=await xh(o);if(!i.required){p.info("attestation:skipped-by-server-policy",{context:e});return}if(!i.hasRegisteredKey){p.info("attestation:skipped-no-registered-key",{context:e});return}}if(!ie())throw p.warn("attestation:unavailable",{context:e}),new Lt(e);p.info("attestation:attempt",{context:e,amount:t,merchant:n});try{let{nonce:i}=await P.getAttestationChallenge(),a=Buffer.from(JSON.stringify({nonce:i,amount:t,merchant:n,context:e})).toString("base64");p.info("touchid:prompt",{context:e,amount:t,merchant:n});let l=await Dn(a,r);return p.info("attestation:success",{context:e,amount:t,merchant:n}),{signature:l,nonce:i,amount:t,merchant:n}}catch(i){throw p.error("attestation:failure",{context:e,amount:t,merchant:n,error:i.message}),i}}var mu="[dry-run] https://placeholder.visa-cli.dev/image.png",kh=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"]),Ch=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 Th(e,t){return t==="run_llm"||e.startsWith("or-")?"llm":t==="generate_image"||kh.has(e)?"image":t==="generate_video"||Ch.has(e)?"video":null}function Eh(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function Ah(e){return e==="llm"?"OpenRouter":"fal.ai"}function qn(e,t,n,r){let o={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:Ah(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${Eh(n)}`;return{...o,content:i,data:{content:i,model:t,dry_run:!0}}}return{...o,urls:[mu],data:{[e==="video"?"videoUrl":"imageUrl"]:mu,metadata:{dry_run:!0}}}}async function Ti(e){let t=e.mode??"mock",n=t==="preflight"?"/v1/telemetry/preflight":"/v1/telemetry/dry-run",r=t==="preflight"?"preflight":null;try{await P.emitTelemetry([{id:pe.randomUUID(),timestamp:new Date().toISOString(),tool_name:e.toolName,user_prompt:e.userContext??"",tool_params:JSON.stringify(e.toolParams),result_success:!0,result_error:null,result_json:JSON.stringify(e.result),payment_rail:r,payment_amount:0,payment_currency:"USD",merchant_name:e.result.merchantName,transaction_id:e.result.transactionId,tx_hash:null,protocol:null,http_status:200,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",event_kind:"mcp_tool",endpoint:n,resolved_model:e.resolvedModel,session_budget_id:null}])}catch(o){p.warn("dry_run:telemetry_failed",{tool:e.toolName,error:o?.message||String(o),mode:t})}}var Rh="https://openrouter.ai/api/v1/chat/completions",Ih="openrouter/free",$h=50,Ph=15e3;function Oh(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 Mh(e,t,n){let r=process.env.OPENROUTER_API_KEY;if(!r)return p.warn("preflight:no_openrouter_key_falling_back_to_mock",{tool:e}),{result:qn("llm",e,t,n),degraded:!0,resolvedModel:null};let o=Oh(t),s;try{s=await Gt(Rh,{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:Ih,messages:[{role:"user",content:o}],max_tokens:$h}),timeoutMs:Ph})}catch(u){return p.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:qn("llm",e,t,n),degraded:!0,resolvedModel:null}}if(!s.ok){let u=await s.text().catch(()=>"");return p.warn("preflight:openrouter_http_error_falling_back_to_mock",{tool:e,status:s.status,bodyExcerpt:u.slice(0,200)}),{result:qn("llm",e,t,n),degraded:!0,resolvedModel:null}}let i;try{i=await s.json()}catch(u){return p.warn("preflight:openrouter_invalid_json_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:qn("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 Xo(e,t,n,r){let o=mi();if(!o)return null;let s=Th(e,r);if(!s)return null;let i=Date.now();if(o==="mock"){let c=qn(s,e,t,r);return await Ti({toolName:r??e,resolvedModel:r&&r!==e?e:null,toolParams:t,result:c,userContext:n,startedAt:i,mode:"mock"}),p.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:s,mode:o}),c}if(s!=="llm"){p.warn("preflight:not_supported_for_kind_falling_back_to_mock",{tool:e,kind:s});let c=qn(s,e,t,r);return await Ti({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 Mh(e,t,r);return await Ti({toolName:r??e,resolvedModel:l??(r&&r!==e?e:null),toolParams:t,result:a,userContext:n,startedAt:i,mode:"preflight"}),p.info("dry_run:payment_intercepted",{tool:e,metaTool:r,kind:s,mode:o}),a}async function ft(e,t,n){let r=await P.paymentPreview({tool:e,url:t},n);if(!r||!r.merchantName||r.amount===void 0||r.amount===null||r.amount<0)throw new Error("Could not determine payment amount and merchant. Try again.");if(!Number.isFinite(r.amount)||r.amount<0||r.amount>999999)throw new Error(`Invalid payment amount: ${r.amount}. Payment rejected for safety.`);return r}function gt(e){return au(e.amount)}function Nh(){return Go.join(kr.homedir(),".visa-mcp","allium-results")}var Sw=16*1024,ww=50*1024*1024;function Lh(){let e=Nh();try{if(!Ue.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=Ue.readdirSync(e),n=0,r=0;for(let o of t)try{let s=Ue.statSync(Go.join(e,o));s.isFile()&&(n+=s.size,r++)}catch{}return{file_count:r,size_bytes:n,path:e}}catch(t){return p.warn("allium:disk_usage_error",{error:t.message}),{file_count:0,size_bytes:0,path:e}}}var pu=3600*1e3,Ei=0;function Uh(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function Cr(e){if(!Hc()&&!(Date.now()<Ei))try{if(!await F.getSessionToken())return;await P.feedSubmit({prompt:e.prompt,tool:e.tool,media_url:e.mediaUrl,media_type:e.mediaType,cost:e.cost,transaction_id:e.transactionId,auto:!0,...e.userContext&&{user_context:e.userContext}}),p.info("feed:submitted",{tool:e.tool,mediaType:e.mediaType,transactionId:e.transactionId})}catch(t){if(Uh(t)){let n=Ei===0;Ei=Date.now()+pu,n&&p.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:pu});return}p.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function Dh(e,t){let n=(e.state||"").trim().toUpperCase(),r=(e.county||"").trim(),o=(e.start_date||"").trim(),s=(e.end_date||o).trim();if(!/^[A-Z]{2}$/.test(n))throw new Error('state must be a 2-letter US state code (e.g. "VA").');if(!r)throw new Error("county is required.");if(!/^\d{4}-\d{2}$/.test(o))throw new Error('start_date must be YYYY-MM (e.g. "2025-08").');if(s&&!/^\d{4}-\d{2}$/.test(s))throw new Error("end_date must be YYYY-MM.");let i="Visa SMI",a=.1,l=`Pay $0.10 to ${i} for SMI data (${n} / ${r})`;p.info("payment:attempt",{tool:"get_visa_smi",amount:a,merchant:i});try{return await Te(async()=>{let c=await Xe("get_visa_smi",a,i,l),u=await P.getVisaSmi({state:n,county:r,start_date:o,end_date:s,attestation:c,idempotencyKey:pe.randomUUID()},t);return u.success?p.info("payment:success",{tool:"get_visa_smi",merchant:i,charged_cents:u.charged_cents}):p.warn("payment:declined",{tool:"get_visa_smi",merchant:i,message:u.error}),u})}catch(c){if(c instanceof ue)return p.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:c.code,retryable:c.retryable}),Ye(c,{amount:a,merchantName:i,description:"Visa SMI data"});throw p.error("payment:failure",{tool:"get_visa_smi",merchant:i,error:c.message}),c}}async function jh(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 Xo("generate_image_card",e,t);if(n)return n;let r=await ft("generate_image_card",void 0,t),o=pe.randomUUID();p.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await Te(async()=>{let s;try{s=await Ut({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:gt(r),userContext:t,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof he)return We(i);throw i}return p.info("payment:success",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Je(i)),Cr({prompt:e.prompt,tool:"generate_image_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):p.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof ue)return p.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Ye(s,r);throw p.error("payment:failure",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function Fh(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 Xo("generate_image_fast_card",e,t);if(n)return n;let r=await ft("generate_image_fast_card",void 0,t),o=pe.randomUUID();p.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await Te(async()=>{let s;try{s=await Ut({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:gt(r),userContext:t,timeoutMs:6e4,idempotencyKey:o})}catch(i){if(i instanceof he)return We(i);throw i}return p.info("payment:success",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Je(i)),Cr({prompt:e.prompt,tool:"generate_image_fast_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):p.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof ue)return p.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Ye(s,r);throw p.error("payment:failure",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function qh(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 Xo("generate_video_tempo_card",e,t);if(n)return n;let r=await ft("generate_video_tempo_card",void 0,t),o=pe.randomUUID();p.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await Te(async()=>{let s;try{s=await Ut({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:gt(r),userContext:t,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof he)return We(i);throw i}return p.info("payment:success",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),s.urls?.length?(s.urls.forEach(i=>Je(i)),Cr({prompt:e.prompt,tool:"generate_video_tempo_card",mediaUrl:s.urls[0],mediaType:"video",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):p.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof ue)return p.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),Ye(s,r);throw p.error("payment:failure",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function Vh(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 ft("generate_music_tempo_card",void 0,t),r=pe.randomUUID();p.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await Te(async()=>{let o;try{o=await Ut({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:gt(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(s){if(s instanceof he)return We(s);throw s}return p.info("payment:success",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),o.urls?.length&&o.status!=="processing"?(o.urls.forEach(s=>Je(s)),Cr({prompt:e.prompt,tool:"generate_music_tempo_card",mediaUrl:o.urls[0],mediaType:"audio",cost:o.amount??n.amount,transactionId:o.transactionId,userContext:t})):o.urls?.length&&o.status==="processing"?(o._preliminary_urls=o.urls,delete o.urls,p.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):p.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof ue)return p.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Ye(o,n);throw p.error("payment:failure",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}async function Hh(e,t){let n=await ft("check_music_status_tempo_card",void 0,t),r=pe.randomUUID();p.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await Te(async()=>{let o;try{o=await Ut({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:gt(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof he)return We(s);throw s}return p.info("payment:success",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),o.urls?.length&&o.urls.forEach(s=>Je(s)),o})}catch(o){if(o instanceof ue)return p.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Ye(o,n);throw p.error("payment:failure",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}async function Bh(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 ft("query_onchain_prices",void 0,t),r=pe.randomUUID();p.info("payment:attempt",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName});try{return await Te(async()=>{let o;try{o=await Ut({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:gt(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof he)return We(s);throw s}if(p.info("payment:success",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,mode:"session"}),Array.isArray(o?.data))o.data=o.data.map(s=>{if("mint"in s&&!("address"in s)){let{mint:i,...a}=s;return{address:i,...a}}return s});else if(o&&"mint"in o&&!("address"in o)){let{mint:s,...i}=o;return{address:s,...i}}return o})}catch(o){if(o instanceof ue)return p.warn("payment:declined",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),Ye(o,n);throw p.error("payment:failure",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}var Kh=["generate_music_tempo_card"],fu=10,gu=5,hu=new Map;function yu(e){let t=hu.get(e);if(t!==void 0)return t;let r=yr(e)?.isAsync===!0||Kh.includes(e);return hu.set(e,r),r}var Gh=36e4,zh=18e4,Wh=15e3,Jh=12e4,Yh=2e3;function _u(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}async function Xh(e,t){let n;if(e.requests?.some(y=>y.tool||y.tool_id)&&e.requests)n=e.requests.map(y=>{let C=y.tool||y.tool_id||e.tool;if(!C)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let L=Pt(C,y.tier||e.tier,y.prompt??t),{tool:Pe,tool_id:jt,tier:we,params:B,...re}=y,Nr=B&&typeof B=="object"?{...B,...re}:re;return{resolvedTool:L,params:Nr}});else if(e.tool){let y=Pt(e.tool,e.tier,e.params?.prompt??t);n=(e.requests||(e.count&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(L=>({resolvedTool:y,params:L}))}else return _u("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return _u("BATCH_EMPTY","Batch requires at least one item.");if(n.length>fu)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${fu} items. Please split into smaller batches.`};if([...new Set(n.map(y=>y.resolvedTool))].some(yu)&&n.length>gu)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${gu} items. Please use multiple batches for more.`};let i=[...new Set(n.map(y=>y.resolvedTool))],a=i.length===1,l={};for(let y of i)l[y]=await Lu(y);let c=new Set(i.filter(y=>l[y]&&Uu(l[y]))),u={};for(let y of i)c.has(y)||(u[y]=await ft(y,void 0,t));let d=0;for(let y of n)d+=u[y.resolvedTool]?.amount??0;let f=[...new Set([...Object.values(u).map(y=>y.merchantName),...i.filter(y=>c.has(y)).map(y=>l[y]?.name??y)])].join(", "),m=a?i[0]:"mixed";p.info("payment:attempt",{tool:"batch",batchTool:m,count:n.length,totalAmount:d,merchant:f,heterogeneous:!a});let _=n.some(y=>yu(y.resolvedTool)),S=n.some(y=>y.resolvedTool.startsWith("or-")||y.resolvedTool==="run_llm"||y.resolvedTool==="execute_tool"),$=_?Gh:S?zh+n.length*Wh:Jh+n.length*Yh,V=pe.randomUUID(),D=[],w=0,x=0n;return zo(async()=>{let y=!Nt();if(y&&d>0)try{let C=Math.max(1,Math.ceil(d*100));await Ci(P,Xe,{toolName:"batch",userContext:t,sessionKind:"one_shot",minRequiredCents:C,capCentsOverride:C})}catch(C){return C instanceof he?We(C):(p.warn("payment:batch-prewarm-failed",{batchTool:m,count:n.length,error:C?.message||String(C)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:C?.message||"Failed to authenticate batch session",tool:m,count:n.length,failedCount:n.length,results:[]})}try{for(let B=0;B<n.length;B+=1){let re=n[B],Nr=u[re.resolvedTool];try{let Y=c.has(re.resolvedTool)?await P.shortcut(re.resolvedTool,re.params,$,t,"batch"):await wu({toolId:re.resolvedTool,toolParams:re.params,estimatedAmountCents:gt(Nr),userContext:t,metaTool:"batch",timeoutMs:$,idempotencyKey:uh(V,B,re.resolvedTool,re.params)});if(c.has(re.resolvedTool)&&Y&&typeof Y=="object"&&!Array.isArray(Y)&&Y.merchantName==null&&(Y.merchantName=l[re.resolvedTool]?.name??re.resolvedTool),D.push({success:Y?.success!==!1,tool:re.resolvedTool,...Y,...du(V,B,Y)}),Y?.success!==!1){let zn=ze(Y?.amountMicros??Y?.amount_micros),sa=typeof Y?.amount=="number"?Y.amount:Nr?.amount??0;zn!==null&&zn>0n?x+=zn:x+=BigInt(Math.round(sa*1e6)),w+=sa}Y?.urls&&Y.urls.forEach(zn=>Je(zn))}catch(Y){if(Y instanceof he&&D.length===0)return We(Y);p.warn("payment:batch-item-failed",{tool:re.resolvedTool,index:B,error:Y?.message||String(Y)}),D.push({success:!1,tool:re.resolvedTool,...du(V,B),error:Y?.message||String(Y)})}}let C=D.filter(B=>B?.success===!1).length,L=D.length-C,Pe=D.flatMap(B=>Array.isArray(B?.urls)?B.urls:[]),jt=x>0n?Number(x)/1e6:Math.round((w+Number.EPSILON)*100)/100,we=L===0?"failure":C===0?"success":"partial";return p.info("payment:success",{tool:"batch",batchTool:m,count:n.length,totalAmount:d,totalCharged:jt,merchant:f,successCount:L,failedCount:C,outcome:we,mode:"session",batchId:V}),{success:L>0,outcome:we,batch_id:V,tool:a?i[0]:m,count:n.length,successCount:L,failedCount:C,totalCharged:jt,...x>0n?{totalChargedMicros:x.toString(),amountMicros:x.toString(),amount_micros:x.toString()}:{},merchantName:f,results:D,...Pe.length?{urls:Pe}:{}}}catch(C){if(C instanceof ue)return p.warn("payment:declined",{tool:"batch",batchTool:m,count:n.length,totalAmount:d,merchant:f,code:C.code,retryable:C.retryable}),Ye(C,{amount:d,merchantName:f});throw p.error("payment:failure",{tool:"batch",batchTool:m,count:n.length,totalAmount:d,merchant:f,error:C.message}),C}finally{if(y){let C=await Do(P);p.info("batch-session:closed",{budgetId:C.budgetId,closedServerSide:C.closedServerSide})}}})}function Zh(){let e=!1,t;try{let r=Go.join(kr.homedir(),".claude","settings.json");if(Ue.existsSync(r)){let o=JSON.parse(Ue.readFileSync(r,"utf-8")),s=typeof o.statusLine=="object"?o.statusLine.command:"";e=kt(s)}}catch{}let n=Qr();return n||(t="visa-cli config hud enable"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function Qh(e){let[t,n]=await Promise.all([P.getStatus(e),P.getBalance().catch(s=>(p.warn("get_status:balance_fetch_failed",{error:s?.message||String(s)}),null))]);typeof t?.dailyRemaining=="number"&&(t.dailyRemaining=Math.round(t.dailyRemaining*100)/100);let r=Lh();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=Zh(),t.version=yh,Array.isArray(t.cards)&&(t.cards=t.cards.map(s=>({...s,displayName:Ii(s)})),t.cardIdGuidance="cardId values are opaque tool parameters only; refer to cards by brand and last four digits."),n&&n.success&&(t.balanceCents=n.balanceCents,t.amountUsd=n.amountUsd);let o=Nt();if(t.sessionMode=!!o,o){let s=Math.max(0,o.totalCents-o.estimatedCumulative);t.activeSession={budgetId:o.budgetId,capCents:o.totalCents,capUsd:o.totalCents/100,lastReceiptCumulativeCents:o.lastReceiptCumulative,estimatedCumulativeCents:o.estimatedCumulative,spentCents:o.estimatedCumulative,spentUsd:o.estimatedCumulative/100,estimatedRemainingCents:s,estimatedRemainingUsd:s/100,...o.lastToolSpend?{lastToolSpend:{toolName:o.lastToolSpend.toolName,resolvedToolId:o.lastToolSpend.resolvedToolId,estimatedAmountCents:o.lastToolSpend.estimatedAmountCents,estimatedAmountUsd:o.lastToolSpend.estimatedAmountCents/100,voucherCumulativeCents:o.lastToolSpend.voucherCumulativeCents,estimatedCumulativeCents:o.lastToolSpend.estimatedCumulativeCents,receiptDeltaCents:o.lastToolSpend.receiptDeltaCents,receiptCumulativeCents:o.lastToolSpend.receiptCumulativeCents,receiptRemainingCents:o.lastToolSpend.receiptRemainingCents,recordedAt:o.lastToolSpend.recordedAt}}:{},expiresAt:o.expiresAt}}return t}function Ii(e){let t=typeof e.brand=="string"&&e.brand.trim().length>0?e.brand.trim():"card",n=t.charAt(0).toUpperCase()+t.slice(1).toLowerCase(),r=typeof e.last4=="string"&&e.last4.trim().length>0?e.last4.trim():"unknown",o=e.isDefault===!0?" (default)":"";return`${n} ending in ${r}${o}`}async function $u(e,t){try{let r=((await P.getStatus(t)).cards||[]).find(o=>o?.id===e);if(r)return Ii(r)}catch(n){p.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function ey(e){let n=(await P.getStatus(e)).cards||[];return n.length===0?{cards:[],message:"No cards enrolled. Use the add_card tool to add a payment card."}:n.some(o=>!Number.isInteger(o?.id)||o.id<=0)?{success:!1,cards:[],message:"Card action handles are unavailable right now, so remove_card and set_default_card are temporarily disabled."}:{cards:n.map(o=>({...o,displayName:Ii(o)})),message:"Use cardId only as an opaque tool parameter. When speaking to the user, refer to cards by brand and last four digits, not by card id."}}async function ty(e,t){return await P.getTransactions({limit:e.limit,offset:e.offset},t)}async function ny(e,t){return await P.feedback(e.message,e.transaction_id,t)}async function ry(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return hn("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=Fo(String(e.amount));if(n.ok===!1)return{success:!1,error:n.error};let r=n.cents,o=r/100,s=pe.randomUUID();p.info("buy_credits:attempt",{amountCents:r});try{return await Te(async()=>{let i=await Xe("balance-topup",o,"Visa CLI Balance",`top up balance with $${n.displayUsd}`,t,{forceRequired:!0}),a=await P.topupBalance({amount_cents:r,idempotency_key:s,attestation:i});if(a.success){p.info("buy_credits:success",{amountCents:r,balanceCents:a.balanceCents});let l=((a.balanceCents??0)/100).toFixed(2),c=(r/100).toFixed(2);return{...a,amount:r/100,amountMicros:String(r*1e4),merchantName:"Visa CLI Balance",message:`Added $${c} \u2014 balance is now $${l}`}}return p.warn("buy_credits:failed",{amountCents:r,error:a.error}),a})}catch(i){if(i instanceof Lt)return wh();if(i instanceof st)return p.warn("buy_credits:ambiguous",{amountCents:r,code:i.code,transactionId:i.transactionId}),bh(i);throw p.error("buy_credits:failure",{amountCents:r,error:i.message}),i}}function hn(e,t){return{success:!1,error:t,code:e,message:t}}async function oy(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return hn("MISSING_CONFIRMATION","Please confirm by setting confirm: true to update spending controls.");if(e.maxTransactionAmount!==void 0&&(typeof e.maxTransactionAmount!="number"||!Number.isFinite(e.maxTransactionAmount)||e.maxTransactionAmount<.01))return hn("INVALID_VALUE","maxTransactionAmount must be at least $0.01");if(e.dailyLimit!==void 0&&(typeof e.dailyLimit!="number"||!Number.isFinite(e.dailyLimit)||e.dailyLimit<1))return hn("INVALID_VALUE","dailyLimit must be at least $1");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return hn("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");p.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await Te(async()=>{let n=await Xe("spending-controls",0,"","update spending controls"),r=await P.updateSpendingControls({maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit,confirm:!0,attestation:n},t);return p.info("spending_controls:success",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit}),r})}catch(n){if(p.error("spending_controls:failure",{error:n.message}),n instanceof Lt)return Jo(n,"update_spending_controls");if(String(n?.message||n).includes("Attestation required"))return hn("ATTESTATION_REQUIRED","Changing spending controls requires local attestation, even when payment biometric prompts are disabled.");throw n}}async function sy(e){let t=await Sr({api:P,includeDev:!!e.includeDev});return{config:t.entries.map(n=>({key:n.key,value:n.value,source:n.source,hint:n.hint})),statusError:t.statusError}}async function iy(e){if(!e.key||typeof e.key!="string")return{success:!1,error:"key is required. Call config_list first to see available keys."};if(e.value===void 0)return{success:!1,error:"value is required. Use config_unset to remove a setting."};p.info("config:set",{key:e.key});try{let t=ho(e.key,e.value);return p.info("config:set:success",{key:t.key,requiresRestart:t.requiresRestart}),{success:!0,key:t.key,value:t.value,requiresRestart:t.requiresRestart,path:t.path,message:t.requiresRestart?`Saved ${t.key}. Restart Claude Code for the change to take effect.`:`Saved ${t.key}.`}}catch(t){let n=t instanceof it?"UNKNOWN_KEY":t instanceof at?"SERVER_CONTROLLED":t instanceof Ct?"RETIRED_KEY":"INVALID_VALUE";return p.warn("config:set:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(Et).sort()}}}async function ay(e){if(!e.key||typeof e.key!="string")return{success:!1,error:"key is required. Call config_list first to see which keys are currently set via settings.json."};p.info("config:unset",{key:e.key});try{let t=yo(e.key);return p.info("config:unset:success",{key:t.key,removed:t.removed}),{success:!0,key:t.key,removed:t.removed,requiresRestart:t.requiresRestart,path:t.path,message:t.removed?t.requiresRestart?`Removed ${t.key}. Restart Claude Code for the change to take effect.`:`Removed ${t.key}.`:`${t.key} was not set in settings.json \u2014 nothing to remove.`}}catch(t){let n=t instanceof it?"UNKNOWN_KEY":t instanceof at?"SERVER_CONTROLLED":t instanceof Ct?"RETIRED_KEY":"INVALID_VALUE";return p.warn("config:unset:rejected",{key:e.key,code:n,error:t.message}),{success:!1,error:t.message,code:n,settableKeys:Object.keys(Et).sort()}}}async function cy(e){let t=await P.getStatus(e),n=t.attestationRequired!==!1,r=Yo(t),o=ie(),s=n?r?o?`${Ko()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${Ko()} is not available in this process. ${Ri()}`:"Biometric attestation is enabled on the account, but no attestation key is registered. Payments on this device proceed without a biometric signature; processor declines such as INVALID_OR_MISSING_CONFIG are card/account configuration issues, not something biometric setup fixes.":"Biometric attestation is NOT required for payments. Payments will proceed without biometric confirmation.";return{required:n,hasAttestationKey:!!t.hasAttestationKey,hasTelegramAttestationKey:!!t.hasTelegramAttestationKey,hasAnyAttestationKey:r,touchIdAvailable:o,platform:process.platform,effectiveRequiredOnThisDevice:n&&r&&o,canDisableFromThisDevice:!n||!r||o,message:s}}async function ly(e){p.info("biometric:on");let t=await P.setBiometricPreference({required:!0},e);return t.success?(Iu(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:t.error||"unknown error"}}async function uy(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return hn("MISSING_CONFIRMATION","Please confirm by setting confirm: true. Disabling Touch ID is a security downgrade \u2014 the user will be prompted for one final Touch ID confirmation before the change takes effect.");p.info("biometric:off");try{return await Te(async()=>{let n=await P.getStatus(t),r;if(Yo(n)&&(r=await Xe("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${Ko()} confirmation required to disable \u2014 not available on this device.`);let o=await P.setBiometricPreference({required:!1,attestation:r},t);if(!o.success)throw new Error(o.error||"unknown error");return Iu(),{success:!0,required:!1,message:"Touch ID is no longer required for payments."}})}catch(n){if(p.error("biometric:off:failure",{error:n.message}),n instanceof Lt)return Jo(n,"biometric_off");throw n}}var vu=3e4,dy=3e5;async function Pu(e,t,n="login"){let r=pe.randomUUID(),o=`${e}${e.includes("?")?"&":"?"}state=${r}`,s=Je(o);return!s.opened&&s.blockedReason!=="non_internal_host"&&s.blockedReason!=="invalid_url"?Ou(o,s,n):s.opened?{...await Mu(r,t,n),browserUrl:o}:{success:!1,browserUrl:o,message:`Could not open the browser URL safely. Please check the configured auth server and try again. URL: ${o}`}}function Ou(e,t,n){let r=n==="enrollment"?"card enrollment":n==="attestation-recovery"?"biometric reset":"login",o=t.blockedReason==="suppressed"?"browser auto-open is suppressed":t.blockedReason==="headless"?"this process appears to be headless":t.blockedReason==="unsupported_platform"?"this platform has no configured browser opener":"browser auto-open is unavailable";return{success:!1,requiresBrowser:!0,browserUrl:e,message:`Browser auto-open was skipped because ${o}. Open this URL to continue ${r}: ${e}`}}async function Mu(e,t,n="login"){let r=Date.now()+dy;for(;Date.now()<r;)try{let s=await fetch(`${Wo()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:vu,...t&&{user_context:t}}),signal:AbortSignal.timeout(vu+5e3)});if(!s.ok){await St(s,a=>{p.warn("auth_status:retry_after_http_error",{status:s.status,delayMs:a})});continue}let i=await s.json();if(i.status==="pending")continue;if(i.status==="expired")return{success:!1,message:"Session expired. Please try again."};if(i.status==="error")return{success:!1,message:i.error||"Authentication failed. Please try again."};if(i.status==="complete"){if(n==="attestation-recovery"||i.attestationCleared)return p.info("auth:attestation_recovery_complete",{user:i.user||""}),{success:!0,message:"Server-side biometric state cleared. Run visa-cli setup to register a fresh key before reenabling Touch ID."};let a=i.welcomeBonusCents??0,l=Hl(a);if(n!=="enrollment"&&i.sessionToken){await F.saveSessionToken(i.sessionToken);let u=i.user||"",d=i.last4||"****";return p.info("auth:login_complete",{user:u,last4:d,bonusCents:a}),{success:!0,message:`Signed in as ${u}. Card ending in ${d} enrolled and ready for payments.`,...l||{}}}let c=i.last4||"****";return p.info("auth:card_added",{last4:c,bonusCents:a}),{success:!0,message:`Card ending in ${c} enrolled and ready for payments.`,...l||{}}}}catch{await St(void 0,s=>{p.warn("auth_status:retry_after_network_error",{delayMs:s})})}return{success:!1,message:n==="enrollment"?"Card enrollment timed out. Please try again.":n==="attestation-recovery"?"Biometric reset timed out. Please try reset again.":"Login timed out. Please try again."}}async function Nu(e){let t=pe.randomUUID(),n;try{n=await P.startAttestationRecovery(t,e)}catch(s){return{success:!1,message:`Could not start biometric reset: ${s?.message||"unknown error"}`}}if(!n.success||!n.recoveryUrl)return{success:!1,message:n.error||"Could not start biometric reset. Please try again."};let r=Je(n.recoveryUrl);return!r.opened&&r.blockedReason!=="non_internal_host"&&r.blockedReason!=="invalid_url"?Ou(n.recoveryUrl,r,"attestation-recovery"):r.opened?{...await Mu(t,e,"attestation-recovery"),browserUrl:n.recoveryUrl}:{success:!1,browserUrl:n.recoveryUrl,message:`Could not open the browser URL safely. Please check the configured auth server and try again. URL: ${n.recoveryUrl}`}}async function my(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to remove this card."};let n=e.cardId;if(!Number.isInteger(n)||n<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to get the opaque cardId for the card you want to remove."};p.info("cards:remove_attempt",{cardId:n});let r=`remove-card:${n}`,o=`remove ${await $u(n,t)}`;try{return await Te(async()=>{let s=await Xe(r,0,"",o,t,{forceRequired:!0}),i=await P.removeCard(n,{attestation:s},t);return p.info("cards:remove_success",{cardId:n,promotedId:i?.promotedId??null}),i})}catch(s){if(p.error("cards:remove_failure",{cardId:n,error:s.message}),s instanceof Lt)return Jo(s,"remove_card");throw s}}async function py(e,t){let n=e.cardId;if(!Number.isInteger(n)||n<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to get the opaque cardId for the card you want to make default."};p.info("cards:set_default_attempt",{cardId:n});let r=`set-default-card:${n}`,o=`set ${await $u(n,t)} as default`;try{return await Te(async()=>{let s=await Xe(r,0,"",o,t,{forceRequired:!0}),i=await P.setDefaultCard(n,{attestation:s},t);return p.info("cards:set_default_success",{cardId:n}),i})}catch(s){if(p.error("cards:set_default_failure",{cardId:n,error:s.message}),s instanceof Lt)return Jo(s,"set_default_card");throw s}}async function fy(e){return p.info("auth:login_attempt"),Pu(`${Wo()}/login`,e)}function gy(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 hy(e={},t){let n;try{n=gy(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return zo(async()=>{let r=await ru(P,Xe,{toolName:"start_session",userContext:t,capCentsOverride:n});p.info("session:started",{budgetId:r.budgetId,totalCents:r.totalCents,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious});let o=(r.appliedCapCents/100).toFixed(2),s=(r.requestedCapCents/100).toFixed(2),i=`Session started with a $${o} cap. Paid calls will use this approval window until you close it, it expires, or this MCP process restarts.`,a=r.clampedReason==="balance"?`${i} Note: requested cap of $${s} was clamped to your prepaid balance of $${o}. Run buy_credits to top up if you need a larger session.`:i;return{success:!0,budgetId:r.budgetId,totalCents:r.totalCents,amountUsd:r.totalCents/100,requestedCapCents:r.requestedCapCents,appliedCapCents:r.appliedCapCents,clampedReason:r.clampedReason,closedPrevious:r.closedPrevious,message:a}})}async function yy(){let e=Nt();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 _y(){return zo(async()=>{let e=Nt();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 Do(P);p.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=fh(e),r=ze(t.finalCumulativeMicros),o=r??(typeof t.finalCumulativeCents=="number"?BigInt(Math.max(0,t.finalCumulativeCents))*10000n:n.micros),s=Number(o/10000n);return p.info("session:closed:final-spend",{budgetId:t.budgetId,closedServerSide:t.closedServerSide,finalSpendMicros:o.toString(),finalSpendCents:s,finalSpendSource:r!==null?"server.finalCumulativeMicros":typeof t.finalCumulativeCents=="number"?"server.finalCumulativeCents":n.source,totalCents:e.totalCents}),{success:!0,closed:!0,closedServerSide:t.closedServerSide,budgetId:t.budgetId,finalEstimatedCumulativeCents:s,finalEstimatedCumulativeMicros:o.toString(),totalCents:e.totalCents,message:t.closedServerSide?`Explicit approval window closed. Spent ${ph(o)} of $${(e.totalCents/100).toFixed(2)} cap. Future paid calls are pay-as-you-go until you start a new explicit approval window.`:"Explicit approval window cleared locally; server-side close call did not succeed (likely already closed). Future paid calls are pay-as-you-go until you start a new explicit approval window."}})}async function vy(e){if(p.info("auth:add_card_attempt"),!await F.getSessionToken())return{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."};let{code:n}=await P.createEnrollCode();return Pu(`${Wo()}/enroll-card?code=${encodeURIComponent(n)}`,e,"enrollment")}async function by(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};p.info("reset:attempt");let n=!1;try{let r=await P.getStatus(t);if(r&&Yo(r)){let o=await Nu(t);if(!o.success)return o;n=!0}}catch(r){let o=r?.message||"unknown error";if(!/not logged in|session.*expired|no local credentials/i.test(o))return{success:!1,message:`Could not check server biometric state: ${o}`};p.warn("reset:server_attestation_status_unavailable",{error:o})}try{await P.logout(void 0,t)}catch{}if(await F.clearAll(),ie())try{await Io()}catch{}return p.info("reset:success"),{success:!0,message:n?"Device reset. Server-side biometric state and local credentials have been cleared. Use the login tool or visa-cli setup to re-enroll.":"Device reset. Local credentials and keys have been removed. Use the login tool or visa-cli setup to re-enroll."}}async function Sy(e){let t=e.query?.trim()||void 0,n=e.category?.trim()||void 0,r=!t&&!n;p.info("catalog:discover",{query:t,category:n,browseAll:r});try{let s=(await P.catalogSearch(t,n)).tools||[];if(s.length===0)return{content:[{type:"text",text:r?"The tool catalog is currently empty.":`No tools found for "${t||n}". Try a different search term.`}]};if(r){let a={};for(let c of s){let u=c.category||"other";(a[u]??=[]).push(c)}let l=Object.keys(a).sort().map(c=>{let u=a[c].map((f,m)=>`${m+1}. **${f.name}** (${f.id})
127
127
  ${f.description}
128
- Provider: ${f.provider} | Price: ${lu(f)}
128
+ Provider: ${f.provider} | Price: ${bu(f)}
129
129
  Params: ${Object.keys(f.inputSchema?.properties||f.inputSchema||{}).join(", ")||"none"}`).join(`
130
130
 
131
131
  `);return`## ${c.length<=3?c.toUpperCase():c.charAt(0).toUpperCase()+c.slice(1)}
132
132
 
133
133
  ${u}`}).join(`
134
134
 
135
- `);return m.info("catalog:discovered",{count:s.length}),{content:[{type:"text",text:`Available ${s.length} tool(s) by category:
135
+ `);return p.info("catalog:discovered",{count:s.length}),{content:[{type:"text",text:`Available ${s.length} tool(s) by category:
136
136
 
137
137
  ${l}
138
138
 
139
139
  Use execute_tool with the tool id and required params to run any of these.`}],_tools:s}}let i=s.map((a,l)=>`${l+1}. **${a.name}** (${a.id})
140
140
  ${a.description}
141
- Provider: ${a.provider} | Category: ${a.category} | Price: ${lu(a)}
141
+ Provider: ${a.provider} | Category: ${a.category} | Price: ${bu(a)}
142
142
  Params: ${Object.keys(a.inputSchema?.properties||a.inputSchema||{}).join(", ")||"none"}`).join(`
143
143
 
144
- `);return m.info("catalog:discovered",{count:s.length}),{content:[{type:"text",text:`Found ${s.length} tool(s):
144
+ `);return p.info("catalog:discovered",{count:s.length}),{content:[{type:"text",text:`Found ${s.length} tool(s):
145
145
 
146
146
  ${i}
147
147
 
148
- Use execute_tool with the tool id and required params to run any of these.`}],_tools:s}}catch(o){throw m.error("catalog:discover:error",{error:o.message}),new Error(`Failed to search tool catalog: ${o.message}`)}}function lu(e){return e.priceDisplay??`$${(e.priceCents/100).toFixed(2)}`}function sy(e,t){return t==="image"||t==="video"||t==="audio"?t:e?.match(/\.(mp4|webm|mov)/)?"video":"image"}function No(e,t){return Array.isArray(e.type)?e.type.includes(t):e.type===t}function iy(e,t,n){let r=e.inputSchema;if(!r||r.type!=="object")return null;let o=r.properties??{},s=n??e.id;for(let a of Object.keys(t))if(!Object.prototype.hasOwnProperty.call(o,a)){let l=Object.keys(o),c=l.length>0?` Expected: ${l.join(", ")}.`:"";return`Unknown parameter "${a}" for ${s}.${c}`}let i=(r.required??[]).filter(a=>!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0);if(i.length>1)return`${i.join(", ")} are required for ${s}.`;for(let a of r.required??[]){if(!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0)return`${a} is required for ${s}.`;if(t[a]===null)return`${a} cannot be null.`;if(typeof t[a]=="string"&&t[a].trim()==="")return`${a} cannot be empty.`}for(let[a,l]of Object.entries(t)){let c=o[a];if(!(!c||l===void 0||l===null)){if(c.enum&&!c.enum.includes(l))return`${a} must be one of: ${c.enum.map(String).join(", ")}.`;if(No(c,"integer")){if(typeof l!="number"||!Number.isInteger(l))return`${a} must be an integer.`}else if(No(c,"number")){if(typeof l!="number"||!Number.isFinite(l))return`${a} must be a number.`}else if(No(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(No(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 Cu(e){let t=mr(e);if(t)return t;try{return await $.catalogTool(e)}catch(n){return m.warn("catalog:resolve:error",{tool:e,error:n?.message||String(n)}),null}}function Tu(e){let t=e.priceCents,n=e.pricing;return e.executionMode==="free_authenticated"||e.accessMode==="free"||n?.free===!0||t===0||n?.amount===0}async function ay(e,t,n="execute_tool"){let{tool_id:r,params:o,...s}=e,i=o||s;if(!r)return Oo("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 Cu(r);if(!a)return Oo(`Unknown tool: '${r}'. Use discover_tools first to find available tools.`,"UNKNOWN_TOOL");if(a.deprecated){let p=a.replacementTool?` Use '${a.replacementTool}' instead.`:"";return Oo(`Tool '${r}' is deprecated and is no longer available for new paid calls.${p}`,"DEPRECATED_TOOL")}let c=iy(a,i,n&&n!=="execute_tool"?n:void 0);if(c)return m.info("catalog:execute:validation_failed",{tool:r,metaTool:n,error:c}),Oo(c);let u=await Ho(r,i,t,n);if(u)return u;if(Tu(a)){m.info("catalog:execute:free",{tool:r,metaTool:n});let p=await $.shortcut(r,i,6e4,t,n);return p&&typeof p=="object"&&!Array.isArray(p)&&p.merchantName==null&&(p.merchantName=a.name??r),p}let d=await pt(r,void 0,t),f=me.randomUUID();m.info("payment:attempt",{tool:r,amount:d.amount,merchant:d.merchantName});try{return await Ce(async()=>{let p;try{p=await Lt({toolId:r,toolParams:i,estimatedAmountCents:ft(d),userContext:t,metaTool:n,timeoutMs:12e4,idempotencyKey:f})}catch(_){if(_ instanceof ge)return ze(_);throw _}if(m.info("payment:success",{tool:r,amount:d.amount,merchant:d.merchantName,mode:"session"}),p&&typeof p=="object"&&!Array.isArray(p)&&p.merchantName==null&&(p.merchantName=a?.name??r),p.urls?.length){p.urls.forEach(T=>We(T));let _=sy(p.urls[0],p.mediaType);br({prompt:i.prompt||`${r} execution`,tool:r,mediaUrl:p.urls[0],mediaType:_,cost:p.amount??d.amount,transactionId:p.transactionId,userContext:t})}return p})}catch(p){return p instanceof le?(m.warn("payment:declined",{tool:r,amount:d.amount,merchant:d.merchantName,code:p.code,retryable:p.retryable}),Je(p,d)):(cy(p?.message)?m.warn("payment:ambiguous",{tool:r,amount:d.amount,merchant:d.merchantName,error:p.message,note:"Polling/timeout error on async tool \u2014 call may have succeeded. Verify via `visa-cli transactions list`."}):m.error("payment:failure",{tool:r,amount:d.amount,merchant:d.merchantName,error:p.message}),Zg({toolId:r,surface:n,merchantName:d.merchantName,amount:d.amount,message:p?.message||"Tool execution failed."}))}}function cy(e){return e?/\b(task_id|polling?|timeout|timed out|queue|IN_QUEUE|aborted)\b/i.test(e):!1}var Oe=class{static async getStatus(t){return Lh(t)}static async getVisaSmi(t,n){return Sh(t,n)}static async getCards(t){return Uh(t)}static async transactionHistory(t,n){return Dh(t||{},n)}static async feedback(t,n){return jh(t,n)}static async updateSpendingControls(t,n){return qh(t,n)}static async configList(t){return Vh(t||{})}static async configSet(t){return Hh(t||{})}static async configUnset(t){return Bh(t||{})}static async biometricStatus(t){return Kh(t)}static async biometricOn(t){return Gh(t)}static async biometricOff(t,n){return zh(t,n)}static async reset(t,n){return ry(t,n)}static async login(t){return Xh(t)}static async closeSession(t){return ty()}static async startSession(t,n){return Qh(t||{},n)}static async getSessionStatus(t){return ey()}static async addCard(t){return ny(t)}static async removeCard(t,n){return Jh(t,n)}static async setDefaultCard(t,n){return Yh(t,n)}static async buyCredits(t,n){return Fh(t,n)}static async batch(t,n){return Oh(t,n)}static async discoverTools(t){return oy(t)}static async executeTool(t,n,r="execute_tool"){return ay(t,n,r)}static async shortcut(t,n,r){switch(t){case"generate_image_card":return wh(n,r);case"generate_image_fast_card":return xh(n,r);case"generate_video_tempo_card":return kh(n,r);case"generate_music_tempo_card":return Ch(n,r);case"check_music_status_tempo_card":return Th(n,r);case"query_onchain_prices_card":return Eh(n,r);default:{let o=await pt(t,void 0,r);m.info("payment:attempt",{tool:t});try{let s=await Lt({toolId:t,toolParams:n,estimatedAmountCents:ft(o),userContext:r,timeoutMs:6e4});return m.info("payment:success",{tool:t,mode:"session"}),s.urls?.length&&s.urls.forEach(i=>We(i)),s}catch(s){if(s instanceof ge)return ze(s);if(s instanceof le)return m.warn("payment:declined",{tool:t,code:s.code,retryable:s.retryable}),Je(s,o);throw m.error("payment:failure",{tool:t,error:s.message}),s}}}}static async submitFeedback(t,n,r){m.info("feedback:submit",{length:t.length,transactionId:n,hasContext:!!r});try{let o=await $.submitFeedback(t,n,r);return m.info("feedback:submitted",{transactionId:n}),o}catch(o){let s=o instanceof Error?o.message:"Unknown error";throw m.error("feedback:error",{error:s,transactionId:n}),o}}static async getFeedback(t,n){m.info("feedback:list",{limit:t||20});try{let r=await $.getFeedback(t,n);return m.info("feedback:listed",{count:r?.feedback?.length||0}),r}catch(r){let o=r instanceof Error?r.message:"Unknown error";throw m.error("feedback:error",{error:o}),r}}};function Eu(e,t=process.stderr){if(qe()||!e?.updateAvailable)return!1;let{latestVersion:n}=e.updateAvailable;if(!n)return!1;let r=`Update available: v${n}. Run: visa-cli update`;return t.write(`
148
+ Use execute_tool with the tool id and required params to run any of these.`}],_tools:s}}catch(o){throw p.error("catalog:discover:error",{error:o.message}),new Error(`Failed to search tool catalog: ${o.message}`)}}function bu(e){return e.priceDisplay??`$${(e.priceCents/100).toFixed(2)}`}function wy(e,t){return t==="image"||t==="video"||t==="audio"?t:e?.match(/\.(mp4|webm|mov)/)?"video":"image"}function Ho(e,t){return Array.isArray(e.type)?e.type.includes(t):e.type===t}function xy(e,t,n){let r=e.inputSchema;if(!r||r.type!=="object")return null;let o=r.properties??{},s=n??e.id;for(let a of Object.keys(t))if(!Object.prototype.hasOwnProperty.call(o,a)){let l=Object.keys(o),c=l.length>0?` Expected: ${l.join(", ")}.`:"";return`Unknown parameter "${a}" for ${s}.${c}`}let i=(r.required??[]).filter(a=>!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0);if(i.length>1)return`${i.join(", ")} are required for ${s}.`;for(let a of r.required??[]){if(!Object.prototype.hasOwnProperty.call(t,a)||t[a]===void 0)return`${a} is required for ${s}.`;if(t[a]===null)return`${a} cannot be null.`;if(typeof t[a]=="string"&&t[a].trim()==="")return`${a} cannot be empty.`}for(let[a,l]of Object.entries(t)){let c=o[a];if(!(!c||l===void 0||l===null)){if(c.enum&&!c.enum.includes(l))return`${a} must be one of: ${c.enum.map(String).join(", ")}.`;if(Ho(c,"integer")){if(typeof l!="number"||!Number.isInteger(l))return`${a} must be an integer.`}else if(Ho(c,"number")){if(typeof l!="number"||!Number.isFinite(l))return`${a} must be a number.`}else if(Ho(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(Ho(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 Lu(e){let t=yr(e);if(t)return t;try{return await P.catalogTool(e)}catch(n){return p.warn("catalog:resolve:error",{tool:e,error:n?.message||String(n)}),null}}function Uu(e){let t=e.priceCents,n=e.pricing;return e.executionMode==="free_authenticated"||e.accessMode==="free"||n?.free===!0||t===0||n?.amount===0}async function ky(e,t,n="execute_tool"){let{tool_id:r,params:o,...s}=e,i=o||s;if(!r)return Vo("tool_id is required. Use discover_tools first to find available tools.","MISSING_TOOL_ID");p.info("catalog:execute",{tool:r,metaTool:n});let a=await Lu(r);if(!a)return Vo(`Unknown tool: '${r}'. Use discover_tools first to find available tools.`,"UNKNOWN_TOOL");if(a.deprecated){let m=a.replacementTool?` Use '${a.replacementTool}' instead.`:"";return Vo(`Tool '${r}' is deprecated and is no longer available for new paid calls.${m}`,"DEPRECATED_TOOL")}let c=xy(a,i,n&&n!=="execute_tool"?n:void 0);if(c)return p.info("catalog:execute:validation_failed",{tool:r,metaTool:n,error:c}),Vo(c);let u=await Xo(r,i,t,n);if(u)return u;if(Uu(a)){p.info("catalog:execute:free",{tool:r,metaTool:n});let m=await P.shortcut(r,i,6e4,t,n);return m&&typeof m=="object"&&!Array.isArray(m)&&m.merchantName==null&&(m.merchantName=a.name??r),m}let d=await ft(r,void 0,t),f=pe.randomUUID();p.info("payment:attempt",{tool:r,amount:d.amount,merchant:d.merchantName});try{return await Te(async()=>{let m;try{m=await Ut({toolId:r,toolParams:i,estimatedAmountCents:gt(d),userContext:t,metaTool:n,timeoutMs:12e4,idempotencyKey:f})}catch(_){if(_ instanceof he)return We(_);throw _}if(p.info("payment:success",{tool:r,amount:d.amount,merchant:d.merchantName,mode:"session"}),m&&typeof m=="object"&&!Array.isArray(m)&&m.merchantName==null&&(m.merchantName=a?.name??r),m.urls?.length){m.urls.forEach(S=>Je(S));let _=wy(m.urls[0],m.mediaType);Cr({prompt:i.prompt||`${r} execution`,tool:r,mediaUrl:m.urls[0],mediaType:_,cost:m.amount??d.amount,transactionId:m.transactionId,userContext:t})}return m})}catch(m){return m instanceof ue?(p.warn("payment:declined",{tool:r,amount:d.amount,merchant:d.merchantName,code:m.code,retryable:m.retryable}),Ye(m,d)):(Cy(m?.message)?p.warn("payment:ambiguous",{tool:r,amount:d.amount,merchant:d.merchantName,error:m.message,note:"Polling/timeout error on async tool \u2014 call may have succeeded. Verify via `visa-cli transactions list`."}):p.error("payment:failure",{tool:r,amount:d.amount,merchant:d.merchantName,error:m.message}),gh({toolId:r,surface:n,merchantName:d.merchantName,amount:d.amount,message:m?.message||"Tool execution failed."}))}}function Cy(e){return e?/\b(task_id|polling?|timeout|timed out|queue|IN_QUEUE|aborted)\b/i.test(e):!1}var Ne=class{static async getStatus(t){return Qh(t)}static async getVisaSmi(t,n){return Dh(t,n)}static async getCards(t){return ey(t)}static async transactionHistory(t,n){return ty(t||{},n)}static async feedback(t,n){return ny(t,n)}static async updateSpendingControls(t,n){return oy(t,n)}static async configList(t){return sy(t||{})}static async configSet(t){return iy(t||{})}static async configUnset(t){return ay(t||{})}static async biometricStatus(t){return cy(t)}static async biometricOn(t){return ly(t)}static async biometricOff(t,n){return uy(t,n)}static async reset(t,n){return by(t,n)}static async login(t){return fy(t)}static async closeSession(t){return _y()}static async startSession(t,n){return hy(t||{},n)}static async getSessionStatus(t){return yy()}static async addCard(t){return vy(t)}static async removeCard(t,n){return my(t,n)}static async setDefaultCard(t,n){return py(t,n)}static async buyCredits(t,n){return ry(t,n)}static async batch(t,n){return Xh(t,n)}static async discoverTools(t){return Sy(t)}static async executeTool(t,n,r="execute_tool"){return ky(t,n,r)}static async shortcut(t,n,r){switch(t){case"generate_image_card":return jh(n,r);case"generate_image_fast_card":return Fh(n,r);case"generate_video_tempo_card":return qh(n,r);case"generate_music_tempo_card":return Vh(n,r);case"check_music_status_tempo_card":return Hh(n,r);case"query_onchain_prices_card":return Bh(n,r);default:{let o=await ft(t,void 0,r);p.info("payment:attempt",{tool:t});try{let s=await Ut({toolId:t,toolParams:n,estimatedAmountCents:gt(o),userContext:r,timeoutMs:6e4});return p.info("payment:success",{tool:t,mode:"session"}),s.urls?.length&&s.urls.forEach(i=>Je(i)),s}catch(s){if(s instanceof he)return We(s);if(s instanceof ue)return p.warn("payment:declined",{tool:t,code:s.code,retryable:s.retryable}),Ye(s,o);throw p.error("payment:failure",{tool:t,error:s.message}),s}}}}static async submitFeedback(t,n,r){p.info("feedback:submit",{length:t.length,transactionId:n,hasContext:!!r});try{let o=await P.submitFeedback(t,n,r);return p.info("feedback:submitted",{transactionId:n}),o}catch(o){let s=o instanceof Error?o.message:"Unknown error";throw p.error("feedback:error",{error:s,transactionId:n}),o}}static async getFeedback(t,n){p.info("feedback:list",{limit:t||20});try{let r=await P.getFeedback(t,n);return p.info("feedback:listed",{count:r?.feedback?.length||0}),r}catch(r){let o=r instanceof Error?r.message:"Unknown error";throw p.error("feedback:error",{error:o}),r}}};function Du(e,t=process.stderr){if(Ve()||!e?.updateAvailable)return!1;let{latestVersion:n}=e.updateAvailable;if(!n)return!1;let r=`Update available: v${n}. Run: visa-cli update`;return t.write(`
149
149
  \x1B[33m\u2191 ${r}\x1B[0m
150
- `),!0}function Au(e){let t=Array.isArray(e.inputSchema?.required)?e.inputSchema.required.filter(o=>typeof o=="string"):[],n=e.inputSchema?.properties&&typeof e.inputSchema.properties=="object"?e.inputSchema.properties:{};if(t.length===0)return{prompt:"a lobster"};let r={};for(let o of t)r[o]=ly(o,n[o]?.description);return r}function ly(e,t){let n=e.toLowerCase();return n==="prompt"?"a lobster":n==="text"?"Hello from Visa CLI.":n.endsWith("image_url")||n==="image_url"?"https://example.com/sample.jpg":n.endsWith("audio_url")||n==="audio_url"?"https://example.com/sample.wav":n.endsWith("video_url")||n==="video_url"?"https://example.com/sample.mp4":n==="taskid"||n==="task_id"?"task_abc123":n==="request_id"||n==="requestid"?"req_abc123":n==="model_path"||n==="model"?"fal-ai/flux/schnell":n==="language"?"en":t&&/\bUR?L\b|https?:\/\//i.test(t)?"https://example.com/sample":"example"}function uy(e){let t=Xe(e.referralCode,"");if(!t)return[];let n=["Referrals",` Your code ${t}`],r=Xe(e.referralLink,"");if(r&&n.push(` Your link ${r}`),typeof e.referralCount=="number"&&Number.isFinite(e.referralCount)){let o=Math.max(0,Math.trunc(e.referralCount));n.push(` Joined ${o} ${o===1?"person":"people"} via your link`)}return n}var dy=20;function Iu(e,t,n,r){let o=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=_y(e.spendingControls).dailyLimit,a=Math.max(0,Sr(e.dailyCardFundedTopupSpent??e.dailySpent)),l=i>0?Math.min(i,Math.max(0,Sr(e.dailyCardFundedTopupRemaining??e.dailyRemaining??i-a))):0,c=i>0?Math.min(1,a/i):0,d=(Array.isArray(t)?t:[]).filter(fy),f=d.slice(0,3),p=gy(d,3),_=(e.cards??[]).slice(0,3),T=r.latestVersion?gn(r.latestVersion):"",P=r.updateCheckDisabled?"update checks disabled":T?`update ready: v${T}`:"up to date",H=Math.round(c*100),D=Xe(e.status,e.enrolled?"approved":"not enrolled"),w=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${D} | touch id: ${n?"ready":"unavailable"}`,`Version: v${o} | ${P}`,`Top-up meter: ${Ru(c)} ${String(H).padStart(3," ")}% | remaining ${Dn(l)}/day | daily top-up cap ${Dn(i)}`,"","Card top-ups",` Remaining ${Dn(l)} / ${Dn(i)}`,` Usage ${Ru(c)} ${H}%`,` Top-ups today ${Dn(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",..._.length>0?_.map(k=>` ${yy(k)}`):[" No cards enrolled"],"","Last 3 services",...p.length>0?p.map((k,L)=>` ${L+1}. ${k}`):[" No paid services yet"],"","Recent receipts",...f.length>0?f.map(k=>` ${hy(k)}`):[" No receipts yet"]],y=uy(e);return y.length>0&&w.push("",...y),T&&!r.updateCheckDisabled?(w.push("",`Update: v${T} ready \u2014 run \`visa-cli update\``),r.updateMessage&&w.push(` ${gn(r.updateMessage)}`)):r.updateMessage&&w.push("",`Update: ${gn(r.updateMessage)}`),`${w.join(`
150
+ `),!0}function ju(e){let t=Array.isArray(e.inputSchema?.required)?e.inputSchema.required.filter(o=>typeof o=="string"):[],n=e.inputSchema?.properties&&typeof e.inputSchema.properties=="object"?e.inputSchema.properties:{};if(t.length===0)return{prompt:"a lobster"};let r={};for(let o of t)r[o]=Ty(o,n[o]?.description);return r}function Ty(e,t){let n=e.toLowerCase();return n==="prompt"?"a lobster":n==="text"?"Hello from Visa CLI.":n.endsWith("image_url")||n==="image_url"?"https://example.com/sample.jpg":n.endsWith("audio_url")||n==="audio_url"?"https://example.com/sample.wav":n.endsWith("video_url")||n==="video_url"?"https://example.com/sample.mp4":n==="taskid"||n==="task_id"?"task_abc123":n==="request_id"||n==="requestid"?"req_abc123":n==="model_path"||n==="model"?"fal-ai/flux/schnell":n==="language"?"en":t&&/\bUR?L\b|https?:\/\//i.test(t)?"https://example.com/sample":"example"}function Ey(e){let t=Ze(e.referralCode,"");if(!t)return[];let n=["Referrals",` Your code ${t}`],r=Ze(e.referralLink,"");if(r&&n.push(` Your link ${r}`),typeof e.referralCount=="number"&&Number.isFinite(e.referralCount)){let o=Math.max(0,Math.trunc(e.referralCount));n.push(` Joined ${o} ${o===1?"person":"people"} via your link`)}return n}var Ay=20;function qu(e,t,n,r){let o=r.currentVersion==="0.0.0"&&e.version?e.version:r.currentVersion,i=Ny(e.spendingControls).dailyLimit,a=Math.max(0,Tr(e.dailyCardFundedTopupSpent??e.dailySpent)),l=i>0?Math.min(i,Math.max(0,Tr(e.dailyCardFundedTopupRemaining??e.dailyRemaining??i-a))):0,c=i>0?Math.min(1,a/i):0,d=(Array.isArray(t)?t:[]).filter($y),f=d.slice(0,3),m=Py(d,3),_=(e.cards??[]).slice(0,3),S=r.latestVersion?yn(r.latestVersion):"",$=r.updateCheckDisabled?"update checks disabled":S?`update ready: v${S}`:"up to date",V=Math.round(c*100),D=Ze(e.status,e.enrolled?"approved":"not enrolled"),x=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${D} | touch id: ${n?"ready":"unavailable"}`,`Version: v${o} | ${$}`,`Top-up meter: ${Fu(c)} ${String(V).padStart(3," ")}% | remaining ${Vn(l)}/day | daily top-up cap ${Vn(i)}`,"","Card top-ups",` Remaining ${Vn(l)} / ${Vn(i)}`,` Usage ${Fu(c)} ${V}%`,` Top-ups today ${Vn(a)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",..._.length>0?_.map(C=>` ${My(C)}`):[" No cards enrolled"],"","Last 3 services",...m.length>0?m.map((C,L)=>` ${L+1}. ${C}`):[" No paid services yet"],"","Recent receipts",...f.length>0?f.map(C=>` ${Oy(C)}`):[" No receipts yet"]],y=Ey(e);return y.length>0&&x.push("",...y),S&&!r.updateCheckDisabled?(x.push("",`Update: v${S} ready \u2014 run \`visa-cli update\``),r.updateMessage&&x.push(` ${yn(r.updateMessage)}`)):r.updateMessage&&x.push("",`Update: ${yn(r.updateMessage)}`),`${x.join(`
151
151
  `)}
152
- `}function my(e){return e.tool_name!=null}function py(e){return Sr(e.amount)===0&&e.status==="failed"}function fy(e){return my(e)&&!py(e)}function gy(e,t=1/0){let n=new Set,r=[];for(let o of e){if(r.length>=t)break;let s=Xe(o.merchant_name,"Unknown merchant"),i=Xe(o.tool_name,"unknown_tool"),a=`${s} :: ${i}`;n.has(a)||(n.add(a),r.push(`${s} [${i}]`))}return r}function hy(e){let t=Xe(e.merchant_name,"Unknown merchant"),n=Xe(e.tool_name,"unknown_tool"),r=Dn(Sr(e.amount)),o=Xe(e.status,"unknown"),s=vy(e.created_at);return`${r} ${o.padEnd(9)} ${t} [${n}] ${s}`}function yy(e){let t=Xe(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function _y(e){return{dailyLimit:Sr(e?.daily_limit??e?.dailyLimit??0)}}function Sr(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function Dn(e){return`$${e.toFixed(2)}`}function Ru(e,t=dy){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function Xe(e,t){let n=gn(e??"").trim();return n.length>0?n:t}function vy(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?Xe(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function gn(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 by=/^[1-9]\d{0,9}$/;function xi(e){if(!by.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 $u(e){let t=gn(e.brand||"Visa"),n=gn(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 Ze=E(require("fs")),ne=E(require("path")),Sy=["npm","pnpm","yarn","bun"],wy=/\s+/,xy=process.platform==="win32"?"visa-cli.cmd":"visa-cli",ki=["node_modules","@visa","cli"];function ky(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(wy)[0]??"",r=n.indexOf("/"),o=r===-1?n:n.slice(0,r);return Sy.includes(o)?o:void 0}function Ci(e){if(!e)return;let t=e;try{t=Ze.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 Cy(e=process.argv[1]){return ky()??Ci(process.env.npm_execpath)??Ci(process.env.npm_node_execpath)??Ci(e)}function Ty(e=process.env.PATH??""){let t=[];for(let n of e.split(ne.delimiter))n&&t.push(n);return t}function Ey(e=process.env.PATH??""){let t=new Set,n=[];for(let r of Ty(e))try{let o=ne.join(r,xy);Ze.accessSync(o,Ze.constants.X_OK);let s=ne.resolve(o);t.has(s)||(t.add(s),n.push(o))}catch{}return n}function Pu(e){try{let t=Ze.readFileSync(ne.join(e,"package.json"),"utf-8"),n=JSON.parse(t);if(n.name==="@visa/cli"&&typeof n.version=="string")return n.version}catch{}}function Ay(e){let t=ne.resolve(e).split(ne.sep);for(let n=t.length-ki.length;n>=0;n--)if(ki.every((r,o)=>t[n+o]===r)){let r=t.slice(0,n+ki.length).join(ne.sep)||ne.sep;if(Pu(r))return r}}function Ry(e){if(!e)return;let t=ne.normalize(e),n=t.split(ne.sep),r=s=>s.every((a,l)=>n[n.length-s.length+l]===a)?n.slice(0,-s.length).join(ne.sep)||ne.parse(t).root:void 0,o=r(["lib","node_modules","@visa","cli"]);if(o)return o;if(process.platform==="win32")return r(["node_modules","@visa","cli"])}function Iy(e,t){let n=ne.resolve(e);try{n=Ze.realpathSync(e)}catch{}let r=Ay(n);return{binPath:e,realPath:n,packageRoot:r,version:r?Pu(r):void 0,prefix:Ry(r),isActive:n===t}}function $y(e,t=process.env.PATH??""){let n=e??process.argv[1],r=n?ne.resolve(n):"";try{n&&(r=Ze.realpathSync(n))}catch{}let o=e?[e]:[n,...Ey(t)].filter(Boolean),s=new Map;for(let d of o){let f=Iy(d,r),p=s.get(f.realPath);s.set(f.realPath,p?{...f,binPath:p.binPath}:f)}let i=[...s.values()],a=i.find(d=>d.isActive);!a&&i.length>0&&!e&&(a={...i[0],isActive:!0},i[0]=a);let l=new Set(i.map(d=>d.packageRoot).filter(Boolean)),c=!!a?.packageRoot&&l.size>1,u=a?.prefix;return{active:a,installs:i,hasConflictingInstalls:c,recommendedPrefix:u}}function Py(e,t=process.platform){return/^[A-Za-z0-9_./:@+-]+$/.test(e)?e:t==="win32"?`"${e.replace(/"/g,'""')}"`:`'${e.replace(/'/g,"'\\''")}'`}function Ti(e,t,n,r={}){let o=t??Cy(n)??"npm",s=r.withDiagnostics?$y(n):void 0,a=`@visa/cli@${e??"latest"}`;switch(o){case"npm":if(s?.hasConflictingInstalls&&s.recommendedPrefix){let l=s.recommendedPrefix;return{packageManager:o,command:"npm",args:["install","-g","--prefix",l,a],display:`npm install -g --prefix ${Py(l)} ${a}`,diagnostics:s}}return{packageManager:o,command:"npm",args:["install","-g",a],display:`npm install -g ${a}`,diagnostics:s};case"pnpm":return{packageManager:o,command:"pnpm",args:["add","-g",a],display:`pnpm add -g ${a}`,diagnostics:s};case"yarn":return{packageManager:o,command:"yarn",args:["global","add",a],display:`yarn global add ${a}`,diagnostics:s};case"bun":return{packageManager:o,command:"bun",args:["add","-g",a],display:`bun add -g ${a}`,diagnostics:s}}}function My(e){let t=e.isActive?" (active)":"",n=e.version?` v${e.version}`:" version unknown",r=e.prefix?` via ${e.prefix}`:"";return` - ${e.binPath}${t}: ${n}${r}`}function Ei(e,t){if(!e.hasConflictingInstalls)return null;let n=["Multiple Visa CLI installs detected.",...e.installs.map(My)];return t&&(e.recommendedPrefix?n.push("The update command below targets the active install so your shell actually picks up the new version."):n.push("The update command is shown below; remove duplicate installs if your shell still picks up an older version."),n.push(` ${t}`)),n.join(`
153
- `)}var Jo=E(yr());var Oy=["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 Ny(){let e=new Set;for(let t of Oy)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of fr)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var bw=Ny();var Ai=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 Cw=new Set(fr),Tw=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...Ai,...fr]);var j=E(require("fs")),O=E(require("path")),Mu=E(require("os")),Q=Mu.homedir(),Ly=["Claude_","Anthropic.ClaudeDesktop_"],jn=class extends Error{constructor(n,r,o){super(Dy(n,r,o));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function Ou(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
154
- `)}function Uy(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=Ou(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function Dy(e,t,n){let r=t.replace(Q,"~"),o=Ou(n).split(`
155
- `).find(Boolean),s=o?` (${o})`:"";return e.id==="codex"?`Could not update Codex MCP config at ${r}: filesystem access was denied${s}. In Codex, rerun with elevated filesystem access or run \`visa-cli install codex\` outside the sandbox.`:`Could not update ${e.displayName} MCP config at ${r}: filesystem access was denied${s}.`}function wr(){return process.env.APPDATA||O.join(Q,"AppData","Roaming")}function jy(){return process.env.LOCALAPPDATA||O.join(Q,"AppData","Local")}function Ri(e){return process.platform==="win32"?e.win32:e.posix}function Nu(){if(process.platform!=="win32")return;let e=O.join(jy(),"Packages");if(j.existsSync(e))try{let t=j.readdirSync(e,"utf-8");for(let n of Ly){let r=t.filter(o=>o.startsWith(n)).sort()[0];if(r)return O.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function Lu(){if(process.platform==="win32"){let e=Nu();return e?O.join(e,"claude_desktop_config.json"):O.join(wr(),"Claude","claude_desktop_config.json")}return O.join(Q,"Library","Application Support","Claude","claude_desktop_config.json")}function Uu(){if(process.platform!=="win32")return[O.join(Q,"Library","Application Support","Claude")];let e=[O.join(wr(),"Claude")],t=Nu();return t&&e.push(t),e}function Bo(e){return e.id==="claude-desktop"?Lu():e.globalConfigPath}function Fy(e){return e.id==="claude-desktop"?Uu():e.detectPaths}var Ue=[{id:"claude",displayName:"Claude Code",globalConfigPath:O.join(Q,".claude.json"),configKey:"mcpServers",detectPaths:[O.join(Q,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:Lu(),configKey:"mcpServers",detectPaths:Uu(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:O.join(Q,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[O.join(Q,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:O.join(Q,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[O.join(Q,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:O.join(Q,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[O.join(Q,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:Ri({win32:O.join(wr(),"Roo","mcp_settings.json"),posix:O.join(Q,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[O.join(Q,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:O.join(Q,".vscode","mcp.json"),configKey:"servers",detectPaths:[O.join(Q,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:Ri({win32:O.join(wr(),"Zed","settings.json"),posix:O.join(Q,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:Ri({win32:[O.join(wr(),"Zed")],posix:[O.join(Q,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:O.join(Q,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[O.join(Q,".codex")],postInstallHint:"Restart Codex to connect."}];function Ii(e){return Ue.find(t=>t.id===e)}function xr(e){return Fy(e).some(t=>{if(t.includes("*")){let n=O.dirname(t),r=O.basename(t).replaceAll("*","");if(!j.existsSync(n))return!1;try{return j.readdirSync(n).some(o=>o.startsWith(r))}catch{return!1}}return j.existsSync(t)})}function Du(){return{command:"node",args:[O.resolve(__dirname,"mcp-server/index.js")]}}function $i(e,t){return t==="project"?"json":e.configFormat??"json"}function qy(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 Pi(e,t){let n=`[mcp_servers.${t}]`,r=e.findIndex(s=>s.trim()===n);if(r===-1)return;let o=r+1;for(;o<e.length&&!e[o].trim().startsWith("[");)o++;return{start:r,end:o}}function Mi(e,t){let n=e.split(`
156
- `),r=Pi(n,t);if(!r)return;let o={};for(let s=r.start+1;s<r.end;s++){let i=n[s].trim().match(/^(\w+)\s*=\s*(.+)$/);i&&(o[i[1]]=qy(i[2]))}return Object.keys(o).length>0?o:void 0}function Vy(e,t,n){let r=`[${n.args.map(l=>`"${l}"`).join(", ")}]`,o=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],s=e.split(`
157
- `),i=Pi(s,t);if(i){s.splice(i.start,i.end-i.start,...o);let l=s.join(`
152
+ `}function Ry(e){return e.tool_name!=null}function Iy(e){return Tr(e.amount)===0&&e.status==="failed"}function $y(e){return Ry(e)&&!Iy(e)}function Py(e,t=1/0){let n=new Set,r=[];for(let o of e){if(r.length>=t)break;let s=Ze(o.merchant_name,"Unknown merchant"),i=Ze(o.tool_name,"unknown_tool"),a=`${s} :: ${i}`;n.has(a)||(n.add(a),r.push(`${s} [${i}]`))}return r}function Oy(e){let t=Ze(e.merchant_name,"Unknown merchant"),n=Ze(e.tool_name,"unknown_tool"),r=Vn(Tr(e.amount)),o=Ze(e.status,"unknown"),s=Ly(e.created_at);return`${r} ${o.padEnd(9)} ${t} [${n}] ${s}`}function My(e){let t=Ze(e.brand?.toUpperCase(),"CARD"),n=e.isDefault?" default":"";return`${t} ****${e.last4}${n}`}function Ny(e){return{dailyLimit:Tr(e?.daily_limit??e?.dailyLimit??0)}}function Tr(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function Vn(e){return`$${e.toFixed(2)}`}function Fu(e,t=Ay){let n=Math.max(0,Math.min(1,e)),r=Math.round(n*t);return`[${"\u2588".repeat(r)}${"\u2591".repeat(t-r)}]`}function Ze(e,t){let n=yn(e??"").trim();return n.length>0?n:t}function Ly(e){if(!e)return"unknown time";let t=new Date(e);return Number.isNaN(t.getTime())?Ze(e,"unknown time"):t.toISOString().slice(0,16).replace("T"," ")}function yn(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 Uy=/^[1-9]\d{0,9}$/;function $i(e){if(!Uy.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 Vu(e){let t=yn(e.brand||"Visa"),n=yn(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 Qe=E(require("fs")),ne=E(require("path")),Dy=["npm","pnpm","yarn","bun"],jy=/\s+/,Fy=process.platform==="win32"?"visa-cli.cmd":"visa-cli",Pi=["node_modules","@visa","cli"];function qy(){let e=process.env.npm_config_user_agent;if(!e)return;let t=e.trim();if(t==="")return;let n=t.split(jy)[0]??"",r=n.indexOf("/"),o=r===-1?n:n.slice(0,r);return Dy.includes(o)?o:void 0}function Oi(e){if(!e)return;let t=e;try{t=Qe.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 Vy(e=process.argv[1]){return qy()??Oi(process.env.npm_execpath)??Oi(process.env.npm_node_execpath)??Oi(e)}function Hy(e=process.env.PATH??""){let t=[];for(let n of e.split(ne.delimiter))n&&t.push(n);return t}function By(e=process.env.PATH??""){let t=new Set,n=[];for(let r of Hy(e))try{let o=ne.join(r,Fy);Qe.accessSync(o,Qe.constants.X_OK);let s=ne.resolve(o);t.has(s)||(t.add(s),n.push(o))}catch{}return n}function Hu(e){try{let t=Qe.readFileSync(ne.join(e,"package.json"),"utf-8"),n=JSON.parse(t);if(n.name==="@visa/cli"&&typeof n.version=="string")return n.version}catch{}}function Ky(e){let t=ne.resolve(e).split(ne.sep);for(let n=t.length-Pi.length;n>=0;n--)if(Pi.every((r,o)=>t[n+o]===r)){let r=t.slice(0,n+Pi.length).join(ne.sep)||ne.sep;if(Hu(r))return r}}function Gy(e){if(!e)return;let t=ne.normalize(e),n=t.split(ne.sep),r=s=>s.every((a,l)=>n[n.length-s.length+l]===a)?n.slice(0,-s.length).join(ne.sep)||ne.parse(t).root:void 0,o=r(["lib","node_modules","@visa","cli"]);if(o)return o;if(process.platform==="win32")return r(["node_modules","@visa","cli"])}function zy(e,t){let n=ne.resolve(e);try{n=Qe.realpathSync(e)}catch{}let r=Ky(n);return{binPath:e,realPath:n,packageRoot:r,version:r?Hu(r):void 0,prefix:Gy(r),isActive:n===t}}function Wy(e,t=process.env.PATH??""){let n=e??process.argv[1],r=n?ne.resolve(n):"";try{n&&(r=Qe.realpathSync(n))}catch{}let o=e?[e]:[n,...By(t)].filter(Boolean),s=new Map;for(let d of o){let f=zy(d,r),m=s.get(f.realPath);s.set(f.realPath,m?{...f,binPath:m.binPath}:f)}let i=[...s.values()],a=i.find(d=>d.isActive);!a&&i.length>0&&!e&&(a={...i[0],isActive:!0},i[0]=a);let l=new Set(i.map(d=>d.packageRoot).filter(Boolean)),c=!!a?.packageRoot&&l.size>1,u=a?.prefix;return{active:a,installs:i,hasConflictingInstalls:c,recommendedPrefix:u}}function Jy(e,t=process.platform){return/^[A-Za-z0-9_./:@+-]+$/.test(e)?e:t==="win32"?`"${e.replace(/"/g,'""')}"`:`'${e.replace(/'/g,"'\\''")}'`}function Mi(e,t,n,r={}){let o=t??Vy(n)??"npm",s=r.withDiagnostics?Wy(n):void 0,a=`@visa/cli@${e??"latest"}`;switch(o){case"npm":if(s?.hasConflictingInstalls&&s.recommendedPrefix){let l=s.recommendedPrefix;return{packageManager:o,command:"npm",args:["install","-g","--prefix",l,a],display:`npm install -g --prefix ${Jy(l)} ${a}`,diagnostics:s}}return{packageManager:o,command:"npm",args:["install","-g",a],display:`npm install -g ${a}`,diagnostics:s};case"pnpm":return{packageManager:o,command:"pnpm",args:["add","-g",a],display:`pnpm add -g ${a}`,diagnostics:s};case"yarn":return{packageManager:o,command:"yarn",args:["global","add",a],display:`yarn global add ${a}`,diagnostics:s};case"bun":return{packageManager:o,command:"bun",args:["add","-g",a],display:`bun add -g ${a}`,diagnostics:s}}}function Yy(e){let t=e.isActive?" (active)":"",n=e.version?` v${e.version}`:" version unknown",r=e.prefix?` via ${e.prefix}`:"";return` - ${e.binPath}${t}: ${n}${r}`}function Ni(e,t){if(!e.hasConflictingInstalls)return null;let n=["Multiple Visa CLI installs detected.",...e.installs.map(Yy)];return t&&(e.recommendedPrefix?n.push("The update command below targets the active install so your shell actually picks up the new version."):n.push("The update command is shown below; remove duplicate installs if your shell still picks up an older version."),n.push(` ${t}`)),n.join(`
153
+ `)}var rs=E(wr());var Xy=["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 Zy(){let e=new Set;for(let t of Xy)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));for(let t of vr)e.add(t),e.add(t.replace(/-/g,"_")),e.add(t.replace(/_/g,"-"));return e}var Fw=Zy();var Li=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 Kw=new Set(vr),Gw=new Set(["batch","buy_credits","execute_tool","get_visa_smi",...Li,...vr]);var j=E(require("fs")),M=E(require("path")),Bu=E(require("os")),Q=Bu.homedir(),Qy=["Claude_","Anthropic.ClaudeDesktop_"],Hn=class extends Error{constructor(n,r,o){super(t_(n,r,o));this.client=n;this.configPath=r;this.name="McpConfigAccessError"}client;configPath};function Ku(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
154
+ `)}function e_(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=Ku(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}function t_(e,t,n){let r=t.replace(Q,"~"),o=Ku(n).split(`
155
+ `).find(Boolean),s=o?` (${o})`:"";return e.id==="codex"?`Could not update Codex MCP config at ${r}: filesystem access was denied${s}. In Codex, rerun with elevated filesystem access or run \`visa-cli install codex\` outside the sandbox.`:`Could not update ${e.displayName} MCP config at ${r}: filesystem access was denied${s}.`}function Er(){return process.env.APPDATA||M.join(Q,"AppData","Roaming")}function n_(){return process.env.LOCALAPPDATA||M.join(Q,"AppData","Local")}function Ui(e){return process.platform==="win32"?e.win32:e.posix}function Gu(){if(process.platform!=="win32")return;let e=M.join(n_(),"Packages");if(j.existsSync(e))try{let t=j.readdirSync(e,"utf-8");for(let n of Qy){let r=t.filter(o=>o.startsWith(n)).sort()[0];if(r)return M.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function zu(){if(process.platform==="win32"){let e=Gu();return e?M.join(e,"claude_desktop_config.json"):M.join(Er(),"Claude","claude_desktop_config.json")}return M.join(Q,"Library","Application Support","Claude","claude_desktop_config.json")}function Wu(){if(process.platform!=="win32")return[M.join(Q,"Library","Application Support","Claude")];let e=[M.join(Er(),"Claude")],t=Gu();return t&&e.push(t),e}function Zo(e){return e.id==="claude-desktop"?zu():e.globalConfigPath}function r_(e){return e.id==="claude-desktop"?Wu():e.detectPaths}var De=[{id:"claude",displayName:"Claude Code",globalConfigPath:M.join(Q,".claude.json"),configKey:"mcpServers",detectPaths:[M.join(Q,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:zu(),configKey:"mcpServers",detectPaths:Wu(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:M.join(Q,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[M.join(Q,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:M.join(Q,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[M.join(Q,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:M.join(Q,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[M.join(Q,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:Ui({win32:M.join(Er(),"Roo","mcp_settings.json"),posix:M.join(Q,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[M.join(Q,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:M.join(Q,".vscode","mcp.json"),configKey:"servers",detectPaths:[M.join(Q,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:Ui({win32:M.join(Er(),"Zed","settings.json"),posix:M.join(Q,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:Ui({win32:[M.join(Er(),"Zed")],posix:[M.join(Q,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:M.join(Q,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[M.join(Q,".codex")],postInstallHint:"Restart Codex to connect."}];function Di(e){return De.find(t=>t.id===e)}function Ar(e){return r_(e).some(t=>{if(t.includes("*")){let n=M.dirname(t),r=M.basename(t).replaceAll("*","");if(!j.existsSync(n))return!1;try{return j.readdirSync(n).some(o=>o.startsWith(r))}catch{return!1}}return j.existsSync(t)})}function Ju(){return{command:"node",args:[M.resolve(__dirname,"mcp-server/index.js")]}}function ji(e,t){return t==="project"?"json":e.configFormat??"json"}function o_(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 Fi(e,t){let n=`[mcp_servers.${t}]`,r=e.findIndex(s=>s.trim()===n);if(r===-1)return;let o=r+1;for(;o<e.length&&!e[o].trim().startsWith("[");)o++;return{start:r,end:o}}function qi(e,t){let n=e.split(`
156
+ `),r=Fi(n,t);if(!r)return;let o={};for(let s=r.start+1;s<r.end;s++){let i=n[s].trim().match(/^(\w+)\s*=\s*(.+)$/);i&&(o[i[1]]=o_(i[2]))}return Object.keys(o).length>0?o:void 0}function s_(e,t,n){let r=`[${n.args.map(l=>`"${l}"`).join(", ")}]`,o=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],s=e.split(`
157
+ `),i=Fi(s,t);if(i){s.splice(i.start,i.end-i.start,...o);let l=s.join(`
158
158
  `);return l.endsWith(`
159
159
  `)?l:l+`
160
160
  `}let a=e.trimEnd();return a+(a.length>0?`
161
161
 
162
162
  `:"")+o.join(`
163
163
  `)+`
164
- `}function Hy(e,t){let n=e.split(`
165
- `),r=Pi(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
164
+ `}function i_(e,t){let n=e.split(`
165
+ `),r=Fi(n,t);return r?(n.splice(r.start,r.end-r.start),n.join(`
166
166
  `).replace(/\n{3,}/g,`
167
167
 
168
- `)):e}function kr(e,t="global"){let n=t==="project"?O.join(process.cwd(),".mcp.json"):Bo(e);try{let r=O.dirname(n);j.existsSync(r)||j.mkdirSync(r,{recursive:!0});let o=$i(e,t),s=Du();if(o==="toml"){let i=j.existsSync(n)?j.readFileSync(n,"utf-8"):"",a=Vy(i,"visa-cli",s);j.writeFileSync(n,a)}else{let i={};if(j.existsSync(n))try{i=JSON.parse(j.readFileSync(n,"utf-8"))}catch{i={}}i[e.configKey]=i[e.configKey]||{},i[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(s):s,j.writeFileSync(n,JSON.stringify(i,null,2)+`
169
- `)}}catch(r){throw Uy(r)?new jn(e,n,r):r}return{installed:!0,configPath:n,message:e.postInstallHint}}function Oi(e,t="global"){let n=t==="project"?O.join(process.cwd(),".mcp.json"):Bo(e);if(!j.existsSync(n))return{removed:!1,configPath:n};if($i(e,t)==="toml"){let i=j.readFileSync(n,"utf-8");return Mi(i,"visa-cli")?(j.writeFileSync(n,Hy(i,"visa-cli")),{removed:!0,configPath:n}):{removed:!1,configPath:n}}let o;try{o=JSON.parse(j.readFileSync(n,"utf-8"))}catch{return{removed:!1,configPath:n}}let s=o[e.configKey];return!s||!s["visa-cli"]?{removed:!1,configPath:n}:(delete s["visa-cli"],j.writeFileSync(n,JSON.stringify(o,null,2)+`
170
- `),{removed:!0,configPath:n})}function ju(e,t="global"){let n=t==="project"?O.join(process.cwd(),".mcp.json"):Bo(e);if(!j.existsSync(n))return!1;if($i(e,t)==="toml")try{let o=j.readFileSync(n,"utf-8");return!!Mi(o,"visa-cli")}catch{return!1}try{return!!JSON.parse(j.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function By(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 Ky(e,t){if(e===t)return!0;let n=O.resolve(e),r=O.resolve(t);if(n===r)return!0;try{let o=j.realpathSync(n),s=j.realpathSync(r);return o===s}catch{return!1}}function Cr(){let e=Du(),t=e.args[e.args.length-1],n=[];for(let r of Ue){let o=Bo(r);if(!j.existsSync(o))continue;let s=r.configFormat??"json",i;if(s==="toml")try{let c=j.readFileSync(o,"utf-8");i=Mi(c,"visa-cli")}catch{continue}else{let c;try{c=JSON.parse(j.readFileSync(o,"utf-8"))}catch{continue}i=c?.[r.configKey]?.["visa-cli"]}if(!i)continue;let a=By(i);if(!a||Ky(a,t))continue;let l=j.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:o,currentPath:a,expectedPath:t,staleReason:l})}return n}function Ni(e){return{configPath:kr(e.client,"global").configPath}}var Fi=(0,Ju.promisify)(zu.execFile);function Li(){let e=nt();setImmediate(()=>{xs(e,{getCommand:()=>Xr(process.execPath,process.argv[1])})})}process.stdout.on("error",e=>{throw e.code==="EPIPE"&&process.exit(0),e});process.stderr.on("error",e=>{throw e.code==="EPIPE"&&process.exit(0),e});function Jy(e){let t=z.homedir(),n=o=>o.replace(t,"~"),r=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
171
- ${r}: ${n(e.currentPath)}`}function Yu(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(Jy(n))}function Fu(e){console.log(` ! ${e.client.displayName} skipped: ${e.message}`)}function De(){this.help({error:!1})}var W=new Gu.Command,Yy=new Set(["pay",...Ai]),zo=null,Tr=!1;function ae(){return zo=new we(()=>F.getSessionToken()),zo}function Xu(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function qu(e){if(e instanceof Kt)return!0;let t=e instanceof Error?e.message:"";return/attestation required|invalid signature|rotate biometric key|biometric key/i.test(t)}var Vu=0,Hu="",Xy="attestation-key-rotation";async function Zy(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:Vu,merchant:Hu,context:Xy})).toString("base64");return{signature:await On(n,"verify Visa CLI Touch ID setup"),nonce:t,amount:Vu,merchant:Hu}}async function Qy(e){let t=await kl(),n=await Zy(e);await e.registerAttestationKey(t,n)}async function Zu(e,t,n=!1){let r=await So();console.log(" Attestation key generated."),await e.registerAttestationKey(r),console.log(" Attestation key registered with server."),t&&(await e.setBiometricPreference({required:!0}),n&&m.info("attestation:requirement-restored-after-recovery",{surface:"setup"}),console.log(n?" Touch ID requirement re-enabled after biometric recovery.":" Touch ID requirement enabled."))}async function Ui(e){if(!await Vi(e))throw new Error("Could not clear stale server biometric state. Run `visa-cli config reset`, then `visa-cli setup`.");await Zu(e,!0,!0)}function Qu(e){return async()=>{let t=await Vi(e);return{success:t,...t?{}:{message:"Biometric recovery was not completed."}}}}async function e_(e){let r=Date.now()+3e5;for(;Date.now()<r;)try{let o=await globalThis.fetch(`${ye()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:3e4}),signal:AbortSignal.timeout(35e3)});if(!o.ok){await bt(o,i=>{m.warn("auth_status:retry_after_http_error",{status:o.status,delayMs:i})});continue}let s=await o.json();if(s.status==="pending")continue;if(s.status==="complete"&&s.attestationCleared)return;if(s.status==="expired")throw new Error("Biometric reset session expired. Please run visa-cli config reset again.");if(s.status==="error")throw new Error(s.error||"Biometric reset failed. Please try again.")}catch(o){if(o?.message&&!/fetch failed|network|abort/i.test(o.message))throw o;await bt(void 0,s=>{m.warn("auth_status:retry_after_network_error",{delayMs:s})})}throw new Error("Biometric reset timed out after 5 minutes. Please run visa-cli config reset again.")}async function Vi(e){let t;try{t=await e.getStatus()}catch(o){let s=o?.message||"";if(/not logged in|session.*expired|no local credentials/i.test(s))return!1;throw new Error(`Could not check server biometric state: ${s||"unknown error"}`)}if(!Xu(t))return!1;let n=Wo.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 fs(r.recoveryUrl),await e_(n),console.log(" Server biometric state cleared."),!0}function Er(e){return`$${(e/100).toFixed(2)}`}function qi(e,t,n=!1){if(!e){let i=Er(t);return n&&t>=0?`+${i}`:i}let r=(0,Jo.fromWire)(e),o=r%10000n===0n?2:6,s=(0,Jo.toDisplay)(r,{decimals:o});return n&&r>=0n?`+${s}`:s}function t_(e){return qi(e,0)}function n_(e){let t=`visa-cli-${z.hostname()||"local"}`,n=(e?.trim()||t).trim();if(!n)throw new Error("API key label is required.");if(n.length>128)throw new Error("API key label must be 128 characters or fewer.");return n}function r_(e){if(!e)return;let t=e.split(",").map(s=>s.trim()).filter(Boolean),n=Array.from(new Set(t)),r=n.find(s=>s.length>64);if(r)throw new Error(`Tool id is too long: ${r}`);let o=n.find(s=>Yy.has(s));if(o)throw new Error(`Tool id "${o}" is retired for direct API-key access. Use category meta-tools or discover/execute instead.`);return n}function o_(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 ed(e){return e&&e.length>0?e.join(", "):"all tools"}function Hi(e,t){return t||(typeof e!="number"||!Number.isFinite(e)?"price unknown":`$${(e/100).toFixed(2)}`)}function s_(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 td(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 Di(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function i_(e){let t=new Map;for(let n of e){let r=n.category||"other",o=t.get(r)??[];o.push(n),t.set(r,o)}return new Map([...t.entries()].sort(([n],[r])=>n.localeCompare(r)))}function a_(e){let t=Math.max(4,Math.min(28,e.reduce((i,a)=>Math.max(i,a.id.length),0))),n=7,r=Math.max(8,Math.min(12,e.reduce((i,a)=>Math.max(i,(a.category||"").length),0))),o=typeof process.stdout.columns=="number"&&process.stdout.columns>0?process.stdout.columns:100,s=Math.max(40,o-(t+n+r+10));console.log(`
168
+ `)):e}function Rr(e,t="global"){let n=t==="project"?M.join(process.cwd(),".mcp.json"):Zo(e);try{let r=M.dirname(n);j.existsSync(r)||j.mkdirSync(r,{recursive:!0});let o=ji(e,t),s=Ju();if(o==="toml"){let i=j.existsSync(n)?j.readFileSync(n,"utf-8"):"",a=s_(i,"visa-cli",s);j.writeFileSync(n,a)}else{let i={};if(j.existsSync(n))try{i=JSON.parse(j.readFileSync(n,"utf-8"))}catch{i={}}i[e.configKey]=i[e.configKey]||{},i[e.configKey]["visa-cli"]=e.buildEntry?e.buildEntry(s):s,j.writeFileSync(n,JSON.stringify(i,null,2)+`
169
+ `)}}catch(r){throw e_(r)?new Hn(e,n,r):r}return{installed:!0,configPath:n,message:e.postInstallHint}}function Vi(e,t="global"){let n=t==="project"?M.join(process.cwd(),".mcp.json"):Zo(e);if(!j.existsSync(n))return{removed:!1,configPath:n};if(ji(e,t)==="toml"){let i=j.readFileSync(n,"utf-8");return qi(i,"visa-cli")?(j.writeFileSync(n,i_(i,"visa-cli")),{removed:!0,configPath:n}):{removed:!1,configPath:n}}let o;try{o=JSON.parse(j.readFileSync(n,"utf-8"))}catch{return{removed:!1,configPath:n}}let s=o[e.configKey];return!s||!s["visa-cli"]?{removed:!1,configPath:n}:(delete s["visa-cli"],j.writeFileSync(n,JSON.stringify(o,null,2)+`
170
+ `),{removed:!0,configPath:n})}function Yu(e,t="global"){let n=t==="project"?M.join(process.cwd(),".mcp.json"):Zo(e);if(!j.existsSync(n))return!1;if(ji(e,t)==="toml")try{let o=j.readFileSync(n,"utf-8");return!!qi(o,"visa-cli")}catch{return!1}try{return!!JSON.parse(j.readFileSync(n,"utf-8"))?.[e.configKey]?.["visa-cli"]}catch{return!1}}function a_(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 c_(e,t){if(e===t)return!0;let n=M.resolve(e),r=M.resolve(t);if(n===r)return!0;try{let o=j.realpathSync(n),s=j.realpathSync(r);return o===s}catch{return!1}}function Ir(){let e=Ju(),t=e.args[e.args.length-1],n=[];for(let r of De){let o=Zo(r);if(!j.existsSync(o))continue;let s=r.configFormat??"json",i;if(s==="toml")try{let c=j.readFileSync(o,"utf-8");i=qi(c,"visa-cli")}catch{continue}else{let c;try{c=JSON.parse(j.readFileSync(o,"utf-8"))}catch{continue}i=c?.[r.configKey]?.["visa-cli"]}if(!i)continue;let a=a_(i);if(!a||c_(a,t))continue;let l=j.existsSync(a)?"mismatch":"missing";n.push({client:r,configPath:o,currentPath:a,expectedPath:t,staleReason:l})}return n}function Hi(e){return{configPath:Rr(e.client,"global").configPath}}var Wi=(0,id.promisify)(od.execFile);function Bi(){let e=rt();setImmediate(()=>{Ps(e,{getCommand:()=>so(process.execPath,process.argv[1])})})}process.stdout.on("error",e=>{throw e.code==="EPIPE"&&process.exit(0),e});process.stderr.on("error",e=>{throw e.code==="EPIPE"&&process.exit(0),e});function m_(e){let t=z.homedir(),n=o=>o.replace(t,"~"),r=e.staleReason==="missing"?"path missing on disk":"path mismatch";return` \u2022 ${e.client.displayName} (${n(e.configPath)})
171
+ ${r}: ${n(e.currentPath)}`}function ad(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(m_(n))}function Xu(e){console.log(` ! ${e.client.displayName} skipped: ${e.message}`)}function je(){this.help({error:!1})}var W=new rd.Command,p_=new Set(["pay",...Li]),ts=null,$r=!1;function ae(){return ts=new xe(()=>F.getSessionToken()),ts}function cd(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}function Zu(e){if(e instanceof zt)return!0;let t=e instanceof Error?e.message:"";return/attestation required|invalid signature|rotate biometric key|biometric key/i.test(t)}var Qu=0,ed="",f_="attestation-key-rotation";async function g_(e){let{nonce:t}=await e.getAttestationChallenge(),n=Buffer.from(JSON.stringify({nonce:t,amount:Qu,merchant:ed,context:f_})).toString("base64");return{signature:await Dn(n,"verify Visa CLI Touch ID setup"),nonce:t,amount:Qu,merchant:ed}}async function h_(e){let t=await Nl(),n=await g_(e);await e.registerAttestationKey(t,n)}async function ld(e,t,n=!1){let r=await Ro();console.log(" Attestation key generated."),await e.registerAttestationKey(r),console.log(" Attestation key registered with server."),t&&(await e.setBiometricPreference({required:!0}),n&&p.info("attestation:requirement-restored-after-recovery",{surface:"setup"}),console.log(n?" Touch ID requirement re-enabled after biometric recovery.":" Touch ID requirement enabled."))}async function Ki(e){if(!await Yi(e))throw new Error("Could not clear stale server biometric state. Run `visa-cli config reset`, then `visa-cli setup`.");await ld(e,!0,!0)}function ud(e){return async()=>{let t=await Yi(e);return{success:t,...t?{}:{message:"Biometric recovery was not completed."}}}}async function y_(e){let r=Date.now()+3e5;for(;Date.now()<r;)try{let o=await globalThis.fetch(`${_e()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:3e4}),signal:AbortSignal.timeout(35e3)});if(!o.ok){await St(o,i=>{p.warn("auth_status:retry_after_http_error",{status:o.status,delayMs:i})});continue}let s=await o.json();if(s.status==="pending")continue;if(s.status==="complete"&&s.attestationCleared)return;if(s.status==="expired")throw new Error("Biometric reset session expired. Please run visa-cli config reset again.");if(s.status==="error")throw new Error(s.error||"Biometric reset failed. Please try again.")}catch(o){if(o?.message&&!/fetch failed|network|abort/i.test(o.message))throw o;await St(void 0,s=>{p.warn("auth_status:retry_after_network_error",{delayMs:s})})}throw new Error("Biometric reset timed out after 5 minutes. Please run visa-cli config reset again.")}async function Yi(e){let t;try{t=await e.getStatus()}catch(o){let s=o?.message||"";if(/not logged in|session.*expired|no local credentials/i.test(s))return!1;throw new Error(`Could not check server biometric state: ${s||"unknown error"}`)}if(!cd(t))return!1;let n=ns.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 ws(r.recoveryUrl),await y_(n),console.log(" Server biometric state cleared."),!0}function Pr(e){return`$${(e/100).toFixed(2)}`}function Ji(e,t,n=!1){if(!e){let i=Pr(t);return n&&t>=0?`+${i}`:i}let r=(0,rs.fromWire)(e),o=r%10000n===0n?2:6,s=(0,rs.toDisplay)(r,{decimals:o});return n&&r>=0n?`+${s}`:s}function __(e){return Ji(e,0)}function v_(e){let t=`visa-cli-${z.hostname()||"local"}`,n=(e?.trim()||t).trim();if(!n)throw new Error("API key label is required.");if(n.length>128)throw new Error("API key label must be 128 characters or fewer.");return n}function b_(e){if(!e)return;let t=e.split(",").map(s=>s.trim()).filter(Boolean),n=Array.from(new Set(t)),r=n.find(s=>s.length>64);if(r)throw new Error(`Tool id is too long: ${r}`);let o=n.find(s=>p_.has(s));if(o)throw new Error(`Tool id "${o}" is retired for direct API-key access. Use category meta-tools or discover/execute instead.`);return n}function S_(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 dd(e){return e&&e.length>0?e.join(", "):"all tools"}function Xi(e,t){return t||(typeof e!="number"||!Number.isFinite(e)?"price unknown":`$${(e/100).toFixed(2)}`)}function w_(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 md(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 Gi(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}\u2026`}function x_(e){let t=new Map;for(let n of e){let r=n.category||"other",o=t.get(r)??[];o.push(n),t.set(r,o)}return new Map([...t.entries()].sort(([n],[r])=>n.localeCompare(r)))}function k_(e){let t=Math.max(4,Math.min(28,e.reduce((i,a)=>Math.max(i,a.id.length),0))),n=7,r=Math.max(8,Math.min(12,e.reduce((i,a)=>Math.max(i,(a.category||"").length),0))),o=typeof process.stdout.columns=="number"&&process.stdout.columns>0?process.stdout.columns:100,s=Math.max(40,o-(t+n+r+10));console.log(`
172
172
  Merchant tools
173
- `),console.log(` ${"Tool".padEnd(t)} ${"Price".padEnd(n)} ${"Category".padEnd(r)} Params`),console.log(` ${"\u2500".repeat(t)} ${"\u2500".repeat(n)} ${"\u2500".repeat(r)} ${"\u2500".repeat(Math.min(s,32))}`);for(let i of e)console.log(` ${Di(i.id,t).padEnd(t)} ${Hi(i.priceCents,i.priceDisplay).padEnd(n)} ${Di(i.category||"other",r).padEnd(r)} ${Di(td(i),s)}`);console.log("\nUse `visa-cli merchants describe <tool>` for full details (incl. parameter types)."),console.log('Shortcut: `visa-cli generate image "a lobster"`\n')}function c_(e){console.log(`
173
+ `),console.log(` ${"Tool".padEnd(t)} ${"Price".padEnd(n)} ${"Category".padEnd(r)} Params`),console.log(` ${"\u2500".repeat(t)} ${"\u2500".repeat(n)} ${"\u2500".repeat(r)} ${"\u2500".repeat(Math.min(s,32))}`);for(let i of e)console.log(` ${Gi(i.id,t).padEnd(t)} ${Xi(i.priceCents,i.priceDisplay).padEnd(n)} ${Gi(i.category||"other",r).padEnd(r)} ${Gi(md(i),s)}`);console.log("\nUse `visa-cli merchants describe <tool>` for full details (incl. parameter types)."),console.log('Shortcut: `visa-cli generate image "a lobster"`\n')}function C_(e){console.log(`
174
174
  Merchant tools
175
- `);for(let[t,n]of i_(e)){console.log(t[0]?.toUpperCase()+t.slice(1));for(let r of n)console.log(` ${r.id.padEnd(28)} ${Hi(r.priceCents,r.priceDisplay).padEnd(8)} ${r.description}`),console.log(` Params: ${td(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"
176
- `)}function Bi(e,t={}){let n=t.format&&Vr(t.format)?t.format:void 0;if(t.json||n!==void 0){let i=t.command??"tool.run",a=n??"json",l,c=e?.content?.[0]?.text;typeof c=="string"&&(l=c);let u=Array.isArray(e?.urls)&&typeof e.urls[0]=="string"?e.urls[0]:void 0;if(!l&&u&&u.startsWith("data:")&&(l=u),l)try{let d=vn(l);if(d){let f=typeof e?.merchantName=="string"?e.merchantName:"media",p=typeof e?.transactionId=="string"?`${f}-${e.transactionId}`:f,_=Gn(d,{tag:p}),T=ls(i,e);T.success&&(T.filePath=_.filePath,T.mime=_.mime,T.bytes=_.bytes,u&&u.startsWith("data:")&&(T.urls=void 0)),Jn(T,a);return}}catch(d){Jn(zn(i,`Failed to save inline media: ${d instanceof Error?d.message:String(d)}`),a),process.exitCode=rd;return}Jn(ls(i,e),a);return}if(e?.content?.[0]?.text&&typeof e.content[0].text=="string"){try{let i=vn(e.content[0].text);if(i){let a=typeof e?.merchantName=="string"?e.merchantName:"media",l=typeof e?.transactionId=="string"?`${a}-${e.transactionId}`:a,c=Gn(i,{tag:l});console.log("Saved inline image to file:"),console.log(` ${c.filePath}`),console.log(` (${c.mime}, ${(c.bytes/1024).toFixed(1)} KB)`),console.log(` Open with: open "${c.filePath}"`);return}}catch(i){console.error(`(warning: could not save inline image to disk: ${i instanceof Error?i.message:String(i)})`)}console.log(e.content[0].text);return}let o=Array.isArray(e?.urls)?e.urls:Array.isArray(e?.receipt?.urls)?e.receipt.urls:[];if(e?.success===!1){let i=JSON.stringify(e,null,2);console.log("Result:"),console.log(i);return}if(console.log("Done"),typeof e?.merchantName=="string"&&console.log(`Merchant: ${e.merchantName}`),typeof e?.amount=="number"&&console.log(`Cost: $${e.amount.toFixed(2)}`),typeof e?.transactionId=="string"&&console.log(`Transaction: ${e.transactionId}`),o.length>0){console.log(`
175
+ `);for(let[t,n]of x_(e)){console.log(t[0]?.toUpperCase()+t.slice(1));for(let r of n)console.log(` ${r.id.padEnd(28)} ${Xi(r.priceCents,r.priceDisplay).padEnd(8)} ${r.description}`),console.log(` Params: ${md(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"
176
+ `)}function Zi(e,t={}){let n=t.format&&zr(t.format)?t.format:void 0;if(t.json||n!==void 0){let i=t.command??"tool.run",a=n??"json",l,c=e?.content?.[0]?.text;typeof c=="string"&&(l=c);let u=Array.isArray(e?.urls)&&typeof e.urls[0]=="string"?e.urls[0]:void 0;if(!l&&u&&u.startsWith("data:")&&(l=u),l)try{let d=Sn(l);if(d){let f=typeof e?.merchantName=="string"?e.merchantName:"media",m=typeof e?.transactionId=="string"?`${f}-${e.transactionId}`:f,_=Yn(d,{tag:m}),S=ys(i,e);S.success&&(S.filePath=_.filePath,S.mime=_.mime,S.bytes=_.bytes,u&&u.startsWith("data:")&&(S.urls=void 0)),Qn(S,a);return}}catch(d){Qn(Xn(i,`Failed to save inline media: ${d instanceof Error?d.message:String(d)}`),a),process.exitCode=fd;return}Qn(ys(i,e),a);return}if(e?.content?.[0]?.text&&typeof e.content[0].text=="string"){try{let i=Sn(e.content[0].text);if(i){let a=typeof e?.merchantName=="string"?e.merchantName:"media",l=typeof e?.transactionId=="string"?`${a}-${e.transactionId}`:a,c=Yn(i,{tag:l});console.log("Saved inline image to file:"),console.log(` ${c.filePath}`),console.log(` (${c.mime}, ${(c.bytes/1024).toFixed(1)} KB)`),console.log(` Open with: open "${c.filePath}"`);return}}catch(i){console.error(`(warning: could not save inline image to disk: ${i instanceof Error?i.message:String(i)})`)}console.log(e.content[0].text);return}let o=Array.isArray(e?.urls)?e.urls:Array.isArray(e?.receipt?.urls)?e.receipt.urls:[];if(e?.success===!1){let i=JSON.stringify(e,null,2);console.log("Result:"),console.log(i);return}if(console.log("Done"),typeof e?.merchantName=="string"&&console.log(`Merchant: ${e.merchantName}`),typeof e?.amount=="number"&&console.log(`Cost: $${e.amount.toFixed(2)}`),typeof e?.transactionId=="string"&&console.log(`Transaction: ${e.transactionId}`),o.length>0){console.log(`
177
177
  Result URLs:`);for(let i of o)console.log(` ${i}`);return}let s=JSON.stringify(e,null,2);s&&s!=="{}"&&(console.log(`
178
- Result:`),console.log(s))}var l_=new Set(["INVALID_TOOL_PARAMS","MISSING_TOOL_ID","UNKNOWN_TOOL"]),nd=0,rd=1,u_=2;function d_(e){if(e?.success!==!1)return nd;let n=(typeof e?.error_code=="string"?e.error_code:typeof e?.code=="string"?e.code:"").toUpperCase();return l_.has(n)?u_:rd}function Ki(e){let t=d_(e);t!==nd&&(process.exitCode=t)}function Fn(e,t,n={}){let r=typeof n=="boolean"?{json:n}:n,o=t instanceof Error?t.message:String(t),s=r.format&&Vr(r.format)?r.format:void 0;if(r.json||s!==void 0){let i=s??"json";Jn(zn(e,o),i)}else console.error("Error:",o);process.exit(1)}async function m_(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 od=100,sd=200;function Bu(e){let t=Number.parseInt(e,10);return Number.isNaN(t)?Number.NaN:t}function p_(e){let t=typeof e.limit=="number"&&Number.isInteger(e.limit)?Math.max(1,Math.min(e.limit,sd)):od,n=typeof e.offset=="number"&&Number.isInteger(e.offset)?Math.max(0,e.offset):0;return{limit:t,offset:n}}function f_(e){let t=`
178
+ Result:`),console.log(s))}var T_=new Set(["INVALID_TOOL_PARAMS","MISSING_TOOL_ID","UNKNOWN_TOOL"]),pd=0,fd=1,E_=2;function A_(e){if(e?.success!==!1)return pd;let n=(typeof e?.error_code=="string"?e.error_code:typeof e?.code=="string"?e.code:"").toUpperCase();return T_.has(n)?E_:fd}function Qi(e){let t=A_(e);t!==pd&&(process.exitCode=t)}function Bn(e,t,n={}){let r=typeof n=="boolean"?{json:n}:n,o=t instanceof Error?t.message:String(t),s=r.format&&zr(r.format)?r.format:void 0;if(r.json||s!==void 0){let i=s??"json";Qn(Xn(e,o),i)}else console.error("Error:",o);process.exit(1)}async function R_(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 gd=100,hd=200;function td(e){let t=Number.parseInt(e,10);return Number.isNaN(t)?Number.NaN:t}function I_(e){let t=typeof e.limit=="number"&&Number.isInteger(e.limit)?Math.max(1,Math.min(e.limit,hd)):gd,n=typeof e.offset=="number"&&Number.isInteger(e.offset)?Math.max(0,e.offset):0;return{limit:t,offset:n}}function $_(e){let t=`
179
179
  Options:
180
180
  `,n=`
181
181
  Commands:
182
- `,r=e.indexOf(t),o=e.indexOf(n);if(r===-1||o===-1||r>o)return e;let s=f=>{let _=e.slice(f+1).search(/\n[A-Z][A-Za-z ]+:\n/);return _===-1?e.length:f+1+_},i=s(r),a=s(o),l=e.slice(0,r),c=e.slice(r,i),u=e.slice(o,a),d=e.slice(a);return`${l}${u}${c}${d}`}function g_(e){if(!e.startsWith("Usage: "))return e;let t=e.indexOf(`
182
+ `,r=e.indexOf(t),o=e.indexOf(n);if(r===-1||o===-1||r>o)return e;let s=f=>{let _=e.slice(f+1).search(/\n[A-Z][A-Za-z ]+:\n/);return _===-1?e.length:f+1+_},i=s(r),a=s(o),l=e.slice(0,r),c=e.slice(r,i),u=e.slice(o,a),d=e.slice(a);return`${l}${u}${c}${d}`}function P_(e){if(!e.startsWith("Usage: "))return e;let t=e.indexOf(`
183
183
 
184
184
  `);if(t===-1)return e;let n=e.slice(0,t),r=e.slice(t+2),o=r.indexOf(`
185
185
 
@@ -187,18 +187,18 @@ Commands:
187
187
 
188
188
  ${n}
189
189
 
190
- ${i}`:e}function h_(e){return e.replace(/(^|\n)(Commands:\n)([\s\S]*?)(?=\n[A-Z][A-Za-z ]+:\n|$)/g,(t,n,r,o)=>{let s=o.split(`
191
- `).map(y_).join(`
192
- `);return`${n}${r}${s}`})}function y_(e){if(!e.startsWith(" "))return e;let n=2,r=n;for(;r<e.length&&e[r]!==" "&&e[r]!==" ";)r+=1;if(r===n)return e;let o=-1;for(let l=r;l<e.length-1;l+=1){if(e[l]!==" "||e[l+1]!==" ")continue;let c=l+2;for(;c<e.length&&e[c]===" ";)c+=1;if(c<e.length){o=c;break}}if(o===-1)return e;let s=e.slice(n,r),i=e.slice(o),a=Math.max(2,o-2-s.length);return` ${s}${" ".repeat(a)}${i}`}function __(e){return e.replace(/^(Usage: .+?) \[options\](?= |$)/gm,"$1")}function v_(e){return e.replace(/^Options:$/gm,"Flags:")}function id(e){let t=e.helpInformation.bind(e);e.helpInformation=()=>v_(__(h_(f_(g_(t())))));for(let n of e.commands)id(n)}function b_(e){let t=new Map(e.map((r,o)=>[r,o]));W.commands.sort((r,o)=>{let s=t.get(r.name())??Number.MAX_SAFE_INTEGER,i=t.get(o.name())??Number.MAX_SAFE_INTEGER;return s-i})}W.name("visa-cli").description("Visa CLI - set up MCP payments, manage credentials, and monitor AI spend").version(Kn().version).addHelpCommand(!1).action(De);W.hook("preAction",async()=>{await pa()});W.command("setup").description("Register MCP server, authenticate, and generate attestation key").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--yes","Accept setup prompts without asking for unattended setup").option("--hud","Install the Visa HUD during setup without prompting").option("--no-hud","Skip installing the Visa HUD during setup").action(async e=>{let t=!1,n=()=>{t||(t=!0,console.log(`
190
+ ${i}`:e}function O_(e){return e.replace(/(^|\n)(Commands:\n)([\s\S]*?)(?=\n[A-Z][A-Za-z ]+:\n|$)/g,(t,n,r,o)=>{let s=o.split(`
191
+ `).map(M_).join(`
192
+ `);return`${n}${r}${s}`})}function M_(e){if(!e.startsWith(" "))return e;let n=2,r=n;for(;r<e.length&&e[r]!==" "&&e[r]!==" ";)r+=1;if(r===n)return e;let o=-1;for(let l=r;l<e.length-1;l+=1){if(e[l]!==" "||e[l+1]!==" ")continue;let c=l+2;for(;c<e.length&&e[c]===" ";)c+=1;if(c<e.length){o=c;break}}if(o===-1)return e;let s=e.slice(n,r),i=e.slice(o),a=Math.max(2,o-2-s.length);return` ${s}${" ".repeat(a)}${i}`}function N_(e){return e.replace(/^(Usage: .+?) \[options\](?= |$)/gm,"$1")}function L_(e){return e.replace(/^Options:$/gm,"Flags:")}function yd(e){let t=e.helpInformation.bind(e);e.helpInformation=()=>L_(N_(O_($_(P_(t())))));for(let n of e.commands)yd(n)}function U_(e){let t=new Map(e.map((r,o)=>[r,o]));W.commands.sort((r,o)=>{let s=t.get(r.name())??Number.MAX_SAFE_INTEGER,i=t.get(o.name())??Number.MAX_SAFE_INTEGER;return s-i})}W.name("visa-cli").description("Visa CLI - set up MCP payments, manage credentials, and monitor AI spend").version(Jn().version).addHelpCommand(!1).action(je);W.hook("preAction",async()=>{await Sa()});W.command("setup").description("Register MCP server, authenticate, and generate attestation key").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--yes","Accept setup prompts without asking for unattended setup").option("--hud","Install the Visa HUD during setup without prompting").option("--no-hud","Skip installing the Visa HUD during setup").action(async e=>{let t=!1,n=()=>{t||(t=!0,console.log(`
193
193
 
194
- Setup interrupted.`),console.log(" If you signed in via the browser but did not finish card enrollment, the"),console.log(" server-side enrollment may have expired. Re-run `visa-cli setup` \u2014 it will"),console.log(" resume from your current state or restart cleanly."),console.log(""),process.exit(130))};process.on("SIGINT",n);let r=()=>{process.removeListener("SIGINT",n)};try{if(e.check){let S=Cr();Yu(S,"MCP config check:"),S.length>0&&(console.log("\nRun `visa-cli setup` (or `visa-cli install --repair`) to rewrite these entries."),r(),process.exit(1)),r();return}console.log("Step 1: Registering MCP server...");let o=Cr(),s=new Map(o.map(S=>[S.client.id,S])),i=new Set,a=new Set,l=new Set;for(let S of Ue)if(xr(S)){let w;try{w=kr(S)}catch(L){if(L instanceof jn){Fu(L),a.add(S.displayName),l.add(S.id);continue}throw L}let y=s.get(S.id),k=y?` \u2014 repaired stale ${y.staleReason} entry`:"";console.log(` \u2713 ${S.displayName} (${w.configPath.replace(z.homedir(),"~")})${k}`),y&&i.add(S.id)}let c=o.filter(S=>!i.has(S.client.id)&&!l.has(S.client.id)),u=0;for(let S of c){try{Ni(S)}catch(w){if(w instanceof jn){Fu(w),a.add(S.client.displayName),l.add(S.client.id);continue}throw w}console.log(` \u2713 ${S.client.displayName} (${S.configPath.replace(z.homedir(),"~")}) \u2014 repaired stale ${S.staleReason} entry`),u++}let d=i.size+u;d===0&&a.size===0?console.log(" \u2713 MCP config verified \u2014 nothing to repair."):d>0&&console.log(` \u2713 Repaired ${d} stale MCP config ${d===1?"entry":"entries"}.`),a.size>0&&console.log(` ! Skipped MCP registration for: ${Array.from(a).join(", ")}. Rerun with access to those config files to complete registration.`),console.log(`
195
- Step 2: Checking authentication...`);let f=await F.getSessionToken();if(f)try{await new we(()=>Promise.resolve(f)).getStatus(),console.log(" Already authenticated.")}catch(S){let w=S instanceof Error?S.message:"";w.includes("session has expired")||w.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await F.clearAll(),f=null):console.log(` Couldn't verify session (${w||"unknown error"}) \u2014 continuing with existing token.`)}if(!f){let S=null;try{let{stdout:w}=await Fi("gh",["auth","token"],{timeout:5e3});S=w.trim()}catch{}if(S||(S=process.env.GITHUB_TOKEN||null),S)try{console.log(" Found GitHub token \u2014 attempting headless login...");let w=await globalThis.fetch(`${ye()}/v1/auth/token-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({github_token:S}),signal:AbortSignal.timeout(1e4)});if(w.ok){let y=await w.json();if(y.success&&y.sessionToken){let k=y.sessionToken;f=k,await F.saveSessionToken(k),console.log(` Signed in as ${y.user} (headless).`)}}else(await w.json().catch(()=>({}))).hint==="card_required"&&console.log(" GitHub token valid but no card on file \u2014 opening browser to finish onboarding...")}catch{}}if(f||(console.log(" No session found. Opening browser for GitHub login..."),f=await new Promise(async(S,w)=>{let y=Wo.randomUUID(),k=`${ye()}/login?state=${y}`;await fs(k);let L=3e4,$e=300*1e3,Dt=Date.now()+$e;for(;Date.now()<Dt;)try{let Se=await globalThis.fetch(`${ye()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:y,timeout:L}),signal:AbortSignal.timeout(L+5e3)});if(!Se.ok){await bt(Se,re=>{m.warn("auth_status:retry_after_http_error",{status:Se.status,delayMs:re})});continue}let B=await Se.json();if(B.status==="pending")continue;if(B.status==="expired"){w(new Error("Session expired. Please run setup again."));return}if(B.status==="complete"&&B.sessionToken){console.log(` Signed in as ${B.user}.`),S(B.sessionToken);return}}catch{await bt(void 0,Se=>{m.warn("auth_status:retry_after_network_error",{delayMs:Se})})}w(new Error("Login timed out after 5 minutes. Please run setup again."))}),await F.saveSessionToken(f),console.log(" Session token saved.")),console.log(`
196
- Step 3: Setting up authentication...`),!ie())console.log(" Not macOS \u2014 skipping biometric setup.");else{try{await Fi("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 S=ae();try{let w=await S.getStatus(),y=!0;if(Xu(w))if(await xl())try{await Qy(S),console.log(" Attestation key already registered with server."),console.log(" Existing local Touch ID key verified and preserved."),y=!1}catch(k){if(!qu(k))throw k;console.log(" Existing local Touch ID key does not match server biometric state."),await Ui(S),y=!1}else console.log(" Server already has a biometric key, but this device has no local key."),await Ui(S),y=!1;y&&await Zu(S,w.attestationRequired===!1)}catch(w){let y=w?.message||"unknown error";if(qu(w)){console.log(" Server already has a biometric key for this account, but this device cannot prove access to it.");let k=!1;try{await Ui(S),k=!0}catch(L){console.error(` Biometric recovery failed: ${L?.message||"unknown error"}`)}if(!k){let L=w instanceof Kt&&w.hint?w.hint:"Run `visa-cli config reset` to clear server-side biometric state through GitHub, then run `visa-cli setup` again.";console.error(` ${L}`),process.exit(1)}}else console.error(` Biometric setup failed: ${y}`),process.exit(1)}}let p=nt(),_=J.existsSync(Ie.join(z.homedir(),".claude.json")),T=e.hud===!0;if(e.hud===void 0&&_&&!e.yes&&process.stdin.isTTY&&(console.log(`
197
- Step 4: Visa HUD`),console.log(" Pin balance, card, spend, model, and session activity below the Claude Code input."),console.log(yc()),T=await hc(" Install the Visa HUD now?",!1)),T)if(!_)console.log(`
194
+ Setup interrupted.`),console.log(" If you signed in via the browser but did not finish card enrollment, the"),console.log(" server-side enrollment may have expired. Re-run `visa-cli setup` \u2014 it will"),console.log(" resume from your current state or restart cleanly."),console.log(""),process.exit(130))};process.on("SIGINT",n);let r=()=>{process.removeListener("SIGINT",n)};try{if(e.check){let w=Ir();ad(w,"MCP config check:"),w.length>0&&(console.log("\nRun `visa-cli setup` (or `visa-cli install --repair`) to rewrite these entries."),r(),process.exit(1)),r();return}console.log("Step 1: Registering MCP server...");let o=Ir(),s=new Map(o.map(w=>[w.client.id,w])),i=new Set,a=new Set,l=new Set;for(let w of De)if(Ar(w)){let x;try{x=Rr(w)}catch(L){if(L instanceof Hn){Xu(L),a.add(w.displayName),l.add(w.id);continue}throw L}let y=s.get(w.id),C=y?` \u2014 repaired stale ${y.staleReason} entry`:"";console.log(` \u2713 ${w.displayName} (${x.configPath.replace(z.homedir(),"~")})${C}`),y&&i.add(w.id)}let c=o.filter(w=>!i.has(w.client.id)&&!l.has(w.client.id)),u=0;for(let w of c){try{Hi(w)}catch(x){if(x instanceof Hn){Xu(x),a.add(w.client.displayName),l.add(w.client.id);continue}throw x}console.log(` \u2713 ${w.client.displayName} (${w.configPath.replace(z.homedir(),"~")}) \u2014 repaired stale ${w.staleReason} entry`),u++}let d=i.size+u;d===0&&a.size===0?console.log(" \u2713 MCP config verified \u2014 nothing to repair."):d>0&&console.log(` \u2713 Repaired ${d} stale MCP config ${d===1?"entry":"entries"}.`),a.size>0&&console.log(` ! Skipped MCP registration for: ${Array.from(a).join(", ")}. Rerun with access to those config files to complete registration.`),console.log(`
195
+ Step 2: Checking authentication...`);let f=await F.getSessionToken();if(f)try{await new xe(()=>Promise.resolve(f)).getStatus(),console.log(" Already authenticated.")}catch(w){let x=w instanceof Error?w.message:"";x.includes("session has expired")||x.includes("Not logged in")?(console.log(" Existing session expired \u2014 re-authenticating..."),await F.clearAll(),f=null):console.log(` Couldn't verify session (${x||"unknown error"}) \u2014 continuing with existing token.`)}if(!f){let w=null;try{let{stdout:x}=await Wi("gh",["auth","token"],{timeout:5e3});w=x.trim()}catch{}if(w||(w=process.env.GITHUB_TOKEN||null),w)try{console.log(" Found GitHub token \u2014 attempting headless login...");let x=await globalThis.fetch(`${_e()}/v1/auth/token-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({github_token:w}),signal:AbortSignal.timeout(1e4)});if(x.ok){let y=await x.json();if(y.success&&y.sessionToken){let C=y.sessionToken;f=C,await F.saveSessionToken(C),console.log(` Signed in as ${y.user} (headless).`)}}else(await x.json().catch(()=>({}))).hint==="card_required"&&console.log(" GitHub token valid but no card on file \u2014 opening browser to finish onboarding...")}catch{}}if(f||(console.log(" No session found. Opening browser for GitHub login..."),f=await new Promise(async(w,x)=>{let y=ns.randomUUID(),C=`${_e()}/login?state=${y}`;await ws(C);let L=3e4,Pe=300*1e3,jt=Date.now()+Pe;for(;Date.now()<jt;)try{let we=await globalThis.fetch(`${_e()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:y,timeout:L}),signal:AbortSignal.timeout(L+5e3)});if(!we.ok){await St(we,re=>{p.warn("auth_status:retry_after_http_error",{status:we.status,delayMs:re})});continue}let B=await we.json();if(B.status==="pending")continue;if(B.status==="expired"){x(new Error("Session expired. Please run setup again."));return}if(B.status==="complete"&&B.sessionToken){console.log(` Signed in as ${B.user}.`),w(B.sessionToken);return}}catch{await St(void 0,we=>{p.warn("auth_status:retry_after_network_error",{delayMs:we})})}x(new Error("Login timed out after 5 minutes. Please run setup again."))}),await F.saveSessionToken(f),console.log(" Session token saved.")),console.log(`
196
+ Step 3: Setting up authentication...`),!ie())console.log(" Not macOS \u2014 skipping biometric setup.");else{try{await Wi("clang",["--version"])}catch{console.error(" Xcode Command Line Tools are required for payment authentication."),console.error(" Install them by running: xcode-select --install"),console.error(" Then re-run: visa-cli setup"),process.exit(1)}let w=ae();try{let x=await w.getStatus(),y=!0;if(cd(x))if(await Ml())try{await h_(w),console.log(" Attestation key already registered with server."),console.log(" Existing local Touch ID key verified and preserved."),y=!1}catch(C){if(!Zu(C))throw C;console.log(" Existing local Touch ID key does not match server biometric state."),await Ki(w),y=!1}else console.log(" Server already has a biometric key, but this device has no local key."),await Ki(w),y=!1;y&&await ld(w,x.attestationRequired===!1)}catch(x){let y=x?.message||"unknown error";if(Zu(x)){console.log(" Server already has a biometric key for this account, but this device cannot prove access to it.");let C=!1;try{await Ki(w),C=!0}catch(L){console.error(` Biometric recovery failed: ${L?.message||"unknown error"}`)}if(!C){let L=x instanceof zt&&x.hint?x.hint:"Run `visa-cli config reset` to clear server-side biometric state through GitHub, then run `visa-cli setup` again.";console.error(` ${L}`),process.exit(1)}}else console.error(` Biometric setup failed: ${y}`),process.exit(1)}}let m=rt(),_=J.existsSync($e.join(z.homedir(),".claude.json")),S=e.hud===!0;if(e.hud===void 0&&_&&!e.yes&&process.stdin.isTTY&&(console.log(`
197
+ Step 4: Visa HUD`),console.log(" Pin balance, card, spend, model, and session activity below the Claude Code input."),console.log(Ac()),S=await Ec(" Install the Visa HUD now?",!1)),S)if(!_)console.log(`
198
198
  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(`
199
- Step 4: Enabling the Visa spend HUD...`);let S=tr(p),w=S.installed==="new"||S.installed==="already-visa"||S.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${w}${S.message}`);try{let y=ae(),k=await y.getStatus(),L={currentVersion:y.getClientVersion(),latestVersion:y.lastSignals?.updateAvailable?.latestVersion,updateCheckDisabled:qe()},$e=_s(k,L);vs($e,k),console.log(` Preview: ${$e.split(`
199
+ Step 4: Enabling the Visa spend HUD...`);let w=ir(m),x=w.installed==="new"||w.installed==="already-visa"||w.installed==="other-hud-present"?" \u2713 ":" Skipped: ";console.log(`${x}${w.message}`);try{let y=ae(),C=await y.getStatus(),L={currentVersion:y.getClientVersion(),latestVersion:y.lastSignals?.updateAvailable?.latestVersion,updateCheckDisabled:Ve()},Pe=Es(C,L);As(Pe,C),console.log(` Preview: ${Pe.split(`
200
200
  `)[0]}`)}catch{}}else e.hud!==!1&&(console.log(`
201
- Step 4: Visa HUD not installed.`),console.log(" Enable later with: visa-cli config hud enable"));let P="\x1B[1m",H="\x1B[2m",D="\x1B[0m";console.log(`
201
+ Step 4: Visa HUD not installed.`),console.log(" Enable later with: visa-cli config hud enable"));let $="\x1B[1m",V="\x1B[2m",D="\x1B[0m";console.log(`
202
202
  \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
203
203
  \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
204
  \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
@@ -206,81 +206,81 @@ Step 4: Visa HUD not installed.`),console.log(" Enable later with: visa-cli co
206
206
  \u255A\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551
207
207
  \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u2588 CLI
208
208
 
209
- ${P}Setup complete.${D} Restart Claude Code or run /mcp to connect.
209
+ ${$}Setup complete.${D} Restart Claude Code or run /mcp to connect.
210
210
 
211
- ${P}Try it out:${D}
211
+ ${$}Try it out:${D}
212
212
  \u2022 Ask Claude: "Generate an image of a neon cityscape"
213
213
  \u2022 Ask Claude: "What's the price of ETH on Base?"
214
214
  \u2022 Check balance: visa-cli balance show
215
215
 
216
216
  \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510
217
- \u2502 ${P}Recommended: enable the spend HUD${D} \u2502
217
+ \u2502 ${$}Recommended: enable the spend HUD${D} \u2502
218
218
  \u2502 \u2502
219
219
  \u2502 Keep an eye on what your agents are spending. \u2502
220
220
  \u2502 Shows your balance, active card, and recent tool usage \u2502
221
221
  \u2502 on every prompt. \u2502
222
222
  \u2502 \u2502
223
- \u2502 ${H}$${D} visa-cli config hud enable \u2502
223
+ \u2502 ${V}$${D} visa-cli config hud enable \u2502
224
224
  \u2502 \u2502
225
225
  \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
226
226
 
227
- ${P}Verify:${D} visa-cli status
228
- ${P}Docs:${D} https://visacli.sh
229
- `),r()}catch(o){console.error("Error:",o.message),r(),process.exit(1)}});W.command("install [client]",{hidden:!0}).description("Register MCP server with an AI client (claude, cursor, windsurf, cline, zed, ...)").option("--all","Install for all detected clients").option("--list","Show supported clients and install status").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--repair","Repair stale MCP client configs without re-running the full setup flow").option("--scope <scope>","Install scope: global or project","global").action(async(e,t)=>{try{if(t.check){let s=Cr();Yu(s,"MCP config check:"),s.length>0&&process.exit(1);return}if(t.repair){let s=Cr();if(s.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of s)Ni(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(z.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
227
+ ${$}Verify:${D} visa-cli status
228
+ ${$}Docs:${D} https://visacli.sh
229
+ `),r()}catch(o){console.error("Error:",o.message),r(),process.exit(1)}});W.command("install [client]",{hidden:!0}).description("Register MCP server with an AI client (claude, cursor, windsurf, cline, zed, ...)").option("--all","Install for all detected clients").option("--list","Show supported clients and install status").option("--check","Scan MCP client configs for stale visa-cli entries and exit without making changes").option("--repair","Repair stale MCP client configs without re-running the full setup flow").option("--scope <scope>","Install scope: global or project","global").action(async(e,t)=>{try{if(t.check){let s=Ir();ad(s,"MCP config check:"),s.length>0&&process.exit(1);return}if(t.repair){let s=Ir();if(s.length===0){console.log("\u2713 MCP config verified \u2014 nothing to repair.");return}for(let i of s)Hi(i),console.log(` \u2713 ${i.client.displayName} (${i.configPath.replace(z.homedir(),"~")}) \u2014 repaired stale ${i.staleReason} entry`);console.log(`
230
230
  Repaired ${s.length} stale MCP config ${s.length===1?"entry":"entries"}.`);return}if(t.list){console.log(`
231
231
  \x1B[1mSupported MCP Clients\x1B[0m
232
- `),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 Ue){let l=xr(a),c=ju(a),u=l?"Yes":"No",d=c?"Yes":"No",f=a.globalConfigPath.replace(z.homedir(),"~");console.log(` ${a.displayName.padEnd(18)} ${u.padEnd(10)} ${d.padEnd(11)} ${f}`)}console.log("");return}let n=t.scope==="project"?"project":"global";if(t.all){let s=[],i=[];for(let a of Ue){if(!xr(a)){i.push(a.displayName);continue}kr(a,n),s.push(a.displayName)}s.length>0&&console.log(`Installed for: ${s.join(", ")}.`),i.length>0&&console.log(`Skipped: ${i.map(a=>`${a} (not detected)`).join(", ")}.`),s.length===0&&i.length===0&&console.log("No supported clients found.");return}e||(console.error("Usage: visa-cli install <client>"),console.error(" visa-cli install --all"),console.error(" visa-cli install --list"),console.error(`
233
- Supported clients: ${Ue.map(s=>s.id).join(", ")}`),process.exit(1));let r=Ii(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${Ue.map(s=>s.id).join(", ")}`),process.exit(1)),n==="global"&&!xr(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let o=kr(r,n);console.log(`Registered visa-cli MCP server in ${o.configPath}`),console.log(o.message)}catch(n){console.error("Error:",n.message),process.exit(1)}});W.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{Tr=!1;try{let e=ae(),[t,n]=await Promise.all([e.getStatus(),e.getTransactions().catch(o=>{if(process.env.VISA_CLI_DEBUG){let s=o instanceof Error?o.message:String(o);process.stderr.write(`[visa-cli] getTransactions failed (HUD will omit): ${s}
234
- `)}return{transactions:[]}})]),r={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:qe()};process.stdout.write(Iu(t,Array.isArray(n?.transactions)?n.transactions:[],ie(),r)),Tr=!0}catch(e){Tr=!1,console.error("Error:",e.message),process.exit(1)}});function S_(e){let t=e.map($u),n=Math.max(2,...t.map(i=>i.id.length)),r=Math.max(5,...t.map(i=>i.brand.length)),o=Math.max(4,...t.map(i=>i.card.length)),s=7;console.log(`
232
+ `),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 De){let l=Ar(a),c=Yu(a),u=l?"Yes":"No",d=c?"Yes":"No",f=a.globalConfigPath.replace(z.homedir(),"~");console.log(` ${a.displayName.padEnd(18)} ${u.padEnd(10)} ${d.padEnd(11)} ${f}`)}console.log("");return}let n=t.scope==="project"?"project":"global";if(t.all){let s=[],i=[];for(let a of De){if(!Ar(a)){i.push(a.displayName);continue}Rr(a,n),s.push(a.displayName)}s.length>0&&console.log(`Installed for: ${s.join(", ")}.`),i.length>0&&console.log(`Skipped: ${i.map(a=>`${a} (not detected)`).join(", ")}.`),s.length===0&&i.length===0&&console.log("No supported clients found.");return}e||(console.error("Usage: visa-cli install <client>"),console.error(" visa-cli install --all"),console.error(" visa-cli install --list"),console.error(`
233
+ Supported clients: ${De.map(s=>s.id).join(", ")}`),process.exit(1));let r=Di(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${De.map(s=>s.id).join(", ")}`),process.exit(1)),n==="global"&&!Ar(r)&&(console.error(`${r.displayName} not detected on this machine.`),console.error(`Expected: ${r.detectPaths.join(", ")}`),process.exit(1));let o=Rr(r,n);console.log(`Registered visa-cli MCP server in ${o.configPath}`),console.log(o.message)}catch(n){console.error("Error:",n.message),process.exit(1)}});W.command("status").description("Check enrollment, cards, wallet, and spending controls").action(async()=>{$r=!1;try{let e=ae(),[t,n]=await Promise.all([e.getStatus(),e.getTransactions().catch(o=>{if(process.env.VISA_CLI_DEBUG){let s=o instanceof Error?o.message:String(o);process.stderr.write(`[visa-cli] getTransactions failed (HUD will omit): ${s}
234
+ `)}return{transactions:[]}})]),r={currentVersion:e.getClientVersion(),latestVersion:e.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:Ve()};process.stdout.write(qu(t,Array.isArray(n?.transactions)?n.transactions:[],ie(),r)),$r=!0}catch(e){$r=!1,console.error("Error:",e.message),process.exit(1)}});function D_(e){let t=e.map(Vu),n=Math.max(2,...t.map(i=>i.id.length)),r=Math.max(5,...t.map(i=>i.brand.length)),o=Math.max(4,...t.map(i=>i.card.length)),s=7;console.log(`
235
235
  Cards
236
236
  `),console.log(` ${"ID".padEnd(n)} ${"Brand".padEnd(r)} ${"Card".padEnd(o)} Default`),console.log(` ${"\u2500".repeat(n)} ${"\u2500".repeat(r)} ${"\u2500".repeat(o)} ${"\u2500".repeat(s)}`);for(let i of t)console.log(` ${i.id.padEnd(n)} ${i.brand.padEnd(r)} ${i.card.padEnd(o)} ${i.default}`);console.log(`
237
237
  Use:`),console.log(" visa-cli cards default <id>"),console.log(` visa-cli cards remove <id>
238
- `)}async function ad(e,t){if(t.yes)return"confirmed";if(!process.stdin.isTTY)return"refused-non-tty";let n=(0,Wu.createInterface)({input:process.stdin,output:process.stdout});try{let r=(await n.question(`${e} [y/N] `)).trim();return/^y(es)?$/i.test(r)?"confirmed":"declined"}finally{n.close()}}var Yo=W.command("cards").description("Manage enrolled payment cards").addHelpCommand(!1).action(De);Yo.command("list").alias("ls").description("List enrolled payment cards").action(async()=>{try{let e=await Oe.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}S_(t)}catch(e){console.error("Error:",e.message),process.exit(1)}});Yo.command("add").description("Add a new Visa card").action(async()=>{try{let e=await Oe.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)}});Yo.command("remove <card-id>").alias("rm").description("Remove an enrolled card").option("-y, --yes","Skip the interactive confirmation prompt").action(async(e,t)=>{try{let n=xi(e),r=await ad(`Remove card ${n}? This cannot be undone.`,t);if(r==="refused-non-tty"&&(console.error("Refusing to remove card without --yes in a non-interactive shell."),process.exit(1)),r==="declined"){console.log("Aborted.");return}let o=await Oe.removeCard({cardId:n,confirm:!0},"visa-cli cards remove");o?.success===!1&&(console.error(o.error||o.message||"Failed to remove card."),process.exit(1)),console.log(o?.message||`Removed card ${n}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});Yo.command("default <card-id>").alias("set-default").description("Set the default payment card").action(async e=>{try{let t=xi(e),n=await Oe.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 Gi=W.command("tokens",{hidden:!0}).description("Create and manage API tokens for apps and agents").addHelpCommand(!1).action(De);function zi(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)}Gi.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 ae().createAppApiKey({label:n_(e),allowed_tools:r_(t.tools),daily_cap_cents:o_(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: ${ed(r.allowed_tools)}`),console.log(`Daily cap: ${Er(r.daily_cap_cents)}/day`),console.log(""),console.log("Store this key now. It will not be shown again."),console.log(""),r.biometric_enabled?(console.log("---------------------------------------------------------------"),console.log("Biometric (Touch ID) is currently ON for this account."),console.log("This API token can still be used headlessly. Per-call Touch ID is"),console.log("not required; spending is bounded by the token daily cap and tools."),console.log("---------------------------------------------------------------"),console.log("")):r.biometric_warning&&(console.log("Note: API tokens bypass per-call biometric verification."),console.log("Keep daily caps and allowed tools scoped for headless use."),console.log("")),console.log("Prepaid session-budget flow:"),console.log(` curl -X POST ${ye()}/v1/api/session-budget/create \\`),console.log(` -H "X-Api-Key: ${r.key}" \\`),console.log(' -H "Content-Type: application/json" \\'),console.log(` -d '{"total_cents":500}'`),console.log(""),console.log("Then execute a tool with the returned budget.id:"),console.log(` curl -X POST ${ye()}/v1/api/session-budget/stream/or-gpt-4o-mini \\`),console.log(` -H "X-Api-Key: ${r.key}" \\`),console.log(' -H "Content-Type: application/json" \\'),console.log(` -d '{"session_budget_id":"sb_...","cumulative_cents":0,"nonce":"nonce-at-least-16","idempotency_key":"idem-at-least-16","prompt":"Say hello in one sentence."}'`)}catch(n){zi(n)}});Gi.command("list").description("List API tokens for the authenticated user").option("--json","Output raw JSON").action(async e=>{try{let n=await ae().listAppApiKeys();if(e.json){console.log(JSON.stringify(n,null,2));return}let r=n.keys||[];if(r.length===0){console.log("No API tokens found. Create one with: visa-cli tokens create");return}console.log("API tokens"),console.log("");for(let o of r)console.log(`${o.id}. ${o.label} (${o.key_prefix})`),console.log(` Status: ${o.status}`),console.log(` Owner: ${o.owner}`),console.log(` Allowed tools: ${ed(o.allowed_tools)}`),console.log(` Daily cap: ${Er(o.daily_cap_cents)}/day`),console.log(` Last used: ${o.last_used_at||"never"}`)}catch(t){zi(t)}});Gi.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 ae().revokeAppApiKey(t);console.log(`Revoked API token ${r.revoked}.`)}catch(t){zi(t)}});async function cd(){try{console.log(`Resetting Visa CLI...
239
- `);let e=ae();await Vi(e);try{await e.logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}if(await F.clearAll(),console.log(" Keychain credentials cleared."),ie())try{await wo(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}console.log(`
240
- Reset complete.`)}catch(e){console.error("Error:",e.message),process.exit(1)}}W.command("reset",{hidden:!0}).description("Deprecated alias for `config reset`").action(cd);var Wi=W.command("balance").description("Manage prepaid balance").addHelpCommand(!1).action(De);Wi.command("show").description("Show prepaid balance + recent ledger entries").action(async()=>{try{let t=await new we(()=>F.getSessionToken()).getBalance();if(console.log(`
241
- Balance: ${qi(t.balanceMicros,t.balanceCents)}
238
+ `)}async function _d(e,t){if(t.yes)return"confirmed";if(!process.stdin.isTTY)return"refused-non-tty";let n=(0,sd.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 os=W.command("cards").description("Manage enrolled payment cards").addHelpCommand(!1).action(je);os.command("list").alias("ls").description("List enrolled payment cards").action(async()=>{try{let e=await Ne.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}D_(t)}catch(e){console.error("Error:",e.message),process.exit(1)}});os.command("add").description("Add a new Visa card").action(async()=>{try{let e=await Ne.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)}});os.command("remove <card-id>").alias("rm").description("Remove an enrolled card").option("-y, --yes","Skip the interactive confirmation prompt").action(async(e,t)=>{try{let n=$i(e),r=await _d(`Remove card ${n}? This cannot be undone.`,t);if(r==="refused-non-tty"&&(console.error("Refusing to remove card without --yes in a non-interactive shell."),process.exit(1)),r==="declined"){console.log("Aborted.");return}let o=await Ne.removeCard({cardId:n,confirm:!0},"visa-cli cards remove");o?.success===!1&&(console.error(o.error||o.message||"Failed to remove card."),process.exit(1)),console.log(o?.message||`Removed card ${n}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});os.command("default <card-id>").alias("set-default").description("Set the default payment card").action(async e=>{try{let t=$i(e),n=await Ne.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 ea=W.command("tokens",{hidden:!0}).description("Create and manage API tokens for apps and agents").addHelpCommand(!1).action(je);function ta(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)}ea.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 ae().createAppApiKey({label:v_(e),allowed_tools:b_(t.tools),daily_cap_cents:S_(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: ${dd(r.allowed_tools)}`),console.log(`Daily cap: ${Pr(r.daily_cap_cents)}/day`),console.log(""),console.log("Store this key now. It will not be shown again."),console.log(""),r.biometric_enabled?(console.log("---------------------------------------------------------------"),console.log("Biometric (Touch ID) is currently ON for this account."),console.log("This API token can still be used headlessly. Per-call Touch ID is"),console.log("not required; spending is bounded by the token daily cap and tools."),console.log("---------------------------------------------------------------"),console.log("")):r.biometric_warning&&(console.log("Note: API tokens bypass per-call biometric verification."),console.log("Keep daily caps and allowed tools scoped for headless use."),console.log("")),console.log("Prepaid session-budget flow:"),console.log(` curl -X POST ${_e()}/v1/api/session-budget/create \\`),console.log(` -H "X-Api-Key: ${r.key}" \\`),console.log(' -H "Content-Type: application/json" \\'),console.log(` -d '{"total_cents":500}'`),console.log(""),console.log("Then execute a tool with the returned budget.id:"),console.log(` curl -X POST ${_e()}/v1/api/session-budget/stream/or-gpt-4o-mini \\`),console.log(` -H "X-Api-Key: ${r.key}" \\`),console.log(' -H "Content-Type: application/json" \\'),console.log(` -d '{"session_budget_id":"sb_...","cumulative_cents":0,"nonce":"nonce-at-least-16","idempotency_key":"idem-at-least-16","prompt":"Say hello in one sentence."}'`)}catch(n){ta(n)}});ea.command("list").description("List API tokens for the authenticated user").option("--json","Output raw JSON").action(async e=>{try{let n=await ae().listAppApiKeys();if(e.json){console.log(JSON.stringify(n,null,2));return}let r=n.keys||[];if(r.length===0){console.log("No API tokens found. Create one with: visa-cli tokens create");return}console.log("API tokens"),console.log("");for(let o of r)console.log(`${o.id}. ${o.label} (${o.key_prefix})`),console.log(` Status: ${o.status}`),console.log(` Owner: ${o.owner}`),console.log(` Allowed tools: ${dd(o.allowed_tools)}`),console.log(` Daily cap: ${Pr(o.daily_cap_cents)}/day`),console.log(` Last used: ${o.last_used_at||"never"}`)}catch(t){ta(t)}});ea.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 ae().revokeAppApiKey(t);console.log(`Revoked API token ${r.revoked}.`)}catch(t){ta(t)}});async function vd(){try{console.log(`Resetting Visa CLI...
239
+ `);let e=ae();await Yi(e);try{await e.logout(),console.log(" Server session invalidated.")}catch{console.log(" Server logout skipped (no active session).")}if(await F.clearAll(),console.log(" Keychain credentials cleared."),ie())try{await Io(),console.log(" Secure Enclave key deleted.")}catch{console.log(" No Secure Enclave key to delete.")}console.log(`
240
+ Reset complete.`)}catch(e){console.error("Error:",e.message),process.exit(1)}}W.command("reset",{hidden:!0}).description("Deprecated alias for `config reset`").action(vd);var na=W.command("balance").description("Manage prepaid balance").addHelpCommand(!1).action(je);na.command("show").description("Show prepaid balance + recent ledger entries").action(async()=>{try{let t=await new xe(()=>F.getSessionToken()).getBalance();if(console.log(`
241
+ Balance: ${Ji(t.balanceMicros,t.balanceCents)}
242
242
  `),t.ledger.length===0){console.log(` (no ledger entries \u2014 top up to begin: visa-cli balance topup --amount 5)
243
- `);return}let n=t.ledger.slice(0,20),r=[],o=t.balanceCents,s=t.balanceMicros?BigInt(t.balanceMicros):null;for(let u of n)r.push(s!=null?s.toString():String(o*1e4)),s!=null&&u.deltaMicros?s-=BigInt(u.deltaMicros):(s=null,o-=u.deltaCents);let i=19,a=11,l=13,c=18;console.log(` ${"TIMESTAMP".padEnd(i)} ${"DELTA".padStart(a)} ${"BALANCE".padStart(l)} ${"REASON".padEnd(c)} TOOL`),console.log(` ${"\u2500".repeat(i)} ${"\u2500".repeat(a)} ${"\u2500".repeat(l)} ${"\u2500".repeat(c)} ${"\u2500".repeat(20)}`),n.forEach((u,d)=>{let f=(u.createdAt||"").slice(0,19),p=qi(u.deltaMicros,u.deltaCents,!0),_=t_(r[d]),T=(u.reason??"").slice(0,c),P=u.toolName??"";console.log(` ${f.padEnd(i)} ${p.padStart(a)} ${_.padStart(l)} ${T.padEnd(c)} ${P}`)}),console.log()}catch(e){e instanceof ot&&(console.error(`Top-up pending reconciliation [${e.code}]: ${e.message}`),e.transactionId&&console.error(`Transaction: ${e.transactionId}`),process.exit(1)),console.error("Error:",e.message),process.exit(1)}});Wi.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=Po(e.amount);if(!t.ok)throw new Error(t.error);let n=t.cents,r=n/100,o=new we(()=>F.getSessionToken());if(!ie())throw new Error(Mo);let s=Wo.randomUUID(),i=await gr(o,async()=>{let a;if(ie()){let{nonce:l}=await o.getAttestationChallenge(),c=Buffer.from(JSON.stringify({nonce:l,amount:r,merchant:"Visa CLI Balance",context:"balance-topup"})).toString("base64");a={signature:await On(c,`top up balance with $${t.displayUsd}`),nonce:l,amount:r,merchant:"Visa CLI Balance"}}return o.topupBalance({amount_cents:n,idempotency_key:s,attestation:a})},Qu(o));if(i.success)console.log(`Top-up complete: +$${(n/100).toFixed(2)} \u2192 balance now $${((i.balanceCents??0)/100).toFixed(2)}`),i.transactionId&&console.log(`Transaction: ${i.transactionId}`),ja();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 ld=Wi.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(De);ld.command("show").description("Show current auto-topup configuration").action(async()=>{try{let t=await new we(()=>F.getSessionToken()).getAutoTopup();if(t.targetCents==null||t.targetCents===0){console.log(`
243
+ `);return}let n=t.ledger.slice(0,20),r=[],o=t.balanceCents,s=t.balanceMicros?BigInt(t.balanceMicros):null;for(let u of n)r.push(s!=null?s.toString():String(o*1e4)),s!=null&&u.deltaMicros?s-=BigInt(u.deltaMicros):(s=null,o-=u.deltaCents);let i=19,a=11,l=13,c=18;console.log(` ${"TIMESTAMP".padEnd(i)} ${"DELTA".padStart(a)} ${"BALANCE".padStart(l)} ${"REASON".padEnd(c)} TOOL`),console.log(` ${"\u2500".repeat(i)} ${"\u2500".repeat(a)} ${"\u2500".repeat(l)} ${"\u2500".repeat(c)} ${"\u2500".repeat(20)}`),n.forEach((u,d)=>{let f=(u.createdAt||"").slice(0,19),m=Ji(u.deltaMicros,u.deltaCents,!0),_=__(r[d]),S=(u.reason??"").slice(0,c),$=u.toolName??"";console.log(` ${f.padEnd(i)} ${m.padStart(a)} ${_.padStart(l)} ${S.padEnd(c)} ${$}`)}),console.log()}catch(e){e instanceof st&&(console.error(`Top-up pending reconciliation [${e.code}]: ${e.message}`),e.transactionId&&console.error(`Transaction: ${e.transactionId}`),process.exit(1)),console.error("Error:",e.message),process.exit(1)}});na.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=Fo(e.amount);if(!t.ok)throw new Error(t.error);let n=t.cents,r=n/100,o=new xe(()=>F.getSessionToken());if(!ie())throw new Error(qo);let s=ns.randomUUID(),i=await br(o,async()=>{let a;if(ie()){let{nonce:l}=await o.getAttestationChallenge(),c=Buffer.from(JSON.stringify({nonce:l,amount:r,merchant:"Visa CLI Balance",context:"balance-topup"})).toString("base64");a={signature:await Dn(c,`top up balance with $${t.displayUsd}`),nonce:l,amount:r,merchant:"Visa CLI Balance"}}return o.topupBalance({amount_cents:n,idempotency_key:s,attestation:a})},ud(o));if(i.success)console.log(`Top-up complete: +$${(n/100).toFixed(2)} \u2192 balance now $${((i.balanceCents??0)/100).toFixed(2)}`),i.transactionId&&console.log(`Transaction: ${i.transactionId}`),Ya();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 bd=na.command("auto-topup").description("Show or disable automatic balance top-ups (read/disable only \u2014 re-enabling is retired pending mandate model)").addHelpCommand(!1).action(je);bd.command("show").description("Show current auto-topup configuration").action(async()=>{try{let t=await new xe(()=>F.getSessionToken()).getAutoTopup();if(t.targetCents==null||t.targetCents===0){console.log(`
244
244
  Auto-topup: disabled
245
- `);return}let n=Er(t.targetCents),r=Er(t.thresholdCents),o=12,s=13;console.log(),console.log(` ${"STATE".padEnd(o)} enabled`),console.log(` ${"TARGET".padEnd(o)} ${n.padStart(s)} (refill balance to this amount)`),console.log(` ${"THRESHOLD".padEnd(o)} ${r.padStart(s)} (trigger refill when balance drops below this)`),console.log(),console.log(" Disable with: visa-cli balance auto-topup disable"),console.log()}catch(e){console.error("Error:",e.message),process.exit(1)}});ld.command("disable").description("Disable auto-topup").action(async()=>{try{let t=await new we(()=>F.getSessionToken()).disableAutoTopup();t.success||(console.error(`Auto-topup disable failed: ${t.error||"Unknown error"}`),process.exit(1)),console.log("Auto-topup disabled. Your balance will no longer refill automatically.")}catch(e){console.error("Error:",e.message),process.exit(1)}});var w_=W.command("session",{hidden:!0}).description("Inspect session budgets");w_.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 we(()=>F.getSessionToken()),[n,r]=await Promise.allSettled([t.getSessionBudget(e),t.getSessionLedger(e)]),o=n.status==="fulfilled"?n.value.budget:void 0,s=r.status==="fulfilled"?r.value:void 0;if(!o&&!s?.ledger?.length&&(console.error(`Session not found: ${e}`),process.exit(1)),console.log(`
245
+ `);return}let n=Pr(t.targetCents),r=Pr(t.thresholdCents),o=12,s=13;console.log(),console.log(` ${"STATE".padEnd(o)} enabled`),console.log(` ${"TARGET".padEnd(o)} ${n.padStart(s)} (refill balance to this amount)`),console.log(` ${"THRESHOLD".padEnd(o)} ${r.padStart(s)} (trigger refill when balance drops below this)`),console.log(),console.log(" Disable with: visa-cli balance auto-topup disable"),console.log()}catch(e){console.error("Error:",e.message),process.exit(1)}});bd.command("disable").description("Disable auto-topup").action(async()=>{try{let t=await new xe(()=>F.getSessionToken()).disableAutoTopup();t.success||(console.error(`Auto-topup disable failed: ${t.error||"Unknown error"}`),process.exit(1)),console.log("Auto-topup disabled. Your balance will no longer refill automatically.")}catch(e){console.error("Error:",e.message),process.exit(1)}});var j_=W.command("session",{hidden:!0}).description("Inspect session budgets");j_.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 xe(()=>F.getSessionToken()),[n,r]=await Promise.allSettled([t.getSessionBudget(e),t.getSessionLedger(e)]),o=n.status==="fulfilled"?n.value.budget:void 0,s=r.status==="fulfilled"?r.value:void 0;if(!o&&!s?.ledger?.length&&(console.error(`Session not found: ${e}`),process.exit(1)),console.log(`
246
246
  Session: ${e}`),o){let i=(o.totalCents/100).toFixed(2),a=(o.cumulativeCents/100).toFixed(2),l=(o.remainingCents/100).toFixed(2);console.log(` Status: ${o.status}${o.expired?" (expired)":""}`),console.log(` Budget: $${i} \xB7 spent $${a} \xB7 remaining $${l}`),console.log(` Created: ${o.createdAt}`),console.log(` Expires: ${o.expiresAt}`)}if(s?.ledger?.length){console.log(`
247
247
  PSP References (CyberSource activity):`);let i=8,a=9,l=36;console.log(` ${"TYPE".padEnd(i)} ${"AMOUNT".padStart(a)} ${"CYBERSOURCE TX ID".padEnd(l)} CREATED`),console.log(` ${"\u2500".repeat(i)} ${"\u2500".repeat(a)} ${"\u2500".repeat(l)} ${"\u2500".repeat(19)}`);for(let c of s.ledger){let u=`$${(c.amountCents/100).toFixed(2)}`;console.log(` ${c.type.padEnd(i)} ${u.padStart(a)} ${(c.transactionId||"").padEnd(l)} ${(c.createdAt||"").slice(0,19)}`)}}else o&&console.log(`
248
- (no PSP references yet \u2014 no holds placed)`);console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});async function ud(e){(!e||e.trim().length===0)&&(console.log('Usage: visa-cli feedback "your message"'),process.exit(1));try{await F.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await ae().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}}W.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action(ud);W.command("update").description("Update Visa CLI to the latest stable version").action(async()=>{let e=Ti(void 0,void 0,void 0,{withDiagnostics:!0}),t=e.diagnostics?Ei(e.diagnostics,e.display):null;try{t&&console.warn(`Warning: ${t}`),console.log(`Updating Visa CLI with ${e.packageManager}: ${e.display}`);let{stdout:n,stderr:r}=await Fi(e.command,e.args,{timeout:5*6e4,maxBuffer:10*1024*1024});n.trim()&&process.stdout.write(n),r.trim()&&process.stderr.write(r);let o=xs(nt(),{force:!0});for(let s of o.messages)console.log(s);console.log("Visa CLI update complete. Restart any running MCP clients to use the new version.")}catch(n){console.error(`Update failed while running: ${e.display}`),console.error(n?.message??String(n)),process.exit(1)}});var Qe=W.command("config").description("Manage CLI configuration and local integrations").addHelpCommand(!1).action(De);function dd(e){return[Ie.join(e,".zshrc"),Ie.join(e,".bashrc"),Ie.join(e,".bash_profile"),Ie.join(e,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),Ie.join(e,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),Ie.join(e,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),Ie.join(e,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),Ie.join(e,".config","powershell","Microsoft.PowerShell_profile.ps1")]}function x_(e){let t=new Map;for(let n of dd(e))try{J.existsSync(n)&&t.set(n,J.readFileSync(n,"utf-8"))}catch{}return t}function k_(e){let t=[];for(let[n,r]of e)try{(J.existsSync(n)?J.readFileSync(n,"utf-8"):"")!==r&&t.push(n)}catch{}return t}function C_(e){let t=[];for(let n of dd(e))try{if(!J.existsSync(n))continue;let r=J.readFileSync(n,"utf-8");Qn(r)!==r.trimEnd()&&t.push(n)}catch{}return t}Qe.command("feedback",{hidden:!0}).description("Deprecated alias for `feedback`").argument("[message]","Your feedback message").action(ud);Qe.command("list").description("Show resolved config values (env vars, server state, defaults) with their source").option("--json","Output as JSON for scripting / agent consumption").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").option("--verbose","Show one-line hints beneath entries that have them").action(async e=>{try{let t=ae(),n=await hr({api:t,includeDev:!!e.dev});if(e.json){console.log($l(n));return}n.statusError&&(console.error(`Warning: could not reach auth server (${n.statusError}).`),console.error("Server-sourced entries show '\u2014'. Log in with `visa-cli setup` if you expected values here."),console.error("")),console.log(Il(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});Qe.command("get <key>").description("Print the resolved value of a single config key (pipe-friendly)").option("--raw","Print the underlying value as JSON instead of the formatted display string").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").action(async(e,t)=>{try{let n=ae(),o=(await hr({api:n,includeDev:!!t.dev})).entries.find(s=>s.key===e);o||(console.error(`Error: unknown config key '${e}'. Run 'visa-cli config list' to see available keys.`),process.exit(1)),t.raw?console.log(JSON.stringify(o.value)):console.log(o.formatted)}catch(n){console.error("Error:",n.message),process.exit(1)}});function T_(){return Object.entries(Tt).map(([e,t])=>` ${e.padEnd(22)} (${t.type}) ${t.description}`).join(`
249
- `)}Qe.command("set <key> <value>").description("Persist a CLI setting to ~/.visa-mcp/settings.json").addHelpText("after",`
248
+ (no PSP references yet \u2014 no holds placed)`);console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});async function Sd(e){(!e||e.trim().length===0)&&(console.log('Usage: visa-cli feedback "your message"'),process.exit(1));try{await F.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1)),await ae().feedback(e.trim()),console.log("Feedback submitted. Thanks!")}catch(t){console.error("Error:",t.message),process.exit(1)}}W.command("feedback").description("Submit feedback about Visa CLI").argument("[message]","Your feedback message").action(Sd);W.command("update").description("Update Visa CLI to the latest stable version").action(async()=>{let e=Mi(void 0,void 0,void 0,{withDiagnostics:!0}),t=e.diagnostics?Ni(e.diagnostics,e.display):null;try{t&&console.warn(`Warning: ${t}`),console.log(`Updating Visa CLI with ${e.packageManager}: ${e.display}`);let{stdout:n,stderr:r}=await Wi(e.command,e.args,{timeout:5*6e4,maxBuffer:10*1024*1024});n.trim()&&process.stdout.write(n),r.trim()&&process.stderr.write(r);let o=Ps(rt(),{force:!0});for(let s of o.messages)console.log(s);console.log("Visa CLI update complete. Restart any running MCP clients to use the new version.")}catch(n){console.error(`Update failed while running: ${e.display}`),console.error(n?.message??String(n)),process.exit(1)}});var et=W.command("config").description("Manage CLI configuration and local integrations").addHelpCommand(!1).action(je);function wd(e){return[$e.join(e,".zshrc"),$e.join(e,".bashrc"),$e.join(e,".bash_profile"),$e.join(e,"Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),$e.join(e,"Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),$e.join(e,"OneDrive","Documents","PowerShell","Microsoft.PowerShell_profile.ps1"),$e.join(e,"OneDrive","Documents","WindowsPowerShell","Microsoft.PowerShell_profile.ps1"),$e.join(e,".config","powershell","Microsoft.PowerShell_profile.ps1")]}function F_(e){let t=new Map;for(let n of wd(e))try{J.existsSync(n)&&t.set(n,J.readFileSync(n,"utf-8"))}catch{}return t}function q_(e){let t=[];for(let[n,r]of e)try{(J.existsSync(n)?J.readFileSync(n,"utf-8"):"")!==r&&t.push(n)}catch{}return t}function V_(e){let t=[];for(let n of wd(e))try{if(!J.existsSync(n))continue;let r=J.readFileSync(n,"utf-8");or(r)!==r.trimEnd()&&t.push(n)}catch{}return t}et.command("feedback",{hidden:!0}).description("Deprecated alias for `feedback`").argument("[message]","Your feedback message").action(Sd);et.command("list").description("Show resolved config values (env vars, server state, defaults) with their source").option("--json","Output as JSON for scripting / agent consumption").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").option("--verbose","Show one-line hints beneath entries that have them").action(async e=>{try{let t=ae(),n=await Sr({api:t,includeDev:!!e.dev});if(e.json){console.log(Vl(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(ql(n.entries,{verbose:!!e.verbose}))}catch(t){console.error("Error:",t.message),process.exit(1)}});et.command("get <key>").description("Print the resolved value of a single config key (pipe-friendly)").option("--raw","Print the underlying value as JSON instead of the formatted display string").option("--dev","Include developer/test hooks (VISA_MOCK_*, VISA_CLI_DEBUG)").action(async(e,t)=>{try{let n=ae(),o=(await Sr({api:n,includeDev:!!t.dev})).entries.find(s=>s.key===e);o||(console.error(`Error: unknown config key '${e}'. Run 'visa-cli config list' to see available keys.`),process.exit(1)),t.raw?console.log(JSON.stringify(o.value)):console.log(o.formatted)}catch(n){console.error("Error:",n.message),process.exit(1)}});function H_(){return Object.entries(Et).map(([e,t])=>` ${e.padEnd(22)} (${t.type}) ${t.description}`).join(`
249
+ `)}et.command("set <key> <value>").description("Persist a CLI setting to ~/.visa-mcp/settings.json").addHelpText("after",`
250
250
  Settable keys:
251
- ${T_()}`).action((e,t)=>{try{let n=ao(e,t);console.log(`Saved ${n.key}=${JSON.stringify(n.value)} \u2192 ${n.path}`),n.requiresRestart&&console.log("Restart Claude Code (or your MCP-enabled client) for the change to take effect.")}catch(n){n instanceof st||n instanceof it||n instanceof kt?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});Qe.command("unset <key>").description("Remove a CLI setting from ~/.visa-mcp/settings.json (falls back to env var or default)").action(e=>{try{let t=co(e);t.removed?(console.log(`Removed ${t.key} from ${t.path}`),t.requiresRestart&&console.log("Restart Claude Code (or your MCP-enabled client) for the change to take effect.")):console.log(`No-op: ${t.key} was not set in ${t.path}.`)}catch(t){console.error(`Error: ${t.message}`),process.exit(1)}});Qe.command("reset").description("Log out and clear all credentials").action(cd);var Ji=Qe.command("biometric").description("Manage Touch ID / biometric attestation enforcement").addHelpCommand(!1).action(De);Ji.command("status").description("Show current biometric enforcement state").action(async()=>{try{await F.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let n=await ae().getStatus(),r=n.attestationRequired!==!1,o=!!n.hasAttestationKey,s=ie();console.log(`Server policy: Touch ID ${r?"REQUIRED":"NOT required"}`),console.log(`Attestation key registered: ${o?"yes":"no"}`),console.log(`Touch ID available on this device: ${s?"yes":"no"}`)}catch(e){console.error("Error:",e.message),process.exit(1)}});Ji.command("on").description("Require Touch ID for payments (security upgrade \u2014 no Touch ID needed)").action(async()=>{try{await F.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=ae(),n=await 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)}});Ji.command("off").description("Disable Touch ID requirement (security downgrade \u2014 one Touch ID confirmation required)").action(async()=>{try{await F.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=ae(),n=await t.getStatus();if(n.attestationRequired===!1){console.log("Touch ID is already disabled.");return}n.hasAttestationKey&&!ie()&&(console.error("Touch ID is unavailable on this device but the server has a registered key."),console.error("Disable Touch ID from a device that can sign, or contact support."),process.exit(1));let r=await gr(t,async()=>{let o;if(n.hasAttestationKey&&ie())try{let{nonce:s}=await t.getAttestationChallenge(),i=0,a="",l=Buffer.from(JSON.stringify({nonce:s,amount:i,merchant:a,context:"biometric-preference"})).toString("base64");o={signature:await On(l,"disable Touch ID requirement"),nonce:s,amount:i,merchant:a}}catch(s){throw new Error(`Touch ID confirmation failed: ${s?.message||"cancelled"}`)}return t.setBiometricPreference({required:!1,attestation:o})},Qu(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 hn=Qe.command("shell-hud").description("Manage the shell prompt HUD (opt-in \u2014 prefer: visa-cli config hud enable)").addHelpCommand(!1).action(De);function md(){let e=Gr();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function pd(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 E_(){pd(As(void 0,{homeDir:z.homedir(),installVisaStatusLine:tr,installShellHud:Gr}))}function fd(){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"),E_()}function Xo(){let e=tt();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}hn.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(md);hn.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(fd);hn.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Xo);hn.command("disable").description("Disable the persistent shell HUD").action(Xo);hn.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${zr()}
252
- `)});hn.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,r=(d,f,p)=>{console.log(` ${f?"\u2713":"\u2717"} ${d}: ${p}`),f||(n=!1)};console.log(`Shell HUD Doctor
253
- `);let o=wn();if(r("Shell detected",!!o,o??"none (zsh, bash, or PowerShell required)"),o){let d=Zn(o),f=e(d);if(r("RC file exists",f,d.replace(z.homedir(),"~")),f){let _=t(d,"utf-8").includes("visa-cli shell hud v2");r("HUD block installed",!!_,_?"found in rc file":"missing \u2014 run: visa-cli config hud enable shell")}}let s=St(),i=e(s);if(r("Cache file",i,i?s.replace(z.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let d=JSON.parse(t(s,"utf-8")),f=Date.now()-(d.renderedAt??0),p=Math.round(f/1e3),_=p<=30;console.log(` ${_?"\u2713":"\u26A0"} Cache freshness: ${p}s old${_?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{r("Cache readable",!1,"corrupt JSON")}let a=Xn(),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 F.getSessionToken()}catch{}if(r("Auth token",u,u?"found in keychain":"missing \u2014 run: visa-cli setup"),u)try{await ae().getStatus(),r("API connectivity",!0,"GET /v1/status OK")}catch(d){let f=d instanceof Error?d.message:"unknown error";r("API connectivity",!1,f)}console.log(n?`
251
+ ${H_()}`).action((e,t)=>{try{let n=ho(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 it||n instanceof at||n instanceof Ct?console.error(`Error: ${n.message}`):console.error(`Error: ${n.message}`),process.exit(1)}});et.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=yo(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)}});et.command("reset").description("Log out and clear all credentials").action(vd);var ra=et.command("biometric").description("Manage Touch ID / biometric attestation enforcement").addHelpCommand(!1).action(je);ra.command("status").description("Show current biometric enforcement state").action(async()=>{try{await F.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let n=await ae().getStatus(),r=n.attestationRequired!==!1,o=!!n.hasAttestationKey,s=ie();console.log(`Server policy: Touch ID ${r?"REQUIRED":"NOT required"}`),console.log(`Attestation key registered: ${o?"yes":"no"}`),console.log(`Touch ID available on this device: ${s?"yes":"no"}`)}catch(e){console.error("Error:",e.message),process.exit(1)}});ra.command("on").description("Require Touch ID for payments (security upgrade \u2014 no Touch ID needed)").action(async()=>{try{await F.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=ae(),n=await 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)}});ra.command("off").description("Disable Touch ID requirement (security downgrade \u2014 one Touch ID confirmation required)").action(async()=>{try{await F.getSessionToken()||(console.error("Not logged in. Run visa-cli setup first."),process.exit(1));let t=ae(),n=await t.getStatus();if(n.attestationRequired===!1){console.log("Touch ID is already disabled.");return}n.hasAttestationKey&&!ie()&&(console.error("Touch ID is unavailable on this device but the server has a registered key."),console.error("Disable Touch ID from a device that can sign, or contact support."),process.exit(1));let r=await br(t,async()=>{let o;if(n.hasAttestationKey&&ie())try{let{nonce:s}=await t.getAttestationChallenge(),i=0,a="",l=Buffer.from(JSON.stringify({nonce:s,amount:i,merchant:a,context:"biometric-preference"})).toString("base64");o={signature:await Dn(l,"disable Touch ID requirement"),nonce:s,amount:i,merchant:a}}catch(s){throw new Error(`Touch ID confirmation failed: ${s?.message||"cancelled"}`)}return t.setBiometricPreference({required:!1,attestation:o})},ud(t));r.success||(console.error(`Failed: ${r.error||"unknown error"}`),process.exit(1)),console.log("Touch ID is no longer required for payments.")}catch(e){console.error("Error:",e.message),process.exit(1)}});var _n=et.command("shell-hud").description("Manage the shell prompt HUD (opt-in \u2014 prefer: visa-cli config hud enable)").addHelpCommand(!1).action(je);function xd(){let e=eo();e.installed||(console.error(e.message),process.exit(1)),console.log(e.message)}function kd(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 B_(){kd(Ls(void 0,{homeDir:z.homedir(),installVisaStatusLine:ir,installShellHud:eo}))}function Cd(){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"),B_()}function ss(){let e=nt();e.removed||(console.error(e.message),process.exit(1)),console.log(e.message)}_n.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(xd);_n.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(Cd);_n.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(ss);_n.command("disable").description("Disable the persistent shell HUD").action(ss);_n.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${to()}
252
+ `)});_n.command("doctor").description("Diagnose shell HUD installation and connectivity").action(async()=>{let{existsSync:e,readFileSync:t}=await import("fs"),n=!0,r=(d,f,m)=>{console.log(` ${f?"\u2713":"\u2717"} ${d}: ${m}`),f||(n=!1)};console.log(`Shell HUD Doctor
253
+ `);let o=Tn();if(r("Shell detected",!!o,o??"none (zsh, bash, or PowerShell required)"),o){let d=rr(o),f=e(d);if(r("RC file exists",f,d.replace(z.homedir(),"~")),f){let _=t(d,"utf-8").includes("visa-cli shell hud v2");r("HUD block installed",!!_,_?"found in rc file":"missing \u2014 run: visa-cli config hud enable shell")}}let s=wt(),i=e(s);if(r("Cache file",i,i?s.replace(z.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),i)try{let d=JSON.parse(t(s,"utf-8")),f=Date.now()-(d.renderedAt??0),m=Math.round(f/1e3),_=m<=30;console.log(` ${_?"\u2713":"\u26A0"} Cache freshness: ${m}s old${_?"":" (stale \u2014 will refresh on next prompt)"}`)}catch{r("Cache readable",!1,"corrupt JSON")}let a=nr(),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 F.getSessionToken()}catch{}if(r("Auth token",u,u?"found in keychain":"missing \u2014 run: visa-cli setup"),u)try{await ae().getStatus(),r("API connectivity",!0,"GET /v1/status OK")}catch(d){let f=d instanceof Error?d.message:"unknown error";r("API connectivity",!1,f)}console.log(n?`
254
254
  All checks passed.`:`
255
- Some checks failed \u2014 see above.`),n||process.exit(1)});async function gd(e){if(!(!e.force&&Ua()))try{let t=ae(),[n,r,o,s]=await Promise.allSettled([t.getStatus(),t.getBalance(),t.listAppApiKeys(),t.getTransactions({limit:1})]);if(n.status==="rejected")throw n.reason;let i=n.value,a=i.prepaidBalance?.cents;if(typeof a=="number"){i.balanceCents=a;let u=i.prepaidBalance?.amountUsd;i.amountUsd=typeof u=="number"?u:a/100}if(r.status==="fulfilled"&&r.value.success&&(i.balanceCents=r.value.balanceCents,i.amountUsd=r.value.amountUsd),o.status==="fulfilled"&&o.value.success&&(i.apiKeyCount=Array.isArray(o.value.keys)?o.value.keys.length:0),s.status==="fulfilled"){let u=s.value,f=(Array.isArray(u)?u:Array.isArray(u.transactions)?u.transactions:[]).find(p=>p&&typeof p.tool_name=="string"&&p.tool_name.length>0);f&&f.created_at&&(i.lastService={toolName:f.tool_name,createdAt:f.created_at})}let l={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:qe()},c=_s(i,l);vs(c,i)}catch(t){let n=t instanceof Error?t.message:"unknown refresh failure";Da(n)}finally{Ft()}}hn.command("refresh").description("Refresh the shell HUD cache (no-op if cache is fresh unless --force)").option("--force","Bypass the cache freshness gate and always refresh").action(gd);var yn=W.command("shell-hud",{hidden:!0}).description("Deprecated alias for `config shell-hud`");yn.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(md);yn.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(fd);yn.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(Xo);yn.command("disable").description("Disable the persistent shell HUD").action(Xo);yn.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${zr()}
256
- `)});yn.command("doctor").description("Show the new shell HUD doctor command").action(()=>{console.log("Run: visa-cli config shell-hud doctor")});yn.command("refresh").description("Refresh the shell HUD cache (no-op if cache is fresh unless --force)").option("--force","Bypass the cache freshness gate and always refresh").action(gd);async function hd(e){try{let t=await Qa(),n=zr(),r=n,o=n.split(`
257
- `)[0],s=Fa();if(!t&&o.includes("loading")){process.stdout.write(`VISA | HUD not initialized \u2014 run: visa-cli config hud enable
258
- `),Li();return}if(e.json){let a=await sc(r,t,s);process.stdout.write(`${JSON.stringify(a,null,2)}
259
- `),Li();return}let i=await nc(r,t,s);process.stdout.write(`${i}
260
- `),Li()}catch(t){let n=t instanceof Error?t.message:"unknown error";console.error(`Failed to render Visa HUD: ${n}`),process.exit(1)}}Qe.command("statusline").description("Output the Visa HUD for agent statusline integrations").option("--json","Output structured JSON for clients that render their own HUD").action(hd);W.command("statusline",{hidden:!0}).description("Deprecated alias for `config statusline`").option("--json","Output structured JSON for clients that render their own HUD").action(hd);var qn=Qe.command("hud").description("Manage the Visa spend HUD \u2014 one command for all surfaces").addHelpCommand(!1);qn.description("Show which HUD surfaces are currently enabled").action(()=>{let e="\x1B[1m",t="\x1B[2m",n="\x1B[32m",r="\x1B[33m",o="\x1B[0m";console.log(`
255
+ Some checks failed \u2014 see above.`),n||process.exit(1)});async function Td(e){if(!(!e.force&&Wa()))try{await xs();let t=ae(),[n,r,o,s]=await Promise.allSettled([t.getStatus(),t.getBalance(),t.listAppApiKeys(),t.getTransactions({limit:1})]);if(n.status==="rejected")throw n.reason;let i=n.value,a=i.prepaidBalance?.cents;if(typeof a=="number"){i.balanceCents=a;let u=i.prepaidBalance?.amountUsd;i.amountUsd=typeof u=="number"?u:a/100}if(r.status==="fulfilled"&&r.value.success&&(i.balanceCents=r.value.balanceCents,i.amountUsd=r.value.amountUsd),o.status==="fulfilled"&&o.value.success&&(i.apiKeyCount=Array.isArray(o.value.keys)?o.value.keys.length:0),s.status==="fulfilled"){let u=s.value,f=(Array.isArray(u)?u:Array.isArray(u.transactions)?u.transactions:[]).find(m=>m&&typeof m.tool_name=="string"&&m.tool_name.length>0);f&&f.created_at&&(i.lastService={toolName:f.tool_name,createdAt:f.created_at})}let l={currentVersion:t.getClientVersion(),latestVersion:t.lastSignals.updateAvailable?.latestVersion,updateCheckDisabled:Ve()},c=Es(i,l);As(c,i)}catch(t){let n=t instanceof Error?t.message:"unknown refresh failure";Ja(n)}finally{Vt()}}_n.command("refresh").description("Refresh the shell HUD cache (no-op if cache is fresh unless --force)").option("--force","Bypass the cache freshness gate and always refresh").action(Td);var vn=W.command("shell-hud",{hidden:!0}).description("Deprecated alias for `config shell-hud`");vn.command("install").description("Install the persistent shell HUD into your zsh or bash rc file").action(xd);vn.command("enable").description("Deprecated alias for `config hud enable` (Claude Code statusLine)").action(Cd);vn.command("uninstall").description("Remove the persistent shell HUD from your shell rc file").action(ss);vn.command("disable").description("Disable the persistent shell HUD").action(ss);vn.command("segment").description("Print the cached shell HUD segment").action(()=>{process.stdout.write(`${to()}
256
+ `)});vn.command("doctor").description("Show the new shell HUD doctor command").action(()=>{console.log("Run: visa-cli config shell-hud doctor")});vn.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(Td);async function Ed(e){try{await xs();let t=await uc(),n=to(),r=n,o=n.split(`
257
+ `)[0],s=Xa();if(!t&&o.includes("loading")){process.stdout.write(`VISA | HUD not initialized \u2014 run: visa-cli config hud enable
258
+ `),Bi();return}if(e.json){let a=await hc(r,t,s);process.stdout.write(`${JSON.stringify(a,null,2)}
259
+ `),Bi();return}let i=await pc(r,t,s);process.stdout.write(`${i}
260
+ `),Bi()}catch(t){let n=t instanceof Error?t.message:"unknown error";console.error(`Failed to render Visa HUD: ${n}`),process.exit(1)}}et.command("statusline").description("Output the Visa HUD for agent statusline integrations").option("--json","Output structured JSON for clients that render their own HUD").action(Ed);W.command("statusline",{hidden:!0}).description("Deprecated alias for `config statusline`").option("--json","Output structured JSON for clients that render their own HUD").action(Ed);var Kn=et.command("hud").description("Manage the Visa spend HUD \u2014 one command for all surfaces").addHelpCommand(!1);Kn.description("Show which HUD surfaces are currently enabled").action(()=>{let e="\x1B[1m",t="\x1B[2m",n="\x1B[32m",r="\x1B[33m",o="\x1B[0m";console.log(`
261
261
  ${e}Visa HUD Status${o}
262
- `);let s=nt(),i=!1,a=!1;try{if(J.existsSync(s)){let _=JSON.parse(J.readFileSync(s,"utf-8")),T=typeof _.statusLine=="object"?_.statusLine.command:"";i=xt(T),a=!!_.statusLine&&!i}}catch{}let l=i?`${n}\u2713${o}`:`${t}\u2717${o}`,c=i?"registered in ~/.claude/settings.json":a?`${r}another HUD is configured${o} \u2014 edit settings.json to switch`:"not enabled";console.log(` ${l} ${e}Claude Code${o} (statusLine) ${c}`);let u=Vt(z.homedir()),d=u.length>0||Kr(),f=d?`${n}\u2713${o}`:`${t}\u2717${o}`,p=d?`installed in shell rc file${u.length>0?` (${u.map(_=>_.replace(z.homedir(),"~")).join(", ")})`:""}`:"not installed (opt-in)";console.log(` ${f} ${e}Shell prompt${o} ${p}`),i&&d&&console.log(` ${r}!${o} ${e}Overlap${o} Claude statusLine and shell prompt HUD are both installed. Remove shell prompt output with: visa-cli config hud disable shell`),console.log(`
263
- ${e}Quick start:${o}`),i||console.log(` visa-cli config hud enable ${t}# Claude Code statusLine (recommended)${o}`),d||console.log(` visa-cli config hud enable shell ${t}# zsh/bash prompt line (opt-in)${o}`),i&&d&&console.log(` ${n}All surfaces enabled.${o}`),(i||d)&&console.log(` visa-cli config hud disable [shell] ${t}# remove a surface${o}`),console.log(` visa-cli config hud doctor ${t}# diagnose connectivity${o}`),console.log()});qn.command("enable").description("Enable the Visa HUD \u2014 claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{pd(As(e,{homeDir:z.homedir(),installVisaStatusLine:tr,installShellHud:Gr}))});qn.command("disable").description("Disable the Visa HUD from a surface: claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{let t=e??"claude";if(t==="shell"||t==="prompt"){let s=tt();s.removed||(console.error(s.message),process.exit(1)),console.log(s.message);return}let n=to(t);n||(console.error(`Unknown HUD surface: ${t}`),console.error("Supported: claude (default), shell, all"),process.exit(1));let r=!1,o=!1;if(n==="claude"||n==="claude-code"||n==="all"){let s=nt(),i=ks(s);console.log(i.message),i.removed&&(o=!0),!i.removed&&n!=="all"&&(r=!0);let a=i.status==="removed"||i.status==="missing-settings"||i.status==="missing-statusline";if(n!=="all"&&!e&&a&&!Qr()&&Vt(z.homedir()).length>0){let c=tt();c.removed&&c.rcPaths&&c.rcPaths.length>0&&(console.log(`Also cleaned legacy shell-prompt HUD block from ${c.rcPaths.map(u=>u.replace(z.homedir(),"~")).join(", ")} (was leaking output above every shell prompt). Set VISA_HUD_KEEP_SHELL=1 (or true / yes / on) if you want the shell surface to stay.`),o=!0,(i.status==="missing-settings"||i.status==="missing-statusline")&&(r=!1))}}if(n==="all"){let s=tt();console.log(s.message),s.removed&&(o=!0),!s.removed&&n!=="all"&&(r=!0)}n==="all"&&!o&&(r=!0),r&&process.exit(1)});qn.command("doctor").description("Diagnose HUD installation and connectivity across all surfaces").option("--fix","Self-heal locally fixable issues (stale cache, legacy placeholder, orphan precmd block)").option("-y, --yes","Allow --fix to remove overlapping shell HUD blocks without an interactive prompt").action(async e=>{let t=!0,n=(p,_,T)=>{console.log(` ${_?"\u2713":"\u2717"} ${p}: ${T}`),_||(t=!1)};console.log(`Visa HUD Doctor
264
- `);let r=[],o=Ti(void 0,void 0,void 0,{withDiagnostics:!0}),s=o.diagnostics?Ei(o.diagnostics,o.display):null;s&&(console.log(`\u26A0 ${s}`),console.log(""));let i=nt(),a=!1;try{if(J.existsSync(i)){let p=JSON.parse(J.readFileSync(i,"utf-8")),_=typeof p.statusLine=="object"?p.statusLine.command:"";a=xt(_)}}catch{}n("Claude Code statusLine",a,a?"registered":"not registered \u2014 run: visa-cli config hud enable");let l=C_(z.homedir()),c=wn();if(n("Shell detected",!!c,c??"none (zsh, bash, or PowerShell required)"),c){let p=Zn(c),_=J.existsSync(p);if(n("RC file exists",_,p.replace(z.homedir(),"~")),_){let P=J.readFileSync(p,"utf-8").includes("visa-cli shell hud v2");console.log(` ${P?"\u2713":"\u2013"} Shell HUD block: ${P?"installed":"not installed (opt-in \u2014 run: visa-cli config hud enable shell)"}`)}}if(l.length>0&&console.log(` \u2713 Shell HUD rc scan: installed in ${l.map(p=>p.replace(z.homedir(),"~")).join(", ")}`),a&&l.length>0&&e.fix){let p=l.map(T=>T.replace(z.homedir(),"~")).join(", "),_=e.yes===!0;if(!_&&process.stdin.isTTY&&(_=await ad(`Remove shell prompt HUD block from ${p}?`,{})==="confirmed"),_){let T=x_(z.homedir());tt();let P=k_(T);if(P.length>0){let H=P.map(D=>D.replace(z.homedir(),"~")).join(", ");console.log(` \u2713 --fix: cleaned legacy shell-prompt HUD block from ${H}`),r.push(`removed shell precmd block from ${H}`)}}else console.log(` ! --fix: preserving shell prompt HUD block in ${p}; rerun with --yes or remove it explicitly with: visa-cli config hud disable shell`)}else a&&l.length>0&&console.log(" ! Overlap notice: Claude Code statusLine and shell prompt HUD are both installed. If the prompt output is unintended, run: visa-cli config hud disable shell \u2014 or rerun with: visa-cli config hud doctor --fix --yes");let u=St(),d=J.existsSync(u);if(n("HUD cache file",d,d?u.replace(z.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),d)try{let p=JSON.parse(J.readFileSync(u,"utf-8")),_=Date.now()-(p.renderedAt??0),T=Math.round(_/1e3),P=T<=30,H=typeof p.line=="string"?p.line:"",D=H.length>0&&Wr(H);if(console.log(` ${P?"\u2713":"\u26A0"} Cache freshness: ${T}s old${P?"":" (stale \u2014 will refresh on next prompt)"}`),D&&console.log(' \u26A0 Cache content: legacy placeholder (HUD will display "VISA | HUD not ready" until next successful refresh)'),e.fix&&(!P||D)){let S=!1;try{J.rmSync(u,{force:!0}),S=!0}catch{}try{let w=Xn();J.existsSync(w)&&(J.rmSync(w,{force:!0}),S=!0)}catch{}if(S){let w=D?"cache held legacy placeholder":`cache was ${T}s stale`;console.log(` \u2713 --fix: cleared HUD cache (${w}); next prompt will trigger a fresh refresh`),r.push("cleared HUD cache");let y=Ie.join(z.homedir(),".visa-cli","shell-hud.lock");J.existsSync(y)&&(Ft(),console.log(" \u2713 --fix: cleared shell HUD refresh lock"),r.push("cleared shell HUD refresh lock"))}}}catch{if(console.log(" \u2717 Cache readable: corrupt JSON"),e.fix)try{J.rmSync(u,{force:!0}),console.log(" \u2713 --fix: removed corrupt cache file; next prompt will trigger a fresh refresh"),r.push("removed corrupt cache");let p=Ie.join(z.homedir(),".visa-cli","shell-hud.lock");J.existsSync(p)&&(Ft(),console.log(" \u2713 --fix: cleared shell HUD refresh lock"),r.push("cleared shell HUD refresh lock"))}catch{t=!1}else t=!1}let f=!1;try{f=!!await F.getSessionToken()}catch{}if(n("Auth token",f,f?"found in keychain":"missing \u2014 run: visa-cli setup"),f)try{await ae().getStatus(),n("API connectivity",!0,"GET /v1/status OK")}catch(p){let _=p instanceof Error?p.message:"unknown error";n("API connectivity",!1,_)}e.fix&&(r.length===0?console.log(`
262
+ `);let s=rt(),i=!1,a=!1;try{if(J.existsSync(s)){let _=JSON.parse(J.readFileSync(s,"utf-8")),S=typeof _.statusLine=="object"?_.statusLine.command:"";i=kt(S),a=!!_.statusLine&&!i}}catch{}let l=i?`${n}\u2713${o}`:`${t}\u2717${o}`,c=i?"registered in ~/.claude/settings.json":a?`${r}another HUD is configured${o} \u2014 edit settings.json to switch`:"not enabled";console.log(` ${l} ${e}Claude Code${o} (statusLine) ${c}`);let u=Bt(z.homedir()),d=u.length>0||Qr(),f=d?`${n}\u2713${o}`:`${t}\u2717${o}`,m=d?`installed in shell rc file${u.length>0?` (${u.map(_=>_.replace(z.homedir(),"~")).join(", ")})`:""}`:"not installed (opt-in)";console.log(` ${f} ${e}Shell prompt${o} ${m}`),i&&d&&console.log(` ${r}!${o} ${e}Overlap${o} Claude statusLine and shell prompt HUD are both installed. Remove shell prompt output with: visa-cli config hud disable shell`),console.log(`
263
+ ${e}Quick start:${o}`),i||console.log(` visa-cli config hud enable ${t}# Claude Code statusLine (recommended)${o}`),d||console.log(` visa-cli config hud enable shell ${t}# zsh/bash prompt line (opt-in)${o}`),i&&d&&console.log(` ${n}All surfaces enabled.${o}`),(i||d)&&console.log(` visa-cli config hud disable [shell] ${t}# remove a surface${o}`),console.log(` visa-cli config hud doctor ${t}# diagnose connectivity${o}`),console.log()});Kn.command("enable").description("Enable the Visa HUD \u2014 claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{kd(Ls(e,{homeDir:z.homedir(),installVisaStatusLine:ir,installShellHud:eo}))});Kn.command("disable").description("Disable the Visa HUD from a surface: claude (default), shell, or all").argument("[surface]","Target surface: claude (default), shell, or all").action(e=>{let t=e??"claude";if(t==="shell"||t==="prompt"){let s=nt();s.removed||(console.error(s.message),process.exit(1)),console.log(s.message);return}let n=lo(t);n||(console.error(`Unknown HUD surface: ${t}`),console.error("Supported: claude (default), shell, all"),process.exit(1));let r=!1,o=!1;if(n==="claude"||n==="claude-code"||n==="all"){let s=rt(),i=Os(s);console.log(i.message),i.removed&&(o=!0),!i.removed&&n!=="all"&&(r=!0);let a=i.status==="removed"||i.status==="missing-settings"||i.status==="missing-statusline";if(n!=="all"&&!e&&a&&!ao()&&Bt(z.homedir()).length>0){let c=nt();c.removed&&c.rcPaths&&c.rcPaths.length>0&&(console.log(`Also cleaned legacy shell-prompt HUD block from ${c.rcPaths.map(u=>u.replace(z.homedir(),"~")).join(", ")} (was leaking output above every shell prompt). Set VISA_HUD_KEEP_SHELL=1 (or true / yes / on) if you want the shell surface to stay.`),o=!0,(i.status==="missing-settings"||i.status==="missing-statusline")&&(r=!1))}}if(n==="all"){let s=nt();console.log(s.message),s.removed&&(o=!0),!s.removed&&n!=="all"&&(r=!0)}n==="all"&&!o&&(r=!0),r&&process.exit(1)});Kn.command("doctor").description("Diagnose HUD installation and connectivity across all surfaces").option("--fix","Self-heal locally fixable issues (stale cache, legacy placeholder, orphan precmd block)").option("-y, --yes","Allow --fix to remove overlapping shell HUD blocks without an interactive prompt").action(async e=>{let t=!0,n=(m,_,S)=>{console.log(` ${_?"\u2713":"\u2717"} ${m}: ${S}`),_||(t=!1)};console.log(`Visa HUD Doctor
264
+ `);let r=[],o=Mi(void 0,void 0,void 0,{withDiagnostics:!0}),s=o.diagnostics?Ni(o.diagnostics,o.display):null;s&&(console.log(`\u26A0 ${s}`),console.log(""));let i=rt(),a=!1;try{if(J.existsSync(i)){let m=JSON.parse(J.readFileSync(i,"utf-8")),_=typeof m.statusLine=="object"?m.statusLine.command:"";a=kt(_)}}catch{}n("Claude Code statusLine",a,a?"registered":"not registered \u2014 run: visa-cli config hud enable");let l=V_(z.homedir()),c=Tn();if(n("Shell detected",!!c,c??"none (zsh, bash, or PowerShell required)"),c){let m=rr(c),_=J.existsSync(m);if(n("RC file exists",_,m.replace(z.homedir(),"~")),_){let $=J.readFileSync(m,"utf-8").includes("visa-cli shell hud v2");console.log(` ${$?"\u2713":"\u2013"} Shell HUD block: ${$?"installed":"not installed (opt-in \u2014 run: visa-cli config hud enable shell)"}`)}}if(l.length>0&&console.log(` \u2713 Shell HUD rc scan: installed in ${l.map(m=>m.replace(z.homedir(),"~")).join(", ")}`),a&&l.length>0&&e.fix){let m=l.map(S=>S.replace(z.homedir(),"~")).join(", "),_=e.yes===!0;if(!_&&process.stdin.isTTY&&(_=await _d(`Remove shell prompt HUD block from ${m}?`,{})==="confirmed"),_){let S=F_(z.homedir());nt();let $=q_(S);if($.length>0){let V=$.map(D=>D.replace(z.homedir(),"~")).join(", ");console.log(` \u2713 --fix: cleaned legacy shell-prompt HUD block from ${V}`),r.push(`removed shell precmd block from ${V}`)}}else console.log(` ! --fix: preserving shell prompt HUD block in ${m}; rerun with --yes or remove it explicitly with: visa-cli config hud disable shell`)}else a&&l.length>0&&console.log(" ! Overlap notice: Claude Code statusLine and shell prompt HUD are both installed. If the prompt output is unintended, run: visa-cli config hud disable shell \u2014 or rerun with: visa-cli config hud doctor --fix --yes");let u=wt(),d=J.existsSync(u);if(n("HUD cache file",d,d?u.replace(z.homedir(),"~"):"missing \u2014 HUD has not refreshed yet"),d)try{let m=JSON.parse(J.readFileSync(u,"utf-8")),_=Date.now()-(m.renderedAt??0),S=Math.round(_/1e3),$=S<=30,V=typeof m.line=="string"?m.line:"",D=V.length>0&&no(V);if(console.log(` ${$?"\u2713":"\u26A0"} Cache freshness: ${S}s old${$?"":" (stale \u2014 will refresh on next prompt)"}`),D&&console.log(' \u26A0 Cache content: legacy placeholder (HUD will display "VISA | HUD not ready" until next successful refresh)'),e.fix&&(!$||D)){let w=!1;try{J.rmSync(u,{force:!0}),w=!0}catch{}try{let x=nr();J.existsSync(x)&&(J.rmSync(x,{force:!0}),w=!0)}catch{}if(w){let x=D?"cache held legacy placeholder":`cache was ${S}s stale`;console.log(` \u2713 --fix: cleared HUD cache (${x}); next prompt will trigger a fresh refresh`),r.push("cleared HUD cache");let y=$e.join(z.homedir(),".visa-cli","shell-hud.lock");J.existsSync(y)&&(Vt(),console.log(" \u2713 --fix: cleared shell HUD refresh lock"),r.push("cleared shell HUD refresh lock"))}}}catch{if(console.log(" \u2717 Cache readable: corrupt JSON"),e.fix)try{J.rmSync(u,{force:!0}),console.log(" \u2713 --fix: removed corrupt cache file; next prompt will trigger a fresh refresh"),r.push("removed corrupt cache");let m=$e.join(z.homedir(),".visa-cli","shell-hud.lock");J.existsSync(m)&&(Vt(),console.log(" \u2713 --fix: cleared shell HUD refresh lock"),r.push("cleared shell HUD refresh lock"))}catch{t=!1}else t=!1}let f=!1;try{f=!!await F.getSessionToken()}catch{}if(n("Auth token",f,f?"found in keychain":"missing \u2014 run: visa-cli setup"),f)try{await ae().getStatus(),n("API connectivity",!0,"GET /v1/status OK")}catch(m){let _=m instanceof Error?m.message:"unknown error";n("API connectivity",!1,_)}e.fix&&(r.length===0?console.log(`
265
265
  --fix: no locally fixable issues found.`):console.log(`
266
266
  --fix: applied ${r.length} change${r.length===1?"":"s"} \u2014 ${r.join("; ")}.`)),console.log(t?`
267
267
  All checks passed.`:`
268
- Some checks failed \u2014 see above.`),t||process.exit(1)});qn.command("enable-claude").description("Alias for: hud enable claude").action(()=>{let e=nt(),t=tr(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});qn.command("disable-claude").description("Alias for: hud disable claude").action(()=>{let e=nt(),t=ks(e);console.log(t.message),t.removed||process.exit(1)});var Vn=W.command("merchants").description("List discoverable platform merchants and refresh JIT tools").addHelpCommand(!1).action(De);Vn.description("Discover and run paid merchant tools");Vn.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 we(()=>F.getSessionToken()),n=await t.listPublicMerchants();if(n.length===0){e.json?console.log(JSON.stringify({merchants:[]},null,2)):console.log(`
268
+ Some checks failed \u2014 see above.`),t||process.exit(1)});Kn.command("enable-claude").description("Alias for: hud enable claude").action(()=>{let e=rt(),t=ir(e);console.log(t.message),(t.installed==="error"||t.installed==="malformed-json")&&process.exit(1)});Kn.command("disable-claude").description("Alias for: hud disable claude").action(()=>{let e=rt(),t=Os(e);console.log(t.message),t.removed||process.exit(1)});var Gn=W.command("merchants").description("List discoverable platform merchants and refresh JIT tools").addHelpCommand(!1).action(je);Gn.description("Discover and run paid merchant tools");Gn.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 xe(()=>F.getSessionToken()),n=await t.listPublicMerchants();if(n.length===0){e.json?console.log(JSON.stringify({merchants:[]},null,2)):console.log(`
269
269
  No live platform merchants on this auth server.
270
270
  `);return}let r=await Promise.all(n.map(async a=>{let l=await t.getPublicMerchantDiscover(a.slug);return{slug:a.slug,display_name:a.display_name,provider:l?.title??a.display_name,merchant_of_record:l?.merchant_of_record??a.display_name,upstream:l?.upstream,tools:(l?.routes??[]).filter(c=>c.tool_id).map(c=>({tool_id:c.tool_id,mcp_name:c.tool_id.replace(/-/g,"_"),method:c.method,path:c.path,price_cents:c.price_cents,category:c.category??null,description:c.description??null}))}}));if(e.json){console.log(JSON.stringify({merchants:r},null,2));return}let o="\x1B[1m",s="\x1B[2m",i="\x1B[0m";console.log();for(let a of r){let l=a.merchant_of_record!==a.provider?` ${s}(MoR: ${a.merchant_of_record})${i}`:"";if(console.log(` ${o}${a.provider}${i}${l} ${s}\u2014 slug: ${a.slug}${i}`),a.upstream&&console.log(` ${s}upstream: ${a.upstream}${i}`),a.tools.length===0)console.log(` ${s}(no routes with tool_id \u2014 agents can't see this merchant yet)${i}`);else for(let c of a.tools){let u=c.category?` ${s}[${c.category}]${i}`:"",d=`$${(c.price_cents/100).toFixed(2)}`;console.log(` ${c.tool_id}${u} ${s}\u2192 Claude: ${c.mcp_name}${i} ${d} ${s}${c.method} ${c.path}${i}`),c.description&&console.log(` ${s}${c.description}${i}`)}console.log()}console.log(` ${s}To enable JIT tools in your MCP server, set: visa-cli config set merchants.discover all (or =<slug,...>)${i}
271
- `)}catch(t){console.error("Error:",t.message),process.exit(1)}});Vn.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 ${od}, max ${sd})`,Bu).option("--offset <n>","Pagination offset (default 0)",Bu).action(async e=>{try{let t=ae(),{limit:n,offset:r}=p_(e),o=await m_(t,{query:e.query,category:e.category,limit:n,offset:r});if(e.json){console.log(JSON.stringify({tools:o},null,2));return}if(o.length===0){console.log("No merchant tools found. Try: visa-cli merchants tools --category image");return}e.verbose?c_(o):a_(o)}catch(t){console.error("Error:",t.message),process.exit(1)}});Vn.command("describe <tool>").description("Show tool schema, price, and examples").action(async e=>{try{let n=await ae().catalogTool(e,"discover_tools");n||(console.error(`Tool not found: ${e}`),console.error('Search with: visa-cli merchants tools --query "what you want to do"'),process.exit(1)),console.log(`
271
+ `)}catch(t){console.error("Error:",t.message),process.exit(1)}});Gn.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 ${gd}, max ${hd})`,td).option("--offset <n>","Pagination offset (default 0)",td).action(async e=>{try{let t=ae(),{limit:n,offset:r}=I_(e),o=await R_(t,{query:e.query,category:e.category,limit:n,offset:r});if(e.json){console.log(JSON.stringify({tools:o},null,2));return}if(o.length===0){console.log("No merchant tools found. Try: visa-cli merchants tools --category image");return}e.verbose?C_(o):k_(o)}catch(t){console.error("Error:",t.message),process.exit(1)}});Gn.command("describe <tool>").description("Show tool schema, price, and examples").action(async e=>{try{let n=await ae().catalogTool(e,"discover_tools");n||(console.error(`Tool not found: ${e}`),console.error('Search with: visa-cli merchants tools --query "what you want to do"'),process.exit(1)),console.log(`
272
272
  ${n.id}
273
273
  `),console.log(n.description),console.log(`
274
- Price`),console.log(` ${Hi(n.priceCents,n.priceDisplay)}`),console.log(`
274
+ Price`),console.log(` ${Xi(n.priceCents,n.priceDisplay)}`),console.log(`
275
275
  Provider`),console.log(` ${n.provider} \xB7 ${n.category}`),console.log(`
276
- Inputs`);let r=n.inputSchema?.properties;if(r&&typeof r=="object"&&!Array.isArray(r)){let s=Array.isArray(n.inputSchema.required)?new Set(n.inputSchema.required):new Set,i=Object.entries(r),a=Math.max(12,...i.map(([l])=>l.length));for(let[l,c]of i){let u=s.has(l)?"required":"optional",d=pc(c),f=d?` ${d.padEnd(8)}`:" ",p=c?.description?` - ${c.description}`:"";console.log(` ${l.padEnd(a)} ${u}${f}${p}`)}}else console.log(" No published schema. Use --json with the request body.");console.log(`
277
- Examples`);let o=Au(n);console.log(` visa-cli merchants run ${n.id} --json '${JSON.stringify(o)}'`),n.category==="image"&&console.log(' visa-cli generate image "a lobster on a marble counter"'),console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});function A_(e){return["fal-flux-pro-ultra","fal-flux-pro","fal-flux-schnell","fal-recraft-v3","fal-ideogram-v2","fal-minimax-video","fal-wan-video","fal-kling-video","fal-ace-step-music","query_onchain_prices"].includes(e)}async function Yi(e,t,n){return A_(e)?Oe.shortcut(e,t,n):Oe.executeTool({tool_id:e,params:t},n,"execute_tool")}Vn.command("run <tool>").description("Run any merchant tool by id").option("--json <json>","Tool parameters as a JSON object").option("--prompt <prompt>","Prompt parameter for prompt-shaped tools").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=s_(t.json,"--json");t.prompt&&(n.prompt=t.prompt),Fr({yes:t.yes}),console.log(`Running ${e}`);let r=await Yi(e,n,`visa-cli merchants run ${e}`);Bi(r),Ki(r)}catch(n){console.error("Error:",n.message),process.exit(1)}});Vn.command("refresh").description("Hint: restart the MCP server (Claude/Cursor) to refresh discovered tools \u2014 discovery is in-process").action(()=>{console.log(`
276
+ Inputs`);let r=n.inputSchema?.properties;if(r&&typeof r=="object"&&!Array.isArray(r)){let s=Array.isArray(n.inputSchema.required)?new Set(n.inputSchema.required):new Set,i=Object.entries(r),a=Math.max(12,...i.map(([l])=>l.length));for(let[l,c]of i){let u=s.has(l)?"required":"optional",d=kc(c),f=d?` ${d.padEnd(8)}`:" ",m=c?.description?` - ${c.description}`:"";console.log(` ${l.padEnd(a)} ${u}${f}${m}`)}}else console.log(" No published schema. Use --json with the request body.");console.log(`
277
+ Examples`);let o=ju(n);console.log(` visa-cli merchants run ${n.id} --json '${JSON.stringify(o)}'`),n.category==="image"&&console.log(' visa-cli generate image "a lobster on a marble counter"'),console.log()}catch(t){console.error("Error:",t.message),process.exit(1)}});function K_(e){return["fal-flux-pro-ultra","fal-flux-pro","fal-flux-schnell","fal-recraft-v3","fal-ideogram-v2","fal-minimax-video","fal-wan-video","fal-kling-video","fal-ace-step-music","query_onchain_prices"].includes(e)}async function oa(e,t,n){return K_(e)?Ne.shortcut(e,t,n):Ne.executeTool({tool_id:e,params:t},n,"execute_tool")}Gn.command("run <tool>").description("Run any merchant tool by id").option("--json <json>","Tool parameters as a JSON object").option("--prompt <prompt>","Prompt parameter for prompt-shaped tools").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=w_(t.json,"--json");t.prompt&&(n.prompt=t.prompt),Kr({yes:t.yes}),console.log(`Running ${e}`);let r=await oa(e,n,`visa-cli merchants run ${e}`);Zi(r),Qi(r)}catch(n){console.error("Error:",n.message),process.exit(1)}});Gn.command("refresh").description("Hint: restart the MCP server (Claude/Cursor) to refresh discovered tools \u2014 discovery is in-process").action(()=>{console.log(`
278
278
  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.
279
- `)});var Ar=W.command("generate").description("Generate media with merchant tools").addHelpCommand(!1).action(De);async function Rr(e){Fr({yes:e.yes}),e.json||e.format&&Vr(e.format)||(console.log(`
279
+ `)});var Or=W.command("generate").description("Generate media with merchant tools").addHelpCommand(!1).action(je);async function Mr(e){Kr({yes:e.yes}),e.json||e.format&&zr(e.format)||(console.log(`
280
280
  ${e.kind}
281
281
  `),console.log(`Using: ${e.toolId}`),console.log(`Prompt: ${e.prompt}
282
- `));let n=await Yi(e.toolId,e.params,`visa-cli generate ${e.kind.toLowerCase()}: ${e.prompt}`);Bi(n,{json:e.json,format:e.format,command:e.command??`generate.${e.kind.toLowerCase().replace(/\s+/g,"_")}`}),Ki(n)}var Ut=(e,t)=>n=>(t.includes(n)||W.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 (accepts stdin via `-` or --stdin)").option("--quality <quality>","Image quality: standard or high",Ut("--quality",["standard","high"]),"standard").option("--fast","Use the fast image tool").option("--tool <tool>","Exact tool id override").option("--image-ref <url>","Optional source image URL for edit/style-transfer tools").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Ut("--format",vt)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await jt(e,t),r=t.tool??(t.fast||t.quality!=="high"?"fal-flux-pro":"fal-flux-pro-ultra"),o={prompt:n};t.imageRef&&(o.image_url=t.imageRef),await Rr({kind:"Image generation",toolId:r,params:o,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.image"})}catch(n){Fn("generate.image",n,{json:t.json,format:t.format})}});Ar.command("video [prompt]").description("Generate a video from a prompt (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--aspect-ratio <ratio>","Aspect ratio, when supported by the selected tool").option("--duration <seconds>","Duration in seconds, when supported by the selected tool").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Ut("--format",vt)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await jt(e,t),r={prompt:n};t.aspectRatio&&(r.aspect_ratio=t.aspectRatio),t.duration&&(r.duration=Number(t.duration)),await Rr({kind:"Video generation",toolId:t.tool??"fal-minimax-video",params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.video"})}catch(n){Fn("generate.video",n,{json:t.json,format:t.format})}});Ar.command("music [prompt]").description("Generate music from a prompt (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--instrumental","Generate instrumental music").option("--duration <seconds>","Duration in seconds, when supported by the selected tool").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Ut("--format",vt)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await jt(e,t),r={prompt:n};t.instrumental&&(r.instrumental=!0),t.duration&&(r.duration=Number(t.duration)),await Rr({kind:"Music generation",toolId:t.tool??$t("generate_music"),params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.music"})}catch(n){Fn("generate.music",n,{json:t.json,format:t.format})}});Ar.command("speech [text]").description("Generate speech from text using a voice sample (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--audio-url <url>","Voice sample audio URL for voice cloning").option("--ref-audio-url <url>","Alias for --audio-url").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Ut("--format",vt)).option("--stdin","Read text from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=t.audioUrl??t.refAudioUrl;n||W.error("error: option '--audio-url <url>' is required for visa-cli generate speech",{exitCode:2});let r=await jt(e,t),o={text:r,audio_url:n};await Rr({kind:"Speech generation",toolId:t.tool??"fal-metavoice",params:o,prompt:r,json:t.json,format:t.format,yes:t.yes,command:"generate.speech"})}catch(n){Fn("generate.speech",n,{json:t.json,format:t.format})}});Ar.command("3d [image-url]").alias("model").description("Generate a 3D model from an image URL (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Ut("--format",vt)).option("--stdin","Read image URL from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await jt(e,t),r={image_url:n};await Rr({kind:"3D generation",toolId:t.tool??$t("generate_3d"),params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.3d"})}catch(n){Fn("generate.3d",n,{json:t.json,format:t.format})}});var ji="reasoning",Ku=Object.keys(pr.run_llm.tiers);W.command("run-llm [prompt]").description(`Run a chat-completion against an OpenRouter-backed LLM (default tier: ${ji})`).option("--tier <tier>",`LLM tier: ${Ku.join(" | ")} (resolves to a catalog tool id via the run_llm meta-tool)`,Ut("--tier",Ku),ji).option("--model <id>","Exact catalog tool id (e.g. or-claude-haiku, or-gemini-3-flash). Overrides --tier.").option("--system <prompt>","System prompt (inline string or @./path to a file)").option("--max-tokens <n>","Maximum completion tokens").option("--temperature <n>","Sampling temperature 0-2").option("--image-url <url>","Image URL for vision-capable models (or-gemini-nano-banana-pro, etc.)").option("--from-stdin <field>","Read upstream JSON envelope from stdin and bind .field to a flag value (e.g. --image-url --from-stdin .urls[0])").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Ut("--format",vt)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=t.imageUrl;if(t.fromStdin){let c=await ds(),u=JSON.parse(c),d=ya(u,t.fromStdin);n=n??d}let r=await jt(e,{stdin:t.stdin&&!t.fromStdin});Fr({yes:t.yes});let o={prompt:r},s=await va(t.system);s&&(o.system_prompt=s),t.maxTokens&&(o.max_tokens=Number(t.maxTokens)),t.temperature!==void 0&&(o.temperature=Number(t.temperature)),n&&(o.image_url=n);let i=t.tier??ji,a=t.model??$t("run_llm",i);if(!t.json){console.log(`
282
+ `));let n=await oa(e.toolId,e.params,`visa-cli generate ${e.kind.toLowerCase()}: ${e.prompt}`);Zi(n,{json:e.json,format:e.format,command:e.command??`generate.${e.kind.toLowerCase().replace(/\s+/g,"_")}`}),Qi(n)}var Dt=(e,t)=>n=>(t.includes(n)||W.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 (accepts stdin via `-` or --stdin)").option("--quality <quality>","Image quality: standard or high",Dt("--quality",["standard","high"]),"standard").option("--fast","Use the fast image tool").option("--tool <tool>","Exact tool id override").option("--image-ref <url>","Optional source image URL for edit/style-transfer tools").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Dt("--format",bt)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await Ft(e,t),r=t.tool??(t.fast||t.quality!=="high"?"fal-flux-pro":"fal-flux-pro-ultra"),o={prompt:n};t.imageRef&&(o.image_url=t.imageRef),await Mr({kind:"Image generation",toolId:r,params:o,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.image"})}catch(n){Bn("generate.image",n,{json:t.json,format:t.format})}});Or.command("video [prompt]").description("Generate a video from a prompt (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--aspect-ratio <ratio>","Aspect ratio, when supported by the selected tool").option("--duration <seconds>","Duration in seconds, when supported by the selected tool").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Dt("--format",bt)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await Ft(e,t),r={prompt:n};t.aspectRatio&&(r.aspect_ratio=t.aspectRatio),t.duration&&(r.duration=Number(t.duration)),await Mr({kind:"Video generation",toolId:t.tool??"fal-minimax-video",params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.video"})}catch(n){Bn("generate.video",n,{json:t.json,format:t.format})}});Or.command("music [prompt]").description("Generate music from a prompt (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--instrumental","Generate instrumental music").option("--duration <seconds>","Duration in seconds, when supported by the selected tool").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Dt("--format",bt)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await Ft(e,t),r={prompt:n};t.instrumental&&(r.instrumental=!0),t.duration&&(r.duration=Number(t.duration)),await Mr({kind:"Music generation",toolId:t.tool??Pt("generate_music"),params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.music"})}catch(n){Bn("generate.music",n,{json:t.json,format:t.format})}});Or.command("speech [text]").description("Generate speech from text using a voice sample (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--audio-url <url>","Voice sample audio URL for voice cloning").option("--ref-audio-url <url>","Alias for --audio-url").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Dt("--format",bt)).option("--stdin","Read text from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=t.audioUrl??t.refAudioUrl;n||W.error("error: option '--audio-url <url>' is required for visa-cli generate speech",{exitCode:2});let r=await Ft(e,t),o={text:r,audio_url:n};await Mr({kind:"Speech generation",toolId:t.tool??"fal-metavoice",params:o,prompt:r,json:t.json,format:t.format,yes:t.yes,command:"generate.speech"})}catch(n){Bn("generate.speech",n,{json:t.json,format:t.format})}});Or.command("3d [image-url]").alias("model").description("Generate a 3D model from an image URL (accepts stdin via `-` or --stdin)").option("--tool <tool>","Exact tool id override").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Dt("--format",bt)).option("--stdin","Read image URL from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=await Ft(e,t),r={image_url:n};await Mr({kind:"3D generation",toolId:t.tool??Pt("generate_3d"),params:r,prompt:n,json:t.json,format:t.format,yes:t.yes,command:"generate.3d"})}catch(n){Bn("generate.3d",n,{json:t.json,format:t.format})}});var zi="reasoning",nd=Object.keys(_r.run_llm.tiers);W.command("run-llm [prompt]").description(`Run a chat-completion against an OpenRouter-backed LLM (default tier: ${zi})`).option("--tier <tier>",`LLM tier: ${nd.join(" | ")} (resolves to a catalog tool id via the run_llm meta-tool)`,Dt("--tier",nd),zi).option("--model <id>","Exact catalog tool id (e.g. or-claude-haiku, or-gemini-3-flash). Overrides --tier.").option("--system <prompt>","System prompt (inline string or @./path to a file)").option("--max-tokens <n>","Maximum completion tokens").option("--temperature <n>","Sampling temperature 0-2").option("--image-url <url>","Image URL for vision-capable models (or-gemini-nano-banana-pro, etc.)").option("--from-stdin <field>","Read upstream JSON envelope from stdin and bind .field to a flag value (e.g. --image-url --from-stdin .urls[0])").option("--json","Emit one canonical JSON envelope to stdout").option("--format <fmt>","Output format: json|yaml|tsv|table (implies --json)",Dt("--format",bt)).option("--stdin","Read prompt from stdin (alias for `-`)").option("--yes","Skip the non-TTY confirmation guard (required for paid commands in scripts)").action(async(e,t)=>{try{let n=t.imageUrl;if(t.fromStdin){let c=await vs(),u=JSON.parse(c),d=Ca(u,t.fromStdin);n=n??d}let r=await Ft(e,{stdin:t.stdin&&!t.fromStdin});Kr({yes:t.yes});let o={prompt:r},s=await Ea(t.system);s&&(o.system_prompt=s),t.maxTokens&&(o.max_tokens=Number(t.maxTokens)),t.temperature!==void 0&&(o.temperature=Number(t.temperature)),n&&(o.image_url=n);let i=t.tier??zi,a=t.model??Pt("run_llm",i);if(!t.json){console.log(`
283
283
  LLM completion
284
284
  `),console.log(`Using: ${a}`);let c=r.length>200?`${r.slice(0,200)}\u2026`:r;console.log(`Prompt: ${c}
285
- `)}let l=await Yi(a,o,"visa-cli run-llm");Bi(l,{json:t.json,format:t.format,command:"run-llm"}),Ki(l)}catch(n){Fn("run-llm",n,{json:t.json,format:t.format})}});W.command("uninstall [client]").description("Remove MCP server from an AI client").option("--all","Remove from all clients").option("--scope <scope>","Uninstall scope: global or project","global").action(async(e,t)=>{try{let n=t.scope==="project"?"project":"global";if(t.all){let s=[];for(let i of Ue)Oi(i,n).removed&&s.push(i.displayName);s.length>0?console.log(`Removed visa-cli from: ${s.join(", ")}.`):console.log("visa-cli was not installed in any client.");return}e||(console.error("Usage: visa-cli uninstall <client>"),console.error(" visa-cli uninstall --all"),console.error(`
286
- Supported clients: ${Ue.map(s=>s.id).join(", ")}`),process.exit(1));let r=Ii(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${Ue.map(s=>s.id).join(", ")}`),process.exit(1));let o=Oi(r,n);o.removed?console.log(`Removed visa-cli from ${o.configPath}`):console.log(`visa-cli was not installed for ${r.displayName}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});W.hook("postAction",()=>{if(Tr){Tr=!1;return}zo&&Eu(zo.lastSignals)});b_(["setup","install","status","cards","tokens","balance","merchants","generate","run-llm","config","feedback","update","uninstall"]);id(W);W.parseAsync().catch(async e=>{console.error("Error:",e instanceof Error?e.message:String(e));let{reportFatal:t}=await Promise.resolve().then(()=>(Go(),Ko));await t(e)});process.on("uncaughtException",async e=>{console.error("Uncaught exception:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(Go(),Ko));await t(e)});process.on("unhandledRejection",async e=>{console.error("Unhandled rejection:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(Go(),Ko));await t(e)});0&&(module.exports={printGroupHelpAndExit});
285
+ `)}let l=await oa(a,o,"visa-cli run-llm");Zi(l,{json:t.json,format:t.format,command:"run-llm"}),Qi(l)}catch(n){Bn("run-llm",n,{json:t.json,format:t.format})}});W.command("uninstall [client]").description("Remove MCP server from an AI client").option("--all","Remove from all clients").option("--scope <scope>","Uninstall scope: global or project","global").action(async(e,t)=>{try{let n=t.scope==="project"?"project":"global";if(t.all){let s=[];for(let i of De)Vi(i,n).removed&&s.push(i.displayName);s.length>0?console.log(`Removed visa-cli from: ${s.join(", ")}.`):console.log("visa-cli was not installed in any client.");return}e||(console.error("Usage: visa-cli uninstall <client>"),console.error(" visa-cli uninstall --all"),console.error(`
286
+ Supported clients: ${De.map(s=>s.id).join(", ")}`),process.exit(1));let r=Di(e);r||(console.error(`Unknown client: ${e}`),console.error(`Supported clients: ${De.map(s=>s.id).join(", ")}`),process.exit(1));let o=Vi(r,n);o.removed?console.log(`Removed visa-cli from ${o.configPath}`):console.log(`visa-cli was not installed for ${r.displayName}.`)}catch(n){console.error("Error:",n.message),process.exit(1)}});W.hook("postAction",()=>{if($r){$r=!1;return}ts&&Du(ts.lastSignals)});U_(["setup","install","status","cards","tokens","balance","merchants","generate","run-llm","config","feedback","update","uninstall"]);yd(W);W.parseAsync().catch(async e=>{console.error("Error:",e instanceof Error?e.message:String(e));let{reportFatal:t}=await Promise.resolve().then(()=>(es(),Qo));await t(e)});process.on("uncaughtException",async e=>{console.error("Uncaught exception:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(es(),Qo));await t(e)});process.on("unhandledRejection",async e=>{console.error("Unhandled rejection:",e);let{reportFatal:t}=await Promise.resolve().then(()=>(es(),Qo));await t(e)});0&&(module.exports={printGroupHelpAndExit});