@visa/cli 2.4.0-rc.0 → 2.4.0
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 +5 -5
- package/dist/mcp-server/index.js +5 -5
- package/package.json +1 -1
- package/server.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Qu=Object.create;var kr=Object.defineProperty;var ed=Object.getOwnPropertyDescriptor;var td=Object.getOwnPropertyNames;var nd=Object.getPrototypeOf,rd=Object.prototype.hasOwnProperty;var od=(e,t)=>()=>(e&&(t=e(e=0)),t);var Hi=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),qo=(e,t)=>{for(var n in t)kr(e,n,{get:t[n],enumerable:!0})},Bi=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of td(t))!rd.call(e,o)&&o!==n&&kr(e,o,{get:()=>t[o],enumerable:!(r=ed(t,o))||r.enumerable});return e};var T=(e,t,n)=>(n=e!=null?Qu(nd(e)):{},Bi(t||!e||!e.__esModule?kr(n,"default",{value:e,enumerable:!0}):n,e)),sd=e=>Bi(kr({},"__esModule",{value:!0}),e);var Vn=Hi((a_,_d)=>{_d.exports={name:"@visa/cli",version:"2.4.0
|
|
1
|
+
"use strict";var Qu=Object.create;var kr=Object.defineProperty;var ed=Object.getOwnPropertyDescriptor;var td=Object.getOwnPropertyNames;var nd=Object.getPrototypeOf,rd=Object.prototype.hasOwnProperty;var od=(e,t)=>()=>(e&&(t=e(e=0)),t);var Hi=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),qo=(e,t)=>{for(var n in t)kr(e,n,{get:t[n],enumerable:!0})},Bi=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of td(t))!rd.call(e,o)&&o!==n&&kr(e,o,{get:()=>t[o],enumerable:!(r=ed(t,o))||r.enumerable});return e};var T=(e,t,n)=>(n=e!=null?Qu(nd(e)):{},Bi(t||!e||!e.__esModule?kr(n,"default",{value:e,enumerable:!0}):n,e)),sd=e=>Bi(kr({},"__esModule",{value:!0}),e);var Vn=Hi((a_,_d)=>{_d.exports={name:"@visa/cli",version:"2.4.0",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{"sync:server-json":"node scripts/sync-server-json.mjs","check:server-json":"node scripts/sync-server-json.mjs --check",prebuild:"node scripts/sync-server-json.mjs && pnpm --filter @visa/money build && pnpm --filter @visa-cli/tools build",build:"tsc --noEmit && node esbuild.config.js",prepack:"node scripts/sync-server-json.mjs --check",dev:"tsc --watch",pretest:"pnpm build",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:catalog-e2e":"jest --config jest.catalog-e2e.config.js","test:all":"npm run test:unit && npm run test:integration && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/sdk":"^1.0.0",commander:"^12.1.0",zod:"^3.23.0"},devDependencies:{"@visa/money":"workspace:*","@visa/observability":"workspace:*","@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.31.0","@types/jest":"^30.0.0","@types/node":"^25.9.0","@typescript-eslint/eslint-plugin":"^8.59.4","@typescript-eslint/parser":"^8.59.4","@types/express":"^5.0.0",esbuild:"^0.27.4",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.3","ts-jest":"^29.4.10",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","server.json","README.md","LICENSE"]}});var mr=Hi(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.micros=Gf;te.fromCents=zf;te.fromUsdc=Wf;te.fromUsd=Jf;te.toCents=Yf;te.toCentsForAcquirer=Zf;te.toUsdc=Xf;te.toWire=Qf;te.fromWire=eg;te.toDisplay=tg;te.toUsdRounded2dp=ng;te.add=rg;te.sub=og;te.clampNonNegative=sg;te.isNonNegative=ig;te.max=ag;te.min=cg;var at=10000n,vl=1000000n;function Gf(e){return e}function zf(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*at}function Wf(e){return e}function Jf(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function Yf(e){if(e>=0n)return Number(e/at);let t=e/at,n=e%at;return Number(n===0n?t:t-1n)}function Zf(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/at)}function Xf(e){return e}function Qf(e){return e.toString()}function eg(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 tg(e,t={}){let n=t.decimals??2,r=t.symbol??"$",o=e<0n,s=o?-e:e,i=s/vl,a=s%vl,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 ng(e){let t=e<0n,n=t?-e:e,r=n/at,s=n%at*2n,i;s<at?i=r:s>at?i=r+1n:i=r%2n===0n?r:r+1n;let a=Number(i)/100;return t?-a:a}function rg(e,t){return e+t}function og(e,t){return e-t}function sg(e){return e<0n?0n:e}function ig(e){return e>=0n}function ag(e,t){return e>t?e:t}function cg(e,t){return e<t?e:t}});var No={};qo(No,{initSentry:()=>hy,isSentryConfigured:()=>gy,reportFatal:()=>yy});function gy(){return!1}async function hy(){return null}async function yy(e,t){process.exit(t?.exitCode??1)}var Lo=od(()=>{});var e_={};qo(e_,{printGroupHelpAndExit:()=>Le});module.exports=sd(e_);var Au=require("commander"),Uo=T(require("crypto")),z=T(require("fs")),K=T(require("os")),Re=T(require("path")),Ru=require("child_process"),Iu=require("node:readline/promises"),$u=require("util");var Ar=require("child_process"),ea=require("util"),ft=T(require("fs")),Rr=T(require("os")),Wo=T(require("path"));var Wi=T(require("crypto"));var Ze="e9501a252b778bce5a3d77710667afdd9198a750d1d989d95fb32d80e485bf15";var Ji="VISA_ALLOW_INSECURE_MOCKS",Ki,Gi,zi;function Ho(e){return`${e}-${Wi.randomBytes(24).toString("base64url")}`}function Yi(e=process.env){return e.NODE_ENV==="test"||e[Ji]==="true"}function mt(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&Yi(e)}function gn(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&Yi(e)}function Bo(){return`Set ${Ji}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function Zi(){return Ki??=Ho("mock-session"),Ki}function Xi(e=process.env){return e.NODE_ENV==="test"?Ze:(Gi??=Ho("mock-rc"),Gi)}function Qi(){return zi??=Ho("mock-signature"),zi}var De=(0,ea.promisify)(Ar.execFile),Jo=Wo.join(Rr.homedir(),".visa-mcp"),Fn=Wo.join(Jo,"session-token"),ke="visa-cli",pt="session-token",Tr="rc-access",id=5e3,Er=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function ad(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
|
|
2
2
|
`)}function ta(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=ad(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}async function cd(){try{let{stdout:e}=await De("security",["find-generic-password","-s",ke,"-a",pt,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(ta(e))throw new Er("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 ld(e){try{try{await De("security",["delete-generic-password","-s",ke,"-a",pt],{timeout:5e3})}catch{}return await De("security",["add-generic-password","-s",ke,"-a",pt,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function ud(){try{await De("security",["delete-generic-password","-s",ke,"-a",pt],{timeout:5e3})}catch{}}async function dd(){if(!Yo())return null;try{let{stdout:e}=await De("secret-tool",["lookup","service",ke,"account",pt],{timeout:5e3});return e.trim()||null}catch{return null}}async function md(e){if(!Yo())return!1;try{let t=(0,Ar.execFile)("secret-tool",["store","--label",`${ke} ${pt}`,"service",ke,"account",pt]);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"))},id))]),!0):!1}catch{return!1}}async function pd(){if(Yo())try{await De("secret-tool",["clear","service",ke,"account",pt],{timeout:5e3})}catch{}}function Yo(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function fd(){try{let{stdout:e}=await De("security",["find-generic-password","-s",ke,"-a",Tr,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function gd(e){try{try{await De("security",["delete-generic-password","-s",ke,"-a",Tr],{timeout:5e3})}catch{}await De("security",["add-generic-password","-s",ke,"-a",Tr,"-w",e],{timeout:5e3})}catch{}}async function hd(){try{await De("security",["delete-generic-password","-s",ke,"-a",Tr],{timeout:5e3})}catch{}}function Go(){try{return ft.readFileSync(Fn,"utf-8").trim()||null}catch(e){if(ta(e))throw new Er(`Unable to read Visa CLI credentials from ${Fn}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function na(e){ft.mkdirSync(Jo,{recursive:!0,mode:448}),ft.writeFileSync(Fn,e,{mode:384}),process.platform==="win32"&&yd(Fn)}function zo(){try{ft.unlinkSync(Fn)}catch{}}function yd(e){try{let t=Rr.userInfo().username;(0,Ar.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 Ko(){switch(process.platform){case"darwin":return{get:cd,store:ld,delete:ud};case"linux":return{get:dd,store:md,delete:pd};default:return{get:async()=>Go(),store:async e=>{try{return na(e),!0}catch{return!1}},delete:async()=>zo(),storesInSessionFile:!0}}}var U=class{static async getSessionToken(){if(mt())return Promise.resolve(Zi());let t=Ko(),n=await t.get();if(n)return n;let r=Go();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(mt())return;let n=Ko();if(await n.store(t)){if(await n.get()===t){n.storesInSessionFile||zo();return}await n.delete()}if(na(t),Go()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${Jo} is writable.`))}static async getRcAccessToken(){return mt()?Xi():fd()}static async saveRcAccessToken(t){mt()||await gd(t)}static async deleteSessionToken(){if(mt())return;await Ko().delete(),zo()}static async clearAll(){await this.deleteSessionToken(),await hd()}};var Ir=T(require("crypto")),$r=T(require("tty")),Pr=T(require("fs"));function vd(e){return/-rc\.|-beta\./.test(e)}function Zo(e){return Ir.createHash("sha256").update(e.trim()).digest("hex")}function ra(e){return Ze==="SKIP"?!0:Ir.timingSafeEqual(Buffer.from(Zo(e)),Buffer.from(Ze))}function bd(){try{let e=Pr.openSync("/dev/tty","r+"),t=new $r.ReadStream(e),n=new $r.WriteStream(e),r=!1;return{input:t,output:n,cleanupStreams:()=>{if(!r){r=!0;try{t.destroy()}catch{}try{n.destroy()}catch{}try{Pr.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 Sd(e){return new Promise((t,n)=>{let r;try{r=bd()}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(`
|
|
@@ -101,7 +101,7 @@ ${S}`:p}function Gd(e){let t=` ${B("\u2502",q.dim)} `,n=[];if(typeof e.dailySpen
|
|
|
101
101
|
`)}catch{}}function Ia(){try{let e=Jn();if(!e)return;let t={...e,renderedAt:0};yn(_t(),JSON.stringify(t)+`
|
|
102
102
|
`)}catch{}}function Dt(){try{j.unlinkSync(Ca())}catch{}}function Jn(){let e=_t();if(!j.existsSync(e))return null;try{let t=JSON.parse(j.readFileSync(e,"utf-8"));return typeof t?.line=="string"&&Vr(t.line)?null:t}catch{return null}}function Vr(e){for(let t of e.split(`
|
|
103
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 $a(){return Jn()?.status??null}function Qd(){if(process.env.JEST_WORKER_ID)return;let e=Ca();try{if(j.mkdirSync(V.dirname(e),{recursive:!0}),!sm(e))return;let t=process.argv[1]?V.resolve(process.argv[1]):"";if(!t){Dt();return}let n=(0,Sa.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});n.once("error",Dt),n.unref()}catch{Dt()}}function vt(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 em(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),o="\u2591".repeat(10-n);return`${B(r||"",q.green)}${B(o||"",q.dim)}`}function hn(e){return`$${e.toFixed(2)}`}function tm(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=vt(n.toUpperCase()),s=vt(r);return`${t.isDefault?"default":"active"} ${o} ****${s}`}function nm(){let e=(process.env.COLORTERM??"").toLowerCase();if(e==="truecolor"||e==="24bit")return!0;let t=(process.env.TERM??"").toLowerCase();return t.includes("truecolor")||t.includes("24bit")}var cs=nm(),q={reset:"\x1B[0m",visaBlue:cs?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:cs?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:cs?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function B(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${q.reset}`}function ba(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ps(){let e=Ut.homedir();if(!e||!V.isAbsolute(e))throw new Error("unable to determine a valid home directory");return V.resolve(e)}function rm(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function om(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function sm(e){for(let t=0;t<2;t+=1){let n;try{return n=j.openSync(e,"wx"),j.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let o=j.statSync(e);if(Date.now()-o.mtimeMs<=Fd)return!1;j.unlinkSync(e)}catch{}}finally{n!==void 0&&j.closeSync(n)}}return!1}function ls(e){return e instanceof Error?e.message:"unknown file system error"}function yn(e,t){j.mkdirSync(V.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${(0,wa.randomBytes)(8).toString("hex")}.tmp`;try{j.writeFileSync(n,t),j.renameSync(n,e)}catch(r){try{j.unlinkSync(n)}catch{}throw r}}var im=1440*60*1e3;function Hr(e,t){ne.mkdirSync(me.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Oa.randomBytes(8).toString("hex")}.tmp`;try{ne.writeFileSync(n,JSON.stringify(t,null,2)+`
|
|
104
|
-
`),ne.renameSync(n,e)}catch(r){try{ne.unlinkSync(n)}catch{}throw r}}function Pa(e){return`'${e.replace(/'/g,"'\\''")}'`}var gs="# visa-cli-hud-v1";function Br(e,t){if(!e&&!t&&am())return`visa-cli config statusline ${gs}`;let n=e??process.execPath,r=t??process.argv[1]??"",o=r?me.resolve(r):"";return`${o?`${Pa(n)} ${Pa(o)} config statusline`:"visa-cli config statusline"} ${gs}`}function am(){try{return(0,Na.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function bt(e){return typeof e!="string"?!1:e.includes(gs)?!0:e.includes("visa-cli")&&e.includes("statusline")}function cm(){return"2.4.0
|
|
104
|
+
`),ne.renameSync(n,e)}catch(r){try{ne.unlinkSync(n)}catch{}throw r}}function Pa(e){return`'${e.replace(/'/g,"'\\''")}'`}var gs="# visa-cli-hud-v1";function Br(e,t){if(!e&&!t&&am())return`visa-cli config statusline ${gs}`;let n=e??process.execPath,r=t??process.argv[1]??"",o=r?me.resolve(r):"";return`${o?`${Pa(n)} ${Pa(o)} config statusline`:"visa-cli config statusline"} ${gs}`}function am(){try{return(0,Na.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function bt(e){return typeof e!="string"?!1:e.includes(gs)?!0:e.includes("visa-cli")&&e.includes("statusline")}function cm(){return"2.4.0"}function Kr(e){let t=me.dirname(me.resolve(e));return me.basename(t)===".claude"?me.dirname(t):La.homedir()}function qr(e,t){let n=me.relative(t,e);return!n.startsWith("..")&&!me.isAbsolute(n)?`~/${n}`:e}function lm(e){return me.join(Kr(e),".visa-cli","hud-self-heal.json")}function um(e,t,n,r){try{if(!ne.existsSync(e))return!1;let o=JSON.parse(ne.readFileSync(e,"utf-8"));return o.version===t&&typeof o.checkedAt=="number"&&n-o.checkedAt<r}catch{return!1}}function fs(e,t,n){try{Hr(e,{version:t,checkedAt:n})}catch{}}function dm(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function hs(e,t={}){let n=t.now??Date.now(),r=t.version??cm(),o=t.stampPath??lm(e),s=t.minIntervalMs??im,i=[],a=!1,l=!1;if(!t.force&&um(o,r,n,s))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:i,skippedReason:"recently checked"};try{if(!ne.existsSync(e))return fs(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:l,messages:i};let c=JSON.parse(ne.readFileSync(e,"utf-8")),u=c.statusLine,d=u&&typeof u=="object"&&!Array.isArray(u)?u.command:"";if(!bt(d))return fs(o,r,n),{checked:!0,statusLineRepaired:a,shellHudRemoved:l,messages:i};let g=(t.getCommand??Br)();if(d!==g&&(c.statusLine=dm(u,g),Hr(e,c),a=!0,i.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!Gr()){let p=Kr(e);if(jt(p).length>0){let S=Xe(null,p);if(S.removed&&S.rcPaths&&S.rcPaths.length>0){let y=S.rcPaths.map(R=>qr(R,p)).join(", ");l=!0,i.push(`Cleaned legacy shell-prompt HUD block from ${y}.`)}}}return fs(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
105
|
`)}catch{}}return{checked:!0,statusLineRepaired:a,shellHudRemoved:l,messages:i}}}function mm(e,t){let n=Kr(t),r=jt(n);if(r.length===0)return e;let o=r.map(s=>qr(s,n)).join(", ");return`${e}
|
|
106
106
|
Note: a shell-prompt HUD block was detected in ${o}. If it is unintended, remove it with: visa-cli config hud disable shell`}function Gr(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 Ma(e,t){let n=Kr(t),r=jt(n);if(r.length===0)return e;let o=r.map(i=>qr(i,n)).join(", ");if(Gr())return`${e}
|
|
107
107
|
Note: a legacy shell-prompt HUD block was detected in ${o}. VISA_HUD_KEEP_SHELL set \u2014 leaving it in place. Remove it any time with: visa-cli config hud disable shell`;let s=Xe(null,n);if(s.removed&&s.rcPaths&&s.rcPaths.length>0){let i=s.rcPaths.map(a=>qr(a,n)).join(", ");return`${e}
|
|
@@ -119,10 +119,10 @@ ${a}`}function Sm(e){if(typeof e!="number"||e<=0)return"";let n=(e>1e12?e:e*1e3)
|
|
|
119
119
|
`),{isActive:s}=Wa(e,n,t?.transcript_path);return{schemaVersion:pm,client:t?Qa(t):Ft.UNKNOWN,rendered:o,lines:r.map(bs),visa:{spendLine:bs(e),balanceCents:n?.balanceCents,balanceUsd:n?.amountUsd,sessionMode:n?.sessionMode,activeSession:n?.activeSession,isVisaActive:s},context:t?tc(t):{}}}function Z(e){return e?e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim():""}function Jr(e){if(typeof e=="string")return Z(Ue.basename(e));if(!e||typeof e!="object")return"";let t=typeof e.current_dir=="string"?e.current_dir:typeof e.path=="string"?e.path:"";return Z(t?Ue.basename(t):e.name)}function Za(e){return Z(e.app_name??e.appName??e.app??e.client)}function zr(e){return Z(e.model?.display_name??e.model?.id??e.model_name??e.modelName)}function Xa(e){return Z(e.cwd??e.current_dir??e.project_root)}function Ha(e){let t=Z(e.project);if(t)return t;let n=Xa(e);if(n)return Z(Ue.basename(n));let r=Jr(e.workspace);return r||""}function Ie(e){if(!(typeof e!="number"||!Number.isFinite(e)))return e}function Qa(e){let t=Za(e).toLowerCase();return t.includes("codex")?Ft.CODEX:t.includes("claude")||e.model?.display_name||e.transcript_path||e.rate_limits?Ft.CLAUDE_CODE:e.run_state||e.runState||e.thread_title||e.threadTitle||e.git_branch||Ie(e.context_used)!==void 0?Ft.CODEX:Ft.UNKNOWN}function ec(e){return Qa(e)===Ft.CODEX}function tc(e){let t=Za(e),n=Xa(e),r=Jr(e.workspace),o=Ie(e.context_used)??Ie(e.context_window?.used_percentage??void 0),s=Ie(e.context_remaining)??Ie(e.context_window?.remaining_percentage??void 0);return{...t?{app:t}:{},...zr(e)?{model:zr(e)}:{},...Ha(e)?{project:Ha(e)}:{},...r?{workspace:r}:{},...n?{cwd:n}:{},...Z(e.git_branch??e.branch)?{gitBranch:Z(e.git_branch??e.branch)}:{},...Z(e.status??e.run_state??e.runState)?{status:Z(e.status??e.run_state??e.runState)}:{},...Z(e.thread_title??e.threadTitle)?{threadTitle:Z(e.thread_title??e.threadTitle)}:{},...o!==void 0?{contextUsedPercent:o}:{},...s!==void 0?{contextRemainingPercent:s}:{},...Ie(e.used_tokens)!==void 0?{usedTokens:Ie(e.used_tokens)}:{},...Ie(e.total_input_tokens)!==void 0?{totalInputTokens:Ie(e.total_input_tokens)}:{},...Ie(e.total_output_tokens)!==void 0?{totalOutputTokens:Ie(e.total_output_tokens)}:{}}}function bs(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"")}var rc=T(require("path"));function nc(e){return e instanceof Error?e.message:String(e)}function Ss(e,t){let n=[],r=[],o=e??"claude",s=Wr(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: ${nc(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=rc.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: ${nc(l)}`)}}return{ok:i,messages:n,errors:r}}function oc(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 sc=T(require("os")),ic=require("node:readline/promises"),Qn={card:"default VISA ****7242",balance:"balance $6.38",spentToday:"spent today $0.62",lastActivity:"last Visa tool 38m",model:"Opus 4.6"};async function ac(e,t=!1){if(!process.stdin.isTTY)return t;let n=t?"[Y/n]":"[y/N]",r,o;try{r=(0,ic.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 Rm(e,t){return e.replace(/[\x00-\x1F\x7F\u202A-\u202E\u2066-\u2069]/g,"").trim()||t}function cc(e=sc.hostname()){let t=Vn().version,n=Rm(e,"this-machine");return[" Preview if installed (sample):",` VISA CLI v${t} | ${n} | ${Qn.card}`,` ${Qn.balance} | ${Qn.spentToday} | ${Qn.lastActivity}`,` [${Qn.model}] | you`," Activity live"].join(`
|
|
120
120
|
`)}async function Vt(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 qt=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},vn=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}},Ht=class extends Error{code="SESSION_LOCK_CONTENDED";retryAfterSecs;status;constructor(t,n=1,r){super(t),this.name="SessionLockContendedError",this.retryAfterSecs=n,this.status=r}},ce=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(t,n,r,o,s,i,a,l){super(t),this.name="CardDeclinedError",this.retryable=n,this.code=r,this.reason=o,this.paymentErrorClass=s,this.correlationId=i,this.transactionId=a,this.retryAfter=l}};var lc={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 ws(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&&lc[n]?lc[n]:`Network error contacting the Visa CLI server (${n?`${n}: ${typeof t.message=="string"?t.message:"unknown"}`:typeof t.message=="string"&&t.message.length>0?t.message:"unknown error"}). Check https://visacli.sh for status.`}var ge=T(require("fs")),ks=T(require("path")),uc=T(require("os")),Cs=ks.join(uc.homedir(),".visa-mcp"),er=ks.join(Cs,"mcp-server.log"),Im=5*1024*1024,xs=null;function $m(){ge.existsSync(Cs)||ge.mkdirSync(Cs,{recursive:!0,mode:448})}function Pm(){if(!xs){if($m(),ge.existsSync(er)&&ge.statSync(er).size>Im){let t=er+".1";ge.existsSync(t)&&ge.unlinkSync(t),ge.renameSync(er,t)}xs=ge.createWriteStream(er,{flags:"a"})}return xs}function Mm(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function Yr(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
121
|
`;Mm(e)&&process.stderr.write(o),Pm().write(o)}var m={debug:(...e)=>Yr("DEBUG",...e),info:(...e)=>Yr("INFO",...e),warn:(...e)=>Yr("WARN",...e),error:(...e)=>Yr("ERROR",...e)};var Om=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function mc(e,t){let n=dc(e),r=dc(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:Nm(n.pre,r.pre)>0}function dc(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(Om);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function Nm(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 je(){return!!(pc(process.env.VISA_CLI_NO_UPDATE_CHECK)||pc(process.env.CI)||process.env.NODE_ENV==="test")}function pc(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var wt=T(require("fs")),Rs=require("node:net"),yc=T(require("os")),_c=T(require("path"));var Zr=T(require("fs")),fc=T(require("path")),gc=T(require("os"));var Ts=fc.join(gc.homedir(),".visa-mcp"),tr=class{static ensureConfigDir(){Zr.existsSync(Ts)||Zr.mkdirSync(Ts,{recursive:!0,mode:448})}static getConfigDir(){return Ts}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 hc(e){let t=yc.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}var Lm="settings.json",Dm="must use https unless it points at localhost/loopback for local development";function nr(){return _c.join(tr.getConfigDir(),Lm)}function vc(e){if((0,Rs.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function Um(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 vc(o)}function jm(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,Rs.isIP)(t);return n===4?vc(t):n===6?t==="::1"||Um(t):!1}function Es(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:"&&jm(n.hostname)))throw new Error(`${t} ${Dm}`)}var xt={"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");Es(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)")}}},Is=500,Xr={"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 Bt(){let e=nr();if(!wt.existsSync(e))return{};try{let t=wt.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?(m.warn("settings:corrupt",{path:hc(e),reason:"not_object"}),{}):n}catch(t){return m.warn("settings:corrupt",{path:hc(e),error:t?.message||String(t)}),{}}}function As(e){tr.ensureConfigDir();let t=nr(),n=`${t}.tmp`,r=JSON.stringify(e,null,2)+`
|
|
122
|
-
`;wt.writeFileSync(n,r,{mode:384}),wt.renameSync(n,t)}function $s(e){let t=Bt()[e];return typeof t=="string"?t:void 0}function Qr(e){let t=Bt()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function Ps(e){let t=Bt()[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 tt=class extends Error{constructor(t){let n=Object.keys(xt).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"}},nt=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"}},St=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+Xr[t]),this.name="RetiredSettingKeyError"}},bc=["biometric.","spending.","account.","cards.","biometric"];function eo(e,t){if(bc.some(s=>e.startsWith(s)))throw new nt(e);if(e in Xr)throw new St(e);let n=xt[e];if(!n)throw new tt(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=Bt();return o[e]=r,As(o),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:nr()}}function to(e){if(bc.some(s=>e.startsWith(s)))throw new nt(e);let t=xt[e];if(e in Xr){let s=Bt(),i=e in s;return i&&(delete s[e],As(s)),{key:e,removed:i,requiresRestart:!1,path:nr()}}if(!t)throw new tt(e);let r=Bt(),o=e in r;return o&&(delete r[e],As(r)),{key:e,removed:o,requiresRestart:o&&!!t.requiresRestart,path:nr()}}function Sc(){let e=Bt();return Object.entries(Xr).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}var Fm="https://auth.visacli.sh",Vm="https://auth-visa-code-preview.up.railway.app";function qm(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function Hm(){try{let e=Vn();return qm(e.version)}catch{return!1}}function Bm(e){return e.envVar!==void 0&&e.envVar!==""?(Es(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(Es(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?Vm:Fm}function he(){return Bm({envVar:process.env.VISA_AUTH_URL,settingValue:$s("auth.serverUrl"),isPrerelease:Hm()})}function wc(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":Qr("ui.suppressBrowser")??!1}function xc(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":Qr("ui.suppressFeed")??!1}function Cc(){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=Ps("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):Is}var Km="CARD_REENROLLMENT_REQUIRED",Gm="https://auth.visacli.sh/enroll-card";function zm(){try{return new URL("/enroll-card",he()).toString()}catch{return Gm}}function Wm(e){let t=zm();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 rr="2.4.0
|
|
123
|
-
`)}var Se=class{constructor(t){this.getSessionToken=t;this.baseUrl=he()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!je()){let r=t.headers.get("X-Latest-Version");r&&mc(r,rr)&&(this.lastSignals.updateAvailable={currentVersion:rr,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return rr}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new qt(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(kc(n))}async request(t,n,r,o,s,i){let a=await this.getSessionToken();if(!a)throw new Error(Tc());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 Vt(`${this.baseUrl}${n}`,{method:t,headers:{...l,"X-Visa-CLI-Version":rr,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:o})}catch(d){throw new Error(ws(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===Km){let d=typeof u?.last4=="string"?u.last4:"",g=typeof u?.brand=="string"?u.brand:"card",p=Wm(u?.reenroll_url),v=d?`${g} ending in ${d}`:"your card";throw new Error(`Please re-add ${v} to keep payments running. Open: ${p}`)}if(u?.declined){let d=Number(u.retryAfter??c.headers.get("Retry-After"));throw new ce(u.error||"Your card was declined.",!!u.retryable,u.code,u.reason,u.payment_error_class,u.correlation_id,u.transactionId,Number.isFinite(d)&&d>0?d:void 0)}if(c.status===402){let d=u?.error||"Gateway returned 402",g=typeof u?.error_code=="string"?u.error_code:"";throw g==="SPENDING_LIMIT_EXCEEDED"||g==="DAILY_LIMIT_EXCEEDED"||g==="PER_TXN_LIMIT_EXCEEDED"?new Error(`${d}. Check your limits with get_status or run: visa-cli update-spending-controls`):new Error(d)}throw new Error(u?.error||`Request failed (${c.status}). Try again.`)}return u}async shortcut(t,n,r,o,s){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,o,s)}async shortcutWithSession(t,n,r,o,s,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,l=await this.getSessionToken();if(!l)throw new Error(Tc());let c={Authorization:`Bearer ${l}`,"X-Visa-CLI-Version":rr,"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 Vt(`${this.baseUrl}${a}`,{method:"POST",headers:c,body:JSON.stringify(u),timeoutMs:o})}catch(v){throw new Error(ws(v))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let v=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${v}s. Tip: use the batch tool to combine multiple requests into one.`)}let g=d.headers.get("X-Voucher-Receipt"),p;try{p=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(p),d.status===503){if(p?.error_code==="SESSION_LOCK_CONTENDED"){let S=Number(d.headers.get("Retry-After"))||1;throw new Ht(p?.message||p?.error||"Session budget is being modified by another request. Retry shortly.",S,d.status)}throw new Error(kc(p))}let v=Ym(p?.error_code);if(v||d.status===410){let S=v??"BUDGET_CLOSED";throw new vn(p?.message||p?.error||"Your session was invalidated by the server.",S,{budgetId:n.session_budget_id,status:d.status})}if(p?.declined){let S=Number(p.retryAfter??d.headers.get("Retry-After"));throw new ce(p.error||"Your card was declined.",!!p.retryable,p.code,p.reason,p.payment_error_class,p.correlation_id,p.transactionId,Number.isFinite(S)&&S>0?S:void 0)}throw new Error(p?.error||`Request failed (${d.status}). Try again.`)}return{data:p,voucherReceiptHeader:g}}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async catalogSearch(t,n,r,o){let s=r??"discover_tools",i=new URLSearchParams;t&&i.set("q",t),n&&i.set("category",n),o?.limit!=null&&i.set("limit",String(o.limit)),o?.offset!=null&&i.set("offset",String(o.offset));let a=i.toString();return this.request("GET",`/v1/catalog${a?`?${a}`:""}`,void 0,void 0,void 0,s)}async catalogTool(t,n){let r=n??"discover_tools";try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(t)}`,void 0,void 0,void 0,r)}catch{return null}}async discoverMerchantRoutes(t){try{return await this.request("GET",`/v1/platform/discover/${encodeURIComponent(t)}`)}catch{return null}}async listPublicMerchants(){try{let t=await Vt(`${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 Vt(`${this.baseUrl}/v1/platform/discover/${encodeURIComponent(t)}`,{method:"GET",timeoutMs:8e3});return n.ok?await n.json():null}catch{return null}}async paymentPreview(t,n){return this.request("POST","/v1/payment-preview",t,void 0,n)}async getBalance(){return this.request("GET","/v1/balance")}async topupBalance(t){return this.request("POST","/v1/balance/topup",t)}async createEnrollCode(){return this.request("POST","/v1/enroll-code")}async getAutoTopup(){let t=await this.getBalance();return{success:t.success,targetCents:t.autoTopupCents??null,thresholdCents:t.autoTopupThresholdCents??0}}async disableAutoTopup(){return this.request("PATCH","/v1/balance/auto-topup",{auto_topup_cents:null})}async createSessionBudget(t){return this.request("POST","/v1/session-budget/create",{...t,mode:"prepaid"})}async closeSession(t){return this.request("POST","/v1/session/close",{session_budget_id:t})}async getSessionBudget(t){return this.request("GET",`/v1/session-budget/${encodeURIComponent(t)}`)}async getSessionLedger(t){return this.request("GET",`/v1/session/${encodeURIComponent(t)}/ledger`)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getVisaSmi(t,n){return this.request("POST","/v1/visa/smi",t,6e4,n)}async getTransactions(t,n){let r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.offset!=null&&r.set("offset",String(t.offset));let o=r.toString(),s=o?`/v1/transactions?${o}`:"/v1/transactions";return this.request("GET",s,void 0,void 0,n)}async updateSpendingControls(t,n){return this.request("POST","/v1/spending-controls",t,void 0,n)}async removeCard(t,n,r){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(t))}`,n,void 0,r)}async setDefaultCard(t,n,r){return this.request("POST",`/v1/cards/${encodeURIComponent(String(t))}/default`,n,void 0,r)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t,n){return this.request("POST","/v1/attestation-key",{publicKey:t,...n?{attestation:n}:{}})}async startAttestationRecovery(t,n){return this.request("POST","/v1/attestation-key/recovery/start",{state:t},void 0,n)}async setBiometricPreference(t,n){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,n)}async logout(t,n){return this.request("POST","/v1/logout",t,void 0,n)}async feedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async createAppApiKey(t){return this.request("POST","/v1/api/keys",t)}async listAppApiKeys(){return this.request("GET","/v1/api/keys")}async revokeAppApiKey(t){return this.request("DELETE",`/v1/api/keys/${encodeURIComponent(String(t))}`)}async feedSubmit(t){return this.request("POST","/v1/feed",t)}async feedList(t){let n=new URLSearchParams;t?.tab&&n.set("tab",t.tab),t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset));let r=n.toString();return this.request("GET",`/v1/feed${r?"?"+r:""}`)}async feedVote(t,n){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/vote`,{direction:n})}async feedApprove(t){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/approve`)}async feedDelete(t){return this.request("DELETE",`/v1/feed/${encodeURIComponent(t)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async getFeedback(t,n){let r=new URLSearchParams;t&&r.set("limit",String(t));let o=r.toString();return this.request("GET",`/v1/feedback${o?"?"+o:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}};var f={};qo(f,{BRAND:()=>xp,DIRTY:()=>Kt,EMPTY_PATH:()=>tp,INVALID:()=>I,NEVER:()=>cf,OK:()=>le,ParseStatus:()=>ae,Schema:()=>N,ZodAny:()=>Tt,ZodArray:()=>it,ZodBigInt:()=>zt,ZodBoolean:()=>Wt,ZodBranded:()=>sr,ZodCatch:()=>sn,ZodDate:()=>Jt,ZodDefault:()=>on,ZodDiscriminatedUnion:()=>oo,ZodEffects:()=>Ae,ZodEnum:()=>nn,ZodError:()=>ye,ZodFirstPartyTypeKind:()=>$,ZodFunction:()=>io,ZodIntersection:()=>Qt,ZodIssueCode:()=>h,ZodLazy:()=>en,ZodLiteral:()=>tn,ZodMap:()=>Tn,ZodNaN:()=>An,ZodNativeEnum:()=>rn,ZodNever:()=>$e,ZodNull:()=>Zt,ZodNullable:()=>qe,ZodNumber:()=>Gt,ZodObject:()=>_e,ZodOptional:()=>Te,ZodParsedType:()=>b,ZodPipeline:()=>ir,ZodPromise:()=>Et,ZodReadonly:()=>an,ZodRecord:()=>so,ZodSchema:()=>N,ZodSet:()=>En,ZodString:()=>kt,ZodSymbol:()=>Cn,ZodTransformer:()=>Ae,ZodTuple:()=>Ve,ZodType:()=>N,ZodUndefined:()=>Yt,ZodUnion:()=>Xt,ZodUnknown:()=>st,ZodVoid:()=>kn,addIssueToContext:()=>_,any:()=>Pp,array:()=>Lp,bigint:()=>Ep,boolean:()=>Dc,coerce:()=>af,custom:()=>Oc,date:()=>Ap,datetimeRegex:()=>Pc,defaultErrorMap:()=>rt,discriminatedUnion:()=>Fp,effect:()=>Xp,enum:()=>Jp,function:()=>Gp,getErrorMap:()=>Sn,getParsedType:()=>Fe,instanceof:()=>kp,intersection:()=>Vp,isAborted:()=>no,isAsync:()=>wn,isDirty:()=>ro,isValid:()=>Ct,late:()=>Cp,lazy:()=>zp,literal:()=>Wp,makeIssue:()=>or,map:()=>Bp,nan:()=>Tp,nativeEnum:()=>Yp,never:()=>Op,null:()=>$p,nullable:()=>ef,number:()=>Lc,object:()=>Dp,objectUtil:()=>Ms,oboolean:()=>sf,onumber:()=>of,optional:()=>Qp,ostring:()=>rf,pipeline:()=>nf,preprocess:()=>tf,promise:()=>Zp,quotelessJson:()=>Xm,record:()=>Hp,set:()=>Kp,setErrorMap:()=>ep,strictObject:()=>Up,string:()=>Nc,symbol:()=>Rp,transformer:()=>Xp,tuple:()=>qp,undefined:()=>Ip,union:()=>jp,unknown:()=>Mp,util:()=>L,void:()=>Np});var L;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},e.getValidEnumValues=o=>{let s=e.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return e.objectValues(i)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},e.find=(o,s)=>{for(let i of o)if(s(i))return i},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(L||(L={}));var Ms;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Ms||(Ms={}));var b=L.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Fe=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=L.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Xm=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ye=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,l=0;for(;l<i.path.length;){let c=i.path[l];l===i.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(i))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return o(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,L.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];n[s]=n[s]||[],n[s].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};ye.create=e=>new ye(e);var Qm=(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,L.jsonStringifyReplacer)}`;break;case h.unrecognized_keys:n=`Unrecognized key(s) in object: ${L.joinValues(e.keys,", ")}`;break;case h.invalid_union:n="Invalid input";break;case h.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${L.joinValues(e.options)}`;break;case h.invalid_enum_value:n=`Invalid enum value. Expected ${L.joinValues(e.options)}, received '${e.received}'`;break;case h.invalid_arguments:n="Invalid function arguments";break;case h.invalid_return_type:n="Invalid function return type";break;case h.invalid_date:n="Invalid date";break;case h.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:L.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case h.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case h.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case h.custom:n="Invalid input";break;case h.invalid_intersection_types:n="Intersection results could not be merged";break;case h.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case h.not_finite:n="Number must be finite";break;default:n=t.defaultError,L.assertNever(e)}return{message:n}},rt=Qm;var Ec=rt;function ep(e){Ec=e}function Sn(){return Ec}var or=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}},tp=[];function _(e,t){let n=Sn(),r=or({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===rt?void 0:rt].filter(o=>!!o)});e.common.issues.push(r)}var ae=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let o of n){if(o.status==="aborted")return I;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 I;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}}},I=Object.freeze({status:"aborted"}),Kt=e=>({status:"dirty",value:e}),le=e=>({status:"valid",value:e}),no=e=>e.status==="aborted",ro=e=>e.status==="dirty",Ct=e=>e.status==="valid",wn=e=>typeof Promise<"u"&&e instanceof Promise;var C;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(C||(C={}));var Ee=class{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Ac=(e,t)=>{if(Ct(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new ye(e.common.issues);return this._error=n,this._error}}};function M(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(i,a)=>{let{message:l}=e;return i.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:o}}var N=class{get description(){return this._def.description}_getType(t){return Fe(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Fe(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ae,ctx:{common:t.parent.common,data:t.data,parsedType:Fe(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(wn(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:Fe(t)},o=this._parseSync({data:t,path:r.path,parent:r});return Ac(r,o)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Fe(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return Ct(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=>Ct(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:Fe(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(wn(o)?o:Promise.resolve(o));return Ac(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 Ae({schema:this,typeName:$.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Te.create(this,this._def)}nullable(){return qe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return it.create(this)}promise(){return Et.create(this,this._def)}or(t){return Xt.create([this,t],this._def)}and(t){return Qt.create(this,t,this._def)}transform(t){return new Ae({...M(this._def),schema:this,typeName:$.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new on({...M(this._def),innerType:this,defaultValue:n,typeName:$.ZodDefault})}brand(){return new sr({typeName:$.ZodBranded,type:this,...M(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new sn({...M(this._def),innerType:this,catchValue:n,typeName:$.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return ir.create(this,t)}readonly(){return an.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},np=/^c[^\s-]{8,}$/i,rp=/^[0-9a-z]+$/,op=/^[0-9A-HJKMNP-TV-Z]{26}$/i,sp=/^[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,ip=/^[a-z0-9_-]{21}$/i,ap=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,cp=/^[-+]?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)?)??$/,lp=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,up="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Os,dp=/^(?:(?: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])$/,mp=/^(?:(?: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]))$/,fp=/^(([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])$/,gp=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,hp=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ic="((\\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])))",yp=new RegExp(`^${Ic}$`);function $c(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 _p(e){return new RegExp(`^${$c(e)}$`)}function Pc(e){let t=`${Ic}T${$c(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 vp(e,t){return!!((t==="v4"||!t)&&dp.test(e)||(t==="v6"||!t)&&pp.test(e))}function bp(e,t){if(!ap.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 Sp(e,t){return!!((t==="v4"||!t)&&mp.test(e)||(t==="v6"||!t)&&fp.test(e))}var kt=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 _(s,{code:h.invalid_type,expected:b.string,received:s.parsedType}),I}let r=new ae,o;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),_(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),_(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?_(o,{code:h.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&_(o,{code:h.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")lp.test(t.data)||(o=this._getOrReturnCtx(t,o),_(o,{validation:"email",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Os||(Os=new RegExp(up,"u")),Os.test(t.data)||(o=this._getOrReturnCtx(t,o),_(o,{validation:"emoji",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")sp.test(t.data)||(o=this._getOrReturnCtx(t,o),_(o,{validation:"uuid",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")ip.test(t.data)||(o=this._getOrReturnCtx(t,o),_(o,{validation:"nanoid",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")np.test(t.data)||(o=this._getOrReturnCtx(t,o),_(o,{validation:"cuid",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")rp.test(t.data)||(o=this._getOrReturnCtx(t,o),_(o,{validation:"cuid2",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")op.test(t.data)||(o=this._getOrReturnCtx(t,o),_(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),_(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),_(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),_(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),_(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),_(o,{code:h.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?Pc(s).test(t.data)||(o=this._getOrReturnCtx(t,o),_(o,{code:h.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?yp.test(t.data)||(o=this._getOrReturnCtx(t,o),_(o,{code:h.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?_p(s).test(t.data)||(o=this._getOrReturnCtx(t,o),_(o,{code:h.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?cp.test(t.data)||(o=this._getOrReturnCtx(t,o),_(o,{validation:"duration",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?vp(t.data,s.version)||(o=this._getOrReturnCtx(t,o),_(o,{validation:"ip",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?bp(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),_(o,{validation:"jwt",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?Sp(t.data,s.version)||(o=this._getOrReturnCtx(t,o),_(o,{validation:"cidr",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?gp.test(t.data)||(o=this._getOrReturnCtx(t,o),_(o,{validation:"base64",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?hp.test(t.data)||(o=this._getOrReturnCtx(t,o),_(o,{validation:"base64url",code:h.invalid_string,message:s.message}),r.dirty()):L.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:h.invalid_string,...C.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...C.errToObj(t)})}url(t){return this._addCheck({kind:"url",...C.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...C.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...C.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...C.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...C.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...C.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...C.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...C.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...C.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...C.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...C.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...C.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...C.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...C.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...C.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...C.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...C.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...C.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...C.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...C.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...C.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...C.errToObj(n)})}nonempty(t){return this.min(1,C.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};kt.create=e=>new kt({checks:[],typeName:$.ZodString,coerce:e?.coerce??!1,...M(e)});function wp(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 Gt=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 _(s,{code:h.invalid_type,expected:b.number,received:s.parsedType}),I}let r,o=new ae;for(let s of this._def.checks)s.kind==="int"?L.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),_(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),_(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),_(r,{code:h.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?wp(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),_(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),_(r,{code:h.not_finite,message:s.message}),o.dirty()):L.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,C.toString(n))}gt(t,n){return this.setLimit("min",t,!1,C.toString(n))}lte(t,n){return this.setLimit("max",t,!0,C.toString(n))}lt(t,n){return this.setLimit("max",t,!1,C.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:C.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:C.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:C.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:C.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:C.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:C.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:C.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:C.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:C.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:C.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&L.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};Gt.create=e=>new Gt({checks:[],typeName:$.ZodNumber,coerce:e?.coerce||!1,...M(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 ae;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),_(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),_(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),_(r,{code:h.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):L.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return _(n,{code:h.invalid_type,expected:b.bigint,received:n.parsedType}),I}gte(t,n){return this.setLimit("min",t,!0,C.toString(n))}gt(t,n){return this.setLimit("min",t,!1,C.toString(n))}lte(t,n){return this.setLimit("max",t,!0,C.toString(n))}lt(t,n){return this.setLimit("max",t,!1,C.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:C.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:C.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:C.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:C.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:C.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:C.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};zt.create=e=>new zt({checks:[],typeName:$.ZodBigInt,coerce:e?.coerce??!1,...M(e)});var Wt=class extends N{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==b.boolean){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:b.boolean,received:r.parsedType}),I}return le(t.data)}};Wt.create=e=>new Wt({typeName:$.ZodBoolean,coerce:e?.coerce||!1,...M(e)});var Jt=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 _(s,{code:h.invalid_type,expected:b.date,received:s.parsedType}),I}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return _(s,{code:h.invalid_date}),I}let r=new ae,o;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),_(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),_(o,{code:h.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):L.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:C.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:C.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};Jt.create=e=>new Jt({checks:[],coerce:e?.coerce||!1,typeName:$.ZodDate,...M(e)});var Cn=class extends N{_parse(t){if(this._getType(t)!==b.symbol){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:b.symbol,received:r.parsedType}),I}return le(t.data)}};Cn.create=e=>new Cn({typeName:$.ZodSymbol,...M(e)});var Yt=class extends N{_parse(t){if(this._getType(t)!==b.undefined){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:b.undefined,received:r.parsedType}),I}return le(t.data)}};Yt.create=e=>new Yt({typeName:$.ZodUndefined,...M(e)});var Zt=class extends N{_parse(t){if(this._getType(t)!==b.null){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:b.null,received:r.parsedType}),I}return le(t.data)}};Zt.create=e=>new Zt({typeName:$.ZodNull,...M(e)});var Tt=class extends N{constructor(){super(...arguments),this._any=!0}_parse(t){return le(t.data)}};Tt.create=e=>new Tt({typeName:$.ZodAny,...M(e)});var st=class extends N{constructor(){super(...arguments),this._unknown=!0}_parse(t){return le(t.data)}};st.create=e=>new st({typeName:$.ZodUnknown,...M(e)});var $e=class extends N{_parse(t){let n=this._getOrReturnCtx(t);return _(n,{code:h.invalid_type,expected:b.never,received:n.parsedType}),I}};$e.create=e=>new $e({typeName:$.ZodNever,...M(e)});var kn=class extends N{_parse(t){if(this._getType(t)!==b.undefined){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:b.void,received:r.parsedType}),I}return le(t.data)}};kn.create=e=>new kn({typeName:$.ZodVoid,...M(e)});var it=class e extends N{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==b.array)return _(n,{code:h.invalid_type,expected:b.array,received:n.parsedType}),I;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(_(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&&(_(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&&(_(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 Ee(n,i,n.path,a)))).then(i=>ae.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new Ee(n,i,n.path,a)));return ae.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:C.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:C.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:C.toString(n)}})}nonempty(t){return this.min(1,t)}};it.create=(e,t)=>new it({type:e,minLength:null,maxLength:null,exactLength:null,typeName:$.ZodArray,...M(t)});function xn(e){if(e instanceof _e){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Te.create(xn(r))}return new _e({...e._def,shape:()=>t})}else return e instanceof it?new it({...e._def,type:xn(e.element)}):e instanceof Te?Te.create(xn(e.unwrap())):e instanceof qe?qe.create(xn(e.unwrap())):e instanceof Ve?Ve.create(e.items.map(t=>xn(t))):e}var _e=class e extends N{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=L.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==b.object){let c=this._getOrReturnCtx(t);return _(c,{code:h.invalid_type,expected:b.object,received:c.parsedType}),I}let{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof $e&&this._def.unknownKeys==="strip"))for(let c in o.data)i.includes(c)||a.push(c);let l=[];for(let c of i){let u=s[c],d=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Ee(o,d,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof $e){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&&(_(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 Ee(o,d,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of l){let d=await u.key,g=await u.value;c.push({key:d,value:g,alwaysSet:u.alwaysSet})}return c}).then(c=>ae.mergeObjectSync(r,c)):ae.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return C.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:C.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:$.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of L.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let r of L.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return xn(this)}partial(t){let n={};for(let r of L.objectKeys(this.shape)){let o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let r of L.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Te;)s=s._def.innerType;n[r]=s}return new e({...this._def,shape:()=>n})}keyof(){return Mc(L.objectKeys(this.shape))}};_e.create=(e,t)=>new _e({shape:()=>e,unknownKeys:"strip",catchall:$e.create(),typeName:$.ZodObject,...M(t)});_e.strictCreate=(e,t)=>new _e({shape:()=>e,unknownKeys:"strict",catchall:$e.create(),typeName:$.ZodObject,...M(t)});_e.lazycreate=(e,t)=>new _e({shape:e,unknownKeys:"strip",catchall:$e.create(),typeName:$.ZodObject,...M(t)});var Xt=class extends N{_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new ye(a.ctx.common.issues));return _(n,{code:h.invalid_union,unionErrors:i}),I}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let l of r){let c={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(l=>new ye(l));return _(n,{code:h.invalid_union,unionErrors:a}),I}}get options(){return this._def.options}};Xt.create=(e,t)=>new Xt({options:e,typeName:$.ZodUnion,...M(t)});var ot=e=>e instanceof en?ot(e.schema):e instanceof Ae?ot(e.innerType()):e instanceof tn?[e.value]:e instanceof nn?e.options:e instanceof rn?L.objectValues(e.enum):e instanceof on?ot(e._def.innerType):e instanceof Yt?[void 0]:e instanceof Zt?[null]:e instanceof Te?[void 0,...ot(e.unwrap())]:e instanceof qe?[null,...ot(e.unwrap())]:e instanceof sr||e instanceof an?ot(e.unwrap()):e instanceof sn?ot(e._def.innerType):[],oo=class e extends N{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.object)return _(n,{code:h.invalid_type,expected:b.object,received:n.parsedType}),I;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}):(_(n,{code:h.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),I)}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=ot(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:$.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...M(r)})}};function Ns(e,t){let n=Fe(e),r=Fe(t);if(e===t)return{valid:!0,data:e};if(n===b.object&&r===b.object){let o=L.objectKeys(t),s=L.objectKeys(e).filter(a=>o.indexOf(a)!==-1),i={...e,...t};for(let a of s){let l=Ns(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=Ns(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 Qt=class extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=(s,i)=>{if(no(s)||no(i))return I;let a=Ns(s.value,i.value);return a.valid?((ro(s)||ro(i))&&n.dirty(),{status:n.value,value:a.data}):(_(r,{code:h.invalid_intersection_types}),I)};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}))}};Qt.create=(e,t,n)=>new Qt({left:e,right:t,typeName:$.ZodIntersection,...M(n)});var Ve=class e extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.array)return _(r,{code:h.invalid_type,expected:b.array,received:r.parsedType}),I;if(r.data.length<this._def.items.length)return _(r,{code:h.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),I;!this._def.rest&&r.data.length>this._def.items.length&&(_(r,{code:h.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Ee(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>ae.mergeArray(n,i)):ae.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ve.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ve({items:e,typeName:$.ZodTuple,rest:null,...M(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 _(r,{code:h.invalid_type,expected:b.object,received:r.parsedType}),I;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new Ee(r,a,r.path,a)),value:i._parse(new Ee(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?ae.mergeObjectAsync(n,o):ae.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof N?new e({keyType:t,valueType:n,typeName:$.ZodRecord,...M(r)}):new e({keyType:kt.create(),valueType:t,typeName:$.ZodRecord,...M(n)})}},Tn=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 _(r,{code:h.invalid_type,expected:b.map,received:r.parsedType}),I;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,l],c)=>({key:o._parse(new Ee(r,a,r.path,[c,"key"])),value:s._parse(new Ee(r,l,r.path,[c,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of i){let c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return I;(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 I;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}}}};Tn.create=(e,t,n)=>new Tn({valueType:t,keyType:e,typeName:$.ZodMap,...M(n)});var En=class e extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.set)return _(r,{code:h.invalid_type,expected:b.set,received:r.parsedType}),I;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(_(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&&(_(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 I;u.status==="dirty"&&n.dirty(),c.add(u.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((l,c)=>s._parse(new Ee(r,l,r.path,c)));return r.common.async?Promise.all(a).then(l=>i(l)):i(a)}min(t,n){return new e({...this._def,minSize:{value:t,message:C.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:C.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};En.create=(e,t)=>new En({valueType:e,minSize:null,maxSize:null,typeName:$.ZodSet,...M(t)});var io=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 _(n,{code:h.invalid_type,expected:b.function,received:n.parsedType}),I;function r(a,l){return or({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Sn(),rt].filter(c=>!!c),issueData:{code:h.invalid_arguments,argumentsError:l}})}function o(a,l){return or({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Sn(),rt].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 Et){let a=this;return le(async function(...l){let c=new ye([]),u=await a._def.args.parseAsync(l,s).catch(p=>{throw c.addIssue(r(l,p)),c}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,s).catch(p=>{throw c.addIssue(o(d,p)),c})})}else{let a=this;return le(function(...l){let c=a._def.args.safeParse(l,s);if(!c.success)throw new ye([r(l,c.error)]);let u=Reflect.apply(i,this,c.data),d=a._def.returns.safeParse(u,s);if(!d.success)throw new ye([o(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Ve.create(t).rest(st.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||Ve.create([]).rest(st.create()),returns:n||st.create(),typeName:$.ZodFunction,...M(r)})}},en=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})}};en.create=(e,t)=>new en({getter:e,typeName:$.ZodLazy,...M(t)});var tn=class extends N{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return _(n,{received:n.data,code:h.invalid_literal,expected:this._def.value}),I}return{status:"valid",value:t.data}}get value(){return this._def.value}};tn.create=(e,t)=>new tn({value:e,typeName:$.ZodLiteral,...M(t)});function Mc(e,t){return new nn({values:e,typeName:$.ZodEnum,...M(t)})}var nn=class e extends N{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return _(n,{expected:L.joinValues(r),received:n.parsedType,code:h.invalid_type}),I}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return _(n,{received:n.data,code:h.invalid_enum_value,options:r}),I}return le(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};nn.create=Mc;var rn=class extends N{_parse(t){let n=L.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==b.string&&r.parsedType!==b.number){let o=L.objectValues(n);return _(r,{expected:L.joinValues(o),received:r.parsedType,code:h.invalid_type}),I}if(this._cache||(this._cache=new Set(L.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let o=L.objectValues(n);return _(r,{received:r.data,code:h.invalid_enum_value,options:o}),I}return le(t.data)}get enum(){return this._def.values}};rn.create=(e,t)=>new rn({values:e,typeName:$.ZodNativeEnum,...M(t)});var Et=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 _(n,{code:h.invalid_type,expected:b.promise,received:n.parsedType}),I;let r=n.parsedType===b.promise?n.data:Promise.resolve(n.data);return le(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Et.create=(e,t)=>new Et({type:e,typeName:$.ZodPromise,...M(t)});var Ae=class extends N{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===$.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=>{_(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 I;let l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?I:l.status==="dirty"?Kt(l.value):n.value==="dirty"?Kt(l.value):l});{if(n.value==="aborted")return I;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?I:a.status==="dirty"?Kt(a.value):n.value==="dirty"?Kt(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"?I:(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"?I:(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(!Ct(i))return I;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=>Ct(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):I);L.assertNever(o)}};Ae.create=(e,t,n)=>new Ae({schema:e,typeName:$.ZodEffects,effect:t,...M(n)});Ae.createWithPreprocess=(e,t,n)=>new Ae({schema:t,effect:{type:"preprocess",transform:e},typeName:$.ZodEffects,...M(n)});var Te=class extends N{_parse(t){return this._getType(t)===b.undefined?le(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Te.create=(e,t)=>new Te({innerType:e,typeName:$.ZodOptional,...M(t)});var qe=class extends N{_parse(t){return this._getType(t)===b.null?le(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};qe.create=(e,t)=>new qe({innerType:e,typeName:$.ZodNullable,...M(t)});var on=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}};on.create=(e,t)=>new on({innerType:e,typeName:$.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...M(t)});var sn=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 wn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ye(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ye(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};sn.create=(e,t)=>new sn({innerType:e,typeName:$.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...M(t)});var An=class extends N{_parse(t){if(this._getType(t)!==b.nan){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:b.nan,received:r.parsedType}),I}return{status:"valid",value:t.data}}};An.create=e=>new An({typeName:$.ZodNaN,...M(e)});var xp=Symbol("zod_brand"),sr=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}},ir=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"?I:s.status==="dirty"?(n.dirty(),Kt(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"?I: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:$.ZodPipeline})}},an=class extends N{_parse(t){let n=this._def.innerType._parse(t),r=o=>(Ct(o)&&(o.value=Object.freeze(o.value)),o);return wn(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};an.create=(e,t)=>new an({innerType:e,typeName:$.ZodReadonly,...M(t)});function Rc(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Oc(e,t={},n){return e?Tt.create().superRefine((r,o)=>{let s=e(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Rc(t,r),l=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:l})}});if(!s){let i=Rc(t,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Tt.create()}var Cp={object:_e.lazycreate},$;(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"})($||($={}));var kp=(e,t={message:`Input not instance of ${e.name}`})=>Oc(n=>n instanceof e,t),Nc=kt.create,Lc=Gt.create,Tp=An.create,Ep=zt.create,Dc=Wt.create,Ap=Jt.create,Rp=Cn.create,Ip=Yt.create,$p=Zt.create,Pp=Tt.create,Mp=st.create,Op=$e.create,Np=kn.create,Lp=it.create,Dp=_e.create,Up=_e.strictCreate,jp=Xt.create,Fp=oo.create,Vp=Qt.create,qp=Ve.create,Hp=so.create,Bp=Tn.create,Kp=En.create,Gp=io.create,zp=en.create,Wp=tn.create,Jp=nn.create,Yp=rn.create,Zp=Et.create,Xp=Ae.create,Qp=Te.create,ef=qe.create,tf=Ae.createWithPreprocess,nf=ir.create,rf=()=>Nc().optional(),of=()=>Lc().optional(),sf=()=>Dc().optional(),af={string:(e=>kt.create({...e,coerce:!0})),number:(e=>Gt.create({...e,coerce:!0})),boolean:(e=>Wt.create({...e,coerce:!0})),bigint:(e=>zt.create({...e,coerce:!0})),date:(e=>Jt.create({...e,coerce:!0}))};var cf=I;var Uc=["tempo","mpp_self","merchant_self"];var Ds=f.object({inputPerMillion:f.number().positive(),outputPerMillion:f.number().positive(),contextWindow:f.number().int().positive().optional(),maxOutput:f.number().int().positive().optional(),perRequestFeeCents:f.number().nonnegative().optional()}),lf=f.object({strategy:f.enum(["flat","token","band"]).optional(),pricingModel:f.enum(["per-call","per-token","band"]).optional(),priceCents:f.number().nonnegative().optional(),currency:f.string().optional(),display:f.string().optional(),estimate:f.boolean().optional(),source:f.string().optional(),priceBand:f.record(f.unknown()).optional(),tokenPricing:Ds.optional()}).passthrough(),Us=f.discriminatedUnion("type",[f.object({type:f.literal("shortcut"),routedPath:f.string().min(1).startsWith("/")}),f.object({type:f.literal("custom"),merchantSlug:f.string().min(1),subPath:f.string().optional()}),f.object({type:f.literal("local"),fn:f.string().min(1)}),f.object({type:f.literal("read")})]),js=f.object({amount:f.number().nonnegative(),currency:f.string().length(3).optional(),display:f.string().optional(),free:f.boolean().optional(),batchDiscount:f.number().min(0).max(100).optional()}),jc=f.object({attestation:f.boolean().optional(),rateLimitMs:f.number().positive().optional()}),Fc=f.object({displayName:f.string().optional(),feedbackEligible:f.boolean().optional(),suggestionEligible:f.boolean().optional(),batchable:f.boolean().optional()}),uf=f.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),df=120,mf=120,pf=1200,ff=/^[^\u0000-\u001F\u007F]+$/;function Ls(e,t){return f.string().min(1).max(e).regex(ff,`${t} must not contain control characters`)}var Fs={id:f.string().min(1),name:Ls(df,"name"),description:Ls(pf,"description"),provider:f.string().min(1),model:f.string().min(1),category:uf,priceCents:f.number().nonnegative(),inputSchema:f.record(f.unknown()),gatewayUrl:f.string().min(1),merchantName:Ls(mf,"merchantName"),isAsync:f.boolean().optional(),pollUrl:f.string().optional(),pollInterval:f.number().positive().optional(),pollTimeout:f.number().positive().optional(),tags:f.array(f.string()).optional(),tokenPricing:Ds.optional(),priceDisplay:f.string().optional(),pricingModel:f.enum(["per-call","per-token","band"]).optional(),pricingInfo:lf.optional(),status:f.enum(["available","unavailable"]).optional(),handler:Us.optional(),pricing:js.optional(),security:jc.optional(),engagement:Fc.optional(),enabled:f.boolean().optional(),beta:f.boolean().optional(),deprecated:f.boolean().optional(),replacementTool:f.string().optional(),minCliVersion:f.string().optional(),sunsetAt:f.string().optional(),rail:f.enum(Uc).optional(),pricingStrategy:f.enum(["flat","token","band"]).optional()},Vc=f.object({...Fs,dispatch:f.literal("routed"),routedPath:f.string().min(1).startsWith("/")}).strict(),qc=f.object({...Fs,dispatch:f.literal("enveloped")}).strict(),Hc=f.object({...Fs,handler:Us,pricing:js}).strict(),Bc=f.union([f.discriminatedUnion("dispatch",[Vc,qc]),Hc]);var Vs=/^[a-z0-9][a-z0-9_-]*$/;var hf="https://fal.run",Wc="https://openrouter.mpp.tempo.xyz";function yf(e){let{attestation:t,tool_id:n,...r}=e;return r}var Kc={"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 ao(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"&&Kc[r]&&(i.image_size=Kc[r]),i)}function Gc(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 _f(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 vf(e,t,n,r,o,s,i,a){return _f(e,t,n,"suno-ai",r,o,s,i,{merchantName:"Suno AI",...a})}function X(e,t,n,r,o,s,i,a){return{dispatch:"routed",id:e,name:t,description:n,provider:"fal",model:r,category:o,priceCents:s,inputSchema:i,routedPath:`/api/v1/fal/${r}`,gatewayUrl:`${hf}/${r}`,merchantName:"fal.ai",buildBody:yf,tags:[],...a}}function bf(e){return t=>{let{attestation:n,tool_id:r,prompt:o,system_prompt:s,max_tokens:i,temperature:a,...l}=t;return{model:e,messages:[...s?[{role:"system",content:s}]:[],{role:"user",content:o}],max_tokens:i??1024,temperature:a??.7,...l}}}function Sf(e){return t=>{let{attestation:n,tool_id:r,prompt:o,image_url:s,aspect_ratio:i,max_tokens:a,temperature:l,...c}=t,u=[{type:"text",text:o}];return typeof s=="string"&&s.length>0&&u.push({type:"image_url",image_url:{url:s}}),{model:e,messages:[{role:"user",content:u}],max_tokens:a??1024,temperature:l??.7,...typeof i=="string"&&i.length>0?{image_config:{aspect_ratio:i}}:{},...c}}}function ee(e,t,n,r,o,s,i){let a=i?.perRequestFeeCents??0,l=500/1e6*o*100,c=500/1e6*s*100,u=Math.max(1,Math.ceil(l+c+a)),{perRequestFeeCents:d,...g}=i??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"llm",priceCents:u,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The prompt or question to send to the model"},system_prompt:{type:"string",description:"Optional system prompt to set model behavior"},max_tokens:{type:"integer",description:"Maximum tokens in response (default: 1024)",minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${Wc}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:bf(r),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:o,outputPerMillion:s,...a>0?{perRequestFeeCents:a}:{}},...g}}function qs(e,t,n,r,o,s){return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"image",priceCents:o,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate or edit"},image_url:{type:"string",description:"Optional source image URL for edits"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"1:1"},max_tokens:{type:"integer",description:"Maximum text tokens in response metadata (default: 1024)",minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${Wc}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:Sf(r),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...s}}var Hs=[X("fal-flux-pro-ultra","FLUX Pro Ultra","Highest quality image generation. Best for detailed, photorealistic images.","fal-ai/flux-pro/v1.1-ultra","image",6,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},{tags:["image","flux","photorealistic","high-quality"]}),X("fal-flux-pro","FLUX Pro","Fast, high-quality image generation. Good balance of speed and quality.","fal-ai/flux-pro/v1.1","image",4,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},{tags:["image","flux","fast"],buildBody:ao}),X("fal-flux-dev","FLUX Dev","Open-source image generation. Cheaper, good for experimentation.","fal-ai/flux/dev","image",3,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["image","flux","open-source","cheap"],buildBody:ao}),X("fal-flux-schnell","FLUX Schnell","Fastest image generation. Ultra-cheap, great for drafts and iteration.","fal-ai/flux/schnell","image",1,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["image","flux","fast","cheap","draft"],buildBody:ao}),X("fal-recraft-v3","Recraft V3","Design-focused image generation. Great for illustrations, icons, and graphic design.","fal-ai/recraft/v3/text-to-image","image",5,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},style:{type:"string",description:"Style preset: realistic_image, digital_illustration, vector_illustration, icon"}},required:["prompt"]},{tags:["image","design","illustration","icon","vector"]}),qs("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),qs("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}}),qs("or-gemini-nano-banana-pro","Nano Banana Pro","Google Gemini 3 Pro Image Preview via OpenRouter for professional image generation, edits, and text rendering.","google/gemini-3-pro-image-preview",8,{tags:["image","gemini","google","nano-banana","pro","text-rendering"],tokenPricing:{inputPerMillion:2,outputPerMillion:12}}),X("fal-ideogram-v2","Ideogram V2","Excellent text rendering in images. Best for logos, posters, and text-heavy visuals.","fal-ai/ideogram/v2","image",8,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"1:1"}},required:["prompt"]},{tags:["image","text-rendering","logo","poster","typography"]}),X("fal-ideogram-v2-turbo","Ideogram V2 Turbo","Fast text rendering in images. Good balance of speed and text accuracy.","fal-ai/ideogram/v2/turbo","image",5,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"1:1"}},required:["prompt"]},{tags:["image","text-rendering","fast"]}),X("fal-fast-sdxl","Fast SDXL","Ultra-fast Stable Diffusion. 4-step inference, cheapest option.","fal-ai/fast-sdxl","image",1,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"}},required:["prompt"]},{tags:["image","stable-diffusion","fast","cheap"]}),X("fal-wan-video","Wan Video","Text-to-video generation. Create short video clips from text descriptions.","fal-ai/wan/v2.1/1.3b/text-to-video","video",10,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"},num_frames:{type:"number",description:"Number of frames (default: 81)"}},required:["prompt"]},{tags:["video","text-to-video","wan"]}),X("fal-minimax-video","MiniMax Video","High-quality video generation with excellent motion and coherence.","fal-ai/minimax-video/video-01-live","video",15,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"}},required:["prompt"]},{tags:["video","text-to-video","high-quality"]}),X("fal-kling-video","Kling Video","Professional video generation with cinematic quality.","fal-ai/kling-video/v2/master/text-to-video","video",20,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"},duration:{type:"string",description:"Duration: 5 or 10 seconds",default:"5"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["video","text-to-video","cinematic","professional"]}),X("fal-kling-i2v","Kling Image-to-Video","Animate a still image into a 5\u201310s video clip. Cinematic motion quality.","fal-ai/kling-video/v1.6/standard/image-to-video","video",35,{type:"object",properties:{image_url:{type:"string",description:"URL of the source image (jpg, png, webp, gif, avif)"},prompt:{type:"string",description:"Text description of the motion to animate"},duration:{type:"string",description:"Duration: 5 or 10 seconds",default:"5"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 9:16, 1:1)",default:"16:9"},negative_prompt:{type:"string",description:"Elements to avoid in the generated motion"},cfg_scale:{type:"number",description:"Classifier-free guidance (default 0.5)",default:.5}},required:["image_url","prompt"]},{tags:["video","image-to-video","kling","cinematic"]}),X("fal-stable-audio","Stable Audio","Generate sound effects and ambient audio from text descriptions.","fal-ai/stable-audio","audio",4,{type:"object",properties:{prompt:{type:"string",description:"Description of the audio to generate"},seconds_total:{type:"number",description:"Duration in seconds (max 47)",default:30}},required:["prompt"]},{tags:["audio","sound-effects","ambient"]}),X("fal-ace-step-music","ACE-Step Music","Generate full music tracks from a prompt, with optional vocals or instrumentals.","fal-ai/ace-step/prompt-to-audio","audio",2,{type:"object",properties:{prompt:{type:"string",description:"Description of the song, genre, mood, instruments, and lyrics direction"},instrumental:{type:"boolean",description:"Generate instrumental music without vocals",default:!1},duration:{type:"number",description:"Duration in seconds",default:60}},required:["prompt"]},{tags:["music","song","vocals","instrumental","ace-step"]}),vf("suno-music","Suno Music","AI music generation. Create full songs with vocals or instrumentals.","/suno/generate-music","audio",10,{type:"object",properties:{prompt:{type:"string",description:"Description of the song (genre, mood, instruments)"},instrumental:{type:"boolean",description:"Instrumental only, no vocals",default:!1}},required:["prompt"]},{isAsync:!0,pollUrl:"https://api.sunoapi.org/suno/get-music-status",deprecated:!0,tags:["music","song","vocals","instrumental"],buildBody:e=>{let{attestation:t,tool_id:n,prompt:r,instrumental:o,...s}=e;return{prompt:r,customMode:!1,instrumental:typeof o=="boolean"?o:!1,model:"V4",...s}}}),X("fal-trellis-3d","Trellis 3D","Generate 3D models from images. Upload a photo, get a 3D asset.","fal-ai/trellis","3d",8,{type:"object",properties:{image_url:{type:"string",description:"URL of the image to convert to 3D"}},required:["image_url"]},{tags:["3d","model","image-to-3d"]}),X("fal-aura-sr","Aura SR","Upscale images to higher resolution. 4x upscaling with detail enhancement.","fal-ai/aura-sr","upscale",3,{type:"object",properties:{image_url:{type:"string",description:"URL of the image to upscale"}},required:["image_url"]},{tags:["upscale","super-resolution","enhance"]}),X("fal-metavoice","MetaVoice Voice Cloning","Voice cloning TTS \u2014 clone any voice from an audio sample. Provide text and a voice sample URL.","fal-ai/metavoice-v1","tts",3,{type:"object",properties:{text:{type:"string",description:"Text to convert to speech"},audio_url:{type:"string",description:"URL of the voice sample to clone"}},required:["text","audio_url"]},{tags:["tts","voice","voice-cloning","speech"]}),X("fal-whisper","Whisper Transcription","Transcribe audio to text. Supports multiple languages.","fal-ai/whisper","transcription",2,{type:"object",properties:{audio_url:{type:"string",description:"URL of the audio to transcribe"},language:{type:"string",description:"Language code (e.g. en, es, fr)"}},required:["audio_url"]},{tags:["transcription","speech-to-text","whisper"]}),ee("or-gpt-4o","GPT-4o","OpenAI's flagship multimodal model. Best for complex reasoning and analysis.","openai/gpt-4o",2.5,10,{tags:["llm","gpt","openai","multimodal","reasoning"]}),ee("or-gpt-4o-mini","GPT-4o Mini","Fast, affordable GPT-4o. Great for everyday tasks, chat, and simple analysis.","openai/gpt-4o-mini",.15,.6,{tags:["llm","gpt","openai","fast","cheap"]}),ee("or-claude-opus","Claude Opus 4.7","Anthropic's most capable model. 1M context, reasoning, best for complex tasks.","anthropic/claude-opus-4.7",15,75,{tags:["llm","claude","anthropic","reasoning","coding"]}),ee("or-claude-sonnet","Claude Sonnet 4.6","Anthropic's best balance of intelligence and speed. Excellent for coding and analysis.","anthropic/claude-sonnet-4.6",3,15,{tags:["llm","claude","anthropic","coding","analysis"]}),ee("or-claude-opus-fast","Claude Opus 4.6 Fast","Fast Opus variant with lower latency.","anthropic/claude-opus-4.6-fast",15,75,{tags:["llm","claude","anthropic","fast"]}),ee("or-claude-haiku","Claude 3.5 Haiku","Anthropic's fastest model. Great for quick tasks, chat, and simple reasoning.","anthropic/claude-3.5-haiku",.8,4,{tags:["llm","claude","anthropic","fast"]}),ee("or-gemini-pro","Gemini 2.0 Flash","Google's fast multimodal model. Good for general tasks with long context.","google/gemini-2.0-flash-001",.1,.4,{tags:["llm","gemini","google","multimodal","fast","cheap"]}),ee("or-gemini-3-flash","Gemini 3 Flash","Google's high-speed thinking model for agentic workflows, coding, and multimodal tasks.","google/gemini-3-flash-preview",.5,3,{tags:["llm","gemini","google","agentic","coding","fast"]}),ee("or-gemini-3-pro","Gemini 3 Pro","Google's flagship frontier model for deep reasoning, multimodal analysis, and agentic coding.","google/gemini-3-pro-preview",2,12,{tags:["llm","gemini","google","reasoning","coding","multimodal"]}),ee("or-gemini-3-lite","Gemini 3.1 Flash Lite","Google's efficient multimodal model optimized for low-latency, high-volume agent workloads.","google/gemini-3.1-flash-lite",.25,1.5,{tags:["llm","gemini","google","fast","cheap","multimodal"]}),ee("or-llama-70b","Llama 3.3 70B","Meta's best open model. Strong reasoning, fully open-source.","meta-llama/llama-3.3-70b-instruct",.3,.4,{tags:["llm","llama","meta","open-source","reasoning"]}),ee("or-llama-8b","Llama 3.1 8B","Fast, lightweight open model. Great for simple tasks at minimal cost.","meta-llama/llama-3.1-8b-instruct",.05,.08,{tags:["llm","llama","meta","open-source","fast","cheap"]}),ee("or-mistral-large","Mistral Large","Mistral's flagship model. Strong at multilingual and European languages.","mistralai/mistral-large-2411",2,6,{tags:["llm","mistral","multilingual","european"]}),ee("or-mistral-small","Mistral Small","Fast, efficient Mistral model. Good for everyday tasks.","mistralai/mistral-small-3.1-24b-instruct",.1,.3,{tags:["llm","mistral","fast","cheap"]}),ee("or-deepseek-chat","DeepSeek Chat V3","Strong reasoning model at very low cost. Excellent for coding and math.","deepseek/deepseek-chat-v3-0324",.3,.88,{tags:["llm","deepseek","coding","math","cheap","reasoning"]}),ee("or-deepseek-r1","DeepSeek R1","Advanced reasoning model with chain-of-thought. Best for complex problems.","deepseek/deepseek-r1",.55,2.19,{tags:["llm","deepseek","reasoning","chain-of-thought","math"]}),ee("or-qwen-72b","Qwen 2.5 72B","Alibaba's large model. Strong at coding, math, and multilingual tasks.","qwen/qwen-2.5-72b-instruct",.3,.4,{tags:["llm","qwen","alibaba","coding","multilingual"]}),ee("or-phi-4","Phi-4","Microsoft's compact reasoning model. Punches above its weight for size.","microsoft/phi-4",.07,.14,{tags:["llm","phi","microsoft","compact","cheap","reasoning"]}),ee("or-perplexity-sonar","Perplexity Sonar","Search-augmented LLM. Answers with real-time web sources and citations.","perplexity/sonar",1,1,{perRequestFeeCents:.5,tags:["llm","perplexity","search","web","citations","real-time"]}),{dispatch:"enveloped",id:"query_onchain_prices",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly and daily granularity.",provider:"allium",model:"allium-prices",category:"onchain",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly) or '1d' (daily). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:Gc,tags:["onchain","prices","allium","crypto"]},{dispatch:"enveloped",id:"generate_image_card",name:"Generate Image (Ultra)",description:"Generate a high-quality AI image (FLUX Pro Ultra, 2K, ~$0.06).",provider:"fal",model:"fal-ai/flux-pro/v1.1-ultra",category:"image",priceCents:6,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1-ultra",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro-ultra",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),t},tags:["image","flux","ultra","legacy"]},{dispatch:"enveloped",id:"generate_image_fast_card",name:"Generate Image (Fast)",description:"Generate an AI image (FLUX Pro v1.1, 1K, ~$0.04).",provider:"fal",model:"fal-ai/flux-pro/v1.1",category:"image",priceCents:4,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro",buildBody:e=>ao({prompt:e.prompt,aspect_ratio:e.aspect_ratio}),tags:["image","flux","legacy"]},{dispatch:"enveloped",id:"generate_image_schnell_card",name:"Generate Image (Cheap)",description:"Cheap, fast FLUX image generation (~$0.01).",provider:"fal",model:"fal-ai/flux/schnell",category:"image",priceCents:1,inputSchema:{type:"object",properties:{prompt:{type:"string"},image_size:{type:"string"},num_inference_steps:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux/schnell",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-schnell",buildBody:e=>{let t={prompt:e.prompt};return e.image_size&&(t.image_size=e.image_size),e.num_inference_steps!==void 0&&(t.num_inference_steps=e.num_inference_steps),e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","flux","schnell","legacy"]},{dispatch:"enveloped",id:"generate_image_recraft_card",name:"Generate Image (Recraft)",description:"Recraft V3 image generation with style control.",provider:"fal",model:"fal-ai/recraft-v3",category:"image",priceCents:5,inputSchema:{type:"object",properties:{prompt:{type:"string"},style:{type:"string"},image_size:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/recraft-v3",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-recraft-v3",buildBody:e=>{let t={prompt:e.prompt};return e.style&&(t.style=e.style),e.image_size&&(t.image_size=e.image_size),t},tags:["image","recraft","legacy"]},{dispatch:"enveloped",id:"generate_image_ideogram_card",name:"Generate Image (Ideogram)",description:"Ideogram V2 image generation, strong with text rendering.",provider:"fal",model:"fal-ai/ideogram/v2",category:"image",priceCents:8,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},style_type:{type:"string"},negative_prompt:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/ideogram/v2",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-ideogram-v2",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.style_type&&(t.style_type=e.style_type),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),t},tags:["image","ideogram","text","legacy"]},X("upscale_image_card","Upscale Image","Upscale an image using ESRGAN.","fal-ai/esrgan","upscale",2,{type:"object",properties:{image_url:{type:"string"},scale:{type:"number"}},required:["image_url"]},{buildBody:e=>{let t={image_url:e.image_url};return e.scale!==void 0&&(t.scale=e.scale),t},tags:["upscale","esrgan"],deprecated:!0,replacementTool:"fal-aura-sr"}),X("edit_image_seed_card","Edit Image (SeedEdit)","Inpaint/edit an image with a prompt using SeedEdit.","fal-ai/bytedance/seededit","image",5,{type:"object",properties:{image_url:{type:"string"},prompt:{type:"string"},seed:{type:"number"}},required:["image_url","prompt"]},{buildBody:e=>{let t={image_url:e.image_url,prompt:e.prompt};return e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","edit","inpaint","seededit"],deprecated:!0,replacementTool:"or-gemini-nano-banana"}),{dispatch:"enveloped",id:"generate_video_tempo_card",name:"Generate Video (Grok)",description:"Generate a video from a text prompt using Grok Imagine Video.",provider:"fal",model:"xai/grok-imagine-video/text-to-video",category:"video",priceCents:30,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/xai/grok-imagine-video/text-to-video",merchantName:"Grok Video via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),t},tags:["video","grok","legacy"]},{dispatch:"enveloped",id:"generate_video_kling_card",name:"Generate Video (Kling)",description:"Generate a video using Kling v1.6 (async, ~$0.40).",provider:"fal",model:"fal-ai/kling-video/v1.6/standard/text-to-video",category:"video",priceCents:40,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/kling-video/v1.6/standard/text-to-video",merchantName:"Kling via fal.ai",deprecated:!0,replacementTool:"fal-kling-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","kling","legacy"]},{dispatch:"enveloped",id:"generate_video_wan_card",name:"Generate Video (Wan)",description:"Generate a video using Wan T2V (async, ~$0.25).",provider:"fal",model:"fal-ai/wan/t2v-1.3b",category:"video",priceCents:25,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/wan/t2v-1.3b",merchantName:"Wan T2V via fal.ai",deprecated:!0,replacementTool:"fal-wan-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","wan","legacy"]},{dispatch:"enveloped",id:"generate_video_minimax_card",name:"Generate Video (MiniMax)",description:"Generate a video using MiniMax (async, ~$0.35).",provider:"fal",model:"fal-ai/minimax/video-01",category:"video",priceCents:35,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/minimax/video-01",merchantName:"MiniMax via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","minimax","legacy"]},{dispatch:"enveloped",id:"check_fal_status_card",name:"Check fal Async Job Status",description:"Poll an async fal.ai queue job for completion.",provider:"fal",model:"queue-status",category:"image",priceCents:0,inputSchema:{type:"object",properties:{model_path:{type:"string",description:"Model path (e.g. fal-ai/kling-video/v1.6/standard/text-to-video)"},request_id:{type:"string"}},required:["model_path","request_id"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue",merchantName:"fal.ai",buildUrl:e=>`https://fal.mpp.tempo.xyz/queue/${e.model_path}/requests/${e.request_id}`,buildBody:()=>({}),tags:["status","fal","async","legacy"]},{dispatch:"enveloped",id:"generate_3d_card",name:"Generate 3D Model",description:"Generate a 3D mesh from a text prompt using Meshy (async, ~$0.50).",provider:"fal",model:"fal-ai/meshy-ai/text-to-3d",category:"3d",priceCents:50,inputSchema:{type:"object",properties:{object_prompt:{type:"string"},style_prompt:{type:"string"},negative_prompt:{type:"string"},art_style:{type:"string"},seed:{type:"number"}},required:["object_prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/meshy-ai/text-to-3d",merchantName:"Meshy via fal.ai",deprecated:!0,replacementTool:"fal-trellis-3d",buildBody:e=>{let t={object_prompt:e.object_prompt};return e.style_prompt&&(t.style_prompt=e.style_prompt),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.art_style&&(t.art_style=e.art_style),e.seed!==void 0&&(t.seed=e.seed),t},tags:["3d","mesh","meshy","legacy"]},{dispatch:"enveloped",id:"generate_speech_card",name:"Generate Speech",description:"Text-to-speech using F5-TTS with optional voice cloning.",provider:"fal",model:"fal-ai/f5-tts",category:"tts",priceCents:3,inputSchema:{type:"object",properties:{gen_text:{type:"string",description:"Text to synthesize"},ref_audio_url:{type:"string",description:"Reference audio URL (for voice cloning)"},ref_text:{type:"string",description:"Transcription of ref audio"},remove_silence:{type:"boolean"}},required:["gen_text"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/f5-tts",merchantName:"fal.ai",buildBody:e=>{let t={gen_text:e.gen_text};return e.ref_audio_url&&(t.ref_audio_url=e.ref_audio_url),e.ref_text&&(t.ref_text=e.ref_text),e.remove_silence!==void 0&&(t.remove_silence=e.remove_silence),t},deprecated:!0,replacementTool:"fal-metavoice",tags:["tts","speech","f5-tts","legacy"]},{dispatch:"enveloped",id:"generate_music_tempo_card",name:"Generate Music (Suno)",description:"Generate a music track using Suno (async, ~$0.50).",provider:"suno",model:"suno-v4",category:"audio",priceCents:50,inputSchema:{type:"object",properties:{prompt:{type:"string"},instrumental:{type:"boolean"},model:{type:"string",default:"V4"}},required:["prompt"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/generate-music",merchantName:"Suno via Tempo",buildBody:e=>({prompt:e.prompt,customMode:!1,instrumental:e.instrumental??!1,model:e.model||"V4"}),isAsync:!0,pollUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",pollInterval:15e3,pollTimeout:3e5,deprecated:!0,replacementTool:"fal-ace-step-music",tags:["music","audio","suno","async","legacy"]},{dispatch:"enveloped",id:"check_music_status_tempo_card",name:"Check Music Status",description:"Poll a Suno music generation task for completion.",provider:"suno",model:"suno-status",category:"audio",priceCents:0,inputSchema:{type:"object",properties:{taskId:{type:"string"}},required:["taskId"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",merchantName:"Suno Status",buildBody:e=>({taskId:e.taskId}),deprecated:!0,tags:["music","status","suno","legacy"]},{dispatch:"enveloped",id:"query_onchain_prices_card",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly, daily, and weekly granularity.",provider:"allium",model:"allium-prices",category:"llm",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly), '1d' (daily), or '1w' (weekly). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",deprecated:!0,replacementTool:"query_onchain_prices",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:Gc,tags:["onchain","prices","allium","crypto","legacy"]}];function ar(e){return Hs.find(t=>t.id===e)}var Jc=1,Yc=["pick_one","fan_out"],Zc=["concat","dedupe_by_url","top_k_by_score"],Cf=8,kf=f.object({type:f.string().min(1),description:f.string().min(1),enum:f.array(f.string()).optional(),default:f.unknown().optional(),minimum:f.number().optional(),maximum:f.number().optional()}),Tf=f.object({toolId:f.string().min(1),notes:f.string().min(1)}),Ef=f.string().regex(/^[a-z0-9_-]{1,32}$/,"tier key must be 1-32 chars [a-z0-9_-]"),Af=f.object({providers:f.array(f.string().min(1)).min(1).max(Cf),merge:f.enum(Zc),maxResults:f.number().int().positive().optional()}),Xc=f.object({mode:f.enum(Yc).default("pick_one"),intro:f.string().min(1),defaultTier:f.string().min(1),tiers:f.record(Ef,Tf).refine(e=>Object.keys(e).length>0,{message:"must have at least one tier"}),fanOut:Af.optional(),guidance:f.string().min(1),inputProperties:f.record(f.string(),kf),required:f.array(f.string())}).refine(e=>e.tiers[e.defaultTier]!==void 0,{message:"defaultTier must exist in tiers",path:["defaultTier"]}).refine(e=>e.mode!=="fan_out"||e.fanOut!==void 0,{message:"fan_out mode requires fanOut config",path:["fanOut"]}).refine(e=>e.required.every(t=>t in e.inputProperties),{message:"required entries must exist in inputProperties",path:["required"]}),Rf=f.object({version:f.literal(Jc),generatedAt:f.string().datetime(),tools:f.record(f.string().regex(Vs,"tool name must match MCP naming rules"),Xc).refine(e=>Object.keys(e).length>0,{message:"manifest must have at least one tool"})});var uo=require("child_process"),rl=require("util"),ol=T(require("crypto")),ue=T(require("fs")),sl=T(require("os")),He=T(require("path"));var Rn=(0,rl.promisify)(uo.execFile),mo=He.join(sl.homedir(),".visa-mcp","bin"),cn=He.join(mo,"Visa CLI"),Pf=He.join(__dirname,"..","native"),Qc="6",el=He.join(mo,"visa-keychain.version"),tl=He.join(mo,"visa-keychain.sha256");function nl(e){let t=ue.readFileSync(e);return ol.createHash("sha256").update(t).digest("hex")}async function Ks(){try{if(ue.readFileSync(el,"utf-8").trim()===Qc&&ue.existsSync(cn)){let r=ue.readFileSync(tl,"utf-8").trim();if(nl(cn)!==r)m.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),ue.unlinkSync(cn);else return cn}}catch{}let e=He.join(Pf,"visa-keychain.m");if(ue.existsSync(e)||(e=He.resolve(__dirname,"..","..","native","visa-keychain.m")),ue.existsSync(e)||(e=He.resolve(__dirname,"..","native","visa-keychain.m")),!ue.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");ue.mkdirSync(mo,{recursive:!0,mode:448});try{await Rn("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",cn,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=nl(cn);return ue.writeFileSync(tl,t,{mode:384}),ue.writeFileSync(el,Qc,{mode:384}),cn}async function il(e){let t=await Ks(),n;try{n=(await Rn(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 Bs=null;function re(){return gn()?!0:process.platform!=="darwin"?!1:Bs!==null?Bs:(Bs=!0,!0)}var co="visa-cli",lo="attestation-key";async function Mf(e){try{await Rn("security",["delete-generic-password","-s",co,"-a",lo],{timeout:5e3})}catch{}await Rn("security",["add-generic-password","-s",co,"-a",lo,"-w",e],{timeout:5e3})}async function Gs(){try{let{stdout:e}=await Rn("security",["find-generic-password","-s",co,"-a",lo,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function po(){let e=await il(["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 Mf(n),r}async function al(){return await Gs()!==null}async function cl(){if(gn())return"mock-public-key-spki";let e=await Gs();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await Ks();return new Promise((n,r)=>{let o=(0,uo.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 In(e,t){if(gn())return Promise.resolve(Qi());let n=await Gs();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await Ks(),o=["sign",e];return t&&o.push(t),new Promise((s,i)=>{let a=(0,uo.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 fo(){try{await Rn("security",["delete-generic-password","-s",co,"-a",lo],{timeout:5e3})}catch{}try{await il(["delete-key"])}catch{}}var Of=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],Nf=[...Of.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 Ws(e,t=Nf){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=zs(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(zs(r.match.provider)))&&r.match.keywords.every(o=>n.includes(zs(o))))return r.targetToolId;return null}function zs(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}var cr={generate_image:{intro:'Generate an AI image from a text prompt \u2014 useful for hero shots, marketing assets, social posts, blog covers, app mockups, or any time the user asks for art, a logo, an icon, a thumbnail, or "a picture of \u2026". From $0.01 (fast) to $0.06 (pro), returns a hosted PNG/JPG URL. Default tier: balanced ($0.04, 1K, ~10s).',tiers:{balanced:{toolId:"fal-flux-pro",notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",notes:"Recraft V3 \u2014 vector/flat/illustration styles"}},guidance:"If the user didn't specify a tier, pick 'balanced' unless the prompt clearly signals otherwise (text \u2192 text_heavy, logo/icon \u2192 vector, quick test \u2192 fast, hero/print \u2192 pro).",inputProperties:{prompt:{type:"string",description:"Text description of the image to generate."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9", "1:1", "9:16".',default:"16:9"}},required:["prompt"]},generate_video:{intro:'Generate a short AI video from a text prompt \u2014 useful for product demos, social clips, mood reels, ad concepts, or any "make me a video of \u2026" request. $0.10\u2013$0.40 per ~6s clip depending on tier. Async: returns a request_id; use execute_tool with tool_id "check_fal_status_card" to resolve it (60\u2013180s).',tiers:{balanced:{toolId:"fal-minimax-video",notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",notes:"Kling \u2014 highest quality, cinematic"}},guidance:'Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate and are processed asynchronously. The response includes a request_id and model_path. Poll with execute_tool using tool_id "check_fal_status_card" and params {request_id, model_path}. Do not poll more than once per 30 seconds.',inputProperties:{prompt:{type:"string",description:"Text description of the video scene."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9" or "9:16".',default:"16:9"}},required:["prompt"]},generate_music:{intro:'Generate an original music track from a prompt via ACE-Step. ~$0.02 for the default 60s track. Use for songs, backing tracks, jingles, vocal music, instrumental music, or any "make a song/music/track" request. Takes ~60-90s and may return a request_id to poll with check_fal_status_card. For SFX, chimes, ambient beds, or TTS, use generate_audio instead.',tiers:{ace_step:{toolId:"fal-ace-step-music",notes:"ACE-Step \u2014 prompt-to-music with vocals or instrumentals"}},guidance:"Use for songs and music tracks. Takes ~60-90s and may return a request_id to poll with check_fal_status_card. For sound effects, chimes, ambient beds, or TTS, use generate_audio instead.",inputProperties:{prompt:{type:"string",description:"Musical style, mood, instruments, subject, and lyrics direction."},instrumental:{type:"boolean",description:"True for instrumental music with no vocals; false for vocal tracks.",default:!1},duration:{type:"number",description:"Duration in seconds.",default:60}},required:["prompt"]},generate_audio:{intro:'Generate sound effects from a text prompt (sfx tier \u2014 default), or voice-cloned speech from text + a reference audio URL (tts tier). $0.03\u2013$0.04. Use for SFX, chimes, UI sounds, ambient audio (default sfx), or voice cloning when a reference audio URL is available (pass tier:"tts"). Default tier is sfx; pass tier:"tts" for voice cloning.',tiers:{sfx:{toolId:"fal-stable-audio",notes:"Stable Audio \u2014 sound effects and ambient from a prompt"},tts:{toolId:"fal-metavoice",notes:"MetaVoice \u2014 voice cloning TTS (requires a voice sample URL)"}},guidance:'Default tier is sfx: pass prompt describing the sound. For tts (voice cloning): pass tier:"tts" + text + audio_url.',inputProperties:{prompt:{type:"string",description:"Description of sound to generate (sfx tier, default)."},text:{type:"string",description:"Text to speak aloud (tts tier)."},audio_url:{type:"string",description:"URL of a voice sample to clone (tts tier, required for voice cloning)."}},required:[]},generate_3d:{intro:"Generate a 3D mesh (GLB) from an image URL via Trellis. ~$0.08, ~30\u201360s. Use when the user shares an image and asks for a 3D model, asset, AR-ready mesh, or game-ready GLB.",tiers:{trellis:{toolId:"fal-trellis-3d",notes:"Trellis \u2014 image-to-3D, returns a GLB mesh URL"}},guidance:"Pass an image URL. Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{image_url:{type:"string",description:"URL of the image to convert to a 3D model."}},required:["image_url"]},upscale_image:{intro:'Upscale an image to 4\xD7 resolution via Aura SR (preserves detail without hallucination). ~$0.03. Use whenever the user shares a low-res image and asks to "upscale", "make this higher resolution", "4x this", "enhance", or to print/export at larger size.',tiers:{aura:{toolId:"fal-aura-sr",notes:"Aura SR \u2014 default; preserves detail without hallucination"}},guidance:"Pass the existing image URL. Returns an upscaled version.",inputProperties:{image_url:{type:"string",description:"URL of the image to upscale."}},required:["image_url"]},transcribe_audio:{intro:'Transcribe speech in an audio or video file (URL) to text via OpenAI Whisper. ~$0.02 per file, multilingual, handles long files. Use whenever the user asks to "transcribe this", "what does this audio say", "make subtitles", "convert this to text", or shares an audio/video URL with no other clear intent.',tiers:{whisper:{toolId:"fal-whisper",notes:"OpenAI Whisper \u2014 fast, multilingual"}},guidance:"Pass the URL. Returns the transcript text.",inputProperties:{audio_url:{type:"string",description:"URL of the audio or video file to transcribe."}},required:["audio_url"]},run_llm:{intro:"Run a text prompt through a different LLM (GPT-4o-mini, Claude Sonnet, DeepSeek R1/V3, Perplexity Sonar with web search, or Llama 70B). Token-metered, typically ~$0.01\u2013$0.10 per call. Use for: web-grounded answers (search tier), second-opinion reasoning (reasoning tier), code generation in a different family (coding tier), deep math/logic (deep_reasoning tier), or fast cheap text cleanup (fast tier). Pair with batch for multi-model councils.",tiers:{fast:{toolId:"or-gpt-4o-mini",notes:"GPT-4o Mini. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",notes:"Claude Sonnet. Strong reasoning, long-context. Warn user it is materially pricier than `fast`."},deep_reasoning:{toolId:"or-deepseek-r1",notes:"DeepSeek R1. Deep chain-of-thought reasoning, mid-range pricing."},search:{toolId:"or-perplexity-sonar",notes:"Perplexity Sonar. Search-augmented, web-grounded with citations."},open_source:{toolId:"or-llama-70b",notes:"Llama 3.3 70B. Open-source large model."},coding:{toolId:"or-deepseek-chat",notes:"DeepSeek Chat V3. Strong at code generation."}},guidance:"Pick based on the user's need: fast (most questions, cheapest), reasoning (complex analysis; warn user it is materially pricier than fast), search (questions about current events), coding (code generation), deep_reasoning (hard math/logic problems).",inputProperties:{prompt:{type:"string",description:"The user query."},system_prompt:{type:"string",description:"Optional system prompt to set model behavior."},max_tokens:{type:"number",description:"Maximum output tokens.",default:1024,minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature \u2014 0 is deterministic, higher is more creative.",default:.7,minimum:0,maximum:2}},required:["prompt"]}};function ln(e,t,n){if(!ul(e))return jf(e,n);let r=ll[e];if(!r)return e;let o=Object.keys(r.tiers),s=t||o[0],i=Ff(e,s,n);return i||Vf(e,r,s,o)}function jf(e,t){return Ws({requestedTool:e,intentText:t})??e}function Ff(e,t,n){return Ws({requestedTool:e,metaTool:e,tier:t,intentText:n})}function Vf(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=cr;function ul(e){return e in ll}var lr=Object.keys(cr);function Js(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 Js(e)!==null}var Wl=require("child_process"),de=T(require("crypto")),Oe=T(require("fs")),fr=T(require("os")),Ao=T(require("path"));var ml=!1;async function ur(e,t,n){try{return await t()}catch(r){if(!(r.message==="Invalid signature"||r.code==="ATTESTATION_KEY_DRIFT"||r.error_code==="ATTESTATION_KEY_DRIFT"||r.name==="AttestationDriftError")||!re())throw r;if(m.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(ml)throw m.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;ml=!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 po();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 pl="2.4.0-rc.0";function Ys(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function ho(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=Qr(t);return o!==void 0?{value:o,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function we(e){return e==null?"\u2014":e?"yes":"no"}function yo(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function qf(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function Hf(){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=Ps("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:Is,source:{kind:"default"}}}async function dr(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(H){n=H?.message||"unknown error"}let r=[],o=process.env.VISA_AUTH_URL,s=$s("auth.serverUrl"),i=he(),a=o!==void 0&&o!==""?{kind:"env",var:"VISA_AUTH_URL"}:s!==void 0?{kind:"settings"}:{kind:"default"};r.push({key:"auth.serverUrl",value:i,formatted:i,source:a,hint:a.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),r.push({key:"account.enrolled",value:t?.enrolled??null,formatted:we(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),t?.githubUser&&r.push({key:"account.githubUser",value:t.githubUser,formatted:t.githubUser,source:{kind:"server"}});let l=t?t.attestationRequired!==!1:void 0;r.push({key:"biometric.required",value:l,formatted:we(l),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"},hint:l===!1?"Touch ID prompts are suppressed. Re-enable with `visa-cli config biometric on`.":void 0}),r.push({key:"biometric.keyRegistered",value:t?.hasAttestationKey??null,formatted:we(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:re(),formatted:we(re()),source:{kind:"device"}});let c=t?.spendingControls,u=c?c.max_transaction_amount??c.maxTransactionAmount??null:null,d=c?c.daily_limit??c.dailyLimit??null:null;r.push({key:"spending.maxPerTxn",value:u,formatted:yo(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:yo(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:yo(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:yo(t?.dailyRemaining),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"cards.count",value:t?.cardCount??null,formatted:t?.cardCount!=null?String(t.cardCount):"\u2014",source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}});let g=t?.cards?.find(H=>H.isDefault)??t?.cards?.[0];g&&r.push({key:"cards.default",value:{brand:g.brand??null,last4:g.last4},formatted:`${g.brand||"card"} \u2022\u2022\u2022\u2022 ${g.last4}`,source:{kind:"server"}});let p=Hf();r.push({key:"credit.sessionCapCents",value:p.value,formatted:qf(p.value),source:p.source});let v=Sc();v.length>0&&r.push({key:"settings.retired",value:v.map(H=>H.key),formatted:v.map(H=>H.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${v.map(H=>`visa-cli config unset ${H.key}`).join(" && ")}`});let S=ho("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:S.value,formatted:we(S.value),source:S.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let y=ho("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:y.value,formatted:we(y.value),source:y.source});let R=je(),A;process.env.VISA_CLI_NO_UPDATE_CHECK?A={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?A={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?A={kind:"env",var:"NODE_ENV"}:A={kind:"default"},r.push({key:"ui.updateCheck",value:!R,formatted:we(!R),source:A});let x=ho("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:x.value,formatted:we(x.value),source:x.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let w=ho("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:w.value,formatted:we(w.value),source:w.source});let F=process.env.VISA_DRY_RUN,se=dl();if(r.push({key:"tools.dryRun",value:se,formatted:we(se),source:F===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:pl,formatted:pl,source:{kind:"default"}}),e.includeDev){let H=process.env.VISA_MOCK_KEYCHAIN,be=mt();r.push({key:"dev.mockKeychain",value:be,formatted:we(be),source:Ys("VISA_MOCK_KEYCHAIN",!!H),hint:Bo()});let Y=process.env.VISA_MOCK_TOUCHID,fe=gn();r.push({key:"dev.mockTouchid",value:fe,formatted:we(fe),source:Ys("VISA_MOCK_TOUCHID",!!Y),hint:Bo()});let dt=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!dt,formatted:we(!!dt),source:Ys("VISA_CLI_DEBUG",!!dt)})}return{entries:r,statusError:n}}function Bf(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 fl(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}(${Bf(s.source)})`),t.verbose&&s.hint&&o.push(` ${"\u21B3".padStart(n)} ${s.hint}`)}return o.join(`
|
|
122
|
+
`;wt.writeFileSync(n,r,{mode:384}),wt.renameSync(n,t)}function $s(e){let t=Bt()[e];return typeof t=="string"?t:void 0}function Qr(e){let t=Bt()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function Ps(e){let t=Bt()[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 tt=class extends Error{constructor(t){let n=Object.keys(xt).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"}},nt=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"}},St=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+Xr[t]),this.name="RetiredSettingKeyError"}},bc=["biometric.","spending.","account.","cards.","biometric"];function eo(e,t){if(bc.some(s=>e.startsWith(s)))throw new nt(e);if(e in Xr)throw new St(e);let n=xt[e];if(!n)throw new tt(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=Bt();return o[e]=r,As(o),{key:e,value:r,requiresRestart:!!n.requiresRestart,path:nr()}}function to(e){if(bc.some(s=>e.startsWith(s)))throw new nt(e);let t=xt[e];if(e in Xr){let s=Bt(),i=e in s;return i&&(delete s[e],As(s)),{key:e,removed:i,requiresRestart:!1,path:nr()}}if(!t)throw new tt(e);let r=Bt(),o=e in r;return o&&(delete r[e],As(r)),{key:e,removed:o,requiresRestart:o&&!!t.requiresRestart,path:nr()}}function Sc(){let e=Bt();return Object.entries(Xr).filter(([t])=>t in e).map(([t,n])=>({key:t,value:e[t],hint:n}))}var Fm="https://auth.visacli.sh",Vm="https://auth-visa-code-preview.up.railway.app";function qm(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function Hm(){try{let e=Vn();return qm(e.version)}catch{return!1}}function Bm(e){return e.envVar!==void 0&&e.envVar!==""?(Es(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(Es(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?Vm:Fm}function he(){return Bm({envVar:process.env.VISA_AUTH_URL,settingValue:$s("auth.serverUrl"),isPrerelease:Hm()})}function wc(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":Qr("ui.suppressBrowser")??!1}function xc(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":Qr("ui.suppressFeed")??!1}function Cc(){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=Ps("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):Is}var Km="CARD_REENROLLMENT_REQUIRED",Gm="https://auth.visacli.sh/enroll-card";function zm(){try{return new URL("/enroll-card",he()).toString()}catch{return Gm}}function Wm(e){let t=zm();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 rr="2.4.0",Jm=/^vk_[A-Za-z0-9_-]{32,}$/;function Ym(e){if(typeof e!="string")return null;switch(e){case"BUDGET_CLOSED":case"BUDGET_NOT_FOUND":case"BUDGET_EXPIRED":return e;default:return null}}var Zm="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function bn(e){return typeof e=="string"?e.trim():""}function kc(e){let t=e&&typeof e=="object"?e:{},n=bn(t.error)||bn(t.message);if(!n)return Zm;let r=bn(t.error_code),o=[["surface",bn(t.disabled_surface)],["flag",bn(t.flag)],["correlation_id",bn(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 Tc(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?Jm.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 Se=class{constructor(t){this.getSessionToken=t;this.baseUrl=he()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!je()){let r=t.headers.get("X-Latest-Version");r&&mc(r,rr)&&(this.lastSignals.updateAvailable={currentVersion:rr,latestVersion:r})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return rr}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new qt(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(kc(n))}async request(t,n,r,o,s,i){let a=await this.getSessionToken();if(!a)throw new Error(Tc());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 Vt(`${this.baseUrl}${n}`,{method:t,headers:{...l,"X-Visa-CLI-Version":rr,"X-Source":"cli"},body:r?JSON.stringify(r):void 0,timeoutMs:o})}catch(d){throw new Error(ws(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===Km){let d=typeof u?.last4=="string"?u.last4:"",g=typeof u?.brand=="string"?u.brand:"card",p=Wm(u?.reenroll_url),v=d?`${g} ending in ${d}`:"your card";throw new Error(`Please re-add ${v} to keep payments running. Open: ${p}`)}if(u?.declined){let d=Number(u.retryAfter??c.headers.get("Retry-After"));throw new ce(u.error||"Your card was declined.",!!u.retryable,u.code,u.reason,u.payment_error_class,u.correlation_id,u.transactionId,Number.isFinite(d)&&d>0?d:void 0)}if(c.status===402){let d=u?.error||"Gateway returned 402",g=typeof u?.error_code=="string"?u.error_code:"";throw g==="SPENDING_LIMIT_EXCEEDED"||g==="DAILY_LIMIT_EXCEEDED"||g==="PER_TXN_LIMIT_EXCEEDED"?new Error(`${d}. Check your limits with get_status or run: visa-cli update-spending-controls`):new Error(d)}throw new Error(u?.error||`Request failed (${c.status}). Try again.`)}return u}async shortcut(t,n,r,o,s){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,o,s)}async shortcutWithSession(t,n,r,o,s,i){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,l=await this.getSessionToken();if(!l)throw new Error(Tc());let c={Authorization:`Bearer ${l}`,"X-Visa-CLI-Version":rr,"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 Vt(`${this.baseUrl}${a}`,{method:"POST",headers:c,body:JSON.stringify(u),timeoutMs:o})}catch(v){throw new Error(ws(v))}if(this.parseServerSignals(d),d.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(d.status===429){let v=d.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${v}s. Tip: use the batch tool to combine multiple requests into one.`)}let g=d.headers.get("X-Voucher-Receipt"),p;try{p=await d.json()}catch{throw d.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):d.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!d.ok){if(d.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(p),d.status===503){if(p?.error_code==="SESSION_LOCK_CONTENDED"){let S=Number(d.headers.get("Retry-After"))||1;throw new Ht(p?.message||p?.error||"Session budget is being modified by another request. Retry shortly.",S,d.status)}throw new Error(kc(p))}let v=Ym(p?.error_code);if(v||d.status===410){let S=v??"BUDGET_CLOSED";throw new vn(p?.message||p?.error||"Your session was invalidated by the server.",S,{budgetId:n.session_budget_id,status:d.status})}if(p?.declined){let S=Number(p.retryAfter??d.headers.get("Retry-After"));throw new ce(p.error||"Your card was declined.",!!p.retryable,p.code,p.reason,p.payment_error_class,p.correlation_id,p.transactionId,Number.isFinite(S)&&S>0?S:void 0)}throw new Error(p?.error||`Request failed (${d.status}). Try again.`)}return{data:p,voucherReceiptHeader:g}}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async catalogSearch(t,n,r,o){let s=r??"discover_tools",i=new URLSearchParams;t&&i.set("q",t),n&&i.set("category",n),o?.limit!=null&&i.set("limit",String(o.limit)),o?.offset!=null&&i.set("offset",String(o.offset));let a=i.toString();return this.request("GET",`/v1/catalog${a?`?${a}`:""}`,void 0,void 0,void 0,s)}async catalogTool(t,n){let r=n??"discover_tools";try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(t)}`,void 0,void 0,void 0,r)}catch{return null}}async discoverMerchantRoutes(t){try{return await this.request("GET",`/v1/platform/discover/${encodeURIComponent(t)}`)}catch{return null}}async listPublicMerchants(){try{let t=await Vt(`${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 Vt(`${this.baseUrl}/v1/platform/discover/${encodeURIComponent(t)}`,{method:"GET",timeoutMs:8e3});return n.ok?await n.json():null}catch{return null}}async paymentPreview(t,n){return this.request("POST","/v1/payment-preview",t,void 0,n)}async getBalance(){return this.request("GET","/v1/balance")}async topupBalance(t){return this.request("POST","/v1/balance/topup",t)}async createEnrollCode(){return this.request("POST","/v1/enroll-code")}async getAutoTopup(){let t=await this.getBalance();return{success:t.success,targetCents:t.autoTopupCents??null,thresholdCents:t.autoTopupThresholdCents??0}}async disableAutoTopup(){return this.request("PATCH","/v1/balance/auto-topup",{auto_topup_cents:null})}async createSessionBudget(t){return this.request("POST","/v1/session-budget/create",{...t,mode:"prepaid"})}async closeSession(t){return this.request("POST","/v1/session/close",{session_budget_id:t})}async getSessionBudget(t){return this.request("GET",`/v1/session-budget/${encodeURIComponent(t)}`)}async getSessionLedger(t){return this.request("GET",`/v1/session/${encodeURIComponent(t)}/ledger`)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getVisaSmi(t,n){return this.request("POST","/v1/visa/smi",t,6e4,n)}async getTransactions(t,n){let r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.offset!=null&&r.set("offset",String(t.offset));let o=r.toString(),s=o?`/v1/transactions?${o}`:"/v1/transactions";return this.request("GET",s,void 0,void 0,n)}async updateSpendingControls(t,n){return this.request("POST","/v1/spending-controls",t,void 0,n)}async removeCard(t,n,r){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(t))}`,n,void 0,r)}async setDefaultCard(t,n,r){return this.request("POST",`/v1/cards/${encodeURIComponent(String(t))}/default`,n,void 0,r)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t,n){return this.request("POST","/v1/attestation-key",{publicKey:t,...n?{attestation:n}:{}})}async startAttestationRecovery(t,n){return this.request("POST","/v1/attestation-key/recovery/start",{state:t},void 0,n)}async setBiometricPreference(t,n){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,n)}async logout(t,n){return this.request("POST","/v1/logout",t,void 0,n)}async feedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async createAppApiKey(t){return this.request("POST","/v1/api/keys",t)}async listAppApiKeys(){return this.request("GET","/v1/api/keys")}async revokeAppApiKey(t){return this.request("DELETE",`/v1/api/keys/${encodeURIComponent(String(t))}`)}async feedSubmit(t){return this.request("POST","/v1/feed",t)}async feedList(t){let n=new URLSearchParams;t?.tab&&n.set("tab",t.tab),t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset));let r=n.toString();return this.request("GET",`/v1/feed${r?"?"+r:""}`)}async feedVote(t,n){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/vote`,{direction:n})}async feedApprove(t){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/approve`)}async feedDelete(t){return this.request("DELETE",`/v1/feed/${encodeURIComponent(t)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async getFeedback(t,n){let r=new URLSearchParams;t&&r.set("limit",String(t));let o=r.toString();return this.request("GET",`/v1/feedback${o?"?"+o:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}};var f={};qo(f,{BRAND:()=>xp,DIRTY:()=>Kt,EMPTY_PATH:()=>tp,INVALID:()=>I,NEVER:()=>cf,OK:()=>le,ParseStatus:()=>ae,Schema:()=>N,ZodAny:()=>Tt,ZodArray:()=>it,ZodBigInt:()=>zt,ZodBoolean:()=>Wt,ZodBranded:()=>sr,ZodCatch:()=>sn,ZodDate:()=>Jt,ZodDefault:()=>on,ZodDiscriminatedUnion:()=>oo,ZodEffects:()=>Ae,ZodEnum:()=>nn,ZodError:()=>ye,ZodFirstPartyTypeKind:()=>$,ZodFunction:()=>io,ZodIntersection:()=>Qt,ZodIssueCode:()=>h,ZodLazy:()=>en,ZodLiteral:()=>tn,ZodMap:()=>Tn,ZodNaN:()=>An,ZodNativeEnum:()=>rn,ZodNever:()=>$e,ZodNull:()=>Zt,ZodNullable:()=>qe,ZodNumber:()=>Gt,ZodObject:()=>_e,ZodOptional:()=>Te,ZodParsedType:()=>b,ZodPipeline:()=>ir,ZodPromise:()=>Et,ZodReadonly:()=>an,ZodRecord:()=>so,ZodSchema:()=>N,ZodSet:()=>En,ZodString:()=>kt,ZodSymbol:()=>Cn,ZodTransformer:()=>Ae,ZodTuple:()=>Ve,ZodType:()=>N,ZodUndefined:()=>Yt,ZodUnion:()=>Xt,ZodUnknown:()=>st,ZodVoid:()=>kn,addIssueToContext:()=>_,any:()=>Pp,array:()=>Lp,bigint:()=>Ep,boolean:()=>Dc,coerce:()=>af,custom:()=>Oc,date:()=>Ap,datetimeRegex:()=>Pc,defaultErrorMap:()=>rt,discriminatedUnion:()=>Fp,effect:()=>Xp,enum:()=>Jp,function:()=>Gp,getErrorMap:()=>Sn,getParsedType:()=>Fe,instanceof:()=>kp,intersection:()=>Vp,isAborted:()=>no,isAsync:()=>wn,isDirty:()=>ro,isValid:()=>Ct,late:()=>Cp,lazy:()=>zp,literal:()=>Wp,makeIssue:()=>or,map:()=>Bp,nan:()=>Tp,nativeEnum:()=>Yp,never:()=>Op,null:()=>$p,nullable:()=>ef,number:()=>Lc,object:()=>Dp,objectUtil:()=>Ms,oboolean:()=>sf,onumber:()=>of,optional:()=>Qp,ostring:()=>rf,pipeline:()=>nf,preprocess:()=>tf,promise:()=>Zp,quotelessJson:()=>Xm,record:()=>Hp,set:()=>Kp,setErrorMap:()=>ep,strictObject:()=>Up,string:()=>Nc,symbol:()=>Rp,transformer:()=>Xp,tuple:()=>qp,undefined:()=>Ip,union:()=>jp,unknown:()=>Mp,util:()=>L,void:()=>Np});var L;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},e.getValidEnumValues=o=>{let s=e.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return e.objectValues(i)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},e.find=(o,s)=>{for(let i of o)if(s(i))return i},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(L||(L={}));var Ms;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Ms||(Ms={}));var b=L.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Fe=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=L.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Xm=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ye=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,l=0;for(;l<i.path.length;){let c=i.path[l];l===i.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(i))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return o(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,L.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];n[s]=n[s]||[],n[s].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};ye.create=e=>new ye(e);var Qm=(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,L.jsonStringifyReplacer)}`;break;case h.unrecognized_keys:n=`Unrecognized key(s) in object: ${L.joinValues(e.keys,", ")}`;break;case h.invalid_union:n="Invalid input";break;case h.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${L.joinValues(e.options)}`;break;case h.invalid_enum_value:n=`Invalid enum value. Expected ${L.joinValues(e.options)}, received '${e.received}'`;break;case h.invalid_arguments:n="Invalid function arguments";break;case h.invalid_return_type:n="Invalid function return type";break;case h.invalid_date:n="Invalid date";break;case h.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:L.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case h.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case h.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case h.custom:n="Invalid input";break;case h.invalid_intersection_types:n="Intersection results could not be merged";break;case h.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case h.not_finite:n="Number must be finite";break;default:n=t.defaultError,L.assertNever(e)}return{message:n}},rt=Qm;var Ec=rt;function ep(e){Ec=e}function Sn(){return Ec}var or=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}},tp=[];function _(e,t){let n=Sn(),r=or({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===rt?void 0:rt].filter(o=>!!o)});e.common.issues.push(r)}var ae=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let o of n){if(o.status==="aborted")return I;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 I;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}}},I=Object.freeze({status:"aborted"}),Kt=e=>({status:"dirty",value:e}),le=e=>({status:"valid",value:e}),no=e=>e.status==="aborted",ro=e=>e.status==="dirty",Ct=e=>e.status==="valid",wn=e=>typeof Promise<"u"&&e instanceof Promise;var C;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(C||(C={}));var Ee=class{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Ac=(e,t)=>{if(Ct(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new ye(e.common.issues);return this._error=n,this._error}}};function M(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(i,a)=>{let{message:l}=e;return i.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:o}}var N=class{get description(){return this._def.description}_getType(t){return Fe(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Fe(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ae,ctx:{common:t.parent.common,data:t.data,parsedType:Fe(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(wn(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:Fe(t)},o=this._parseSync({data:t,path:r.path,parent:r});return Ac(r,o)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Fe(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return Ct(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=>Ct(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:Fe(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(wn(o)?o:Promise.resolve(o));return Ac(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 Ae({schema:this,typeName:$.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Te.create(this,this._def)}nullable(){return qe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return it.create(this)}promise(){return Et.create(this,this._def)}or(t){return Xt.create([this,t],this._def)}and(t){return Qt.create(this,t,this._def)}transform(t){return new Ae({...M(this._def),schema:this,typeName:$.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new on({...M(this._def),innerType:this,defaultValue:n,typeName:$.ZodDefault})}brand(){return new sr({typeName:$.ZodBranded,type:this,...M(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new sn({...M(this._def),innerType:this,catchValue:n,typeName:$.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return ir.create(this,t)}readonly(){return an.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},np=/^c[^\s-]{8,}$/i,rp=/^[0-9a-z]+$/,op=/^[0-9A-HJKMNP-TV-Z]{26}$/i,sp=/^[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,ip=/^[a-z0-9_-]{21}$/i,ap=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,cp=/^[-+]?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)?)??$/,lp=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,up="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Os,dp=/^(?:(?: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])$/,mp=/^(?:(?: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]))$/,fp=/^(([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])$/,gp=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,hp=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ic="((\\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])))",yp=new RegExp(`^${Ic}$`);function $c(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 _p(e){return new RegExp(`^${$c(e)}$`)}function Pc(e){let t=`${Ic}T${$c(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 vp(e,t){return!!((t==="v4"||!t)&&dp.test(e)||(t==="v6"||!t)&&pp.test(e))}function bp(e,t){if(!ap.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 Sp(e,t){return!!((t==="v4"||!t)&&mp.test(e)||(t==="v6"||!t)&&fp.test(e))}var kt=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 _(s,{code:h.invalid_type,expected:b.string,received:s.parsedType}),I}let r=new ae,o;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),_(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),_(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?_(o,{code:h.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&_(o,{code:h.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")lp.test(t.data)||(o=this._getOrReturnCtx(t,o),_(o,{validation:"email",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Os||(Os=new RegExp(up,"u")),Os.test(t.data)||(o=this._getOrReturnCtx(t,o),_(o,{validation:"emoji",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")sp.test(t.data)||(o=this._getOrReturnCtx(t,o),_(o,{validation:"uuid",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")ip.test(t.data)||(o=this._getOrReturnCtx(t,o),_(o,{validation:"nanoid",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")np.test(t.data)||(o=this._getOrReturnCtx(t,o),_(o,{validation:"cuid",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")rp.test(t.data)||(o=this._getOrReturnCtx(t,o),_(o,{validation:"cuid2",code:h.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")op.test(t.data)||(o=this._getOrReturnCtx(t,o),_(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),_(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),_(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),_(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),_(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),_(o,{code:h.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?Pc(s).test(t.data)||(o=this._getOrReturnCtx(t,o),_(o,{code:h.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?yp.test(t.data)||(o=this._getOrReturnCtx(t,o),_(o,{code:h.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?_p(s).test(t.data)||(o=this._getOrReturnCtx(t,o),_(o,{code:h.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?cp.test(t.data)||(o=this._getOrReturnCtx(t,o),_(o,{validation:"duration",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?vp(t.data,s.version)||(o=this._getOrReturnCtx(t,o),_(o,{validation:"ip",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?bp(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),_(o,{validation:"jwt",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?Sp(t.data,s.version)||(o=this._getOrReturnCtx(t,o),_(o,{validation:"cidr",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?gp.test(t.data)||(o=this._getOrReturnCtx(t,o),_(o,{validation:"base64",code:h.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?hp.test(t.data)||(o=this._getOrReturnCtx(t,o),_(o,{validation:"base64url",code:h.invalid_string,message:s.message}),r.dirty()):L.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:h.invalid_string,...C.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...C.errToObj(t)})}url(t){return this._addCheck({kind:"url",...C.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...C.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...C.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...C.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...C.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...C.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...C.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...C.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...C.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...C.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...C.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...C.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...C.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...C.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...C.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...C.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...C.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...C.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...C.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...C.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...C.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...C.errToObj(n)})}nonempty(t){return this.min(1,C.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};kt.create=e=>new kt({checks:[],typeName:$.ZodString,coerce:e?.coerce??!1,...M(e)});function wp(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 Gt=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 _(s,{code:h.invalid_type,expected:b.number,received:s.parsedType}),I}let r,o=new ae;for(let s of this._def.checks)s.kind==="int"?L.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),_(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),_(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),_(r,{code:h.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?wp(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),_(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),_(r,{code:h.not_finite,message:s.message}),o.dirty()):L.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,C.toString(n))}gt(t,n){return this.setLimit("min",t,!1,C.toString(n))}lte(t,n){return this.setLimit("max",t,!0,C.toString(n))}lt(t,n){return this.setLimit("max",t,!1,C.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:C.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:C.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:C.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:C.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:C.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:C.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:C.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:C.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:C.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:C.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&L.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};Gt.create=e=>new Gt({checks:[],typeName:$.ZodNumber,coerce:e?.coerce||!1,...M(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 ae;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),_(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),_(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),_(r,{code:h.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):L.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return _(n,{code:h.invalid_type,expected:b.bigint,received:n.parsedType}),I}gte(t,n){return this.setLimit("min",t,!0,C.toString(n))}gt(t,n){return this.setLimit("min",t,!1,C.toString(n))}lte(t,n){return this.setLimit("max",t,!0,C.toString(n))}lt(t,n){return this.setLimit("max",t,!1,C.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:C.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:C.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:C.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:C.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:C.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:C.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};zt.create=e=>new zt({checks:[],typeName:$.ZodBigInt,coerce:e?.coerce??!1,...M(e)});var Wt=class extends N{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==b.boolean){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:b.boolean,received:r.parsedType}),I}return le(t.data)}};Wt.create=e=>new Wt({typeName:$.ZodBoolean,coerce:e?.coerce||!1,...M(e)});var Jt=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 _(s,{code:h.invalid_type,expected:b.date,received:s.parsedType}),I}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return _(s,{code:h.invalid_date}),I}let r=new ae,o;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),_(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),_(o,{code:h.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):L.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:C.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:C.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};Jt.create=e=>new Jt({checks:[],coerce:e?.coerce||!1,typeName:$.ZodDate,...M(e)});var Cn=class extends N{_parse(t){if(this._getType(t)!==b.symbol){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:b.symbol,received:r.parsedType}),I}return le(t.data)}};Cn.create=e=>new Cn({typeName:$.ZodSymbol,...M(e)});var Yt=class extends N{_parse(t){if(this._getType(t)!==b.undefined){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:b.undefined,received:r.parsedType}),I}return le(t.data)}};Yt.create=e=>new Yt({typeName:$.ZodUndefined,...M(e)});var Zt=class extends N{_parse(t){if(this._getType(t)!==b.null){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:b.null,received:r.parsedType}),I}return le(t.data)}};Zt.create=e=>new Zt({typeName:$.ZodNull,...M(e)});var Tt=class extends N{constructor(){super(...arguments),this._any=!0}_parse(t){return le(t.data)}};Tt.create=e=>new Tt({typeName:$.ZodAny,...M(e)});var st=class extends N{constructor(){super(...arguments),this._unknown=!0}_parse(t){return le(t.data)}};st.create=e=>new st({typeName:$.ZodUnknown,...M(e)});var $e=class extends N{_parse(t){let n=this._getOrReturnCtx(t);return _(n,{code:h.invalid_type,expected:b.never,received:n.parsedType}),I}};$e.create=e=>new $e({typeName:$.ZodNever,...M(e)});var kn=class extends N{_parse(t){if(this._getType(t)!==b.undefined){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:b.void,received:r.parsedType}),I}return le(t.data)}};kn.create=e=>new kn({typeName:$.ZodVoid,...M(e)});var it=class e extends N{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==b.array)return _(n,{code:h.invalid_type,expected:b.array,received:n.parsedType}),I;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(_(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&&(_(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&&(_(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 Ee(n,i,n.path,a)))).then(i=>ae.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new Ee(n,i,n.path,a)));return ae.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:C.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:C.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:C.toString(n)}})}nonempty(t){return this.min(1,t)}};it.create=(e,t)=>new it({type:e,minLength:null,maxLength:null,exactLength:null,typeName:$.ZodArray,...M(t)});function xn(e){if(e instanceof _e){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Te.create(xn(r))}return new _e({...e._def,shape:()=>t})}else return e instanceof it?new it({...e._def,type:xn(e.element)}):e instanceof Te?Te.create(xn(e.unwrap())):e instanceof qe?qe.create(xn(e.unwrap())):e instanceof Ve?Ve.create(e.items.map(t=>xn(t))):e}var _e=class e extends N{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=L.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==b.object){let c=this._getOrReturnCtx(t);return _(c,{code:h.invalid_type,expected:b.object,received:c.parsedType}),I}let{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof $e&&this._def.unknownKeys==="strip"))for(let c in o.data)i.includes(c)||a.push(c);let l=[];for(let c of i){let u=s[c],d=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Ee(o,d,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof $e){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&&(_(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 Ee(o,d,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of l){let d=await u.key,g=await u.value;c.push({key:d,value:g,alwaysSet:u.alwaysSet})}return c}).then(c=>ae.mergeObjectSync(r,c)):ae.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return C.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:C.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:$.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of L.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let r of L.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return xn(this)}partial(t){let n={};for(let r of L.objectKeys(this.shape)){let o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let r of L.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Te;)s=s._def.innerType;n[r]=s}return new e({...this._def,shape:()=>n})}keyof(){return Mc(L.objectKeys(this.shape))}};_e.create=(e,t)=>new _e({shape:()=>e,unknownKeys:"strip",catchall:$e.create(),typeName:$.ZodObject,...M(t)});_e.strictCreate=(e,t)=>new _e({shape:()=>e,unknownKeys:"strict",catchall:$e.create(),typeName:$.ZodObject,...M(t)});_e.lazycreate=(e,t)=>new _e({shape:e,unknownKeys:"strip",catchall:$e.create(),typeName:$.ZodObject,...M(t)});var Xt=class extends N{_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new ye(a.ctx.common.issues));return _(n,{code:h.invalid_union,unionErrors:i}),I}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let l of r){let c={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(l=>new ye(l));return _(n,{code:h.invalid_union,unionErrors:a}),I}}get options(){return this._def.options}};Xt.create=(e,t)=>new Xt({options:e,typeName:$.ZodUnion,...M(t)});var ot=e=>e instanceof en?ot(e.schema):e instanceof Ae?ot(e.innerType()):e instanceof tn?[e.value]:e instanceof nn?e.options:e instanceof rn?L.objectValues(e.enum):e instanceof on?ot(e._def.innerType):e instanceof Yt?[void 0]:e instanceof Zt?[null]:e instanceof Te?[void 0,...ot(e.unwrap())]:e instanceof qe?[null,...ot(e.unwrap())]:e instanceof sr||e instanceof an?ot(e.unwrap()):e instanceof sn?ot(e._def.innerType):[],oo=class e extends N{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.object)return _(n,{code:h.invalid_type,expected:b.object,received:n.parsedType}),I;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}):(_(n,{code:h.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),I)}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=ot(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:$.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...M(r)})}};function Ns(e,t){let n=Fe(e),r=Fe(t);if(e===t)return{valid:!0,data:e};if(n===b.object&&r===b.object){let o=L.objectKeys(t),s=L.objectKeys(e).filter(a=>o.indexOf(a)!==-1),i={...e,...t};for(let a of s){let l=Ns(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=Ns(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 Qt=class extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=(s,i)=>{if(no(s)||no(i))return I;let a=Ns(s.value,i.value);return a.valid?((ro(s)||ro(i))&&n.dirty(),{status:n.value,value:a.data}):(_(r,{code:h.invalid_intersection_types}),I)};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}))}};Qt.create=(e,t,n)=>new Qt({left:e,right:t,typeName:$.ZodIntersection,...M(n)});var Ve=class e extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.array)return _(r,{code:h.invalid_type,expected:b.array,received:r.parsedType}),I;if(r.data.length<this._def.items.length)return _(r,{code:h.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),I;!this._def.rest&&r.data.length>this._def.items.length&&(_(r,{code:h.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Ee(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>ae.mergeArray(n,i)):ae.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ve.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ve({items:e,typeName:$.ZodTuple,rest:null,...M(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 _(r,{code:h.invalid_type,expected:b.object,received:r.parsedType}),I;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new Ee(r,a,r.path,a)),value:i._parse(new Ee(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?ae.mergeObjectAsync(n,o):ae.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof N?new e({keyType:t,valueType:n,typeName:$.ZodRecord,...M(r)}):new e({keyType:kt.create(),valueType:t,typeName:$.ZodRecord,...M(n)})}},Tn=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 _(r,{code:h.invalid_type,expected:b.map,received:r.parsedType}),I;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,l],c)=>({key:o._parse(new Ee(r,a,r.path,[c,"key"])),value:s._parse(new Ee(r,l,r.path,[c,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of i){let c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return I;(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 I;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}}}};Tn.create=(e,t,n)=>new Tn({valueType:t,keyType:e,typeName:$.ZodMap,...M(n)});var En=class e extends N{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==b.set)return _(r,{code:h.invalid_type,expected:b.set,received:r.parsedType}),I;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(_(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&&(_(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 I;u.status==="dirty"&&n.dirty(),c.add(u.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((l,c)=>s._parse(new Ee(r,l,r.path,c)));return r.common.async?Promise.all(a).then(l=>i(l)):i(a)}min(t,n){return new e({...this._def,minSize:{value:t,message:C.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:C.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};En.create=(e,t)=>new En({valueType:e,minSize:null,maxSize:null,typeName:$.ZodSet,...M(t)});var io=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 _(n,{code:h.invalid_type,expected:b.function,received:n.parsedType}),I;function r(a,l){return or({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Sn(),rt].filter(c=>!!c),issueData:{code:h.invalid_arguments,argumentsError:l}})}function o(a,l){return or({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Sn(),rt].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 Et){let a=this;return le(async function(...l){let c=new ye([]),u=await a._def.args.parseAsync(l,s).catch(p=>{throw c.addIssue(r(l,p)),c}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,s).catch(p=>{throw c.addIssue(o(d,p)),c})})}else{let a=this;return le(function(...l){let c=a._def.args.safeParse(l,s);if(!c.success)throw new ye([r(l,c.error)]);let u=Reflect.apply(i,this,c.data),d=a._def.returns.safeParse(u,s);if(!d.success)throw new ye([o(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Ve.create(t).rest(st.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||Ve.create([]).rest(st.create()),returns:n||st.create(),typeName:$.ZodFunction,...M(r)})}},en=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})}};en.create=(e,t)=>new en({getter:e,typeName:$.ZodLazy,...M(t)});var tn=class extends N{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return _(n,{received:n.data,code:h.invalid_literal,expected:this._def.value}),I}return{status:"valid",value:t.data}}get value(){return this._def.value}};tn.create=(e,t)=>new tn({value:e,typeName:$.ZodLiteral,...M(t)});function Mc(e,t){return new nn({values:e,typeName:$.ZodEnum,...M(t)})}var nn=class e extends N{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return _(n,{expected:L.joinValues(r),received:n.parsedType,code:h.invalid_type}),I}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return _(n,{received:n.data,code:h.invalid_enum_value,options:r}),I}return le(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};nn.create=Mc;var rn=class extends N{_parse(t){let n=L.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==b.string&&r.parsedType!==b.number){let o=L.objectValues(n);return _(r,{expected:L.joinValues(o),received:r.parsedType,code:h.invalid_type}),I}if(this._cache||(this._cache=new Set(L.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let o=L.objectValues(n);return _(r,{received:r.data,code:h.invalid_enum_value,options:o}),I}return le(t.data)}get enum(){return this._def.values}};rn.create=(e,t)=>new rn({values:e,typeName:$.ZodNativeEnum,...M(t)});var Et=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 _(n,{code:h.invalid_type,expected:b.promise,received:n.parsedType}),I;let r=n.parsedType===b.promise?n.data:Promise.resolve(n.data);return le(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Et.create=(e,t)=>new Et({type:e,typeName:$.ZodPromise,...M(t)});var Ae=class extends N{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===$.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=>{_(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 I;let l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?I:l.status==="dirty"?Kt(l.value):n.value==="dirty"?Kt(l.value):l});{if(n.value==="aborted")return I;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?I:a.status==="dirty"?Kt(a.value):n.value==="dirty"?Kt(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"?I:(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"?I:(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(!Ct(i))return I;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=>Ct(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):I);L.assertNever(o)}};Ae.create=(e,t,n)=>new Ae({schema:e,typeName:$.ZodEffects,effect:t,...M(n)});Ae.createWithPreprocess=(e,t,n)=>new Ae({schema:t,effect:{type:"preprocess",transform:e},typeName:$.ZodEffects,...M(n)});var Te=class extends N{_parse(t){return this._getType(t)===b.undefined?le(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Te.create=(e,t)=>new Te({innerType:e,typeName:$.ZodOptional,...M(t)});var qe=class extends N{_parse(t){return this._getType(t)===b.null?le(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};qe.create=(e,t)=>new qe({innerType:e,typeName:$.ZodNullable,...M(t)});var on=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}};on.create=(e,t)=>new on({innerType:e,typeName:$.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...M(t)});var sn=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 wn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ye(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ye(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};sn.create=(e,t)=>new sn({innerType:e,typeName:$.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...M(t)});var An=class extends N{_parse(t){if(this._getType(t)!==b.nan){let r=this._getOrReturnCtx(t);return _(r,{code:h.invalid_type,expected:b.nan,received:r.parsedType}),I}return{status:"valid",value:t.data}}};An.create=e=>new An({typeName:$.ZodNaN,...M(e)});var xp=Symbol("zod_brand"),sr=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}},ir=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"?I:s.status==="dirty"?(n.dirty(),Kt(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"?I: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:$.ZodPipeline})}},an=class extends N{_parse(t){let n=this._def.innerType._parse(t),r=o=>(Ct(o)&&(o.value=Object.freeze(o.value)),o);return wn(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};an.create=(e,t)=>new an({innerType:e,typeName:$.ZodReadonly,...M(t)});function Rc(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Oc(e,t={},n){return e?Tt.create().superRefine((r,o)=>{let s=e(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Rc(t,r),l=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:l})}});if(!s){let i=Rc(t,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Tt.create()}var Cp={object:_e.lazycreate},$;(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"})($||($={}));var kp=(e,t={message:`Input not instance of ${e.name}`})=>Oc(n=>n instanceof e,t),Nc=kt.create,Lc=Gt.create,Tp=An.create,Ep=zt.create,Dc=Wt.create,Ap=Jt.create,Rp=Cn.create,Ip=Yt.create,$p=Zt.create,Pp=Tt.create,Mp=st.create,Op=$e.create,Np=kn.create,Lp=it.create,Dp=_e.create,Up=_e.strictCreate,jp=Xt.create,Fp=oo.create,Vp=Qt.create,qp=Ve.create,Hp=so.create,Bp=Tn.create,Kp=En.create,Gp=io.create,zp=en.create,Wp=tn.create,Jp=nn.create,Yp=rn.create,Zp=Et.create,Xp=Ae.create,Qp=Te.create,ef=qe.create,tf=Ae.createWithPreprocess,nf=ir.create,rf=()=>Nc().optional(),of=()=>Lc().optional(),sf=()=>Dc().optional(),af={string:(e=>kt.create({...e,coerce:!0})),number:(e=>Gt.create({...e,coerce:!0})),boolean:(e=>Wt.create({...e,coerce:!0})),bigint:(e=>zt.create({...e,coerce:!0})),date:(e=>Jt.create({...e,coerce:!0}))};var cf=I;var Uc=["tempo","mpp_self","merchant_self"];var Ds=f.object({inputPerMillion:f.number().positive(),outputPerMillion:f.number().positive(),contextWindow:f.number().int().positive().optional(),maxOutput:f.number().int().positive().optional(),perRequestFeeCents:f.number().nonnegative().optional()}),lf=f.object({strategy:f.enum(["flat","token","band"]).optional(),pricingModel:f.enum(["per-call","per-token","band"]).optional(),priceCents:f.number().nonnegative().optional(),currency:f.string().optional(),display:f.string().optional(),estimate:f.boolean().optional(),source:f.string().optional(),priceBand:f.record(f.unknown()).optional(),tokenPricing:Ds.optional()}).passthrough(),Us=f.discriminatedUnion("type",[f.object({type:f.literal("shortcut"),routedPath:f.string().min(1).startsWith("/")}),f.object({type:f.literal("custom"),merchantSlug:f.string().min(1),subPath:f.string().optional()}),f.object({type:f.literal("local"),fn:f.string().min(1)}),f.object({type:f.literal("read")})]),js=f.object({amount:f.number().nonnegative(),currency:f.string().length(3).optional(),display:f.string().optional(),free:f.boolean().optional(),batchDiscount:f.number().min(0).max(100).optional()}),jc=f.object({attestation:f.boolean().optional(),rateLimitMs:f.number().positive().optional()}),Fc=f.object({displayName:f.string().optional(),feedbackEligible:f.boolean().optional(),suggestionEligible:f.boolean().optional(),batchable:f.boolean().optional()}),uf=f.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),df=120,mf=120,pf=1200,ff=/^[^\u0000-\u001F\u007F]+$/;function Ls(e,t){return f.string().min(1).max(e).regex(ff,`${t} must not contain control characters`)}var Fs={id:f.string().min(1),name:Ls(df,"name"),description:Ls(pf,"description"),provider:f.string().min(1),model:f.string().min(1),category:uf,priceCents:f.number().nonnegative(),inputSchema:f.record(f.unknown()),gatewayUrl:f.string().min(1),merchantName:Ls(mf,"merchantName"),isAsync:f.boolean().optional(),pollUrl:f.string().optional(),pollInterval:f.number().positive().optional(),pollTimeout:f.number().positive().optional(),tags:f.array(f.string()).optional(),tokenPricing:Ds.optional(),priceDisplay:f.string().optional(),pricingModel:f.enum(["per-call","per-token","band"]).optional(),pricingInfo:lf.optional(),status:f.enum(["available","unavailable"]).optional(),handler:Us.optional(),pricing:js.optional(),security:jc.optional(),engagement:Fc.optional(),enabled:f.boolean().optional(),beta:f.boolean().optional(),deprecated:f.boolean().optional(),replacementTool:f.string().optional(),minCliVersion:f.string().optional(),sunsetAt:f.string().optional(),rail:f.enum(Uc).optional(),pricingStrategy:f.enum(["flat","token","band"]).optional()},Vc=f.object({...Fs,dispatch:f.literal("routed"),routedPath:f.string().min(1).startsWith("/")}).strict(),qc=f.object({...Fs,dispatch:f.literal("enveloped")}).strict(),Hc=f.object({...Fs,handler:Us,pricing:js}).strict(),Bc=f.union([f.discriminatedUnion("dispatch",[Vc,qc]),Hc]);var Vs=/^[a-z0-9][a-z0-9_-]*$/;var hf="https://fal.run",Wc="https://openrouter.mpp.tempo.xyz";function yf(e){let{attestation:t,tool_id:n,...r}=e;return r}var Kc={"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 ao(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"&&Kc[r]&&(i.image_size=Kc[r]),i)}function Gc(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 _f(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 vf(e,t,n,r,o,s,i,a){return _f(e,t,n,"suno-ai",r,o,s,i,{merchantName:"Suno AI",...a})}function X(e,t,n,r,o,s,i,a){return{dispatch:"routed",id:e,name:t,description:n,provider:"fal",model:r,category:o,priceCents:s,inputSchema:i,routedPath:`/api/v1/fal/${r}`,gatewayUrl:`${hf}/${r}`,merchantName:"fal.ai",buildBody:yf,tags:[],...a}}function bf(e){return t=>{let{attestation:n,tool_id:r,prompt:o,system_prompt:s,max_tokens:i,temperature:a,...l}=t;return{model:e,messages:[...s?[{role:"system",content:s}]:[],{role:"user",content:o}],max_tokens:i??1024,temperature:a??.7,...l}}}function Sf(e){return t=>{let{attestation:n,tool_id:r,prompt:o,image_url:s,aspect_ratio:i,max_tokens:a,temperature:l,...c}=t,u=[{type:"text",text:o}];return typeof s=="string"&&s.length>0&&u.push({type:"image_url",image_url:{url:s}}),{model:e,messages:[{role:"user",content:u}],max_tokens:a??1024,temperature:l??.7,...typeof i=="string"&&i.length>0?{image_config:{aspect_ratio:i}}:{},...c}}}function ee(e,t,n,r,o,s,i){let a=i?.perRequestFeeCents??0,l=500/1e6*o*100,c=500/1e6*s*100,u=Math.max(1,Math.ceil(l+c+a)),{perRequestFeeCents:d,...g}=i??{};return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"llm",priceCents:u,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The prompt or question to send to the model"},system_prompt:{type:"string",description:"Optional system prompt to set model behavior"},max_tokens:{type:"integer",description:"Maximum tokens in response (default: 1024)",minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${Wc}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:bf(r),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:o,outputPerMillion:s,...a>0?{perRequestFeeCents:a}:{}},...g}}function qs(e,t,n,r,o,s){return{dispatch:"routed",id:e,name:t,description:n,provider:"openrouter",model:r,category:"image",priceCents:o,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate or edit"},image_url:{type:"string",description:"Optional source image URL for edits"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"1:1"},max_tokens:{type:"integer",description:"Maximum text tokens in response metadata (default: 1024)",minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${Wc}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:Sf(r),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...s}}var Hs=[X("fal-flux-pro-ultra","FLUX Pro Ultra","Highest quality image generation. Best for detailed, photorealistic images.","fal-ai/flux-pro/v1.1-ultra","image",6,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},{tags:["image","flux","photorealistic","high-quality"]}),X("fal-flux-pro","FLUX Pro","Fast, high-quality image generation. Good balance of speed and quality.","fal-ai/flux-pro/v1.1","image",4,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},{tags:["image","flux","fast"],buildBody:ao}),X("fal-flux-dev","FLUX Dev","Open-source image generation. Cheaper, good for experimentation.","fal-ai/flux/dev","image",3,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["image","flux","open-source","cheap"],buildBody:ao}),X("fal-flux-schnell","FLUX Schnell","Fastest image generation. Ultra-cheap, great for drafts and iteration.","fal-ai/flux/schnell","image",1,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["image","flux","fast","cheap","draft"],buildBody:ao}),X("fal-recraft-v3","Recraft V3","Design-focused image generation. Great for illustrations, icons, and graphic design.","fal-ai/recraft/v3/text-to-image","image",5,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},style:{type:"string",description:"Style preset: realistic_image, digital_illustration, vector_illustration, icon"}},required:["prompt"]},{tags:["image","design","illustration","icon","vector"]}),qs("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),qs("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}}),qs("or-gemini-nano-banana-pro","Nano Banana Pro","Google Gemini 3 Pro Image Preview via OpenRouter for professional image generation, edits, and text rendering.","google/gemini-3-pro-image-preview",8,{tags:["image","gemini","google","nano-banana","pro","text-rendering"],tokenPricing:{inputPerMillion:2,outputPerMillion:12}}),X("fal-ideogram-v2","Ideogram V2","Excellent text rendering in images. Best for logos, posters, and text-heavy visuals.","fal-ai/ideogram/v2","image",8,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"1:1"}},required:["prompt"]},{tags:["image","text-rendering","logo","poster","typography"]}),X("fal-ideogram-v2-turbo","Ideogram V2 Turbo","Fast text rendering in images. Good balance of speed and text accuracy.","fal-ai/ideogram/v2/turbo","image",5,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"1:1"}},required:["prompt"]},{tags:["image","text-rendering","fast"]}),X("fal-fast-sdxl","Fast SDXL","Ultra-fast Stable Diffusion. 4-step inference, cheapest option.","fal-ai/fast-sdxl","image",1,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"}},required:["prompt"]},{tags:["image","stable-diffusion","fast","cheap"]}),X("fal-wan-video","Wan Video","Text-to-video generation. Create short video clips from text descriptions.","fal-ai/wan/v2.1/1.3b/text-to-video","video",10,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"},num_frames:{type:"number",description:"Number of frames (default: 81)"}},required:["prompt"]},{tags:["video","text-to-video","wan"]}),X("fal-minimax-video","MiniMax Video","High-quality video generation with excellent motion and coherence.","fal-ai/minimax-video/video-01-live","video",15,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"}},required:["prompt"]},{tags:["video","text-to-video","high-quality"]}),X("fal-kling-video","Kling Video","Professional video generation with cinematic quality.","fal-ai/kling-video/v2/master/text-to-video","video",20,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"},duration:{type:"string",description:"Duration: 5 or 10 seconds",default:"5"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["video","text-to-video","cinematic","professional"]}),X("fal-kling-i2v","Kling Image-to-Video","Animate a still image into a 5\u201310s video clip. Cinematic motion quality.","fal-ai/kling-video/v1.6/standard/image-to-video","video",35,{type:"object",properties:{image_url:{type:"string",description:"URL of the source image (jpg, png, webp, gif, avif)"},prompt:{type:"string",description:"Text description of the motion to animate"},duration:{type:"string",description:"Duration: 5 or 10 seconds",default:"5"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 9:16, 1:1)",default:"16:9"},negative_prompt:{type:"string",description:"Elements to avoid in the generated motion"},cfg_scale:{type:"number",description:"Classifier-free guidance (default 0.5)",default:.5}},required:["image_url","prompt"]},{tags:["video","image-to-video","kling","cinematic"]}),X("fal-stable-audio","Stable Audio","Generate sound effects and ambient audio from text descriptions.","fal-ai/stable-audio","audio",4,{type:"object",properties:{prompt:{type:"string",description:"Description of the audio to generate"},seconds_total:{type:"number",description:"Duration in seconds (max 47)",default:30}},required:["prompt"]},{tags:["audio","sound-effects","ambient"]}),X("fal-ace-step-music","ACE-Step Music","Generate full music tracks from a prompt, with optional vocals or instrumentals.","fal-ai/ace-step/prompt-to-audio","audio",2,{type:"object",properties:{prompt:{type:"string",description:"Description of the song, genre, mood, instruments, and lyrics direction"},instrumental:{type:"boolean",description:"Generate instrumental music without vocals",default:!1},duration:{type:"number",description:"Duration in seconds",default:60}},required:["prompt"]},{tags:["music","song","vocals","instrumental","ace-step"]}),vf("suno-music","Suno Music","AI music generation. Create full songs with vocals or instrumentals.","/suno/generate-music","audio",10,{type:"object",properties:{prompt:{type:"string",description:"Description of the song (genre, mood, instruments)"},instrumental:{type:"boolean",description:"Instrumental only, no vocals",default:!1}},required:["prompt"]},{isAsync:!0,pollUrl:"https://api.sunoapi.org/suno/get-music-status",deprecated:!0,tags:["music","song","vocals","instrumental"],buildBody:e=>{let{attestation:t,tool_id:n,prompt:r,instrumental:o,...s}=e;return{prompt:r,customMode:!1,instrumental:typeof o=="boolean"?o:!1,model:"V4",...s}}}),X("fal-trellis-3d","Trellis 3D","Generate 3D models from images. Upload a photo, get a 3D asset.","fal-ai/trellis","3d",8,{type:"object",properties:{image_url:{type:"string",description:"URL of the image to convert to 3D"}},required:["image_url"]},{tags:["3d","model","image-to-3d"]}),X("fal-aura-sr","Aura SR","Upscale images to higher resolution. 4x upscaling with detail enhancement.","fal-ai/aura-sr","upscale",3,{type:"object",properties:{image_url:{type:"string",description:"URL of the image to upscale"}},required:["image_url"]},{tags:["upscale","super-resolution","enhance"]}),X("fal-metavoice","MetaVoice Voice Cloning","Voice cloning TTS \u2014 clone any voice from an audio sample. Provide text and a voice sample URL.","fal-ai/metavoice-v1","tts",3,{type:"object",properties:{text:{type:"string",description:"Text to convert to speech"},audio_url:{type:"string",description:"URL of the voice sample to clone"}},required:["text","audio_url"]},{tags:["tts","voice","voice-cloning","speech"]}),X("fal-whisper","Whisper Transcription","Transcribe audio to text. Supports multiple languages.","fal-ai/whisper","transcription",2,{type:"object",properties:{audio_url:{type:"string",description:"URL of the audio to transcribe"},language:{type:"string",description:"Language code (e.g. en, es, fr)"}},required:["audio_url"]},{tags:["transcription","speech-to-text","whisper"]}),ee("or-gpt-4o","GPT-4o","OpenAI's flagship multimodal model. Best for complex reasoning and analysis.","openai/gpt-4o",2.5,10,{tags:["llm","gpt","openai","multimodal","reasoning"]}),ee("or-gpt-4o-mini","GPT-4o Mini","Fast, affordable GPT-4o. Great for everyday tasks, chat, and simple analysis.","openai/gpt-4o-mini",.15,.6,{tags:["llm","gpt","openai","fast","cheap"]}),ee("or-claude-opus","Claude Opus 4.7","Anthropic's most capable model. 1M context, reasoning, best for complex tasks.","anthropic/claude-opus-4.7",15,75,{tags:["llm","claude","anthropic","reasoning","coding"]}),ee("or-claude-sonnet","Claude Sonnet 4.6","Anthropic's best balance of intelligence and speed. Excellent for coding and analysis.","anthropic/claude-sonnet-4.6",3,15,{tags:["llm","claude","anthropic","coding","analysis"]}),ee("or-claude-opus-fast","Claude Opus 4.6 Fast","Fast Opus variant with lower latency.","anthropic/claude-opus-4.6-fast",15,75,{tags:["llm","claude","anthropic","fast"]}),ee("or-claude-haiku","Claude 3.5 Haiku","Anthropic's fastest model. Great for quick tasks, chat, and simple reasoning.","anthropic/claude-3.5-haiku",.8,4,{tags:["llm","claude","anthropic","fast"]}),ee("or-gemini-pro","Gemini 2.0 Flash","Google's fast multimodal model. Good for general tasks with long context.","google/gemini-2.0-flash-001",.1,.4,{tags:["llm","gemini","google","multimodal","fast","cheap"]}),ee("or-gemini-3-flash","Gemini 3 Flash","Google's high-speed thinking model for agentic workflows, coding, and multimodal tasks.","google/gemini-3-flash-preview",.5,3,{tags:["llm","gemini","google","agentic","coding","fast"]}),ee("or-gemini-3-pro","Gemini 3 Pro","Google's flagship frontier model for deep reasoning, multimodal analysis, and agentic coding.","google/gemini-3-pro-preview",2,12,{tags:["llm","gemini","google","reasoning","coding","multimodal"]}),ee("or-gemini-3-lite","Gemini 3.1 Flash Lite","Google's efficient multimodal model optimized for low-latency, high-volume agent workloads.","google/gemini-3.1-flash-lite",.25,1.5,{tags:["llm","gemini","google","fast","cheap","multimodal"]}),ee("or-llama-70b","Llama 3.3 70B","Meta's best open model. Strong reasoning, fully open-source.","meta-llama/llama-3.3-70b-instruct",.3,.4,{tags:["llm","llama","meta","open-source","reasoning"]}),ee("or-llama-8b","Llama 3.1 8B","Fast, lightweight open model. Great for simple tasks at minimal cost.","meta-llama/llama-3.1-8b-instruct",.05,.08,{tags:["llm","llama","meta","open-source","fast","cheap"]}),ee("or-mistral-large","Mistral Large","Mistral's flagship model. Strong at multilingual and European languages.","mistralai/mistral-large-2411",2,6,{tags:["llm","mistral","multilingual","european"]}),ee("or-mistral-small","Mistral Small","Fast, efficient Mistral model. Good for everyday tasks.","mistralai/mistral-small-3.1-24b-instruct",.1,.3,{tags:["llm","mistral","fast","cheap"]}),ee("or-deepseek-chat","DeepSeek Chat V3","Strong reasoning model at very low cost. Excellent for coding and math.","deepseek/deepseek-chat-v3-0324",.3,.88,{tags:["llm","deepseek","coding","math","cheap","reasoning"]}),ee("or-deepseek-r1","DeepSeek R1","Advanced reasoning model with chain-of-thought. Best for complex problems.","deepseek/deepseek-r1",.55,2.19,{tags:["llm","deepseek","reasoning","chain-of-thought","math"]}),ee("or-qwen-72b","Qwen 2.5 72B","Alibaba's large model. Strong at coding, math, and multilingual tasks.","qwen/qwen-2.5-72b-instruct",.3,.4,{tags:["llm","qwen","alibaba","coding","multilingual"]}),ee("or-phi-4","Phi-4","Microsoft's compact reasoning model. Punches above its weight for size.","microsoft/phi-4",.07,.14,{tags:["llm","phi","microsoft","compact","cheap","reasoning"]}),ee("or-perplexity-sonar","Perplexity Sonar","Search-augmented LLM. Answers with real-time web sources and citations.","perplexity/sonar",1,1,{perRequestFeeCents:.5,tags:["llm","perplexity","search","web","citations","real-time"]}),{dispatch:"enveloped",id:"query_onchain_prices",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly and daily granularity.",provider:"allium",model:"allium-prices",category:"onchain",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly) or '1d' (daily). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:Gc,tags:["onchain","prices","allium","crypto"]},{dispatch:"enveloped",id:"generate_image_card",name:"Generate Image (Ultra)",description:"Generate a high-quality AI image (FLUX Pro Ultra, 2K, ~$0.06).",provider:"fal",model:"fal-ai/flux-pro/v1.1-ultra",category:"image",priceCents:6,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1-ultra",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro-ultra",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),t},tags:["image","flux","ultra","legacy"]},{dispatch:"enveloped",id:"generate_image_fast_card",name:"Generate Image (Fast)",description:"Generate an AI image (FLUX Pro v1.1, 1K, ~$0.04).",provider:"fal",model:"fal-ai/flux-pro/v1.1",category:"image",priceCents:4,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro",buildBody:e=>ao({prompt:e.prompt,aspect_ratio:e.aspect_ratio}),tags:["image","flux","legacy"]},{dispatch:"enveloped",id:"generate_image_schnell_card",name:"Generate Image (Cheap)",description:"Cheap, fast FLUX image generation (~$0.01).",provider:"fal",model:"fal-ai/flux/schnell",category:"image",priceCents:1,inputSchema:{type:"object",properties:{prompt:{type:"string"},image_size:{type:"string"},num_inference_steps:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux/schnell",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-schnell",buildBody:e=>{let t={prompt:e.prompt};return e.image_size&&(t.image_size=e.image_size),e.num_inference_steps!==void 0&&(t.num_inference_steps=e.num_inference_steps),e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","flux","schnell","legacy"]},{dispatch:"enveloped",id:"generate_image_recraft_card",name:"Generate Image (Recraft)",description:"Recraft V3 image generation with style control.",provider:"fal",model:"fal-ai/recraft-v3",category:"image",priceCents:5,inputSchema:{type:"object",properties:{prompt:{type:"string"},style:{type:"string"},image_size:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/recraft-v3",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-recraft-v3",buildBody:e=>{let t={prompt:e.prompt};return e.style&&(t.style=e.style),e.image_size&&(t.image_size=e.image_size),t},tags:["image","recraft","legacy"]},{dispatch:"enveloped",id:"generate_image_ideogram_card",name:"Generate Image (Ideogram)",description:"Ideogram V2 image generation, strong with text rendering.",provider:"fal",model:"fal-ai/ideogram/v2",category:"image",priceCents:8,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},style_type:{type:"string"},negative_prompt:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/ideogram/v2",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-ideogram-v2",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.style_type&&(t.style_type=e.style_type),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),t},tags:["image","ideogram","text","legacy"]},X("upscale_image_card","Upscale Image","Upscale an image using ESRGAN.","fal-ai/esrgan","upscale",2,{type:"object",properties:{image_url:{type:"string"},scale:{type:"number"}},required:["image_url"]},{buildBody:e=>{let t={image_url:e.image_url};return e.scale!==void 0&&(t.scale=e.scale),t},tags:["upscale","esrgan"],deprecated:!0,replacementTool:"fal-aura-sr"}),X("edit_image_seed_card","Edit Image (SeedEdit)","Inpaint/edit an image with a prompt using SeedEdit.","fal-ai/bytedance/seededit","image",5,{type:"object",properties:{image_url:{type:"string"},prompt:{type:"string"},seed:{type:"number"}},required:["image_url","prompt"]},{buildBody:e=>{let t={image_url:e.image_url,prompt:e.prompt};return e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","edit","inpaint","seededit"],deprecated:!0,replacementTool:"or-gemini-nano-banana"}),{dispatch:"enveloped",id:"generate_video_tempo_card",name:"Generate Video (Grok)",description:"Generate a video from a text prompt using Grok Imagine Video.",provider:"fal",model:"xai/grok-imagine-video/text-to-video",category:"video",priceCents:30,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/xai/grok-imagine-video/text-to-video",merchantName:"Grok Video via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),t},tags:["video","grok","legacy"]},{dispatch:"enveloped",id:"generate_video_kling_card",name:"Generate Video (Kling)",description:"Generate a video using Kling v1.6 (async, ~$0.40).",provider:"fal",model:"fal-ai/kling-video/v1.6/standard/text-to-video",category:"video",priceCents:40,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/kling-video/v1.6/standard/text-to-video",merchantName:"Kling via fal.ai",deprecated:!0,replacementTool:"fal-kling-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","kling","legacy"]},{dispatch:"enveloped",id:"generate_video_wan_card",name:"Generate Video (Wan)",description:"Generate a video using Wan T2V (async, ~$0.25).",provider:"fal",model:"fal-ai/wan/t2v-1.3b",category:"video",priceCents:25,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/wan/t2v-1.3b",merchantName:"Wan T2V via fal.ai",deprecated:!0,replacementTool:"fal-wan-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","wan","legacy"]},{dispatch:"enveloped",id:"generate_video_minimax_card",name:"Generate Video (MiniMax)",description:"Generate a video using MiniMax (async, ~$0.35).",provider:"fal",model:"fal-ai/minimax/video-01",category:"video",priceCents:35,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/minimax/video-01",merchantName:"MiniMax via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","minimax","legacy"]},{dispatch:"enveloped",id:"check_fal_status_card",name:"Check fal Async Job Status",description:"Poll an async fal.ai queue job for completion.",provider:"fal",model:"queue-status",category:"image",priceCents:0,inputSchema:{type:"object",properties:{model_path:{type:"string",description:"Model path (e.g. fal-ai/kling-video/v1.6/standard/text-to-video)"},request_id:{type:"string"}},required:["model_path","request_id"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue",merchantName:"fal.ai",buildUrl:e=>`https://fal.mpp.tempo.xyz/queue/${e.model_path}/requests/${e.request_id}`,buildBody:()=>({}),tags:["status","fal","async","legacy"]},{dispatch:"enveloped",id:"generate_3d_card",name:"Generate 3D Model",description:"Generate a 3D mesh from a text prompt using Meshy (async, ~$0.50).",provider:"fal",model:"fal-ai/meshy-ai/text-to-3d",category:"3d",priceCents:50,inputSchema:{type:"object",properties:{object_prompt:{type:"string"},style_prompt:{type:"string"},negative_prompt:{type:"string"},art_style:{type:"string"},seed:{type:"number"}},required:["object_prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/meshy-ai/text-to-3d",merchantName:"Meshy via fal.ai",deprecated:!0,replacementTool:"fal-trellis-3d",buildBody:e=>{let t={object_prompt:e.object_prompt};return e.style_prompt&&(t.style_prompt=e.style_prompt),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.art_style&&(t.art_style=e.art_style),e.seed!==void 0&&(t.seed=e.seed),t},tags:["3d","mesh","meshy","legacy"]},{dispatch:"enveloped",id:"generate_speech_card",name:"Generate Speech",description:"Text-to-speech using F5-TTS with optional voice cloning.",provider:"fal",model:"fal-ai/f5-tts",category:"tts",priceCents:3,inputSchema:{type:"object",properties:{gen_text:{type:"string",description:"Text to synthesize"},ref_audio_url:{type:"string",description:"Reference audio URL (for voice cloning)"},ref_text:{type:"string",description:"Transcription of ref audio"},remove_silence:{type:"boolean"}},required:["gen_text"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/f5-tts",merchantName:"fal.ai",buildBody:e=>{let t={gen_text:e.gen_text};return e.ref_audio_url&&(t.ref_audio_url=e.ref_audio_url),e.ref_text&&(t.ref_text=e.ref_text),e.remove_silence!==void 0&&(t.remove_silence=e.remove_silence),t},deprecated:!0,replacementTool:"fal-metavoice",tags:["tts","speech","f5-tts","legacy"]},{dispatch:"enveloped",id:"generate_music_tempo_card",name:"Generate Music (Suno)",description:"Generate a music track using Suno (async, ~$0.50).",provider:"suno",model:"suno-v4",category:"audio",priceCents:50,inputSchema:{type:"object",properties:{prompt:{type:"string"},instrumental:{type:"boolean"},model:{type:"string",default:"V4"}},required:["prompt"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/generate-music",merchantName:"Suno via Tempo",buildBody:e=>({prompt:e.prompt,customMode:!1,instrumental:e.instrumental??!1,model:e.model||"V4"}),isAsync:!0,pollUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",pollInterval:15e3,pollTimeout:3e5,deprecated:!0,replacementTool:"fal-ace-step-music",tags:["music","audio","suno","async","legacy"]},{dispatch:"enveloped",id:"check_music_status_tempo_card",name:"Check Music Status",description:"Poll a Suno music generation task for completion.",provider:"suno",model:"suno-status",category:"audio",priceCents:0,inputSchema:{type:"object",properties:{taskId:{type:"string"}},required:["taskId"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",merchantName:"Suno Status",buildBody:e=>({taskId:e.taskId}),deprecated:!0,tags:["music","status","suno","legacy"]},{dispatch:"enveloped",id:"query_onchain_prices_card",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly, daily, and weekly granularity.",provider:"allium",model:"allium-prices",category:"llm",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly), '1d' (daily), or '1w' (weekly). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",deprecated:!0,replacementTool:"query_onchain_prices",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:Gc,tags:["onchain","prices","allium","crypto","legacy"]}];function ar(e){return Hs.find(t=>t.id===e)}var Jc=1,Yc=["pick_one","fan_out"],Zc=["concat","dedupe_by_url","top_k_by_score"],Cf=8,kf=f.object({type:f.string().min(1),description:f.string().min(1),enum:f.array(f.string()).optional(),default:f.unknown().optional(),minimum:f.number().optional(),maximum:f.number().optional()}),Tf=f.object({toolId:f.string().min(1),notes:f.string().min(1)}),Ef=f.string().regex(/^[a-z0-9_-]{1,32}$/,"tier key must be 1-32 chars [a-z0-9_-]"),Af=f.object({providers:f.array(f.string().min(1)).min(1).max(Cf),merge:f.enum(Zc),maxResults:f.number().int().positive().optional()}),Xc=f.object({mode:f.enum(Yc).default("pick_one"),intro:f.string().min(1),defaultTier:f.string().min(1),tiers:f.record(Ef,Tf).refine(e=>Object.keys(e).length>0,{message:"must have at least one tier"}),fanOut:Af.optional(),guidance:f.string().min(1),inputProperties:f.record(f.string(),kf),required:f.array(f.string())}).refine(e=>e.tiers[e.defaultTier]!==void 0,{message:"defaultTier must exist in tiers",path:["defaultTier"]}).refine(e=>e.mode!=="fan_out"||e.fanOut!==void 0,{message:"fan_out mode requires fanOut config",path:["fanOut"]}).refine(e=>e.required.every(t=>t in e.inputProperties),{message:"required entries must exist in inputProperties",path:["required"]}),Rf=f.object({version:f.literal(Jc),generatedAt:f.string().datetime(),tools:f.record(f.string().regex(Vs,"tool name must match MCP naming rules"),Xc).refine(e=>Object.keys(e).length>0,{message:"manifest must have at least one tool"})});var uo=require("child_process"),rl=require("util"),ol=T(require("crypto")),ue=T(require("fs")),sl=T(require("os")),He=T(require("path"));var Rn=(0,rl.promisify)(uo.execFile),mo=He.join(sl.homedir(),".visa-mcp","bin"),cn=He.join(mo,"Visa CLI"),Pf=He.join(__dirname,"..","native"),Qc="6",el=He.join(mo,"visa-keychain.version"),tl=He.join(mo,"visa-keychain.sha256");function nl(e){let t=ue.readFileSync(e);return ol.createHash("sha256").update(t).digest("hex")}async function Ks(){try{if(ue.readFileSync(el,"utf-8").trim()===Qc&&ue.existsSync(cn)){let r=ue.readFileSync(tl,"utf-8").trim();if(nl(cn)!==r)m.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),ue.unlinkSync(cn);else return cn}}catch{}let e=He.join(Pf,"visa-keychain.m");if(ue.existsSync(e)||(e=He.resolve(__dirname,"..","..","native","visa-keychain.m")),ue.existsSync(e)||(e=He.resolve(__dirname,"..","native","visa-keychain.m")),!ue.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");ue.mkdirSync(mo,{recursive:!0,mode:448});try{await Rn("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",cn,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=nl(cn);return ue.writeFileSync(tl,t,{mode:384}),ue.writeFileSync(el,Qc,{mode:384}),cn}async function il(e){let t=await Ks(),n;try{n=(await Rn(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 Bs=null;function re(){return gn()?!0:process.platform!=="darwin"?!1:Bs!==null?Bs:(Bs=!0,!0)}var co="visa-cli",lo="attestation-key";async function Mf(e){try{await Rn("security",["delete-generic-password","-s",co,"-a",lo],{timeout:5e3})}catch{}await Rn("security",["add-generic-password","-s",co,"-a",lo,"-w",e],{timeout:5e3})}async function Gs(){try{let{stdout:e}=await Rn("security",["find-generic-password","-s",co,"-a",lo,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function po(){let e=await il(["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 Mf(n),r}async function al(){return await Gs()!==null}async function cl(){if(gn())return"mock-public-key-spki";let e=await Gs();if(!e)throw new Error("Attestation key not found. Run setup to generate a new key.");let t=await Ks();return new Promise((n,r)=>{let o=(0,uo.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 In(e,t){if(gn())return Promise.resolve(Qi());let n=await Gs();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await Ks(),o=["sign",e];return t&&o.push(t),new Promise((s,i)=>{let a=(0,uo.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 fo(){try{await Rn("security",["delete-generic-password","-s",co,"-a",lo],{timeout:5e3})}catch{}try{await il(["delete-key"])}catch{}}var Of=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],Nf=[...Of.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 Ws(e,t=Nf){for(let r of t)if(r.match.kind==="exact_tool"&&r.match.toolId===e.requestedTool)return r.targetToolId;let n=zs(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(zs(r.match.provider)))&&r.match.keywords.every(o=>n.includes(zs(o))))return r.targetToolId;return null}function zs(e){return(e??"").toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}var cr={generate_image:{intro:'Generate an AI image from a text prompt \u2014 useful for hero shots, marketing assets, social posts, blog covers, app mockups, or any time the user asks for art, a logo, an icon, a thumbnail, or "a picture of \u2026". From $0.01 (fast) to $0.06 (pro), returns a hosted PNG/JPG URL. Default tier: balanced ($0.04, 1K, ~10s).',tiers:{balanced:{toolId:"fal-flux-pro",notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",notes:"Recraft V3 \u2014 vector/flat/illustration styles"}},guidance:"If the user didn't specify a tier, pick 'balanced' unless the prompt clearly signals otherwise (text \u2192 text_heavy, logo/icon \u2192 vector, quick test \u2192 fast, hero/print \u2192 pro).",inputProperties:{prompt:{type:"string",description:"Text description of the image to generate."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9", "1:1", "9:16".',default:"16:9"}},required:["prompt"]},generate_video:{intro:'Generate a short AI video from a text prompt \u2014 useful for product demos, social clips, mood reels, ad concepts, or any "make me a video of \u2026" request. $0.10\u2013$0.40 per ~6s clip depending on tier. Async: returns a request_id; use execute_tool with tool_id "check_fal_status_card" to resolve it (60\u2013180s).',tiers:{balanced:{toolId:"fal-minimax-video",notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",notes:"Kling \u2014 highest quality, cinematic"}},guidance:'Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate and are processed asynchronously. The response includes a request_id and model_path. Poll with execute_tool using tool_id "check_fal_status_card" and params {request_id, model_path}. Do not poll more than once per 30 seconds.',inputProperties:{prompt:{type:"string",description:"Text description of the video scene."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9" or "9:16".',default:"16:9"}},required:["prompt"]},generate_music:{intro:'Generate an original music track from a prompt via ACE-Step. ~$0.02 for the default 60s track. Use for songs, backing tracks, jingles, vocal music, instrumental music, or any "make a song/music/track" request. Takes ~60-90s and may return a request_id to poll with check_fal_status_card. For SFX, chimes, ambient beds, or TTS, use generate_audio instead.',tiers:{ace_step:{toolId:"fal-ace-step-music",notes:"ACE-Step \u2014 prompt-to-music with vocals or instrumentals"}},guidance:"Use for songs and music tracks. Takes ~60-90s and may return a request_id to poll with check_fal_status_card. For sound effects, chimes, ambient beds, or TTS, use generate_audio instead.",inputProperties:{prompt:{type:"string",description:"Musical style, mood, instruments, subject, and lyrics direction."},instrumental:{type:"boolean",description:"True for instrumental music with no vocals; false for vocal tracks.",default:!1},duration:{type:"number",description:"Duration in seconds.",default:60}},required:["prompt"]},generate_audio:{intro:'Generate sound effects from a text prompt (sfx tier \u2014 default), or voice-cloned speech from text + a reference audio URL (tts tier). $0.03\u2013$0.04. Use for SFX, chimes, UI sounds, ambient audio (default sfx), or voice cloning when a reference audio URL is available (pass tier:"tts"). Default tier is sfx; pass tier:"tts" for voice cloning.',tiers:{sfx:{toolId:"fal-stable-audio",notes:"Stable Audio \u2014 sound effects and ambient from a prompt"},tts:{toolId:"fal-metavoice",notes:"MetaVoice \u2014 voice cloning TTS (requires a voice sample URL)"}},guidance:'Default tier is sfx: pass prompt describing the sound. For tts (voice cloning): pass tier:"tts" + text + audio_url.',inputProperties:{prompt:{type:"string",description:"Description of sound to generate (sfx tier, default)."},text:{type:"string",description:"Text to speak aloud (tts tier)."},audio_url:{type:"string",description:"URL of a voice sample to clone (tts tier, required for voice cloning)."}},required:[]},generate_3d:{intro:"Generate a 3D mesh (GLB) from an image URL via Trellis. ~$0.08, ~30\u201360s. Use when the user shares an image and asks for a 3D model, asset, AR-ready mesh, or game-ready GLB.",tiers:{trellis:{toolId:"fal-trellis-3d",notes:"Trellis \u2014 image-to-3D, returns a GLB mesh URL"}},guidance:"Pass an image URL. Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{image_url:{type:"string",description:"URL of the image to convert to a 3D model."}},required:["image_url"]},upscale_image:{intro:'Upscale an image to 4\xD7 resolution via Aura SR (preserves detail without hallucination). ~$0.03. Use whenever the user shares a low-res image and asks to "upscale", "make this higher resolution", "4x this", "enhance", or to print/export at larger size.',tiers:{aura:{toolId:"fal-aura-sr",notes:"Aura SR \u2014 default; preserves detail without hallucination"}},guidance:"Pass the existing image URL. Returns an upscaled version.",inputProperties:{image_url:{type:"string",description:"URL of the image to upscale."}},required:["image_url"]},transcribe_audio:{intro:'Transcribe speech in an audio or video file (URL) to text via OpenAI Whisper. ~$0.02 per file, multilingual, handles long files. Use whenever the user asks to "transcribe this", "what does this audio say", "make subtitles", "convert this to text", or shares an audio/video URL with no other clear intent.',tiers:{whisper:{toolId:"fal-whisper",notes:"OpenAI Whisper \u2014 fast, multilingual"}},guidance:"Pass the URL. Returns the transcript text.",inputProperties:{audio_url:{type:"string",description:"URL of the audio or video file to transcribe."}},required:["audio_url"]},run_llm:{intro:"Run a text prompt through a different LLM (GPT-4o-mini, Claude Sonnet, DeepSeek R1/V3, Perplexity Sonar with web search, or Llama 70B). Token-metered, typically ~$0.01\u2013$0.10 per call. Use for: web-grounded answers (search tier), second-opinion reasoning (reasoning tier), code generation in a different family (coding tier), deep math/logic (deep_reasoning tier), or fast cheap text cleanup (fast tier). Pair with batch for multi-model councils.",tiers:{fast:{toolId:"or-gpt-4o-mini",notes:"GPT-4o Mini. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",notes:"Claude Sonnet. Strong reasoning, long-context. Warn user it is materially pricier than `fast`."},deep_reasoning:{toolId:"or-deepseek-r1",notes:"DeepSeek R1. Deep chain-of-thought reasoning, mid-range pricing."},search:{toolId:"or-perplexity-sonar",notes:"Perplexity Sonar. Search-augmented, web-grounded with citations."},open_source:{toolId:"or-llama-70b",notes:"Llama 3.3 70B. Open-source large model."},coding:{toolId:"or-deepseek-chat",notes:"DeepSeek Chat V3. Strong at code generation."}},guidance:"Pick based on the user's need: fast (most questions, cheapest), reasoning (complex analysis; warn user it is materially pricier than fast), search (questions about current events), coding (code generation), deep_reasoning (hard math/logic problems).",inputProperties:{prompt:{type:"string",description:"The user query."},system_prompt:{type:"string",description:"Optional system prompt to set model behavior."},max_tokens:{type:"number",description:"Maximum output tokens.",default:1024,minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature \u2014 0 is deterministic, higher is more creative.",default:.7,minimum:0,maximum:2}},required:["prompt"]}};function ln(e,t,n){if(!ul(e))return jf(e,n);let r=ll[e];if(!r)return e;let o=Object.keys(r.tiers),s=t||o[0],i=Ff(e,s,n);return i||Vf(e,r,s,o)}function jf(e,t){return Ws({requestedTool:e,intentText:t})??e}function Ff(e,t,n){return Ws({requestedTool:e,metaTool:e,tier:t,intentText:n})}function Vf(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=cr;function ul(e){return e in ll}var lr=Object.keys(cr);function Js(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 Js(e)!==null}var Wl=require("child_process"),de=T(require("crypto")),Oe=T(require("fs")),fr=T(require("os")),Ao=T(require("path"));var ml=!1;async function ur(e,t,n){try{return await t()}catch(r){if(!(r.message==="Invalid signature"||r.code==="ATTESTATION_KEY_DRIFT"||r.error_code==="ATTESTATION_KEY_DRIFT"||r.name==="AttestationDriftError")||!re())throw r;if(m.warn("attestation:key-mismatch",{action:"browser-recovery"}),n){if(ml)throw m.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),r;ml=!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 po();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 pl="2.4.0";function Ys(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function ho(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=Qr(t);return o!==void 0?{value:o,source:{kind:"settings"}}:{value:n!=="opt-in",source:{kind:"default"}}}function we(e){return e==null?"\u2014":e?"yes":"no"}function yo(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function qf(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function Hf(){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=Ps("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:Is,source:{kind:"default"}}}async function dr(e){let t=null,n=null;try{t=await e.api.getStatus()}catch(H){n=H?.message||"unknown error"}let r=[],o=process.env.VISA_AUTH_URL,s=$s("auth.serverUrl"),i=he(),a=o!==void 0&&o!==""?{kind:"env",var:"VISA_AUTH_URL"}:s!==void 0?{kind:"settings"}:{kind:"default"};r.push({key:"auth.serverUrl",value:i,formatted:i,source:a,hint:a.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),r.push({key:"account.enrolled",value:t?.enrolled??null,formatted:we(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),t?.githubUser&&r.push({key:"account.githubUser",value:t.githubUser,formatted:t.githubUser,source:{kind:"server"}});let l=t?t.attestationRequired!==!1:void 0;r.push({key:"biometric.required",value:l,formatted:we(l),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"},hint:l===!1?"Touch ID prompts are suppressed. Re-enable with `visa-cli config biometric on`.":void 0}),r.push({key:"biometric.keyRegistered",value:t?.hasAttestationKey??null,formatted:we(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:re(),formatted:we(re()),source:{kind:"device"}});let c=t?.spendingControls,u=c?c.max_transaction_amount??c.maxTransactionAmount??null:null,d=c?c.daily_limit??c.dailyLimit??null:null;r.push({key:"spending.maxPerTxn",value:u,formatted:yo(u),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:d,formatted:yo(d),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:yo(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:yo(t?.dailyRemaining),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"cards.count",value:t?.cardCount??null,formatted:t?.cardCount!=null?String(t.cardCount):"\u2014",source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}});let g=t?.cards?.find(H=>H.isDefault)??t?.cards?.[0];g&&r.push({key:"cards.default",value:{brand:g.brand??null,last4:g.last4},formatted:`${g.brand||"card"} \u2022\u2022\u2022\u2022 ${g.last4}`,source:{kind:"server"}});let p=Hf();r.push({key:"credit.sessionCapCents",value:p.value,formatted:qf(p.value),source:p.source});let v=Sc();v.length>0&&r.push({key:"settings.retired",value:v.map(H=>H.key),formatted:v.map(H=>H.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${v.map(H=>`visa-cli config unset ${H.key}`).join(" && ")}`});let S=ho("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");r.push({key:"ui.suppressBrowser",value:S.value,formatted:we(S.value),source:S.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let y=ho("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");r.push({key:"ui.suppressFeed",value:y.value,formatted:we(y.value),source:y.source});let R=je(),A;process.env.VISA_CLI_NO_UPDATE_CHECK?A={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?A={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?A={kind:"env",var:"NODE_ENV"}:A={kind:"default"},r.push({key:"ui.updateCheck",value:!R,formatted:we(!R),source:A});let x=ho("VISA_META_TOOLS","tools.meta","opt-out");r.push({key:"tools.meta",value:x.value,formatted:we(x.value),source:x.source,hint:"Persist with `visa-cli config set tools.meta false`. Restart Claude Code for changes to take effect."});let w=ho("VISA_DISCOVER_TOOLS","tools.discover","opt-out");r.push({key:"tools.discover",value:w.value,formatted:we(w.value),source:w.source});let F=process.env.VISA_DRY_RUN,se=dl();if(r.push({key:"tools.dryRun",value:se,formatted:we(se),source:F===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:pl,formatted:pl,source:{kind:"default"}}),e.includeDev){let H=process.env.VISA_MOCK_KEYCHAIN,be=mt();r.push({key:"dev.mockKeychain",value:be,formatted:we(be),source:Ys("VISA_MOCK_KEYCHAIN",!!H),hint:Bo()});let Y=process.env.VISA_MOCK_TOUCHID,fe=gn();r.push({key:"dev.mockTouchid",value:fe,formatted:we(fe),source:Ys("VISA_MOCK_TOUCHID",!!Y),hint:Bo()});let dt=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!dt,formatted:we(!!dt),source:Ys("VISA_CLI_DEBUG",!!dt)})}return{entries:r,statusError:n}}function Bf(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 fl(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}(${Bf(s.source)})`),t.verbose&&s.hint&&o.push(` ${"\u21B3".padStart(n)} ${s.hint}`)}return o.join(`
|
|
124
124
|
`)}function gl(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 At=require("fs"),_l=require("os"),Zs=require("path"),Kf=(0,Zs.join)((0,_l.homedir)(),".visa-mcp"),yl=(0,Zs.join)(Kf,"mcp-session-budget.json");function _o(){try{(0,At.existsSync)(yl)&&(0,At.unlinkSync)(yl)}catch{}}var Qs=require("crypto"),Me=T(mr()),un=null,xe=0,$n=0,ve=0,Rt=null,ei=null,ti=null,bo=Promise.resolve();function lg(e){return Number((0,Me.fromCents)(e))}function Sl(e){return(0,Me.toCents)((0,Me.micros)(BigInt(e)))}function bl(e){return(0,Me.toWire)((0,Me.fromCents)(e))}function Xs(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function vo(e){return typeof e=="string"&&/^\d+$/.test(e)}var ug=43,dg=new RegExp(`^[A-Za-z0-9_-]{${ug}}$`);function mg(e){return typeof e=="string"&&dg.test(e)}function pg(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||un&&e.session_id!==un||typeof e.nonce!="string"||e.nonce.length===0||!mg(e.server_signature)||!Xs(e.cumulative)||!Xs(e.remaining)||!Xs(e.delta)||e.cumulative<xe||ve>0&&e.cumulative>ve||ve>0&&e.remaining>ve||e.cumulative_micros!==void 0&&!vo(e.cumulative_micros)||e.remaining_micros!==void 0&&!vo(e.remaining_micros)||e.delta_micros!==void 0&&!vo(e.delta_micros)||e.reserved_micros!==void 0&&!vo(e.reserved_micros))}function ct(e){un=e,xe=0,$n=0,ve=0,Rt=null,ei=null,ti=null,bo=Promise.resolve()}function pr(e){ve=Math.max(0,Math.floor(e))}function ni(){return un}function ri(e){if(!un)return null;let t=xe+$n;return ve>0&&t>ve&&(t=ve),{session_budget_id:un,cumulative_micros:lg(t),nonce:(0,Qs.randomUUID)(),idempotency_key:e||(0,Qs.randomUUID)()}}function oi(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 pg(r)?(xe=Math.max(xe,r.cumulative),$n=0,Rt=r,r):null}function wl(){return Rt}function si(e){let t=Sl(e.cumulative_micros);xe=Math.max(xe,t),$n=0;let n={status:"accepted",session_id:e.session_budget_id,cumulative:xe,remaining:Math.max(0,ve-xe),delta:0,cumulative_micros:bl(xe),remaining_micros:bl(Math.max(0,ve-xe)),delta_micros:"0",nonce:e.nonce};return Rt=n,n}function ii(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,Me.toCents)((0,Me.micros)(n));if(!Number.isFinite(r)||r<0)return;ei=t;let o=e,s=typeof o.session_id=="string"?o.session_id:un??"";Rt?(typeof o.remaining_micros=="string"&&/^\d+$/.test(o.remaining_micros)&&(Rt.remaining_micros=o.remaining_micros),typeof o.charged_micros=="string"&&/^\d+$/.test(o.charged_micros)&&(Rt.delta_micros=o.charged_micros)):Rt={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 xl(e){let t=e.receipt??null;ti={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:Sl(e.voucher.cumulative_micros),estimatedCumulativeCents:So(),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 Cl(){return ti}function kl(){return xe}function Tl(){return ei}function So(){let e=xe+$n;return ve>0&&e>ve&&(e=ve),e}function El(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return bo=bo.then(()=>{$n+=t}),bo}var fg=10,gg=1,W=null,Al=Promise.resolve();function ai(e){let t=Al.catch(()=>{}).then(e);return Al=t.then(()=>{},()=>{}),t}var pe=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 ai(()=>Rl(e,t,n))}async function Rl(e,t,n){if(_o(),W&&new Date(W.expiresAt).getTime()>Date.now())return ni()!==W.budgetId&&(ct(W.budgetId),pr(W.totalCents)),m.info("mcp-session:active-hit",{budgetId:W.budgetId,tool:n.toolName,remainingEstimatedCents:W.totalCents-So()}),{budgetId:W.budgetId,isFresh:!1,totalCents:W.totalCents,requestedCapCents:W.totalCents,appliedCapCents:W.totalCents,clampedReason:null};W&&(W=null,ct(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"?gg:fg,i=Math.max(s,Math.ceil(n.minRequiredCents??s));if(r.balanceCents<i)throw new pe(r.balanceCents,i);let a=n.capCentsOverride??Cc(),l=Math.min(a,r.balanceCents),c=l<a?"balance":null,u=await t("session_create",l,"Visa CLI Session",`open credit-model session with $${(l/100).toFixed(2)} cap`,n.userContext),d=await e.createSessionBudget({total_cents:l,session_kind:o,...u?{attestation:u}:{}});if(!d.success||!d.budget){let p=d.error||"unknown error";throw new Error(`Failed to open credit session: ${p}`)}let g={budgetId:d.budget.id,expiresAt:d.budget.expiresAt,totalCents:d.budget.totalCents,createdAt:d.budget.createdAt};return W=g,ct(g.budgetId),pr(g.totalCents),m.info("mcp-session:opened",{budgetId:g.budgetId,capCents:g.totalCents,requestedCapCents:a,clampedReason:c,sessionKind:o,expiresAt:g.expiresAt,tool:n.toolName}),{budgetId:g.budgetId,isFresh:!0,totalCents:g.totalCents,requestedCapCents:a,appliedCapCents:g.totalCents,clampedReason:c}}async function Il(e,t,n){return ai(async()=>{let o=It()?await $l(e):null,s=await Rl(e,t,n);return{budgetId:s.budgetId,totalCents:s.totalCents,closedPrevious:o,requestedCapCents:s.requestedCapCents,appliedCapCents:s.appliedCapCents,clampedReason:s.clampedReason}})}async function $l(e){let n=It()?.budgetId??ni(),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 _o(),W=null,ct(null),{closedServerSide:r,budgetId:n,finalCumulativeCents:o,finalCumulativeMicros:s}}async function wo(e){return ai(()=>$l(e))}function It(){return _o(),W?new Date(W.expiresAt).getTime()<=Date.now()?(W=null,ct(null),null):{budgetId:W.budgetId,totalCents:W.totalCents,lastReceiptCumulative:kl(),lastReceiptCumulativeMicros:wl()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:Tl(),estimatedCumulative:So(),lastToolSpend:Cl(),expiresAt:W.expiresAt}:null}var Ml=T(mr()),Pl=10000n;function hg(e){return e<=0n?0:Number((e+Pl-1n)/Pl)}function Ol(e){return hg((0,Ml.fromUsd)(e))}var xo="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.",Nl="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 Ll=Promise.resolve(),Dl=!1;function Ro(e){let t=Ll.catch(()=>{}).then(e);return Ll=t.then(()=>{},()=>{}),t}async function Jl(e){let t=await ci(P,We,{toolName:e.toolId,userContext:e.userContext}),n=ri(e.idempotencyKey);if(!n)throw new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let r=await xg(),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 Ht){let d=Math.min(Math.max(u.retryAfterSecs,0),5)*1e3;m.warn("mcp-session:lock-contended-retrying",{tool:e.toolId,retryAfterSecs:u.retryAfterSecs}),await new Promise(g=>setTimeout(g,d)),{data:o,voucherReceiptHeader:s}=await i()}else throw u}}catch(u){if(u instanceof vn){if(m.warn("mcp-session:server-invalidated-budget",{code:u.code,budgetId:u.budgetId??t.budgetId,tool:e.toolId}),await wo(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 Dl||(Dl=!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}),Yl(e)}throw u instanceof Ht?(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=oi(s)??(n?si(n):null);if(ii(o?.receipt_v2),await El(e.estimatedAmountCents),xl({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),Xl(o))return o;let l=await Zl();if(e.idempotencyKey&&Ql(o,l,e.idempotencyKey))return o;let c=l?To(l):null;return eu(o,r,c)}function Ke(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function di(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(di).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${di(r)}`).join(",")}}`}function yg(e,t,n,r){let o=de.createHash("sha256").update(`${n}:${di(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${o}`}function _g(e,t){return`${e}:${t}`}function vg(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 Ul(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,o=Be(r),s=o!==null?o.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=vg(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),l=i!=null?String(i):a;return{batch_id:e,item_id:_g(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 Yl(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 pe(n.balanceCents,t);let r=t,o=To(n),s=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(r/100).toFixed(2)})`,i=await We("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;ct(l),pr(a.budget.totalCents),m.info("on-demand-session:opened",{budgetId:l,capCents:a.budget.totalCents,tool:e.toolId});try{let c=ri(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(oi(d)||si(c),ii(u?.receipt_v2),Xl(u))return u;let g=await Zl();if(e.idempotencyKey&&Ql(u,g,e.idempotencyKey))return u;let p=g?To(g):null;return eu(u,o,p)}finally{try{await P.closeSession(l)}catch(c){m.warn("on-demand-session:close-failed",{budgetId:l,error:c?.message||String(c)})}ct(null),m.info("on-demand-session:closed",{budgetId:l,tool:e.toolId})}}async function Pt(e){return Ro(async()=>It()?Jl(e):Yl(e))}function Io(){return he()}var P=new Se(()=>U.getSessionToken());function Be(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function To(e){return Be(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function bg(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 Sg(e){let t=Be(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=Be(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=Be(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function Co(e,t="INVALID_TOOL_PARAMS"){return{success:!1,error_code:t,code:t,error:e,message:e}}function wg(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 xg(){try{let e=await P.getBalance();return e.success?To(e):null}catch{return null}}async function Zl(){try{let e=await P.getBalance();return e.success?e:null}catch{return null}}function Xl(e){if(!e||e.success===!1)return!1;let t=Be(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=Be(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 Ql(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=Be(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 Cg="2.4.0
|
|
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}),Yl(e)}throw u instanceof Ht?(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=oi(s)??(n?si(n):null);if(ii(o?.receipt_v2),await El(e.estimatedAmountCents),xl({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:n,receipt:a}),Xl(o))return o;let l=await Zl();if(e.idempotencyKey&&Ql(o,l,e.idempotencyKey))return o;let c=l?To(l):null;return eu(o,r,c)}function Ke(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function di(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(di).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${di(r)}`).join(",")}}`}function yg(e,t,n,r){let o=de.createHash("sha256").update(`${n}:${di(r)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${o}`}function _g(e,t){return`${e}:${t}`}function vg(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 Ul(e,t,n){let r=n?.amountMicros??n?.amount_micros??n?.charged_micros??n?.receipt_v2?.charged_micros??n?.receipt_v2?.actual_micros,o=Be(r),s=o!==null?o.toString():void 0,i=n?.transaction_id??n?.transactionId??n?.receipt_v2?.transaction_id,a=vg(n?.ledger_id??n?.ledgerId??n?.receipt_v2?.ledger_id),l=i!=null?String(i):a;return{batch_id:e,item_id:_g(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 Yl(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 pe(n.balanceCents,t);let r=t,o=To(n),s=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(r/100).toFixed(2)})`,i=await We("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;ct(l),pr(a.budget.totalCents),m.info("on-demand-session:opened",{budgetId:l,capCents:a.budget.totalCents,tool:e.toolId});try{let c=ri(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(oi(d)||si(c),ii(u?.receipt_v2),Xl(u))return u;let g=await Zl();if(e.idempotencyKey&&Ql(u,g,e.idempotencyKey))return u;let p=g?To(g):null;return eu(u,o,p)}finally{try{await P.closeSession(l)}catch(c){m.warn("on-demand-session:close-failed",{budgetId:l,error:c?.message||String(c)})}ct(null),m.info("on-demand-session:closed",{budgetId:l,tool:e.toolId})}}async function Pt(e){return Ro(async()=>It()?Jl(e):Yl(e))}function Io(){return he()}var P=new Se(()=>U.getSessionToken());function Be(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function To(e){return Be(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function bg(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 Sg(e){let t=Be(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let n=Be(e.lastReceiptCumulativeMicros);if(n!==null)return{micros:n,source:"lastReceiptCumulativeMicros"};let r=Be(e.lastToolSpend?.receiptCumulativeMicros);return r!==null?{micros:r,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function Co(e,t="INVALID_TOOL_PARAMS"){return{success:!1,error_code:t,code:t,error:e,message:e}}function wg(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 xg(){try{let e=await P.getBalance();return e.success?To(e):null}catch{return null}}async function Zl(){try{let e=await P.getBalance();return e.success?e:null}catch{return null}}function Xl(e){if(!e||e.success===!1)return!1;let t=Be(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),n=Be(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 Ql(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=Be(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 Cg="2.4.0",lS=["","","You're ready to go! Try:","","Core:",'\u2022 "Show my account status" \u2192 get_status','\u2022 "List my enrolled cards" \u2192 get_cards','\u2022 "Show my paid tool use history" \u2192 transaction_history','\u2022 "Set my daily limit to $50" \u2192 update_spending_controls','\u2022 "Generate 3 variations in parallel" \u2192 batch',"","Category tools:",'\u2022 "Generate an image of a sunset over Tokyo" \u2192 generate_image','\u2022 "Make a 4-second video of a penguin juggling" \u2192 generate_video','\u2022 "Make a song about coding late at night" \u2192 generate_music','\u2022 "Create a sound effect for a checkout chime" \u2192 generate_audio','\u2022 "Create a 3D asset from this product sketch" \u2192 generate_3d','\u2022 "Upscale this product image" \u2192 upscale_image','\u2022 "Transcribe this meeting recording" \u2192 transcribe_audio','\u2022 "Run a reasoning model on this prompt" \u2192 run_llm',"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
|
|
126
126
|
`);function Ge(e){if(!e||typeof e!="string"||wc())return;let t=Kn(e);if(!t)return;let n=is();if(n.headless){m.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`);return}let r=fa(t,Io());if(!r){m.info(`Browser auto-open skipped (non-internal host). URL: ${t}`);return}let o=ha(r);if(!o){m.info(`No browser command for platform "${fr.platform()}". URL: ${r}`);return}(0,Wl.execFile)(o.cmd,o.args,s=>{s&&m.warn(`Browser open failed: ${s.message}. URL: ${r}`)})}async function Ce(e){return ur(P,e,au)}var tu="get_cards",nu="set_default_card";function kg(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 '${tu}' to see enrolled cards and '${nu}' to switch, then retry the original request.`}function Tg(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 '${tu}' to see enrolled cards and '${nu}' to switch. Do not retry automatically.`}function ze(e,t){let n=e.retryable?kg(e.code,e.retryAfter):Tg(e.code,t.merchantName);return{success:!1,declined:!0,retryable:e.retryable,code:e.code,reason:e.reason,payment_error_class:e.paymentErrorClass,correlation_id:e.correlationId,transactionId:e.transactionId,retryAfter:e.retryAfter,merchantName:t.merchantName,amount:t.amount,message:e.message,agent_guidance:n}}var Pn=null,Eg=3e4;function ru(){Pn=null}var $t=class extends Error{constructor(n){super(`${Eo()} attestation is required for this action, but it is not available in this MCP process. `+mi());this.context=n;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function $o(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. `+mi()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function Ag(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:xo,agent_guidance:Nl}}function Eo(){return process.platform==="darwin"?"Touch ID":"local biometric"}function mi(){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 Po(e){return typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0}async function Rg(e){let t=Date.now();if(Pn&&Pn.expiresAt>t)return{required:Pn.required,hasRegisteredKey:Pn.hasRegisteredKey};try{let n=await P.getStatus(e),r=n.attestationRequired!==!1,o=Po(n);return Pn={required:r,hasRegisteredKey:o,expiresAt:t+Eg},{required:r,hasRegisteredKey:o}}catch{return{required:!0,hasRegisteredKey:!0}}}async function We(e,t,n,r,o,s){if(!s?.forceRequired){let i=await Rg(o);if(!i.required){m.info("attestation:skipped-by-server-policy",{context:e});return}if(!i.hasRegisteredKey){m.info("attestation:skipped-no-registered-key",{context:e});return}}if(!re())throw m.warn("attestation:unavailable",{context:e}),new $t(e);m.info("attestation:attempt",{context:e,amount:t,merchant:n});try{let{nonce:i}=await P.getAttestationChallenge(),a=Buffer.from(JSON.stringify({nonce:i,amount:t,merchant:n,context:e})).toString("base64");m.info("touchid:prompt",{context:e,amount:t,merchant:n});let l=await In(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 jl="[dry-run] https://placeholder.visa-cli.dev/image.png",Ig=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"]),$g=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 Pg(e,t){return t==="run_llm"||e.startsWith("or-")?"llm":t==="generate_image"||Ig.has(e)?"image":t==="generate_video"||$g.has(e)?"video":null}function Mg(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function Og(e){return e==="llm"?"OpenRouter":"fal.ai"}function Mn(e,t,n,r){let o={success:!0,transactionId:`dry-run:${r??t}`,amount:0,rail:"dry_run",merchantName:Og(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let i=`[dry-run] echo: ${Mg(n)}`;return{...o,content:i,data:{content:i,model:t,dry_run:!0}}}return{...o,urls:[jl],data:{[e==="video"?"videoUrl":"imageUrl"]:jl,metadata:{dry_run:!0}}}}async function li(e){let t=e.mode??"mock",n=t==="preflight"?"/v1/telemetry/preflight":"/v1/telemetry/dry-run",r=t==="preflight"?"preflight":null;try{await P.emitTelemetry([{id:de.randomUUID(),timestamp:new Date().toISOString(),tool_name:e.toolName,user_prompt:e.userContext??"",tool_params:JSON.stringify(e.toolParams),result_success:!0,result_error:null,result_json:JSON.stringify(e.result),payment_rail:r,payment_amount:0,payment_currency:"USD",merchant_name:e.result.merchantName,transaction_id:e.result.transactionId,tx_hash:null,protocol:null,http_status:200,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",event_kind:"mcp_tool",endpoint:n,resolved_model:e.resolvedModel,session_budget_id:null}])}catch(o){m.warn("dry_run:telemetry_failed",{tool:e.toolName,error:o?.message||String(o),mode:t})}}var Ng="https://openrouter.ai/api/v1/chat/completions",Lg="openrouter/free",Dg=50,Ug=15e3;function jg(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 Fg(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:Mn("llm",e,t,n),degraded:!0,resolvedModel:null};let o=jg(t),s;try{s=await Vt(Ng,{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:Lg,messages:[{role:"user",content:o}],max_tokens:Dg}),timeoutMs:Ug})}catch(u){return m.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:u?.message||String(u)}),{result:Mn("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:Mn("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:Mn("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 Mo(e,t,n,r){let o=Js();if(!o)return null;let s=Pg(e,r);if(!s)return null;let i=Date.now();if(o==="mock"){let c=Mn(s,e,t,r);return await li({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=Mn(s,e,t,r);return await li({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 Fg(e,t,r);return await li({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 lt(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 ut(e){return Ol(e.amount)}function Vg(){return Ao.join(fr.homedir(),".visa-mcp","allium-results")}var uS=16*1024,dS=50*1024*1024;function qg(){let e=Vg();try{if(!Oe.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=Oe.readdirSync(e),n=0,r=0;for(let o of t)try{let s=Oe.statSync(Ao.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 Fl=3600*1e3,ui=0;function Hg(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function gr(e){if(!xc()&&!(Date.now()<ui))try{if(!await U.getSessionToken())return;await P.feedSubmit({prompt:e.prompt,tool:e.tool,media_url:e.mediaUrl,media_type:e.mediaType,cost:e.cost,transaction_id:e.transactionId,auto:!0,...e.userContext&&{user_context:e.userContext}}),m.info("feed:submitted",{tool:e.tool,mediaType:e.mediaType,transactionId:e.transactionId})}catch(t){if(Hg(t)){let n=ui===0;ui=Date.now()+Fl,n&&m.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:Fl});return}m.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function Bg(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 We("get_visa_smi",a,i,l),u=await P.getVisaSmi({state:n,county:r,start_date:o,end_date:s,attestation:c,idempotencyKey:de.randomUUID()},t);return u.success?m.info("payment:success",{tool:"get_visa_smi",merchant:i,charged_cents:u.charged_cents}):m.warn("payment:declined",{tool:"get_visa_smi",merchant:i,message:u.error}),u})}catch(c){if(c instanceof ce)return m.warn("payment:declined",{tool:"get_visa_smi",merchant:i,code:c.code,retryable:c.retryable}),ze(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 Kg(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 Mo("generate_image_card",e,t);if(n)return n;let r=await lt("generate_image_card",void 0,t),o=de.randomUUID();m.info("payment:attempt",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName});try{return await Ce(async()=>{let s;try{s=await Pt({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:ut(r),userContext:t,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof pe)return Ke(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=>Ge(i)),gr({prompt:e.prompt,tool:"generate_image_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):m.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof ce)return m.warn("payment:declined",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),ze(s,r);throw m.error("payment:failure",{tool:"generate_image_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function Gg(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 Mo("generate_image_fast_card",e,t);if(n)return n;let r=await lt("generate_image_fast_card",void 0,t),o=de.randomUUID();m.info("payment:attempt",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName});try{return await Ce(async()=>{let s;try{s=await Pt({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:ut(r),userContext:t,timeoutMs:6e4,idempotencyKey:o})}catch(i){if(i instanceof pe)return Ke(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=>Ge(i)),gr({prompt:e.prompt,tool:"generate_image_fast_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):m.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof ce)return m.warn("payment:declined",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),ze(s,r);throw m.error("payment:failure",{tool:"generate_image_fast_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function zg(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 Mo("generate_video_tempo_card",e,t);if(n)return n;let r=await lt("generate_video_tempo_card",void 0,t),o=de.randomUUID();m.info("payment:attempt",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await Ce(async()=>{let s;try{s=await Pt({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:ut(r),userContext:t,timeoutMs:12e4,idempotencyKey:o})}catch(i){if(i instanceof pe)return Ke(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=>Ge(i)),gr({prompt:e.prompt,tool:"generate_video_tempo_card",mediaUrl:s.urls[0],mediaType:"video",cost:s.amount??r.amount,transactionId:s.transactionId,userContext:t})):m.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(s){if(s instanceof ce)return m.warn("payment:declined",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,code:s.code,retryable:s.retryable}),ze(s,r);throw m.error("payment:failure",{tool:"generate_video_tempo_card",amount:r.amount,merchant:r.merchantName,error:s.message}),s}}async function Wg(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 lt("generate_music_tempo_card",void 0,t),r=de.randomUUID();m.info("payment:attempt",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await Ce(async()=>{let o;try{o=await Pt({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:ut(n),userContext:t,timeoutMs:36e4,idempotencyKey:r})}catch(s){if(s instanceof pe)return Ke(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=>Ge(s)),gr({prompt:e.prompt,tool:"generate_music_tempo_card",mediaUrl:o.urls[0],mediaType:"audio",cost:o.amount??n.amount,transactionId:o.transactionId,userContext:t})):o.urls?.length&&o.status==="processing"?(o._preliminary_urls=o.urls,delete o.urls,m.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):m.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof ce)return m.warn("payment:declined",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),ze(o,n);throw m.error("payment:failure",{tool:"generate_music_tempo_card",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}async function Jg(e,t){let n=await lt("check_music_status_tempo_card",void 0,t),r=de.randomUUID();m.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await Ce(async()=>{let o;try{o=await Pt({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:ut(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof pe)return Ke(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=>Ge(s)),o})}catch(o){if(o instanceof ce)return m.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),ze(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 Yg(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 lt("query_onchain_prices",void 0,t),r=de.randomUUID();m.info("payment:attempt",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName});try{return await Ce(async()=>{let o;try{o=await Pt({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:ut(n),userContext:t,timeoutMs:3e4,idempotencyKey:r})}catch(s){if(s instanceof pe)return Ke(s);throw s}if(m.info("payment:success",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,mode:"session"}),Array.isArray(o?.data))o.data=o.data.map(s=>{if("mint"in s&&!("address"in s)){let{mint:i,...a}=s;return{address:i,...a}}return s});else if(o&&"mint"in o&&!("address"in o)){let{mint:s,...i}=o;return{address:s,...i}}return o})}catch(o){if(o instanceof ce)return m.warn("payment:declined",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),ze(o,n);throw m.error("payment:failure",{tool:"query_onchain_prices",amount:n.amount,merchant:n.merchantName,error:o.message}),o}}var Zg=["generate_music_tempo_card"],Vl=10,ql=5,Hl=new Map;function Bl(e){let t=Hl.get(e);if(t!==void 0)return t;let r=ar(e)?.isAsync===!0||Zg.includes(e);return Hl.set(e,r),r}var Xg=36e4,Qg=18e4,eh=15e3,th=12e4,nh=2e3;function Kl(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}async function rh(e,t){let n;if(e.requests?.some(x=>x.tool||x.tool_id)&&e.requests)n=e.requests.map(x=>{let w=x.tool||x.tool_id||e.tool;if(!w)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let F=ln(w,x.tier||e.tier,x.prompt??t),{tool:se,tool_id:H,tier:be,params:Y,...fe}=x,dt=Y&&typeof Y=="object"?{...Y,...fe}:fe;return{resolvedTool:F,params:dt}});else if(e.tool){let x=ln(e.tool,e.tier,e.params?.prompt??t);n=(e.requests||(e.count&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(F=>({resolvedTool:x,params:F}))}else return Kl("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(n.length===0)return Kl("BATCH_EMPTY","Batch requires at least one item.");if(n.length>Vl)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${Vl} items. Please split into smaller batches.`};if([...new Set(n.map(x=>x.resolvedTool))].some(Bl)&&n.length>ql)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${ql} items. Please use multiple batches for more.`};let i=[...new Set(n.map(x=>x.resolvedTool))],a=i.length===1,l={};for(let x of i)l[x]=await lt(x,void 0,t);let c=0;for(let x of n)c+=l[x.resolvedTool].amount;let u=[...new Set(Object.values(l).map(x=>x.merchantName))].join(", "),d=a?i[0]:"mixed";m.info("payment:attempt",{tool:"batch",batchTool:d,count:n.length,totalAmount:c,merchant:u,heterogeneous:!a});let g=n.some(x=>Bl(x.resolvedTool)),p=n.some(x=>x.resolvedTool.startsWith("or-")||x.resolvedTool==="run_llm"||x.resolvedTool==="execute_tool"),v=g?Xg:p?Qg+n.length*eh:th+n.length*nh,S=de.randomUUID(),y=[],R=0,A=0n;return Ro(async()=>{let x=!It();if(x)try{let w=Math.max(1,Math.ceil(c*100));await ci(P,We,{toolName:"batch",userContext:t,sessionKind:"one_shot",minRequiredCents:w,capCentsOverride:w})}catch(w){return w instanceof pe?Ke(w):(m.warn("payment:batch-prewarm-failed",{batchTool:d,count:n.length,error:w?.message||String(w)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:w?.message||"Failed to authenticate batch session",tool:d,count:n.length,failedCount:n.length,results:[]})}try{for(let Y=0;Y<n.length;Y+=1){let fe=n[Y],dt=l[fe.resolvedTool];try{let ie=await Jl({toolId:fe.resolvedTool,toolParams:fe.params,estimatedAmountCents:ut(dt),userContext:t,metaTool:"batch",timeoutMs:v,idempotencyKey:yg(S,Y,fe.resolvedTool,fe.params)});if(y.push({success:ie?.success!==!1,tool:fe.resolvedTool,...ie,...Ul(S,Y,ie)}),ie?.success!==!1){let jn=Be(ie?.amountMicros??ie?.amount_micros),qi=typeof ie?.amount=="number"?ie.amount:dt.amount;jn!==null&&jn>0n?A+=jn:A+=BigInt(Math.round(qi*1e6)),R+=qi}ie?.urls&&ie.urls.forEach(jn=>Ge(jn))}catch(ie){if(ie instanceof pe&&y.length===0)return Ke(ie);m.warn("payment:batch-item-failed",{tool:fe.resolvedTool,index:Y,error:ie?.message||String(ie)}),y.push({success:!1,tool:fe.resolvedTool,...Ul(S,Y),error:ie?.message||String(ie)})}}let w=y.filter(Y=>Y?.success===!1).length,F=y.length-w,se=y.flatMap(Y=>Array.isArray(Y?.urls)?Y.urls:[]),H=A>0n?Number(A)/1e6:Math.round((R+Number.EPSILON)*100)/100,be=F===0?"failure":w===0?"success":"partial";return m.info("payment:success",{tool:"batch",batchTool:d,count:n.length,totalAmount:c,totalCharged:H,merchant:u,successCount:F,failedCount:w,outcome:be,mode:"session",batchId:S}),{success:F>0,outcome:be,batch_id:S,tool:a?i[0]:d,count:n.length,successCount:F,failedCount:w,totalCharged:H,...A>0n?{totalChargedMicros:A.toString(),amountMicros:A.toString(),amount_micros:A.toString()}:{},merchantName:u,results:y,...se.length?{urls:se}:{}}}catch(w){if(w instanceof ce)return m.warn("payment:declined",{tool:"batch",batchTool:d,count:n.length,totalAmount:c,merchant:u,code:w.code,retryable:w.retryable}),ze(w,{amount:c,merchantName:u});throw m.error("payment:failure",{tool:"batch",batchTool:d,count:n.length,totalAmount:c,merchant:u,error:w.message}),w}finally{if(x){let w=await wo(P);m.info("batch-session:closed",{budgetId:w.budgetId,closedServerSide:w.closedServerSide})}}})}function oh(){let e=!1,t;try{let r=Ao.join(fr.homedir(),".claude","settings.json");if(Oe.existsSync(r)){let o=JSON.parse(Oe.readFileSync(r,"utf-8")),s=typeof o.statusLine=="object"?o.statusLine.command:"";e=bt(s)}}catch{}let n=Ur();return n||(t="visa-cli config hud enable"),{statusLine:e,shellHud:n,...t?{shellHudSetup:t}:{}}}async function sh(e){let[t,n]=await Promise.all([P.getStatus(e),P.getBalance().catch(s=>(m.warn("get_status:balance_fetch_failed",{error:s?.message||String(s)}),null))]);typeof t?.dailyRemaining=="number"&&(t.dailyRemaining=Math.round(t.dailyRemaining*100)/100);let r=qg();r.file_count>0&&(t.alliumResultsOnDisk=r),t.hud=oh(),t.version=Cg,Array.isArray(t.cards)&&(t.cards=t.cards.map(s=>({...s,displayName:pi(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=It();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 pi(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 ou(e,t){try{let r=((await P.getStatus(t)).cards||[]).find(o=>o?.id===e);if(r)return pi(r)}catch(n){m.warn("cards:display_name_lookup_failed",{cardId:e,error:n?.message||String(n)})}return"selected card"}async function ih(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:pi(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 ah(e,t){return await P.getTransactions({limit:e.limit,offset:e.offset},t)}async function ch(e,t){return await P.feedback(e.message,e.transaction_id,t)}var lh=100;async function uh(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return dn("MISSING_CONFIRMATION","Please confirm by setting confirm: true to charge your enrolled card for credits.");if(!e.amount||!Number.isFinite(e.amount)||e.amount<=0)return{success:!1,error:"amount must be a positive number in USD (e.g. 5.00)"};let n=Math.round(e.amount*100);if(n<lh)return{success:!1,error:"Minimum top-up is $1.00"};let r=de.randomUUID();m.info("buy_credits:attempt",{amountCents:n});try{return await Ce(async()=>{let o=await We("balance-topup",e.amount,"Visa CLI Balance",`top up balance with $${e.amount.toFixed(2)}`,t,{forceRequired:!0}),s=await P.topupBalance({amount_cents:n,idempotency_key:r,attestation:o});if(s.success){m.info("buy_credits:success",{amountCents:n,balanceCents:s.balanceCents});let i=((s.balanceCents??0)/100).toFixed(2),a=(n/100).toFixed(2);return{...s,amount:n/100,amountMicros:String(n*1e4),merchantName:"Visa CLI Balance",message:`Added $${a} \u2014 balance is now $${i}`}}return m.warn("buy_credits:failed",{amountCents:n,error:s.error}),s})}catch(o){if(o instanceof $t)return Ag();throw m.error("buy_credits:failure",{amountCents:n,error:o.message}),o}}function dn(e,t){return{success:!1,error:t,code:e,message:t}}async function dh(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return dn("MISSING_CONFIRMATION","Please confirm by setting confirm: true to update spending controls.");if(e.maxTransactionAmount!==void 0&&(typeof e.maxTransactionAmount!="number"||!Number.isFinite(e.maxTransactionAmount)||e.maxTransactionAmount<.01||e.maxTransactionAmount>100))return dn("INVALID_VALUE","maxTransactionAmount must be between $0.01 and $100");if(e.dailyLimit!==void 0&&(typeof e.dailyLimit!="number"||!Number.isFinite(e.dailyLimit)||e.dailyLimit<1||e.dailyLimit>100))return dn("INVALID_VALUE","dailyLimit must be between $1 and $100");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return dn("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 We("spending-controls",0,"","update spending controls"),r=await P.updateSpendingControls({maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit,confirm:!0,attestation:n},t);return m.info("spending_controls:success",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit}),r})}catch(n){if(m.error("spending_controls:failure",{error:n.message}),n instanceof $t)return $o(n,"update_spending_controls");if(String(n?.message||n).includes("Attestation required"))return dn("ATTESTATION_REQUIRED","Changing spending controls requires local attestation, even when payment biometric prompts are disabled.");throw n}}async function mh(e){let t=await dr({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 ph(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=eo(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 tt?"UNKNOWN_KEY":t instanceof nt?"SERVER_CONTROLLED":t instanceof St?"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(xt).sort()}}}async function fh(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=to(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 tt?"UNKNOWN_KEY":t instanceof nt?"SERVER_CONTROLLED":t instanceof St?"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(xt).sort()}}}async function gh(e){let t=await P.getStatus(e),n=t.attestationRequired!==!1,r=Po(t),o=re(),s=n?r?o?`${Eo()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${Eo()} is not available in this process. ${mi()}`:"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 hh(e){m.info("biometric:on");let t=await P.setBiometricPreference({required:!0},e);return t.success?(ru(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:t.error||"unknown error"}}async function yh(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return dn("MISSING_CONFIRMATION","Please confirm by setting confirm: true. Disabling Touch ID is a security downgrade \u2014 the user will be prompted for one final Touch ID confirmation before the change takes effect.");m.info("biometric:off");try{return await Ce(async()=>{let n=await P.getStatus(t),r;if(Po(n)&&(r=await We("biometric-preference",0,"","disable Touch ID requirement"),!r))throw new Error(`${Eo()} 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 ru(),{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 $t)return $o(n,"biometric_off");throw n}}var Gl=3e4,_h=3e5;async function su(e,t,n="login"){let r=de.randomUUID(),o=`${e}${e.includes("?")?"&":"?"}state=${r}`;return Ge(o),iu(r,t,n)}async function iu(e,t,n="login"){let r=Date.now()+_h;for(;Date.now()<r;)try{let s=await fetch(`${Io()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:Gl,...t&&{user_context:t}}),signal:AbortSignal.timeout(Gl+5e3)});if(!s.ok){await yt(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=hl(a);if(i.sessionToken){await U.saveSessionToken(i.sessionToken);let u=i.user||"",d=i.last4||"****";return m.info("auth:login_complete",{user:u,last4:d,bonusCents:a}),{success:!0,message:`Signed in as ${u}. Card ending in ${d} enrolled and ready for payments.`,...l||{}}}let c=i.last4||"****";return m.info("auth:card_added",{last4:c,bonusCents:a}),{success:!0,message:`Card ending in ${c} enrolled and ready for payments.`,...l||{}}}}catch{await yt(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 au(e){let t=de.randomUUID(),n;try{n=await P.startAttestationRecovery(t,e)}catch(r){return{success:!1,message:`Could not start biometric reset: ${r?.message||"unknown error"}`}}return!n.success||!n.recoveryUrl?{success:!1,message:n.error||"Could not start biometric reset. Please try again."}:(Ge(n.recoveryUrl),iu(t,e,"attestation-recovery"))}async function vh(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 ou(n,t)}`;try{return await Ce(async()=>{let s=await We(r,0,"",o,t,{forceRequired:!0}),i=await P.removeCard(n,{attestation:s},t);return m.info("cards:remove_success",{cardId:n,promotedId:i?.promotedId??null}),i})}catch(s){if(m.error("cards:remove_failure",{cardId:n,error:s.message}),s instanceof $t)return $o(s,"remove_card");throw s}}async function bh(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 ou(n,t)} as default`;try{return await Ce(async()=>{let s=await We(r,0,"",o,t,{forceRequired:!0}),i=await P.setDefaultCard(n,{attestation:s},t);return m.info("cards:set_default_success",{cardId:n}),i})}catch(s){if(m.error("cards:set_default_failure",{cardId:n,error:s.message}),s instanceof $t)return $o(s,"set_default_card");throw s}}async function Sh(e){return m.info("auth:login_attempt"),su(`${Io()}/login`,e)}function wh(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 xh(e={},t){let n;try{n=wh(e)}catch(r){return{success:!1,error:r?.message||String(r)}}return Ro(async()=>{let r=await Il(P,We,{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 Ch(){let e=It();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 kh(){return Ro(async()=>{let e=It();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 wo(P);m.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let n=Sg(e),r=Be(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 ${bg(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 Th(e){if(m.info("auth:add_card_attempt"),!await U.getSessionToken())return{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."};let{code:n}=await P.createEnrollCode();return su(`${Io()}/enroll-card?code=${encodeURIComponent(n)}`,e,"enrollment")}async function Eh(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};m.info("reset:attempt");let n=!1;try{let r=await P.getStatus(t);if(r&&Po(r)){let o=await au(t);if(!o.success)return o;n=!0}}catch(r){let o=r?.message||"unknown error";if(!/not logged in|session.*expired|no local credentials/i.test(o))return{success:!1,message:`Could not check server biometric state: ${o}`};m.warn("reset:server_attestation_status_unavailable",{error:o})}try{await P.logout(void 0,t)}catch{}if(await U.clearAll(),re())try{await fo()}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 Ah(e){let t=e.query?.trim()||void 0,n=e.category?.trim()||void 0,r=!t&&!n;m.info("catalog:discover",{query:t,category:n,browseAll:r});try{let s=(await P.catalogSearch(t,n)).tools||[];if(s.length===0)return{content:[{type:"text",text:r?"The tool catalog is currently empty.":`No tools found for "${t||n}". Try a different search term.`}]};if(r){let a={};for(let c of s){let u=c.category||"other";(a[u]??=[]).push(c)}let l=Object.keys(a).sort().map(c=>{let u=a[c].map((g,p)=>`${p+1}. **${g.name}** (${g.id})
|
|
127
127
|
${g.description}
|
|
128
128
|
Provider: ${g.provider} | Price: ${zl(g)}
|